47 #include "llvm/ADT/StringSwitch.h" 48 #include "llvm/ADT/Triple.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/IR/CallingConv.h" 51 #include "llvm/IR/DataLayout.h" 52 #include "llvm/IR/Intrinsics.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/Module.h" 55 #include "llvm/IR/ProfileSummary.h" 56 #include "llvm/ProfileData/InstrProfReader.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/ConvertUTF.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Support/MD5.h" 61 #include "llvm/Support/TimeProfiler.h" 63 using namespace clang;
64 using namespace CodeGen;
67 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
68 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"),
69 llvm::cl::init(
false));
88 llvm_unreachable(
"invalid C++ ABI kind");
96 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
97 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
99 VMContext(M.getContext()), Types(*this), VTables(*this),
103 llvm::LLVMContext &LLVMContext = M.getContext();
104 VoidTy = llvm::Type::getVoidTy(LLVMContext);
105 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
106 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
107 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
108 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
109 HalfTy = llvm::Type::getHalfTy(LLVMContext);
110 FloatTy = llvm::Type::getFloatTy(LLVMContext);
111 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
120 IntPtrTy = llvm::IntegerType::get(LLVMContext,
125 M.getDataLayout().getAllocaAddrSpace());
133 createOpenCLRuntime();
135 createOpenMPRuntime();
140 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
141 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
148 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
151 Block.GlobalUniqueCount = 0;
159 if (
auto E = ReaderOrErr.takeError()) {
161 "Could not read profile %0: %1");
162 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
167 PGOReader = std::move(ReaderOrErr.get());
172 if (CodeGenOpts.CoverageMapping)
178 void CodeGenModule::createObjCRuntime() {
195 llvm_unreachable(
"bad runtime kind");
198 void CodeGenModule::createOpenCLRuntime() {
202 void CodeGenModule::createOpenMPRuntime() {
206 case llvm::Triple::nvptx:
207 case llvm::Triple::nvptx64:
209 "OpenMP NVPTX is only prepared to deal with device code.");
213 if (LangOpts.OpenMPSimd)
221 void CodeGenModule::createCUDARuntime() {
226 Replacements[Name] = C;
229 void CodeGenModule::applyReplacements() {
230 for (
auto &I : Replacements) {
231 StringRef MangledName = I.first();
232 llvm::Constant *Replacement = I.second;
236 auto *OldF = cast<llvm::Function>(Entry);
237 auto *NewF = dyn_cast<llvm::Function>(Replacement);
239 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
240 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
242 auto *CE = cast<llvm::ConstantExpr>(Replacement);
243 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
244 CE->getOpcode() == llvm::Instruction::GetElementPtr);
245 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
250 OldF->replaceAllUsesWith(Replacement);
252 NewF->removeFromParent();
253 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
256 OldF->eraseFromParent();
261 GlobalValReplacements.push_back(std::make_pair(GV, C));
264 void CodeGenModule::applyGlobalValReplacements() {
265 for (
auto &I : GlobalValReplacements) {
266 llvm::GlobalValue *GV = I.first;
267 llvm::Constant *C = I.second;
269 GV->replaceAllUsesWith(C);
270 GV->eraseFromParent();
277 const llvm::GlobalIndirectSymbol &GIS) {
278 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
279 const llvm::Constant *C = &GIS;
281 C = C->stripPointerCasts();
282 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
285 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
288 if (!Visited.insert(GIS2).second)
290 C = GIS2->getIndirectSymbol();
294 void CodeGenModule::checkAliases() {
301 const auto *D = cast<ValueDecl>(GD.getDecl());
303 bool IsIFunc = D->hasAttr<IFuncAttr>();
304 if (
const Attr *A = D->getDefiningAttr())
305 Location = A->getLocation();
307 llvm_unreachable(
"Not an alias or ifunc?");
310 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
314 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
315 }
else if (GV->isDeclaration()) {
317 Diags.
Report(Location, diag::err_alias_to_undefined)
318 << IsIFunc << IsIFunc;
319 }
else if (IsIFunc) {
321 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
322 GV->getType()->getPointerElementType());
324 if (!FTy->getReturnType()->isPointerTy())
325 Diags.
Report(Location, diag::err_ifunc_resolver_return);
328 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
329 llvm::GlobalValue *AliaseeGV;
330 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
331 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
333 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
335 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
336 StringRef AliasSection = SA->getName();
337 if (AliasSection != AliaseeGV->getSection())
338 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
339 << AliasSection << IsIFunc << IsIFunc;
347 if (
auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
348 if (GA->isInterposable()) {
349 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
350 << GV->getName() << GA->getName() << IsIFunc;
351 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
352 GA->getIndirectSymbol(), Alias->getType());
353 Alias->setIndirectSymbol(Aliasee);
363 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
364 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
365 Alias->eraseFromParent();
370 DeferredDeclsToEmit.clear();
372 OpenMPRuntime->clear();
376 StringRef MainFile) {
377 if (!hasDiagnostics())
379 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
380 if (MainFile.empty())
381 MainFile =
"<stdin>";
382 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
385 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
388 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
394 EmitVTablesOpportunistically();
395 applyGlobalValReplacements();
398 emitMultiVersionFunctions();
399 EmitCXXGlobalInitFunc();
400 EmitCXXGlobalDtorFunc();
401 registerGlobalDtorsWithAtExit();
402 EmitCXXThreadLocalInitFunc();
404 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
405 AddGlobalCtor(ObjCInitFunction);
408 if (llvm::Function *CudaCtorFunction =
409 CUDARuntime->makeModuleCtorFunction())
410 AddGlobalCtor(CudaCtorFunction);
413 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
414 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
415 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
417 if (llvm::Function *OpenMPRegistrationFunction =
418 OpenMPRuntime->emitRegistrationFunction()) {
419 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
420 OpenMPRegistrationFunction :
nullptr;
421 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
423 OpenMPRuntime->clear();
427 PGOReader->getSummary(
false).getMD(VMContext),
428 llvm::ProfileSummary::PSK_Instr);
432 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
433 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
435 EmitStaticExternCAliases();
438 CoverageMapping->emit();
439 if (CodeGenOpts.SanitizeCfiCrossDso) {
443 emitAtAvailableLinkGuard();
448 if (CodeGenOpts.Autolink &&
449 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
450 EmitModuleLinkOptions();
465 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
466 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
467 for (
auto *MD : ELFDependentLibraries)
474 CodeGenOpts.NumRegisterParameters);
476 if (CodeGenOpts.DwarfVersion) {
480 CodeGenOpts.DwarfVersion);
482 if (CodeGenOpts.EmitCodeView) {
486 if (CodeGenOpts.CodeViewGHash) {
489 if (CodeGenOpts.ControlFlowGuard) {
493 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
500 llvm::Metadata *Ops[2] = {
501 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
502 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
503 llvm::Type::getInt32Ty(VMContext), 1))};
505 getModule().addModuleFlag(llvm::Module::Require,
506 "StrictVTablePointersRequirement",
507 llvm::MDNode::get(VMContext, Ops));
514 llvm::DEBUG_METADATA_VERSION);
519 uint64_t WCharWidth =
524 if ( Arch == llvm::Triple::arm
525 || Arch == llvm::Triple::armeb
526 || Arch == llvm::Triple::thumb
527 || Arch == llvm::Triple::thumbeb) {
529 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
533 if (CodeGenOpts.SanitizeCfiCrossDso) {
535 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
538 if (CodeGenOpts.CFProtectionReturn &&
541 getModule().addModuleFlag(llvm::Module::Override,
"cf-protection-return",
545 if (CodeGenOpts.CFProtectionBranch &&
548 getModule().addModuleFlag(llvm::Module::Override,
"cf-protection-branch",
552 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
556 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
557 CodeGenOpts.FlushDenorm ? 1 : 0);
561 if (LangOpts.OpenCL) {
562 EmitOpenCLMetadata();
568 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
569 llvm::Metadata *SPIRVerElts[] = {
570 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
572 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
573 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
574 llvm::NamedMDNode *SPIRVerMD =
575 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
576 llvm::LLVMContext &Ctx = TheModule.getContext();
577 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
581 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
582 assert(PLevel < 3 &&
"Invalid PIC Level");
583 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
585 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
590 .Case(
"tiny", llvm::CodeModel::Tiny)
591 .Case(
"small", llvm::CodeModel::Small)
592 .Case(
"kernel", llvm::CodeModel::Kernel)
593 .Case(
"medium", llvm::CodeModel::Medium)
594 .Case(
"large", llvm::CodeModel::Large)
597 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
602 if (CodeGenOpts.NoPLT)
605 SimplifyPersonality();
614 DebugInfo->finalize();
617 EmitVersionIdentMetadata();
620 EmitCommandLineMetadata();
622 EmitTargetMetadata();
625 void CodeGenModule::EmitOpenCLMetadata() {
630 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
631 llvm::Metadata *OCLVerElts[] = {
632 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
634 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
635 Int32Ty, (Version % 100) / 10))};
636 llvm::NamedMDNode *OCLVerMD =
637 TheModule.getOrInsertNamedMetadata(
"opencl.ocl.version");
638 llvm::LLVMContext &Ctx = TheModule.getContext();
639 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
655 return TBAA->getTypeInfo(QTy);
661 return TBAA->getAccessInfo(AccessType);
668 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
674 return TBAA->getTBAAStructInfo(QTy);
680 return TBAA->getBaseTypeInfo(QTy);
686 return TBAA->getAccessTagInfo(Info);
693 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
701 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
709 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
715 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
720 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
733 "cannot compile this %0 yet");
734 std::string Msg =
Type;
743 "cannot compile this %0 yet");
744 std::string Msg =
Type;
754 if (GV->hasDLLImportStorageClass())
757 if (GV->hasLocalLinkage()) {
767 !GV->isDeclarationForLinker())
772 llvm::GlobalValue *GV) {
773 if (GV->hasLocalLinkage())
776 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
780 if (GV->hasDLLImportStorageClass())
783 const llvm::Triple &TT = CGM.
getTriple();
784 if (TT.isWindowsGNUEnvironment()) {
788 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
789 !GV->isThreadLocal())
796 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
804 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
808 if (!TT.isOSBinFormatELF())
815 if (RM != llvm::Reloc::Static && !LOpts.PIE && !LOpts.OpenMPIsDevice)
819 if (!GV->isDeclarationForLinker())
825 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
829 llvm::Triple::ArchType Arch = TT.getArch();
830 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
831 Arch == llvm::Triple::ppc64le)
835 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
836 if (!Var->isThreadLocal() &&
837 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
843 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
858 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
868 if (D->
hasAttr<DLLImportAttr>())
869 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
870 else if (D->
hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
871 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
895 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
896 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
897 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
898 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
899 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
906 return llvm::GlobalVariable::GeneralDynamicTLSModel;
908 return llvm::GlobalVariable::LocalDynamicTLSModel;
910 return llvm::GlobalVariable::InitialExecTLSModel;
912 return llvm::GlobalVariable::LocalExecTLSModel;
914 llvm_unreachable(
"Invalid TLS model!");
918 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
920 llvm::GlobalValue::ThreadLocalMode TLM;
924 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
928 GV->setThreadLocalMode(TLM);
938 const CPUSpecificAttr *
Attr,
950 const TargetAttr *
Attr, raw_ostream &Out) {
951 if (Attr->isDefaultVersion())
956 TargetAttr::ParsedTargetAttr Info =
957 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
960 assert(LHS.startswith(
"+") && RHS.startswith(
"+") &&
961 "Features should always have a prefix.");
968 if (!Info.Architecture.empty()) {
970 Out <<
"arch_" << Info.Architecture;
973 for (StringRef Feat : Info.Features) {
977 Out << Feat.substr(1);
983 bool OmitMultiVersionMangling =
false) {
985 llvm::raw_svector_ostream Out(Buffer);
988 llvm::raw_svector_ostream Out(Buffer);
989 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
991 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
997 assert(II &&
"Attempt to mangle unnamed decl.");
1002 llvm::raw_svector_ostream Out(Buffer);
1003 Out <<
"__regcall3__" << II->
getName();
1009 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
1010 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1011 switch (FD->getMultiVersionKind()) {
1015 FD->getAttr<CPUSpecificAttr>(),
1022 llvm_unreachable(
"None multiversion type isn't valid here");
1029 void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
1037 std::string NonTargetName =
1045 "Other GD should now be a multiversioned function");
1055 if (OtherName != NonTargetName) {
1058 const auto ExistingRecord = Manglings.find(NonTargetName);
1059 if (ExistingRecord != std::end(Manglings))
1060 Manglings.remove(&(*ExistingRecord));
1061 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1064 Entry->setName(OtherName);
1074 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
1083 auto FoundName = MangledDeclNames.find(CanonicalGD);
1084 if (FoundName != MangledDeclNames.end())
1085 return FoundName->second;
1088 const auto *ND = cast<NamedDecl>(GD.
getDecl());
1093 if (
auto *FD = dyn_cast<FunctionDecl>(GD.
getDecl()))
1097 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1098 return MangledDeclNames[CanonicalGD] = Result.first->first();
1107 llvm::raw_svector_ostream Out(Buffer);
1110 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
1111 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1113 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1116 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
1118 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1119 return Result.first->first();
1128 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
1129 llvm::Constant *AssociatedData) {
1131 GlobalCtors.push_back(
Structor(Priority, Ctor, AssociatedData));
1136 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
1137 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1138 DtorsUsingAtExit[Priority].push_back(Dtor);
1143 GlobalDtors.push_back(
Structor(Priority, Dtor,
nullptr));
1146 void CodeGenModule::EmitCtorList(
CtorList &Fns,
const char *GlobalName) {
1147 if (Fns.empty())
return;
1150 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
1151 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1152 TheModule.getDataLayout().getProgramAddressSpace());
1155 llvm::StructType *CtorStructTy = llvm::StructType::get(
1160 auto ctors = builder.
beginArray(CtorStructTy);
1161 for (
const auto &I : Fns) {
1162 auto ctor = ctors.beginStruct(CtorStructTy);
1163 ctor.addInt(
Int32Ty, I.Priority);
1164 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1165 if (I.AssociatedData)
1166 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData,
VoidPtrTy));
1169 ctor.finishAndAddTo(ctors);
1175 llvm::GlobalValue::AppendingLinkage);
1179 list->setAlignment(0);
1184 llvm::GlobalValue::LinkageTypes
1186 const auto *D = cast<FunctionDecl>(GD.
getDecl());
1190 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1193 if (isa<CXXConstructorDecl>(D) &&
1194 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1206 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1207 if (!MDS)
return nullptr;
1209 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
1214 llvm::Function *F) {
1216 llvm::AttributeList PAL;
1218 F->setAttributes(PAL);
1219 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1223 std::string ReadOnlyQual(
"__read_only");
1224 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1225 if (ReadOnlyPos != std::string::npos)
1227 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1229 std::string WriteOnlyQual(
"__write_only");
1230 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1231 if (WriteOnlyPos != std::string::npos)
1232 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1234 std::string ReadWriteQual(
"__read_write");
1235 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1236 if (ReadWritePos != std::string::npos)
1237 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1262 assert(((FD && CGF) || (!FD && !CGF)) &&
1263 "Incorrect use - FD and CGF should either be both null or not!");
1292 std::string typeQuals;
1298 addressQuals.push_back(
1299 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
1303 std::string typeName =
1307 std::string::size_type pos = typeName.find(
"unsigned");
1308 if (pointeeTy.
isCanonical() && pos != std::string::npos)
1309 typeName.erase(pos + 1, 8);
1311 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1313 std::string baseTypeName =
1319 pos = baseTypeName.find(
"unsigned");
1320 if (pos != std::string::npos)
1321 baseTypeName.erase(pos + 1, 8);
1323 argBaseTypeNames.push_back(
1324 llvm::MDString::get(VMContext, baseTypeName));
1328 typeQuals =
"restrict";
1331 typeQuals += typeQuals.empty() ?
"const" :
" const";
1333 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
1335 uint32_t AddrSpc = 0;
1340 addressQuals.push_back(
1341 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
1344 std::string typeName;
1349 .getAsString(Policy);
1354 std::string::size_type pos = typeName.find(
"unsigned");
1356 typeName.erase(pos + 1, 8);
1358 std::string baseTypeName;
1364 .getAsString(Policy);
1378 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1381 pos = baseTypeName.find(
"unsigned");
1382 if (pos != std::string::npos)
1383 baseTypeName.erase(pos + 1, 8);
1385 argBaseTypeNames.push_back(
1386 llvm::MDString::get(VMContext, baseTypeName));
1392 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1396 const Decl *PDecl = parm;
1397 if (
auto *TD = dyn_cast<TypedefType>(ty))
1398 PDecl = TD->getDecl();
1399 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
1400 if (A && A->isWriteOnly())
1401 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
1402 else if (A && A->isReadWrite())
1403 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
1405 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
1407 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
1410 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
1413 Fn->setMetadata(
"kernel_arg_addr_space",
1414 llvm::MDNode::get(VMContext, addressQuals));
1415 Fn->setMetadata(
"kernel_arg_access_qual",
1416 llvm::MDNode::get(VMContext, accessQuals));
1417 Fn->setMetadata(
"kernel_arg_type",
1418 llvm::MDNode::get(VMContext, argTypeNames));
1419 Fn->setMetadata(
"kernel_arg_base_type",
1420 llvm::MDNode::get(VMContext, argBaseTypeNames));
1421 Fn->setMetadata(
"kernel_arg_type_qual",
1422 llvm::MDNode::get(VMContext, argTypeQuals));
1424 Fn->setMetadata(
"kernel_arg_name",
1425 llvm::MDNode::get(VMContext, argNames));
1435 if (!LangOpts.Exceptions)
return false;
1438 if (LangOpts.CXXExceptions)
return true;
1441 if (LangOpts.ObjCExceptions) {
1458 !isa<CXXDestructorDecl>(MD);
1461 std::vector<const CXXRecordDecl *>
1463 llvm::SetVector<const CXXRecordDecl *> MostBases;
1465 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1468 MostBases.insert(RD);
1470 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1472 CollectMostBases(RD);
1473 return MostBases.takeVector();
1477 llvm::Function *F) {
1478 llvm::AttrBuilder B;
1480 if (CodeGenOpts.UnwindTables)
1481 B.addAttribute(llvm::Attribute::UWTable);
1484 B.addAttribute(llvm::Attribute::NoUnwind);
1486 if (!D || !D->
hasAttr<NoStackProtectorAttr>()) {
1488 B.addAttribute(llvm::Attribute::StackProtect);
1490 B.addAttribute(llvm::Attribute::StackProtectStrong);
1492 B.addAttribute(llvm::Attribute::StackProtectReq);
1499 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1501 B.addAttribute(llvm::Attribute::NoInline);
1503 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1509 bool ShouldAddOptNone =
1510 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1512 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
1513 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1514 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
1516 if (ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) {
1517 B.addAttribute(llvm::Attribute::OptimizeNone);
1520 B.addAttribute(llvm::Attribute::NoInline);
1521 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1522 "OptimizeNone and AlwaysInline on same function!");
1527 B.addAttribute(llvm::Attribute::Naked);
1530 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1531 F->removeFnAttr(llvm::Attribute::MinSize);
1532 }
else if (D->
hasAttr<NakedAttr>()) {
1534 B.addAttribute(llvm::Attribute::Naked);
1535 B.addAttribute(llvm::Attribute::NoInline);
1536 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
1537 B.addAttribute(llvm::Attribute::NoDuplicate);
1538 }
else if (D->
hasAttr<NoInlineAttr>()) {
1539 B.addAttribute(llvm::Attribute::NoInline);
1540 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
1541 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1543 B.addAttribute(llvm::Attribute::AlwaysInline);
1547 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1548 B.addAttribute(llvm::Attribute::NoInline);
1552 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
1555 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
1556 return Redecl->isInlineSpecified();
1558 if (any_of(FD->
redecls(), CheckRedeclForInline))
1563 return any_of(Pattern->
redecls(), CheckRedeclForInline);
1565 if (CheckForInline(FD)) {
1566 B.addAttribute(llvm::Attribute::InlineHint);
1567 }
else if (CodeGenOpts.getInlining() ==
1570 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1571 B.addAttribute(llvm::Attribute::NoInline);
1578 if (!D->
hasAttr<OptimizeNoneAttr>()) {
1580 if (!ShouldAddOptNone)
1581 B.addAttribute(llvm::Attribute::OptimizeForSize);
1582 B.addAttribute(llvm::Attribute::Cold);
1585 if (D->
hasAttr<MinSizeAttr>())
1586 B.addAttribute(llvm::Attribute::MinSize);
1589 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1593 F->setAlignment(alignment);
1595 if (!D->
hasAttr<AlignedAttr>())
1596 if (LangOpts.FunctionAlignment)
1597 F->setAlignment(1 << LangOpts.FunctionAlignment);
1604 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1609 if (CodeGenOpts.SanitizeCfiCrossDso)
1610 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1619 llvm::Metadata *
Id =
1622 F->addTypeMetadata(0, Id);
1629 if (dyn_cast_or_null<NamedDecl>(D))
1634 if (D && D->
hasAttr<UsedAttr>())
1637 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1638 const auto *VD = cast<VarDecl>(D);
1639 if (VD->getType().isConstQualified() &&
1645 bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
1646 llvm::AttrBuilder &Attrs) {
1651 std::vector<std::string> Features;
1652 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
1654 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
1655 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() :
nullptr;
1656 bool AddedAttr =
false;
1658 llvm::StringMap<bool> FeatureMap;
1662 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1663 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
1670 TargetAttr::ParsedTargetAttr
ParsedAttr = TD->parse();
1671 if (ParsedAttr.Architecture !=
"" &&
1672 getTarget().isValidCPUName(ParsedAttr.Architecture))
1673 TargetCPU = ParsedAttr.Architecture;
1681 if (TargetCPU !=
"") {
1682 Attrs.addAttribute(
"target-cpu", TargetCPU);
1685 if (!Features.empty()) {
1686 llvm::sort(Features);
1687 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
1694 void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
1695 llvm::GlobalObject *GO) {
1700 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1701 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
1702 GV->addAttribute(
"bss-section", SA->getName());
1703 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
1704 GV->addAttribute(
"data-section", SA->getName());
1705 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
1706 GV->addAttribute(
"rodata-section", SA->getName());
1709 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
1710 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
1711 if (!D->
getAttr<SectionAttr>())
1712 F->addFnAttr(
"implicit-section-name", SA->getName());
1714 llvm::AttrBuilder Attrs;
1715 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
1719 F->removeFnAttr(
"target-cpu");
1720 F->removeFnAttr(
"target-features");
1721 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1725 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
1726 GO->setSection(CSA->getName());
1727 else if (
const auto *SA = D->
getAttr<SectionAttr>())
1728 GO->setSection(SA->getName());
1743 setNonAliasAttributes(GD, F);
1754 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1758 llvm::Function *F) {
1760 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
1765 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1769 if (CodeGenOpts.SanitizeCfiCrossDso) {
1777 F->addTypeMetadata(0, MD);
1781 if (CodeGenOpts.SanitizeCfiCrossDso)
1783 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1786 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1787 bool IsIncompleteFunction,
1793 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1797 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1799 if (!IsIncompleteFunction)
1805 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1807 assert(!F->arg_empty() &&
1808 F->arg_begin()->getType()
1809 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1810 "unexpected this return");
1811 F->addAttribute(1, llvm::Attribute::Returned);
1821 if (!IsIncompleteFunction && F->isDeclaration())
1824 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
1825 F->setSection(CSA->getName());
1826 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
1827 F->setSection(SA->getName());
1832 F->addAttribute(llvm::AttributeList::FunctionIndex,
1833 llvm::Attribute::NoBuiltin);
1840 (
Kind == OO_New ||
Kind == OO_Array_New))
1841 F->addAttribute(llvm::AttributeList::ReturnIndex,
1842 llvm::Attribute::NoAlias);
1845 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1846 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1847 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1848 if (MD->isVirtual())
1849 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1853 if (!CodeGenOpts.SanitizeCfiCrossDso)
1859 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
1863 llvm::LLVMContext &Ctx = F->getContext();
1864 llvm::MDBuilder MDB(Ctx);
1868 int CalleeIdx = *CB->encoding_begin();
1869 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
1870 F->addMetadata(llvm::LLVMContext::MD_callback,
1871 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1872 CalleeIdx, PayloadIndices,
1878 assert(!GV->isDeclaration() &&
1879 "Only globals with definition can force usage.");
1880 LLVMUsed.emplace_back(GV);
1884 assert(!GV->isDeclaration() &&
1885 "Only globals with definition can force usage.");
1886 LLVMCompilerUsed.emplace_back(GV);
1890 std::vector<llvm::WeakTrackingVH> &List) {
1897 UsedArray.resize(List.size());
1898 for (
unsigned i = 0, e = List.size();
i != e; ++
i) {
1900 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1901 cast<llvm::Constant>(&*List[
i]), CGM.
Int8PtrTy);
1904 if (UsedArray.empty())
1906 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1908 auto *GV =
new llvm::GlobalVariable(
1909 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1910 llvm::ConstantArray::get(ATy, UsedArray), Name);
1912 GV->setSection(
"llvm.metadata");
1915 void CodeGenModule::emitLLVMUsed() {
1916 emitUsed(*
this,
"llvm.used", LLVMUsed);
1917 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1922 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1929 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1935 ELFDependentLibraries.push_back(
1936 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
1943 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
1950 llvm::SmallPtrSet<Module *, 16> &Visited) {
1952 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1957 for (
unsigned I = Mod->
Imports.size(); I > 0; --I) {
1958 if (Visited.insert(Mod->
Imports[I - 1]).second)
1976 llvm::Metadata *Args[2] = {
1977 llvm::MDString::get(Context,
"-framework"),
1978 llvm::MDString::get(Context, Mod->
LinkLibraries[I - 1].Library)};
1980 Metadata.push_back(llvm::MDNode::get(Context, Args));
1986 llvm::Metadata *Args[2] = {
1987 llvm::MDString::get(Context,
"lib"),
1988 llvm::MDString::get(Context, Mod->
LinkLibraries[I - 1].Library),
1990 Metadata.push_back(llvm::MDNode::get(Context, Args));
1995 auto *OptString = llvm::MDString::get(Context, Opt);
1996 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2001 void CodeGenModule::EmitModuleLinkOptions() {
2005 llvm::SetVector<clang::Module *> LinkModules;
2006 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2010 for (
Module *M : ImportedModules) {
2016 if (Visited.insert(M).second)
2022 while (!Stack.empty()) {
2025 bool AnyChildren =
false;
2034 if (Visited.insert(
SM).second) {
2035 Stack.push_back(
SM);
2043 LinkModules.insert(Mod);
2052 for (
Module *M : LinkModules)
2053 if (Visited.insert(M).second)
2055 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2056 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2059 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
2060 for (
auto *MD : LinkerOptionsMetadata)
2061 NMD->addOperand(MD);
2064 void CodeGenModule::EmitDeferred() {
2073 if (!DeferredVTables.empty()) {
2074 EmitDeferredVTables();
2079 assert(DeferredVTables.empty());
2083 if (DeferredDeclsToEmit.empty())
2088 std::vector<GlobalDecl> CurDeclsToEmit;
2089 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2096 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2114 if (!GV->isDeclaration())
2118 EmitGlobalDefinition(D, GV);
2123 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2125 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2130 void CodeGenModule::EmitVTablesOpportunistically() {
2136 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2137 &&
"Only emit opportunistic vtables with optimizations");
2141 "This queue should only contain external vtables");
2142 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
2145 OpportunisticVTables.clear();
2149 if (Annotations.empty())
2153 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2154 Annotations[0]->getType(), Annotations.size()), Annotations);
2155 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
2156 llvm::GlobalValue::AppendingLinkage,
2157 Array,
"llvm.global.annotations");
2158 gv->setSection(AnnotationSection);
2162 llvm::Constant *&AStr = AnnotationStrings[Str];
2167 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
2169 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
2170 llvm::GlobalValue::PrivateLinkage, s,
".str");
2171 gv->setSection(AnnotationSection);
2172 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2190 return llvm::ConstantInt::get(
Int32Ty, LineNo);
2194 const AnnotateAttr *AA,
2202 llvm::Constant *Fields[4] = {
2203 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
2204 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
2205 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
2208 return llvm::ConstantStruct::getAnon(Fields);
2212 llvm::GlobalValue *GV) {
2213 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2224 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
2233 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
2244 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2245 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2246 SanitizerKind::MemTag);
2247 if (!EnabledAsanMask)
2250 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(),
Category))
2252 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
2258 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
2259 Ty = AT->getElementType();
2264 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2275 auto Attr = ImbueAttr::NONE;
2277 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2278 if (
Attr == ImbueAttr::NONE)
2279 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2281 case ImbueAttr::NONE:
2283 case ImbueAttr::ALWAYS:
2284 Fn->addFnAttr(
"function-instrument",
"xray-always");
2286 case ImbueAttr::ALWAYS_ARG1:
2287 Fn->addFnAttr(
"function-instrument",
"xray-always");
2288 Fn->addFnAttr(
"xray-log-args",
"1");
2290 case ImbueAttr::NEVER:
2291 Fn->addFnAttr(
"function-instrument",
"xray-never");
2297 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
2299 if (LangOpts.EmitAllDecls)
2302 if (CodeGenOpts.KeepStaticConsts) {
2303 const auto *VD = dyn_cast<
VarDecl>(Global);
2304 if (VD && VD->getType().isConstQualified() &&
2312 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
2313 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
2318 if (
const auto *VD = dyn_cast<VarDecl>(Global))
2326 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2329 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2340 std::string Name =
"_GUID_" + Uuid.lower();
2341 std::replace(Name.begin(), Name.end(),
'-',
'_');
2347 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
2350 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2351 assert(Init &&
"failed to initialize as constant");
2353 auto *GV =
new llvm::GlobalVariable(
2355 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2357 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2363 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
2364 assert(AA &&
"No alias?");
2373 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2377 llvm::Constant *Aliasee;
2378 if (isa<llvm::FunctionType>(DeclTy))
2379 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2383 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2384 llvm::PointerType::getUnqual(DeclTy),
2387 auto *F = cast<llvm::GlobalValue>(Aliasee);
2388 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2389 WeakRefReferences.insert(F);
2395 const auto *Global = cast<ValueDecl>(GD.
getDecl());
2398 if (Global->
hasAttr<WeakRefAttr>())
2403 if (Global->
hasAttr<AliasAttr>())
2404 return EmitAliasDefinition(GD);
2407 if (Global->
hasAttr<IFuncAttr>())
2408 return emitIFuncDefinition(GD);
2411 if (Global->
hasAttr<CPUDispatchAttr>())
2412 return emitCPUDispatchDefinition(GD);
2415 if (LangOpts.CUDA) {
2416 if (LangOpts.CUDAIsDevice) {
2417 if (!Global->
hasAttr<CUDADeviceAttr>() &&
2418 !Global->
hasAttr<CUDAGlobalAttr>() &&
2419 !Global->
hasAttr<CUDAConstantAttr>() &&
2420 !Global->
hasAttr<CUDASharedAttr>() &&
2421 !(LangOpts.HIP && Global->
hasAttr<HIPPinnedShadowAttr>()))
2430 if (isa<FunctionDecl>(Global) && !Global->
hasAttr<CUDAHostAttr>() &&
2431 Global->
hasAttr<CUDADeviceAttr>())
2434 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2435 "Expected Variable or Function");
2439 if (LangOpts.OpenMP) {
2442 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2444 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2445 if (MustBeEmitted(Global))
2448 }
else if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2449 if (MustBeEmitted(Global))
2456 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2468 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
2473 const auto *VD = cast<VarDecl>(Global);
2474 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
2477 if (LangOpts.OpenMP) {
2480 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2481 bool UnifiedMemoryEnabled =
2483 if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2484 !UnifiedMemoryEnabled) {
2487 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2488 (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2489 UnifiedMemoryEnabled)) &&
2490 "Link clause or to clause with unified memory expected.");
2509 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2511 EmitGlobalDefinition(GD);
2518 cast<VarDecl>(Global)->hasInit()) {
2519 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2520 CXXGlobalInits.push_back(
nullptr);
2526 addDeferredDeclToEmit(GD);
2527 }
else if (MustBeEmitted(Global)) {
2529 assert(!MayBeEmittedEagerly(Global));
2530 addDeferredDeclToEmit(GD);
2535 DeferredDecls[MangledName] = GD;
2542 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2543 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2550 struct FunctionIsDirectlyRecursive
2552 const StringRef Name;
2557 bool VisitCallExpr(
const CallExpr *E) {
2562 if (Attr && Name == Attr->getLabel())
2567 StringRef BuiltinName = BI.
getName(BuiltinID);
2568 if (BuiltinName.startswith(
"__builtin_") &&
2569 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
2575 bool VisitStmt(
const Stmt *S) {
2577 if (Child && this->Visit(Child))
2584 struct DLLImportFunctionVisitor
2586 bool SafeToInline =
true;
2588 bool shouldVisitImplicitCode()
const {
return true; }
2590 bool VisitVarDecl(
VarDecl *VD) {
2593 SafeToInline =
false;
2594 return SafeToInline;
2601 return SafeToInline;
2606 SafeToInline = D->hasAttr<DLLImportAttr>();
2607 return SafeToInline;
2612 if (isa<FunctionDecl>(VD))
2613 SafeToInline = VD->
hasAttr<DLLImportAttr>();
2614 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
2615 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
2616 return SafeToInline;
2621 return SafeToInline;
2628 SafeToInline =
true;
2630 SafeToInline = M->
hasAttr<DLLImportAttr>();
2632 return SafeToInline;
2637 return SafeToInline;
2642 return SafeToInline;
2651 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
2653 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2658 Name = Attr->getLabel();
2663 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
2665 return Body ? Walker.Visit(Body) :
false;
2668 bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
2671 const auto *F = cast<FunctionDecl>(GD.
getDecl());
2672 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2675 if (F->hasAttr<DLLImportAttr>()) {
2677 DLLImportFunctionVisitor Visitor;
2678 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2679 if (!Visitor.SafeToInline)
2685 for (
const Decl *Member : Dtor->getParent()->decls())
2686 if (isa<FieldDecl>(Member))
2700 return !isTriviallyRecursive(F);
2703 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2704 return CodeGenOpts.OptimizationLevel > 0;
2707 void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
2708 llvm::GlobalValue *GV) {
2709 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2712 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
2713 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
2717 EmitGlobalFunctionDefinition(GD, GV);
2720 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
2721 const auto *D = cast<ValueDecl>(GD.
getDecl());
2725 "Generating code for declaration");
2727 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
2730 if (!shouldEmitFunction(GD))
2733 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
2735 llvm::raw_string_ostream OS(Name);
2741 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2744 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2745 ABI->emitCXXStructor(GD);
2747 EmitMultiVersionFunctionDefinition(GD, GV);
2749 EmitGlobalFunctionDefinition(GD, GV);
2751 if (Method->isVirtual())
2758 return EmitMultiVersionFunctionDefinition(GD, GV);
2759 return EmitGlobalFunctionDefinition(GD, GV);
2762 if (
const auto *VD = dyn_cast<VarDecl>(D))
2763 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2765 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
2769 llvm::Function *NewFn);
2774 unsigned Priority = 0;
2784 void CodeGenModule::emitMultiVersionFunctions() {
2796 EmitGlobalFunctionDefinition(CurGD,
nullptr);
2805 assert(Func &&
"This should have just been created");
2808 const auto *TA = CurFD->
getAttr<TargetAttr>();
2810 TA->getAddedFeatures(Feats);
2812 Options.emplace_back(cast<llvm::Function>(Func),
2813 TA->getArchitecture(), Feats);
2816 llvm::Function *ResolverFunc;
2820 ResolverFunc = cast<llvm::Function>(
2826 ResolverFunc->setComdat(
2827 getModule().getOrInsertComdat(ResolverFunc->getName()));
2835 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2839 void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
2840 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2841 assert(FD &&
"Not a FunctionDecl?");
2842 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
2843 assert(DD &&
"Not a cpu_dispatch Function?");
2846 if (
const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2856 ResolverType = llvm::FunctionType::get(
2857 llvm::PointerType::get(DeclTy,
2861 ResolverType = DeclTy;
2865 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2866 ResolverName, ResolverType, ResolverGD,
false));
2879 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2882 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
2888 Func = GetOrCreateLLVMFunction(
2889 MangledName, DeclTy, ExistingDecl,
2897 llvm::transform(Features, Features.begin(),
2898 [](StringRef Str) {
return Str.substr(1); });
2899 Features.erase(std::remove_if(
2900 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2902 }), Features.end());
2903 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
2918 while (Options.size() > 1 &&
2920 (Options.end() - 2)->Conditions.Features) == 0) {
2921 StringRef LHSName = (Options.end() - 2)->Function->getName();
2922 StringRef RHSName = (Options.end() - 1)->Function->getName();
2923 if (LHSName.compare(RHSName) < 0)
2924 Options.erase(Options.end() - 2);
2926 Options.erase(Options.end() - 1);
2935 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2937 std::string MangledName =
2942 std::string ResolverName = MangledName;
2944 ResolverName +=
".ifunc";
2946 ResolverName +=
".resolver";
2949 if (llvm::GlobalValue *ResolverGV =
GetGlobalValue(ResolverName))
2956 MultiVersionFuncs.push_back(GD);
2959 llvm::Type *ResolverType = llvm::FunctionType::get(
2960 llvm::PointerType::get(
2963 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2964 MangledName +
".resolver", ResolverType,
GlobalDecl{},
2968 GIF->setName(ResolverName);
2974 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2976 assert(isa<llvm::GlobalValue>(Resolver) &&
2977 "Resolver should be created for the first time");
2989 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2991 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
2997 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2999 if (
getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3000 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
3001 !DontDefer && !IsForDefinition) {
3004 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3006 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3015 const auto *TA = FD->
getAttr<TargetAttr>();
3016 if (TA && TA->isDefaultVersion())
3017 UpdateMultiVersionNames(GD, FD);
3018 if (!IsForDefinition)
3019 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3026 if (WeakRefReferences.erase(Entry)) {
3027 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3028 if (FD && !FD->
hasAttr<WeakAttr>())
3033 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>()) {
3034 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3040 if (IsForDefinition && !Entry->isDeclaration()) {
3047 DiagnosedConflictingDefinitions.insert(GD).second) {
3051 diag::note_previous_definition);
3055 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3056 (Entry->getType()->getElementType() == Ty)) {
3063 if (!IsForDefinition)
3064 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3070 bool IsIncompleteFunction =
false;
3072 llvm::FunctionType *FTy;
3073 if (isa<llvm::FunctionType>(Ty)) {
3074 FTy = cast<llvm::FunctionType>(Ty);
3076 FTy = llvm::FunctionType::get(
VoidTy,
false);
3077 IsIncompleteFunction =
true;
3082 Entry ? StringRef() : MangledName, &
getModule());
3099 if (!Entry->use_empty()) {
3101 Entry->removeDeadConstantUsers();
3104 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3105 F, Entry->getType()->getElementType()->getPointerTo());
3109 assert(F->getName() == MangledName &&
"name was uniqued!");
3111 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3112 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3113 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3114 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3121 if (D && isa<CXXDestructorDecl>(D) &&
3122 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3124 addDeferredDeclToEmit(GD);
3129 auto DDI = DeferredDecls.find(MangledName);
3130 if (DDI != DeferredDecls.end()) {
3134 addDeferredDeclToEmit(DDI->second);
3135 DeferredDecls.erase(DDI);
3150 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3163 if (!IsIncompleteFunction) {
3164 assert(F->getType()->getElementType() == Ty);
3168 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3169 return llvm::ConstantExpr::getBitCast(F, PTy);
3182 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
3189 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
3192 DD->getParent()->getNumVBases() == 0)
3197 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3198 false, llvm::AttributeList(),
3208 for (
const auto &Result : DC->
lookup(&CII))
3209 if (
const auto FD = dyn_cast<FunctionDecl>(Result))
3217 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
3221 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
3223 for (
const auto &Result : DC->
lookup(&NS)) {
3225 if (
auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3226 for (
const auto &Result : LSD->lookup(&NS))
3227 if ((ND = dyn_cast<NamespaceDecl>(Result)))
3231 for (
const auto &Result : ND->
lookup(&CXXII))
3232 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
3242 llvm::FunctionCallee
3244 llvm::AttributeList ExtraAttrs,
3247 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
3251 if (
auto *F = dyn_cast<llvm::Function>(C)) {
3260 if (!Local &&
getTriple().isWindowsItaniumEnvironment() &&
3263 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
3264 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3288 return ExcludeCtor && !Record->hasMutableFields() &&
3289 Record->hasTrivialDestructor();
3307 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3308 llvm::PointerType *Ty,
3314 if (WeakRefReferences.erase(Entry)) {
3315 if (D && !D->
hasAttr<WeakAttr>())
3320 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
3321 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3323 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3326 if (Entry->getType() == Ty)
3331 if (IsForDefinition && !Entry->isDeclaration()) {
3339 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
3341 DiagnosedConflictingDefinitions.insert(D).second) {
3345 diag::note_previous_definition);
3350 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3351 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3355 if (!IsForDefinition)
3356 return llvm::ConstantExpr::getBitCast(Entry, Ty);
3362 auto *GV =
new llvm::GlobalVariable(
3363 getModule(), Ty->getElementType(),
false,
3365 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3370 GV->takeName(Entry);
3372 if (!Entry->use_empty()) {
3373 llvm::Constant *NewPtrForOldDecl =
3374 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3375 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3378 Entry->eraseFromParent();
3384 auto DDI = DeferredDecls.find(MangledName);
3385 if (DDI != DeferredDecls.end()) {
3388 addDeferredDeclToEmit(DDI->second);
3389 DeferredDecls.erase(DDI);
3394 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3407 CXXThreadLocals.push_back(D);
3415 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
3416 EmitGlobalVarDefinition(D);
3421 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
3422 GV->setSection(SA->getName());
3426 if (
getTriple().getArch() == llvm::Triple::xcore &&
3430 GV->setSection(
".cp.rodata");
3435 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3438 const auto *Record =
3440 bool HasMutableFields = Record && Record->hasMutableFields();
3441 if (!HasMutableFields) {
3448 auto *InitType = Init->getType();
3449 if (GV->getType()->getElementType() != InitType) {
3454 GV->setName(StringRef());
3457 auto *NewGV = cast<llvm::GlobalVariable>(
3461 GV->eraseFromParent();
3464 GV->setInitializer(Init);
3465 GV->setConstant(
true);
3466 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3478 assert(
getContext().getTargetAddressSpace(ExpectedAS) ==
3479 Ty->getPointerAddressSpace());
3480 if (AddrSpace != ExpectedAS)
3484 if (GV->isDeclaration())
3494 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3496 false, IsForDefinition);
3497 else if (isa<CXXMethodDecl>(D)) {
3499 cast<CXXMethodDecl>(D));
3503 }
else if (isa<FunctionDecl>(D)) {
3515 unsigned Alignment) {
3516 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
3517 llvm::GlobalVariable *OldGV =
nullptr;
3521 if (GV->getType()->getElementType() == Ty)
3526 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
3531 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
3532 Linkage,
nullptr, Name);
3536 GV->takeName(OldGV);
3538 if (!OldGV->use_empty()) {
3539 llvm::Constant *NewPtrForOldDecl =
3540 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3541 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3544 OldGV->eraseFromParent();
3548 !GV->hasAvailableExternallyLinkage())
3549 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3551 GV->setAlignment(Alignment);
3570 llvm::PointerType *PTy =
3571 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
3574 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3584 ? llvm::PointerType::get(
3586 : llvm::PointerType::getUnqual(Ty);
3587 auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy,
nullptr);
3588 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3593 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
3601 if (GV && !GV->isDeclaration())
3606 if (!MustBeEmitted(D) && !GV) {
3607 DeferredDecls[MangledName] = D;
3612 EmitGlobalVarDefinition(D);
3622 if (LangOpts.OpenCL) {
3631 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3632 if (D && D->
hasAttr<CUDAConstantAttr>())
3634 else if (D && D->
hasAttr<CUDASharedAttr>())
3636 else if (D && D->
hasAttr<CUDADeviceAttr>())
3644 if (LangOpts.OpenMP) {
3646 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3654 if (LangOpts.OpenCL)
3656 if (
auto AS =
getTarget().getConstantAddressSpace())
3657 return AS.getValue();
3669 static llvm::Constant *
3671 llvm::GlobalVariable *GV) {
3672 llvm::Constant *Cast = GV;
3678 GV->getValueType()->getPointerTo(
3685 template<
typename SomeDecl>
3687 llvm::GlobalValue *GV) {
3693 if (!D->template hasAttr<UsedAttr>())
3702 const SomeDecl *
First = D->getFirstDecl();
3703 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3709 std::pair<StaticExternCMap::iterator, bool> R =
3710 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3715 R.first->second =
nullptr;
3724 if (D.
hasAttr<CUDAGlobalAttr>())
3727 if (D.
hasAttr<SelectAnyAttr>())
3731 if (
auto *VD = dyn_cast<VarDecl>(&D))
3745 llvm_unreachable(
"No such linkage");
3749 llvm::GlobalObject &GO) {
3752 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3756 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
3766 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3767 OpenMPRuntime->emitTargetGlobalVariable(D))
3770 llvm::Constant *Init =
nullptr;
3772 bool NeedsGlobalCtor =
false;
3783 bool IsCUDASharedVar =
3787 bool IsCUDAShadowVar =
3789 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
3790 D->
hasAttr<CUDASharedAttr>());
3793 bool IsHIPPinnedShadowVar =
3796 (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
3797 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
3798 else if (!InitExpr) {
3812 emitter.emplace(*
this);
3813 Init = emitter->tryEmitForInitializer(*InitDecl);
3822 NeedsGlobalCtor =
true;
3825 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
3832 DelayedCXXInitPosition.erase(D);
3837 llvm::Constant *Entry =
3841 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3842 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3843 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3845 CE->getOpcode() == llvm::Instruction::GetElementPtr);
3846 Entry = CE->getOperand(0);
3850 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3861 if (!GV || GV->getType()->getElementType() != InitType ||
3862 GV->getType()->getAddressSpace() !=
3866 Entry->setName(StringRef());
3869 GV = cast<llvm::GlobalVariable>(
3873 llvm::Constant *NewPtrForOldDecl =
3874 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3875 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3878 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3883 if (D->
hasAttr<AnnotateAttr>())
3887 llvm::GlobalValue::LinkageTypes
Linkage =
3897 if (GV && LangOpts.CUDA) {
3898 if (LangOpts.CUDAIsDevice) {
3900 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>()))
3901 GV->setExternallyInitialized(
true);
3907 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
3908 D->
hasAttr<HIPPinnedShadowAttr>()) {
3916 if (D->
hasAttr<CUDAConstantAttr>())
3922 }
else if (D->
hasAttr<CUDASharedAttr>())
3932 if (!IsHIPPinnedShadowVar)
3933 GV->setInitializer(Init);
3934 if (emitter) emitter->finalize(GV);
3937 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3941 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
3944 GV->setConstant(
true);
3959 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3960 !llvm::GlobalVariable::isWeakLinkage(Linkage))
3963 GV->setLinkage(Linkage);
3964 if (D->
hasAttr<DLLImportAttr>())
3965 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3966 else if (D->
hasAttr<DLLExportAttr>())
3967 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3969 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3971 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3973 GV->setConstant(
false);
3978 if (!GV->getInitializer()->isNullValue())
3979 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3982 setNonAliasAttributes(D, GV);
3984 if (D->
getTLSKind() && !GV->isThreadLocal()) {
3986 CXXThreadLocals.push_back(D);
3993 if (NeedsGlobalCtor || NeedsGlobalDtor)
3994 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3996 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4001 DI->EmitGlobalVariable(GV, D);
4009 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
4020 if (D->
hasAttr<SectionAttr>())
4026 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
4027 D->
hasAttr<PragmaClangDataSectionAttr>() ||
4028 D->
hasAttr<PragmaClangRodataSectionAttr>())
4036 if (D->
hasAttr<WeakImportAttr>())
4046 if (D->
hasAttr<AlignedAttr>())
4055 if (FD->isBitField())
4057 if (FD->
hasAttr<AlignedAttr>())
4085 if (IsConstantVariable)
4086 return llvm::GlobalVariable::WeakODRLinkage;
4088 return llvm::GlobalVariable::WeakAnyLinkage;
4093 return llvm::GlobalVariable::LinkOnceAnyLinkage;
4098 return llvm::GlobalValue::AvailableExternallyLinkage;
4112 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4129 return llvm::Function::WeakODRLinkage;
4134 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4136 CodeGenOpts.NoCommon))
4137 return llvm::GlobalVariable::CommonLinkage;
4143 if (D->
hasAttr<SelectAnyAttr>())
4144 return llvm::GlobalVariable::WeakODRLinkage;
4152 const VarDecl *VD,
bool IsConstant) {
4160 llvm::Function *newFn) {
4162 if (old->use_empty())
return;
4164 llvm::Type *newRetTy = newFn->getReturnType();
4168 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4170 llvm::Value::use_iterator use = ui++;
4171 llvm::User *user = use->getUser();
4175 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4176 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4182 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4183 if (!callSite)
continue;
4184 if (!callSite->isCallee(&*use))
4189 if (callSite->getType() != newRetTy && !callSite->use_empty())
4194 llvm::AttributeList oldAttrs = callSite->getAttributes();
4197 unsigned newNumArgs = newFn->arg_size();
4198 if (callSite->arg_size() < newNumArgs)
4204 bool dontTransform =
false;
4205 for (llvm::Argument &A : newFn->args()) {
4206 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4207 dontTransform =
true;
4212 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4220 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4223 callSite->getOperandBundlesAsDefs(newBundles);
4225 llvm::CallBase *newCall;
4226 if (dyn_cast<llvm::CallInst>(callSite)) {
4230 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4232 oldInvoke->getUnwindDest(), newArgs,
4233 newBundles,
"", callSite);
4237 if (!newCall->getType()->isVoidTy())
4238 newCall->takeName(callSite);
4239 newCall->setAttributes(llvm::AttributeList::get(
4240 newFn->getContext(), oldAttrs.getFnAttributes(),
4241 oldAttrs.getRetAttributes(), newArgAttrs));
4242 newCall->setCallingConv(callSite->getCallingConv());
4245 if (!callSite->use_empty())
4246 callSite->replaceAllUsesWith(newCall);
4249 if (callSite->getDebugLoc())
4250 newCall->setDebugLoc(callSite->getDebugLoc());
4252 callSite->eraseFromParent();
4266 llvm::Function *NewFn) {
4268 if (!isa<llvm::Function>(Old))
return;
4287 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
4288 llvm::GlobalValue *GV) {
4289 const auto *D = cast<FunctionDecl>(GD.
getDecl());
4296 if (!GV || (GV->getType()->getElementType() != Ty))
4302 if (!GV->isDeclaration())
4309 auto *Fn = cast<llvm::Function>(GV);
4322 setNonAliasAttributes(GD, Fn);
4325 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
4326 AddGlobalCtor(Fn, CA->getPriority());
4327 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
4328 AddGlobalDtor(Fn, DA->getPriority());
4329 if (D->
hasAttr<AnnotateAttr>())
4333 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
4334 const auto *D = cast<ValueDecl>(GD.
getDecl());
4335 const AliasAttr *AA = D->
getAttr<AliasAttr>();
4336 assert(AA &&
"Not an alias?");
4340 if (AA->getAliasee() == MangledName) {
4341 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4348 if (Entry && !Entry->isDeclaration())
4351 Aliases.push_back(GD);
4357 llvm::Constant *Aliasee;
4358 llvm::GlobalValue::LinkageTypes
LT;
4359 if (isa<llvm::FunctionType>(DeclTy)) {
4360 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4364 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4365 llvm::PointerType::getUnqual(DeclTy),
4376 if (GA->getAliasee() == Entry) {
4377 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4381 assert(Entry->isDeclaration());
4390 GA->takeName(Entry);
4392 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4394 Entry->eraseFromParent();
4396 GA->setName(MangledName);
4404 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4407 if (
const auto *VD = dyn_cast<VarDecl>(D))
4408 if (VD->getTLSKind())
4414 void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
4415 const auto *D = cast<ValueDecl>(GD.
getDecl());
4416 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
4417 assert(IFA &&
"Not an ifunc?");
4421 if (IFA->getResolver() == MangledName) {
4422 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4428 if (Entry && !Entry->isDeclaration()) {
4431 DiagnosedConflictingDefinitions.insert(GD).second) {
4432 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
4435 diag::note_previous_definition);
4440 Aliases.push_back(GD);
4443 llvm::Constant *Resolver =
4444 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4446 llvm::GlobalIFunc *GIF =
4450 if (GIF->getResolver() == Entry) {
4451 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4454 assert(Entry->isDeclaration());
4463 GIF->takeName(Entry);
4465 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4467 Entry->eraseFromParent();
4469 GIF->setName(MangledName);
4480 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4483 bool &IsUTF16,
unsigned &StringLength) {
4484 StringRef String = Literal->
getString();
4485 unsigned NumBytes = String.size();
4489 StringLength = NumBytes;
4490 return *Map.insert(std::make_pair(String,
nullptr)).first;
4497 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
4498 llvm::UTF16 *ToPtr = &ToBuf[0];
4500 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4501 ToPtr + NumBytes, llvm::strictConversion);
4504 StringLength = ToPtr - &ToBuf[0];
4508 return *Map.insert(std::make_pair(
4509 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4510 (StringLength + 1) * 2),
4516 unsigned StringLength = 0;
4517 bool isUTF16 =
false;
4518 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4523 if (
auto *C = Entry.second)
4526 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
4527 llvm::Constant *Zeros[] = { Zero, Zero };
4530 const llvm::Triple &Triple =
getTriple();
4533 const bool IsSwiftABI =
4534 static_cast<unsigned>(CFRuntime) >=
4539 if (!CFConstantStringClassRef) {
4540 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
4542 Ty = llvm::ArrayType::get(Ty, 0);
4544 switch (CFRuntime) {
4548 CFConstantStringClassName =
4549 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN" 4550 :
"$s10Foundation19_NSCFConstantStringCN";
4554 CFConstantStringClassName =
4555 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN" 4556 :
"$S10Foundation19_NSCFConstantStringCN";
4560 CFConstantStringClassName =
4561 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN" 4562 :
"__T010Foundation19_NSCFConstantStringCN";
4569 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4570 llvm::GlobalValue *GV =
nullptr;
4572 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4578 for (
const auto &Result : DC->
lookup(&II))
4579 if ((VD = dyn_cast<VarDecl>(Result)))
4582 if (Triple.isOSBinFormatELF()) {
4587 if (!VD || !VD->
hasAttr<DLLExportAttr>())
4588 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4590 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4598 CFConstantStringClassRef =
4599 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4600 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4608 auto Fields = Builder.beginStruct(STy);
4611 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4615 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4616 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4618 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4622 llvm::Constant *C =
nullptr;
4624 auto Arr = llvm::makeArrayRef(
4625 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4626 Entry.first().size() / 2);
4627 C = llvm::ConstantDataArray::get(VMContext, Arr);
4629 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4635 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
4636 llvm::GlobalValue::PrivateLinkage, C,
".str");
4637 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4647 if (Triple.isOSBinFormatMachO())
4648 GV->setSection(isUTF16 ?
"__TEXT,__ustring" 4649 :
"__TEXT,__cstring,cstring_literals");
4652 else if (Triple.isOSBinFormatELF())
4653 GV->setSection(
".rodata");
4656 llvm::Constant *Str =
4657 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4661 Str = llvm::ConstantExpr::getBitCast(Str,
Int8PtrTy);
4665 llvm::IntegerType *LengthTy =
4675 Fields.addInt(LengthTy, StringLength);
4680 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
4682 llvm::GlobalVariable::PrivateLinkage);
4683 GV->addAttribute(
"objc_arc_inert");
4684 switch (Triple.getObjectFormat()) {
4685 case llvm::Triple::UnknownObjectFormat:
4686 llvm_unreachable(
"unknown file format");
4687 case llvm::Triple::XCOFF:
4688 llvm_unreachable(
"XCOFF is not yet implemented");
4689 case llvm::Triple::COFF:
4690 case llvm::Triple::ELF:
4691 case llvm::Triple::Wasm:
4692 GV->setSection(
"cfstring");
4694 case llvm::Triple::MachO:
4695 GV->setSection(
"__DATA,__cfstring");
4704 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4708 if (ObjCFastEnumerationStateType.isNull()) {
4720 for (
size_t i = 0;
i < 4; ++
i) {
4725 FieldTypes[
i],
nullptr,
4737 return ObjCFastEnumerationStateType;
4751 Str.resize(CAT->getSize().getZExtValue());
4752 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
4756 llvm::Type *ElemTy = AType->getElementType();
4757 unsigned NumElements = AType->getNumElements();
4760 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4762 Elements.reserve(NumElements);
4766 Elements.resize(NumElements);
4767 return llvm::ConstantDataArray::get(VMContext, Elements);
4770 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4772 Elements.reserve(NumElements);
4776 Elements.resize(NumElements);
4777 return llvm::ConstantDataArray::get(VMContext, Elements);
4780 static llvm::GlobalVariable *
4789 auto *GV =
new llvm::GlobalVariable(
4790 M, C->getType(), !CGM.
getLangOpts().WritableStrings,
LT, C, GlobalName,
4791 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4793 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4794 if (GV->isWeakForLinker()) {
4795 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
4796 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4811 llvm::GlobalVariable **Entry =
nullptr;
4812 if (!LangOpts.WritableStrings) {
4813 Entry = &ConstantStringMap[C];
4814 if (
auto GV = *Entry) {
4823 StringRef GlobalVariableName;
4824 llvm::GlobalValue::LinkageTypes
LT;
4829 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4830 !LangOpts.WritableStrings) {
4831 llvm::raw_svector_ostream Out(MangledNameBuffer);
4833 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4834 GlobalVariableName = MangledNameBuffer;
4836 LT = llvm::GlobalValue::PrivateLinkage;
4837 GlobalVariableName = Name;
4844 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
4865 const std::string &Str,
const char *GlobalName) {
4866 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4871 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
4874 llvm::GlobalVariable **Entry =
nullptr;
4875 if (!LangOpts.WritableStrings) {
4876 Entry = &ConstantStringMap[C];
4877 if (
auto GV = *Entry) {
4878 if (Alignment.getQuantity() > GV->getAlignment())
4879 GV->setAlignment(Alignment.getQuantity());
4887 GlobalName =
".str";
4890 GlobalName, Alignment);
4908 MaterializedType = E->
getType();
4912 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4919 llvm::raw_svector_ostream Out(Name);
4921 VD, E->getManglingNumber(), Out);
4924 if (E->getStorageDuration() ==
SD_Static) {
4938 Value = &EvalResult.
Val;
4944 llvm::Constant *InitialValue =
nullptr;
4945 bool Constant =
false;
4949 emitter.emplace(*
this);
4950 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4953 Type = InitialValue->getType();
4961 llvm::GlobalValue::LinkageTypes
Linkage =
4965 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4969 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4977 auto *GV =
new llvm::GlobalVariable(
4978 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4979 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4980 if (emitter) emitter->finalize(GV);
4984 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4985 if (VD->getTLSKind())
4987 llvm::Constant *CV = GV;
4993 MaterializedGlobalTemporaryMap[E] = CV;
4999 void CodeGenModule::EmitObjCPropertyImplementations(
const 5013 const_cast<ObjCImplementationDecl *>(D), PID);
5017 const_cast<ObjCImplementationDecl *>(D), PID);
5026 if (ivar->getType().isDestructedType())
5096 EmitDeclContext(LSD);
5099 void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
5100 for (
auto *I : DC->
decls()) {
5106 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5107 for (
auto *M : OID->methods())
5122 case Decl::CXXConversion:
5123 case Decl::CXXMethod:
5131 case Decl::CXXDeductionGuide:
5136 case Decl::Decomposition:
5137 case Decl::VarTemplateSpecialization:
5139 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
5140 for (
auto *B : DD->bindings())
5141 if (
auto *HD = B->getHoldingVar())
5147 case Decl::IndirectField:
5151 case Decl::Namespace:
5152 EmitDeclContext(cast<NamespaceDecl>(D));
5154 case Decl::ClassTemplateSpecialization: {
5155 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5158 Spec->hasDefinition())
5159 DebugInfo->completeTemplateDefinition(*Spec);
5161 case Decl::CXXRecord:
5165 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
5168 for (
auto *I : cast<CXXRecordDecl>(D)->decls())
5169 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5173 case Decl::UsingShadow:
5174 case Decl::ClassTemplate:
5175 case Decl::VarTemplate:
5177 case Decl::VarTemplatePartialSpecialization:
5178 case Decl::FunctionTemplate:
5179 case Decl::TypeAliasTemplate:
5186 DI->EmitUsingDecl(cast<UsingDecl>(*D));
5188 case Decl::NamespaceAlias:
5190 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5192 case Decl::UsingDirective:
5194 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5196 case Decl::CXXConstructor:
5199 case Decl::CXXDestructor:
5203 case Decl::StaticAssert:
5210 case Decl::ObjCInterface:
5211 case Decl::ObjCCategory:
5214 case Decl::ObjCProtocol: {
5215 auto *Proto = cast<ObjCProtocolDecl>(D);
5216 if (Proto->isThisDeclarationADefinition())
5221 case Decl::ObjCCategoryImpl:
5224 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5227 case Decl::ObjCImplementation: {
5228 auto *OMD = cast<ObjCImplementationDecl>(D);
5229 EmitObjCPropertyImplementations(OMD);
5230 EmitObjCIvarInitializations(OMD);
5235 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
5236 OMD->getClassInterface()), OMD->getLocation());
5239 case Decl::ObjCMethod: {
5240 auto *OMD = cast<ObjCMethodDecl>(D);
5246 case Decl::ObjCCompatibleAlias:
5247 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5250 case Decl::PragmaComment: {
5251 const auto *PCD = cast<PragmaCommentDecl>(D);
5252 switch (PCD->getCommentKind()) {
5254 llvm_unreachable(
"unexpected pragma comment kind");
5269 case Decl::PragmaDetectMismatch: {
5270 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5275 case Decl::LinkageSpec:
5276 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5279 case Decl::FileScopeAsm: {
5281 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5284 if (LangOpts.OpenMPIsDevice)
5286 auto *AD = cast<FileScopeAsmDecl>(D);
5287 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5291 case Decl::Import: {
5292 auto *Import = cast<ImportDecl>(D);
5295 if (!ImportedModules.insert(Import->getImportedModule()))
5299 if (!Import->getImportedOwningModule()) {
5301 DI->EmitImportDecl(*Import);
5305 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5307 Visited.insert(Import->getImportedModule());
5308 Stack.push_back(Import->getImportedModule());
5310 while (!Stack.empty()) {
5312 if (!EmittedModuleInitializers.insert(Mod).second)
5321 Sub != SubEnd; ++Sub) {
5324 if ((*Sub)->IsExplicit)
5327 if (Visited.insert(*Sub).second)
5328 Stack.push_back(*Sub);
5335 EmitDeclContext(cast<ExportDecl>(D));
5338 case Decl::OMPThreadPrivate:
5342 case Decl::OMPAllocate:
5345 case Decl::OMPDeclareReduction:
5349 case Decl::OMPDeclareMapper:
5353 case Decl::OMPRequires:
5361 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
5368 if (!CodeGenOpts.CoverageMapping)
5371 case Decl::CXXConversion:
5372 case Decl::CXXMethod:
5374 case Decl::ObjCMethod:
5375 case Decl::CXXConstructor:
5376 case Decl::CXXDestructor: {
5377 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5382 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5383 if (I == DeferredEmptyCoverageMappingDecls.end())
5384 DeferredEmptyCoverageMappingDecls[D] =
true;
5394 if (!CodeGenOpts.CoverageMapping)
5396 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5397 if (Fn->isTemplateInstantiation())
5400 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5401 if (I == DeferredEmptyCoverageMappingDecls.end())
5402 DeferredEmptyCoverageMappingDecls[D] =
false;
5412 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5415 const Decl *D = Entry.first;
5417 case Decl::CXXConversion:
5418 case Decl::CXXMethod:
5420 case Decl::ObjCMethod: {
5427 case Decl::CXXConstructor: {
5434 case Decl::CXXDestructor: {
5451 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5452 return llvm::ConstantInt::get(i64, PtrInt);
5456 llvm::NamedMDNode *&GlobalMetadata,
5458 llvm::GlobalValue *Addr) {
5459 if (!GlobalMetadata)
5461 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
5464 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5467 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
5475 void CodeGenModule::EmitStaticExternCAliases() {
5478 for (
auto &I : StaticExternCValues) {
5480 llvm::GlobalValue *Val = I.second;
5488 auto Res = Manglings.find(MangledName);
5489 if (Res == Manglings.end())
5491 Result = Res->getValue();
5502 void CodeGenModule::EmitDeclMetadata() {
5503 llvm::NamedMDNode *GlobalMetadata =
nullptr;
5505 for (
auto &I : MangledDeclNames) {
5506 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
5516 void CodeGenFunction::EmitDeclMetadata() {
5517 if (LocalDeclMap.empty())
return;
5522 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
5524 llvm::NamedMDNode *GlobalMetadata =
nullptr;
5526 for (
auto &I : LocalDeclMap) {
5527 const Decl *D = I.first;
5529 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5531 Alloca->setMetadata(
5532 DeclPtrKind, llvm::MDNode::get(
5533 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5534 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5541 void CodeGenModule::EmitVersionIdentMetadata() {
5542 llvm::NamedMDNode *IdentMetadata =
5543 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
5545 llvm::LLVMContext &Ctx = TheModule.getContext();
5547 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5548 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5551 void CodeGenModule::EmitCommandLineMetadata() {
5552 llvm::NamedMDNode *CommandLineMetadata =
5553 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
5555 llvm::LLVMContext &Ctx = TheModule.getContext();
5557 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5558 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5561 void CodeGenModule::EmitTargetMetadata() {
5568 for (
unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5569 auto Val = *(MangledDeclNames.begin() + I);
5576 void CodeGenModule::EmitCoverageFile() {
5581 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
5585 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
5586 llvm::LLVMContext &Ctx = TheModule.getContext();
5587 auto *CoverageDataFile =
5589 auto *CoverageNotesFile =
5591 for (
int i = 0, e = CUNode->getNumOperands();
i != e; ++
i) {
5592 llvm::MDNode *CU = CUNode->getOperand(
i);
5593 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5594 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5598 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5601 assert(Uuid.size() == 36);
5602 for (
unsigned i = 0;
i < 36; ++
i) {
5603 if (
i == 8 ||
i == 13 ||
i == 18 ||
i == 23) assert(Uuid[
i] ==
'-');
5608 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5610 llvm::Constant *Field3[8];
5611 for (
unsigned Idx = 0; Idx < 8; ++Idx)
5612 Field3[Idx] = llvm::ConstantInt::get(
5613 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5615 llvm::Constant *Fields[4] = {
5616 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
5617 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
5618 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
5619 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
5622 return llvm::ConstantStruct::getAnon(Fields);
5631 return llvm::Constant::getNullValue(
Int8PtrTy);
5634 LangOpts.ObjCRuntime.isGNUFamily())
5642 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5644 for (
auto RefExpr : D->
varlists()) {
5645 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5647 VD->getAnyInitializer() &&
5648 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
5653 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5654 CXXGlobalInits.push_back(InitFunction);
5659 CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
5666 std::string OutName;
5667 llvm::raw_string_ostream Out(OutName);
5681 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
5686 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
5706 for (
auto &Param : FnType->param_types())
5711 GeneralizedParams, FnType->getExtProtoInfo());
5718 llvm_unreachable(
"Encountered unknown FunctionType");
5723 GeneralizedMetadataIdMap,
".generalized");
5730 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5731 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5732 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5733 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5734 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5735 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5736 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5737 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5743 llvm::Metadata *MD =
5745 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
5747 if (CodeGenOpts.SanitizeCfiCrossDso)
5750 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5753 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
5754 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
5759 assert(TD !=
nullptr);
5760 TargetAttr::ParsedTargetAttr
ParsedAttr = TD->parse();
5762 ParsedAttr.Features.erase(
5763 llvm::remove_if(ParsedAttr.Features,
5764 [&](
const std::string &Feat) {
5765 return !Target.isValidFeatureName(
5766 StringRef{Feat}.substr(1));
5777 StringRef TargetCPU =
Target.getTargetOpts().CPU;
5779 if (
const auto *TD = FD->
getAttr<TargetAttr>()) {
5784 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5785 Target.getTargetOpts().FeaturesAsWritten.begin(),
5786 Target.getTargetOpts().FeaturesAsWritten.end());
5788 if (ParsedAttr.Architecture !=
"" &&
5789 Target.isValidCPUName(ParsedAttr.Architecture))
5790 TargetCPU = ParsedAttr.Architecture;
5797 ParsedAttr.Features);
5798 }
else if (
const auto *SD = FD->
getAttr<CPUSpecificAttr>()) {
5800 Target.getCPUSpecificCPUDispatchFeatures(
5802 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5803 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU, Features);
5806 Target.getTargetOpts().Features);
5812 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&
getModule());
5821 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()},
false);
5823 "__translate_sampler_initializer"),
void setLinkage(Linkage L)
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
llvm::PointerType * Int8PtrPtrTy
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
const llvm::DataLayout & getDataLayout() const
virtual bool checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const
Check if the target supports CFProtection branch.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
The generic AArch64 ABI is also a modified version of the Itanium ABI, but it has fewer divergences t...
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
FunctionDecl * getDefinition()
Get the definition for this declaration.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const CXXDestructorDecl * getDestructor() const
Represents a function declaration or definition.
llvm::IntegerType * IntTy
int
void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
Expr * getInit() const
Get the initializer.
External linkage, which indicates that the entity can be referred to from other translation units...
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
std::vector< const CXXRecordDecl * > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
A (possibly-)qualified type.
The iOS 64-bit ABI is follows ARM's published 64-bit ABI more closely, but we don't guarantee to foll...
CodeGenTypes & getTypes()
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
std::vector< Module * >::iterator submodule_iterator
const CodeGenOptions & getCodeGenOpts() const
GlobalDecl getWithDecl(const Decl *D)
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"), llvm::cl::init(false))
unsigned getNumBases() const
Retrieves the number of base classes of this class.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target...
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
llvm::LLVMContext & getLLVMContext()
GlobalDecl getWithMultiVersionIndex(unsigned Index)
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
CXXDtorType getDtorType() const
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
submodule_iterator submodule_begin()
bool containsNonAsciiOrNull() const
The standard implementation of ConstantInitBuilder used in Clang.
Stmt - This represents one statement.
FunctionType - C99 6.7.5.3 - Function Declarators.
SanitizerSet Sanitize
Set of enabled sanitizers.
virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, raw_ostream &)=0
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
Defines the SourceManager interface.
CharUnits getAlignOfGlobalVarInChars(QualType T) const
Return the alignment in characters that should be given to a global variable with type T...
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
bool isRecordType() const
unsigned getTypeAlignIfKnown(QualType T) const
Return the ABI-specified alignment of a type, in bits, or 0 if the type is incomplete and we cannot d...
virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, raw_ostream &)=0
Defines the clang::Module class, which describes a module in the source code.
const Type * getTypeForDecl() const
CoreFoundationABI CFRuntime
Decl - This represents one declaration (or definition), e.g.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
FunctionDecl * getOperatorNew() const
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
Defines the C++ template declaration subclasses.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
GlobalDecl getCanonicalDecl() const
LangAS ASTAllocaAddressSpace
The base class of the type hierarchy.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
const ABIInfo & getABIInfo() const
getABIInfo() - Returns ABI info helper for the target.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
bool isBlacklistedLocation(SanitizerMask Mask, SourceLocation Loc, StringRef Category=StringRef()) const
Represent a C++ namespace.
Represents a call to a C++ constructor.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
virtual void completeDefinition()
Note that the definition of this type is now complete.
const TargetInfo & getTargetInfo() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process...
Interoperability with the latest known version of the Swift runtime.
constexpr XRayInstrMask Function
static const llvm::GlobalObject * getAliasedGlobal(const llvm::GlobalIndirectSymbol &GIS)
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
Linkage getLinkage() const
Determine the linkage of this type.
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
Represents a variable declaration or definition.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const T * getAs() const
Member-template getAs<specific type>'.
Visibility getVisibility() const
CGDebugInfo * getModuleDebugInfo()
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
bool supportsCOMDAT() const
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Class supports emissionof SIMD-only code.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
ObjCMethodDecl - Represents an instance or class method declaration.
DiagnosticsEngine & getDiags() const
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
Describes how types, statements, expressions, and declarations should be printed. ...
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool supportsIFunc() const
Identify whether this target supports IFuncs.
Represents a parameter to a function.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Represents a struct/union/class.
LanguageIDs getLanguage() const
Return the language specified by this linkage specification.
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
unsigned getIntAlign() const
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
llvm::IntegerType * Int64Ty
field_range fields() const
SourceLocation getBeginLoc() const LLVM_READONLY
The generic Mips ABI is a modified version of the Itanium ABI.
Represents a member of a struct/union/class.
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
llvm::IntegerType * SizeTy
void startDefinition()
Starts the definition of this tag declaration.
bool isReferenceType() const
Interoperability with the Swift 4.1 runtime.
SanitizerMask Mask
Bitmask of enabled sanitizers.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
__DEVICE__ int max(int __a, int __b)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
unsigned getCharByteWidth() const
llvm::CallingConv::ID RuntimeCC
std::string CodeModel
The code model to use (-mcmodel).
Describes a module or submodule.
bool shouldMangleDeclName(const NamedDecl *D)
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
static void AppendTargetMangling(const CodeGenModule &CGM, const TargetAttr *Attr, raw_ostream &Out)
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
unsigned getLength() const
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e...
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
FunctionDecl * getOperatorDelete() const
CharUnits - This is an opaque type for sizes expressed in character units.
APValue Val
Val - This is the value the expression can be folded to.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void setDSOLocal(llvm::GlobalValue *GV) const
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
bool hasConstructorVariants() const
Does this ABI have different entrypoints for complete-object and base-subobject constructors?
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type...
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::PointerType * VoidPtrTy
Concrete class used by the front-end to report problems and issues.
const clang::PrintingPolicy & getPrintingPolicy() const
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
CXXCtorType getCtorType() const
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
Module * Parent
The parent of this module.
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Defines the Diagnostic-related interfaces.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality...
submodule_iterator submodule_end()
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Represents binding an expression to a temporary.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
CXXTemporary * getTemporary()
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
CharUnits getPointerAlign() const
void EmitTentativeDefinition(const VarDecl *D)
void addInstanceMethod(ObjCMethodDecl *method)
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
llvm::SanitizerStatReport & getSanStats()
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents an ObjC class declaration.
Represents a linkage specification.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
The iOS ABI is a partial implementation of the ARM ABI.
Interoperability with the Swift 5.0 runtime.
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void mangleName(const NamedDecl *D, raw_ostream &)
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
bool hasProfileClangUse() const
Check if Clang profile use is on.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
llvm::PointerType * getSamplerType(const Type *T)
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
const XRayFunctionFilter & getXRayFilter() const
'watchos' is a variant of iOS for Apple's watchOS.
llvm::StringMap< SectionInfo > SectionInfos
llvm::Type * HalfTy
float, double
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
StringRef getString() const
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
virtual bool checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const
Check if the target supports CFProtection branch.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Represents a prototype with parameter type info, e.g.
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
The generic ARM ABI is a modified version of the Itanium ABI proposed by ARM for use on ARM-based pla...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
void setHasDestructors(bool val)
const TargetCodeGenInfo & getTargetCodeGenInfo()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
Represents a ValueDecl that came out of a declarator.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
llvm::CallingConv::ID getRuntimeCC() const
Exposes information about the current target.
llvm::SmallVector< StringRef, 8 > Features
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode *> &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
This represents one expression.
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isImplicitlyDeclared=false, bool isDefined=false, ImplementationControl impControl=None, bool HasRelatedResultType=false)
Emit only debug info necessary for generating line number tables (-gline-tables-only).
Selector getSetterName() const
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target, in bits.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
unsigned getLine() const
Return the presumed line number of this location.
Organizes the cross-function state that is used while generating code coverage mapping data...
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Represents a C++ destructor within a class.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
Defines version macros and version-related utility functions for Clang.
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
static uint64_t GetX86CpuSupportsMask(ArrayRef< StringRef > FeatureStrs)
Linkage getLinkage() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint32_t getCodeUnit(size_t i) const
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TLSKind getTLSKind() const
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CGOpenMPRuntime(CodeGenModule &CGM)
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
void GenOpenCLArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
llvm::IntegerType * Int32Ty
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
virtual bool validateCpuSupports(StringRef Name) const
clang::ObjCRuntime ObjCRuntime
propimpl_range property_impls() const
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
QualType getEncodedType() const
llvm::PointerType * AllocaInt8PtrTy
bool isExternallyVisible(Linkage L)
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
QualType getRecordType(const RecordDecl *Decl) const
Represents an unpacked "presumed" location which can be presented to the user.
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
virtual void getCPUSpecificCPUDispatchFeatures(StringRef Name, llvm::SmallVectorImpl< StringRef > &Features) const
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
const TargetInfo & getTarget() const
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method...
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, llvm::GlobalValue *GV)
This template specialization was implicitly instantiated from a template.
'gnustep' is the modern non-fragile GNUstep runtime.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
const LangOptions & getLangOpts() const
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
ASTContext & getContext() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
const SanitizerBlacklist & getSanitizerBlacklist() const
GlobalDecl - represents a global declaration.
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue...
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
WatchOS is a modernisation of the iOS ABI, which roughly means it's the iOS64 ABI ported to 32-bits...
bool isConstQualified() const
Determine whether this type is const-qualified.
std::string CPU
If given, the name of the target CPU to generate code for.
The l-value was considered opaque, so the alignment was determined from a type.
const char * getFilename() const
Return the presumed filename of this location.
QualType getWideCharType() const
Return the type of wide characters.
unsigned char IntAlignInBytes
static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD, const NamedDecl *ND, bool OmitMultiVersionMangling=false)
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
SelectorTable & Selectors
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
QualType getCanonicalType() const
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification, prepare to emit an alias for it to the expected name.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Encodes a location in the source.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
LangAS getAddressSpace() const
Return the address space of this type.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D...
'objfw' is the Objective-C runtime included in ObjFW
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Represents the declaration of a struct/union/class/enum.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
Represents a call to a member function that may be written either with member call syntax (e...
ASTContext & getASTContext() const LLVM_READONLY
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
llvm::IntegerType * Int16Ty
const Decl * getDecl() const
virtual void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var, unsigned Flags)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
ParsedAttr - Represents a syntactic attribute.
static void removeImageAccessQualifier(std::string &TyName)
LangAS getStringLiteralAddressSpace() const
Return the AST address space of string literal, which is used to emit the string literal as global va...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD)
Parses the target attributes passed in, and returns only the ones that are valid feature names...
virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF=nullptr)
Emit a code for initialization of threadprivate variable.
Represents a static or instance method of a struct/union/class.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
Weak for now, might become strong later in this TU.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
const ParmVarDecl * getParamDecl(unsigned i) const
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings startin...
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool isObjCObjectPointerType() const
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
Represents one property declaration in an Objective-C interface.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
The generic Itanium ABI is the standard ABI of most open-source and Unix-like platforms.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
MangleContext & getMangleContext()
Gets the mangle context.
This template specialization was instantiated from a template due to an explicit instantiation defini...
CGCXXABI * CreateMicrosoftCXXABI(CodeGenModule &CGM)
Creates a Microsoft-family ABI.
static unsigned TargetMVPriority(const TargetInfo &TI, const CodeGenFunction::MultiVersionResolverOption &RO)
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
llvm::CallingConv::ID getRuntimeCC() const
Return the calling convention to use for system runtime functions.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, GlobalDecl GD)
std::vector< Structor > CtorList
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
static unsigned ArgInfoAddressSpace(LangAS AS)
virtual void mangleTypeName(QualType T, raw_ostream &)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing...
CXXCtorType
C++ constructor types.
The WebAssembly ABI is a modified version of the Itanium ABI.
void addReplacement(StringRef Name, llvm::Constant *C)
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character...
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
StringRef getName() const
Return the actual identifier string.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
ObjCIvarDecl * getNextIvar()
TLS with a dynamic initializer.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
const ObjCInterfaceDecl * getClassInterface() const
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool hasSideEffects() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
virtual char CPUSpecificManglingCharacter(StringRef Name) const
EvalResult is a struct with detailed info about an evaluated expression.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
unsigned char PointerAlignInBytes
bool isVisibilityExplicit() const
The basic abstraction for the target Objective-C runtime.
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
llvm::iterator_range< submodule_iterator > submodules()
std::string SymbolPartition
The name of the partition that symbols are assigned to, specified with -fsymbol-partition (see https:...
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
const Expr * getInit() const
FileID getMainFileID() const
Returns the FileID of the main source file.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
llvm::IntegerType * IntPtrTy
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
void UpdateCompletedType(const TagDecl *TD)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
llvm::Module & getModule() const
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration...
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
unsigned getMultiVersionIndex() const
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual llvm::Optional< LangAS > getConstantAddressSpace() const
Return an AST address space which can be used opportunistically for constant global memory...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
void setHasNonZeroConstructors(bool val)
Represents a C++ base or member initializer.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
CanQualType UnsignedLongTy
Implements C++ ABI-specific code generation functions.
ObjCEncodeExpr, used for @encode in Objective-C.
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable *> &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
virtual unsigned multiVersionSortPriority(StringRef Name) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
virtual void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
emitTargetMD - Provides a convenient hook to handle extra target-specific metadata for the given glob...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
llvm::PointerType * Int8PtrTy
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
virtual uint64_t getMaxPointerWidth() const
Return the maximum width of pointers on this target.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
StringRef getMangledName(GlobalDecl GD)
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create or return a runtime function declaration with the specified type and name. ...
void addDecl(Decl *D)
Add the declaration D into this context.
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
Represents a base class of a C++ class.
static const char AnnotationSection[]
SourceManager & getSourceManager()
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
QualType withCVRQualifiers(unsigned CVR) const
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
StringRef getUuidStr() const
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TranslationUnitDecl * getTranslationUnitDecl() const
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
Interoperability with the Swift 4.2 runtime.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Represents a C++ struct/union/class.
CGCXXABI * CreateItaniumCXXABI(CodeGenModule &CGM)
Creates an Itanium-family ABI.
bool isTLSSupported() const
Whether the target supports thread-local storage.
A specialization of Address that requires the address to be an LLVM Constant.
ObjCIvarDecl - Represents an ObjC instance variable.
static bool HasNonDllImportDtor(QualType T)
void Release()
Finalize LLVM code generation.
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
ASTImporterLookupTable & LT
Builtin::Context & BuiltinInfo
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void EmitGlobalAnnotations()
Emit all the global annotations.
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
uint64_t getPointerAlign(unsigned AddrSpace) const
StringLiteral - This represents a string literal expression, e.g.
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
void finalize(llvm::GlobalVariable *global)
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class...
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< MultiVersionResolverOption > Options)
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
CGCXXABI & getCXXABI() const
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, unsigned Alignment)
Will return a global variable of the given type.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
The top declaration context.
unsigned char SizeSizeInBytes
A reference to a declared variable, function, enum, etc.
NamedDecl * getMostRecentDecl()
GVALinkage
A more specific kind of linkage than enum Linkage.
bool isPointerType() const
struct clang::CodeGen::CodeGenFunction::MultiVersionResolverOption::Conds Conditions
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
CodeGenVTables & getVTables()
This represents a decl that may have a name.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
void setAccess(AccessSpecifier AS)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
bool isConstant(const ASTContext &Ctx) const
unsigned getTargetAddressSpace(QualType T) const
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Selector getGetterName() const
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
const LangOptions & getLangOpts() const
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
FullSourceLoc getFullLoc(SourceLocation Loc) const
This represents '#pragma omp threadprivate ...' directive.
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Represents the canonical version of C arrays with a specified constant size.
This class handles loading and caching of source files into memory.
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
Defines enum values for all the target-independent builtin functions.
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable)
Returns LLVM linkage for a declarator.
Attr - This represents one attribute.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
SourceLocation getLocation() const
bool isExternallyVisible() const
APValue * getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, bool MayCreate)
Get the storage for the constant value of a materialized temporary of static storage duration...
virtual std::string getDeviceStubName(llvm::StringRef Name) const =0
Construct and return the stub name of a kernel.
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const llvm::Triple & getTriple() const