47 #include "llvm/ADT/Triple.h" 48 #include "llvm/Analysis/TargetLibraryInfo.h" 49 #include "llvm/IR/CallSite.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/ProfileData/InstrProfReader.h" 56 #include "llvm/Support/ConvertUTF.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/MD5.h" 60 using namespace clang;
61 using namespace CodeGen;
64 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
65 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"),
66 llvm::cl::init(
false));
85 llvm_unreachable(
"invalid C++ ABI kind");
93 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
96 VMContext(M.getContext()), Types(*this), VTables(*this),
100 llvm::LLVMContext &LLVMContext = M.getContext();
101 VoidTy = llvm::Type::getVoidTy(LLVMContext);
102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106 HalfTy = llvm::Type::getHalfTy(LLVMContext);
107 FloatTy = llvm::Type::getFloatTy(LLVMContext);
108 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
117 IntPtrTy = llvm::IntegerType::get(LLVMContext,
122 M.getDataLayout().getAllocaAddrSpace());
130 createOpenCLRuntime();
132 createOpenMPRuntime();
137 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
138 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
145 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
148 Block.GlobalUniqueCount = 0;
156 if (
auto E = ReaderOrErr.takeError()) {
158 "Could not read profile %0: %1");
159 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
164 PGOReader = std::move(ReaderOrErr.get());
169 if (CodeGenOpts.CoverageMapping)
175 void CodeGenModule::createObjCRuntime() {
192 llvm_unreachable(
"bad runtime kind");
195 void CodeGenModule::createOpenCLRuntime() {
199 void CodeGenModule::createOpenMPRuntime() {
203 case llvm::Triple::nvptx:
204 case llvm::Triple::nvptx64:
206 "OpenMP NVPTX is only prepared to deal with device code.");
210 if (LangOpts.OpenMPSimd)
218 void CodeGenModule::createCUDARuntime() {
223 Replacements[Name] = C;
226 void CodeGenModule::applyReplacements() {
227 for (
auto &I : Replacements) {
228 StringRef MangledName = I.first();
233 auto *OldF = cast<llvm::Function>(Entry);
234 auto *NewF = dyn_cast<llvm::Function>(
Replacement);
236 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
237 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
240 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
241 CE->getOpcode() == llvm::Instruction::GetElementPtr);
242 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
247 OldF->replaceAllUsesWith(Replacement);
249 NewF->removeFromParent();
250 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 OldF->eraseFromParent();
258 GlobalValReplacements.push_back(std::make_pair(GV, C));
261 void CodeGenModule::applyGlobalValReplacements() {
262 for (
auto &I : GlobalValReplacements) {
263 llvm::GlobalValue *GV = I.first;
264 llvm::Constant *C = I.second;
266 GV->replaceAllUsesWith(C);
267 GV->eraseFromParent();
274 const llvm::GlobalIndirectSymbol &GIS) {
275 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
276 const llvm::Constant *C = &GIS;
278 C = C->stripPointerCasts();
279 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
282 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!Visited.insert(GIS2).second)
287 C = GIS2->getIndirectSymbol();
291 void CodeGenModule::checkAliases() {
298 const auto *D = cast<ValueDecl>(GD.getDecl());
300 bool IsIFunc = D->hasAttr<IFuncAttr>();
301 if (
const Attr *A = D->getDefiningAttr())
302 Location = A->getLocation();
304 llvm_unreachable(
"Not an alias or ifunc?");
307 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
311 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
312 }
else if (GV->isDeclaration()) {
314 Diags.
Report(Location, diag::err_alias_to_undefined)
315 << IsIFunc << IsIFunc;
316 }
else if (IsIFunc) {
318 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
319 GV->getType()->getPointerElementType());
321 if (!FTy->getReturnType()->isPointerTy())
322 Diags.
Report(Location, diag::err_ifunc_resolver_return);
323 if (FTy->getNumParams())
324 Diags.
Report(Location, diag::err_ifunc_resolver_params);
327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
328 llvm::GlobalValue *AliaseeGV;
329 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
334 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
336 if (AliasSection != AliaseeGV->getSection())
337 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
338 << AliasSection << IsIFunc << IsIFunc;
346 if (
auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347 if (GA->isInterposable()) {
348 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
369 DeferredDeclsToEmit.clear();
371 OpenMPRuntime->clear();
375 StringRef MainFile) {
376 if (!hasDiagnostics())
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile =
"<stdin>";
381 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
384 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
387 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
393 EmitVTablesOpportunistically();
394 applyGlobalValReplacements();
397 emitMultiVersionFunctions();
398 EmitCXXGlobalInitFunc();
399 EmitCXXGlobalDtorFunc();
400 registerGlobalDtorsWithAtExit();
401 EmitCXXThreadLocalInitFunc();
403 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
404 AddGlobalCtor(ObjCInitFunction);
407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
409 AddGlobalCtor(CudaCtorFunction);
412 if (llvm::Function *OpenMPRegistrationFunction =
413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction :
nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
418 OpenMPRuntime->clear();
421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
425 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
426 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
428 EmitStaticExternCAliases();
431 CoverageMapping->emit();
432 if (CodeGenOpts.SanitizeCfiCrossDso) {
436 emitAtAvailableLinkGuard();
441 if (CodeGenOpts.Autolink &&
442 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
443 EmitModuleLinkOptions();
449 CodeGenOpts.NumRegisterParameters);
451 if (CodeGenOpts.DwarfVersion) {
455 CodeGenOpts.DwarfVersion);
457 if (CodeGenOpts.EmitCodeView) {
461 if (CodeGenOpts.ControlFlowGuard) {
465 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
472 llvm::Metadata *Ops[2] = {
473 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
474 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
475 llvm::Type::getInt32Ty(VMContext), 1))};
477 getModule().addModuleFlag(llvm::Module::Require,
478 "StrictVTablePointersRequirement",
479 llvm::MDNode::get(VMContext, Ops));
486 llvm::DEBUG_METADATA_VERSION);
491 uint64_t WCharWidth =
496 if ( Arch == llvm::Triple::arm
497 || Arch == llvm::Triple::armeb
498 || Arch == llvm::Triple::thumb
499 || Arch == llvm::Triple::thumbeb) {
501 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
505 if (CodeGenOpts.SanitizeCfiCrossDso) {
507 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
510 if (CodeGenOpts.CFProtectionReturn &&
513 getModule().addModuleFlag(llvm::Module::Override,
"cf-protection-return",
517 if (CodeGenOpts.CFProtectionBranch &&
520 getModule().addModuleFlag(llvm::Module::Override,
"cf-protection-branch",
524 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
528 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
529 CodeGenOpts.FlushDenorm ? 1 : 0);
533 if (LangOpts.OpenCL) {
534 EmitOpenCLMetadata();
536 if (
getTriple().getArch() == llvm::Triple::spir ||
537 getTriple().getArch() == llvm::Triple::spir64) {
540 llvm::Metadata *SPIRVerElts[] = {
541 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542 Int32Ty, LangOpts.OpenCLVersion / 100)),
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
545 llvm::NamedMDNode *SPIRVerMD =
546 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
547 llvm::LLVMContext &Ctx = TheModule.getContext();
548 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
552 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
553 assert(PLevel < 3 &&
"Invalid PIC Level");
554 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
556 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
559 if (CodeGenOpts.NoPLT)
562 SimplifyPersonality();
571 DebugInfo->finalize();
574 EmitVersionIdentMetadata();
576 EmitTargetMetadata();
579 void CodeGenModule::EmitOpenCLMetadata() {
582 llvm::Metadata *OCLVerElts[] = {
583 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
584 Int32Ty, LangOpts.OpenCLVersion / 100)),
585 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
586 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
587 llvm::NamedMDNode *OCLVerMD =
588 TheModule.getOrInsertNamedMetadata(
"opencl.ocl.version");
589 llvm::LLVMContext &Ctx = TheModule.getContext();
590 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
606 return TBAA->getTypeInfo(QTy);
612 return TBAA->getAccessInfo(AccessType);
619 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
625 return TBAA->getTBAAStructInfo(QTy);
631 return TBAA->getBaseTypeInfo(QTy);
637 return TBAA->getAccessTagInfo(Info);
644 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
652 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
660 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
666 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
671 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
684 "cannot compile this %0 yet");
685 std::string Msg =
Type;
694 "cannot compile this %0 yet");
695 std::string Msg =
Type;
705 if (GV->hasDLLImportStorageClass())
708 if (GV->hasLocalLinkage()) {
721 llvm::GlobalValue *GV) {
722 if (GV->hasLocalLinkage())
725 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
729 if (GV->hasDLLImportStorageClass())
732 const llvm::Triple &TT = CGM.
getTriple();
738 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
742 if (!TT.isOSBinFormatELF())
749 if (RM != llvm::Reloc::Static && !LOpts.PIE)
753 if (!GV->isDeclarationForLinker())
759 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
763 llvm::Triple::ArchType Arch = TT.getArch();
764 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
765 Arch == llvm::Triple::ppc64le)
769 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
770 if (!Var->isThreadLocal() &&
771 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
777 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
792 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
802 if (D->
hasAttr<DLLImportAttr>())
803 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
804 else if (D->
hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
805 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
828 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
829 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
830 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
831 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
832 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
839 return llvm::GlobalVariable::GeneralDynamicTLSModel;
841 return llvm::GlobalVariable::LocalDynamicTLSModel;
843 return llvm::GlobalVariable::InitialExecTLSModel;
845 return llvm::GlobalVariable::LocalExecTLSModel;
847 llvm_unreachable(
"Invalid TLS model!");
851 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
853 llvm::GlobalValue::ThreadLocalMode TLM;
857 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
861 GV->setThreadLocalMode(TLM);
871 const CPUSpecificAttr *
Attr,
881 const TargetAttr *
Attr, raw_ostream &Out) {
882 if (Attr->isDefaultVersion())
887 TargetAttr::ParsedTargetAttr Info =
888 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
891 assert(LHS.startswith(
"+") && RHS.startswith(
"+") &&
892 "Features should always have a prefix.");
899 if (!Info.Architecture.empty()) {
901 Out <<
"arch_" << Info.Architecture;
904 for (StringRef Feat : Info.Features) {
908 Out << Feat.substr(1);
914 bool OmitMultiVersionMangling =
false) {
916 llvm::raw_svector_ostream Out(Buffer);
919 llvm::raw_svector_ostream Out(Buffer);
920 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
922 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
928 assert(II &&
"Attempt to mangle unnamed decl.");
933 llvm::raw_svector_ostream Out(Buffer);
934 Out <<
"__regcall3__" << II->
getName();
940 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
941 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
942 if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
944 CGM, FD->getAttr<CPUSpecificAttr>(), Out);
952 void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
960 std::string NonTargetName =
968 "Other GD should now be a multiversioned function");
976 if (OtherName != NonTargetName) {
979 const auto ExistingRecord = Manglings.find(NonTargetName);
980 if (ExistingRecord != std::end(Manglings))
981 Manglings.remove(&(*ExistingRecord));
982 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
985 Entry->setName(OtherName);
995 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
1009 const auto *SD = FD->
getAttr<CPUSpecificAttr>();
1011 std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1015 auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1016 if (FoundName != CPUSpecificMangledDeclNames.end())
1017 return FoundName->second;
1019 auto Result = CPUSpecificManglings.insert(
1021 return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1024 auto FoundName = MangledDeclNames.find(CanonicalGD);
1025 if (FoundName != MangledDeclNames.end())
1026 return FoundName->second;
1029 const auto *ND = cast<NamedDecl>(GD.
getDecl());
1032 return MangledDeclNames[CanonicalGD] = Result.first->first();
1041 llvm::raw_svector_ostream Out(Buffer);
1044 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
1045 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1047 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1050 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
1052 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1053 return Result.first->first();
1062 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
1063 llvm::Constant *AssociatedData) {
1065 GlobalCtors.push_back(
Structor(Priority, Ctor, AssociatedData));
1070 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
1071 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1072 DtorsUsingAtExit[Priority].push_back(Dtor);
1077 GlobalDtors.push_back(
Structor(Priority, Dtor,
nullptr));
1080 void CodeGenModule::EmitCtorList(
CtorList &Fns,
const char *GlobalName) {
1081 if (Fns.empty())
return;
1084 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
1085 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
1088 llvm::StructType *CtorStructTy = llvm::StructType::get(
1093 auto ctors = builder.
beginArray(CtorStructTy);
1094 for (
const auto &I : Fns) {
1095 auto ctor = ctors.beginStruct(CtorStructTy);
1096 ctor.addInt(
Int32Ty, I.Priority);
1097 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1098 if (I.AssociatedData)
1099 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData,
VoidPtrTy));
1102 ctor.finishAndAddTo(ctors);
1108 llvm::GlobalValue::AppendingLinkage);
1112 list->setAlignment(0);
1117 llvm::GlobalValue::LinkageTypes
1119 const auto *D = cast<FunctionDecl>(GD.
getDecl());
1123 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1126 if (isa<CXXConstructorDecl>(D) &&
1127 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1139 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1140 if (!MDS)
return nullptr;
1142 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
1147 llvm::Function *F) {
1149 llvm::AttributeList PAL;
1151 F->setAttributes(PAL);
1152 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1162 if (!LangOpts.Exceptions)
return false;
1165 if (LangOpts.CXXExceptions)
return true;
1168 if (LangOpts.ObjCExceptions) {
1185 !isa<CXXDestructorDecl>(MD);
1188 std::vector<const CXXRecordDecl *>
1190 llvm::SetVector<const CXXRecordDecl *> MostBases;
1192 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1195 MostBases.insert(RD);
1197 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1199 CollectMostBases(RD);
1200 return MostBases.takeVector();
1204 llvm::Function *F) {
1205 llvm::AttrBuilder B;
1207 if (CodeGenOpts.UnwindTables)
1208 B.addAttribute(llvm::Attribute::UWTable);
1211 B.addAttribute(llvm::Attribute::NoUnwind);
1213 if (!D || !D->
hasAttr<NoStackProtectorAttr>()) {
1215 B.addAttribute(llvm::Attribute::StackProtect);
1217 B.addAttribute(llvm::Attribute::StackProtectStrong);
1219 B.addAttribute(llvm::Attribute::StackProtectReq);
1226 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1228 B.addAttribute(llvm::Attribute::NoInline);
1230 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1236 bool ShouldAddOptNone =
1237 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1239 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
1240 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1241 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
1243 if (ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) {
1244 B.addAttribute(llvm::Attribute::OptimizeNone);
1247 B.addAttribute(llvm::Attribute::NoInline);
1248 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1249 "OptimizeNone and AlwaysInline on same function!");
1254 B.addAttribute(llvm::Attribute::Naked);
1257 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1258 F->removeFnAttr(llvm::Attribute::MinSize);
1259 }
else if (D->
hasAttr<NakedAttr>()) {
1261 B.addAttribute(llvm::Attribute::Naked);
1262 B.addAttribute(llvm::Attribute::NoInline);
1263 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
1264 B.addAttribute(llvm::Attribute::NoDuplicate);
1265 }
else if (D->
hasAttr<NoInlineAttr>()) {
1266 B.addAttribute(llvm::Attribute::NoInline);
1267 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
1268 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1270 B.addAttribute(llvm::Attribute::AlwaysInline);
1274 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1275 B.addAttribute(llvm::Attribute::NoInline);
1279 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
1281 return Redecl->isInlineSpecified();
1283 B.addAttribute(llvm::Attribute::InlineHint);
1284 }
else if (CodeGenOpts.getInlining() ==
1287 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1288 B.addAttribute(llvm::Attribute::NoInline);
1295 if (!D->
hasAttr<OptimizeNoneAttr>()) {
1297 if (!ShouldAddOptNone)
1298 B.addAttribute(llvm::Attribute::OptimizeForSize);
1299 B.addAttribute(llvm::Attribute::Cold);
1302 if (D->
hasAttr<MinSizeAttr>())
1303 B.addAttribute(llvm::Attribute::MinSize);
1306 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1310 F->setAlignment(alignment);
1312 if (!D->
hasAttr<AlignedAttr>())
1313 if (LangOpts.FunctionAlignment)
1314 F->setAlignment(1 << LangOpts.FunctionAlignment);
1321 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1326 if (CodeGenOpts.SanitizeCfiCrossDso)
1327 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1336 llvm::Metadata *
Id =
1339 F->addTypeMetadata(0, Id);
1346 if (dyn_cast_or_null<NamedDecl>(D))
1351 if (D && D->
hasAttr<UsedAttr>())
1355 bool CodeGenModule::GetCPUAndFeaturesAttributes(
const Decl *D,
1356 llvm::AttrBuilder &Attrs) {
1361 std::vector<std::string> Features;
1362 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1364 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
1365 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() :
nullptr;
1366 bool AddedAttr =
false;
1368 llvm::StringMap<bool> FeatureMap;
1372 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1373 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
1380 TargetAttr::ParsedTargetAttr
ParsedAttr = TD->parse();
1381 if (ParsedAttr.Architecture !=
"" &&
1382 getTarget().isValidCPUName(ParsedAttr.Architecture))
1383 TargetCPU = ParsedAttr.Architecture;
1391 if (TargetCPU !=
"") {
1392 Attrs.addAttribute(
"target-cpu", TargetCPU);
1395 if (!Features.empty()) {
1396 llvm::sort(Features.begin(), Features.end());
1397 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
1404 void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
1405 llvm::GlobalObject *GO) {
1410 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1411 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
1412 GV->addAttribute(
"bss-section", SA->getName());
1413 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
1414 GV->addAttribute(
"data-section", SA->getName());
1415 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
1416 GV->addAttribute(
"rodata-section", SA->getName());
1419 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
1420 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
1421 if (!D->
getAttr<SectionAttr>())
1422 F->addFnAttr(
"implicit-section-name", SA->getName());
1424 llvm::AttrBuilder Attrs;
1425 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1429 F->removeFnAttr(
"target-cpu");
1430 F->removeFnAttr(
"target-features");
1431 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1435 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
1436 GO->setSection(CSA->getName());
1437 else if (
const auto *SA = D->
getAttr<SectionAttr>())
1438 GO->setSection(SA->getName());
1453 setNonAliasAttributes(GD, F);
1464 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1468 llvm::Function *F) {
1470 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
1475 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1479 if (CodeGenOpts.SanitizeCfiCrossDso) {
1487 F->addTypeMetadata(0, MD);
1491 if (CodeGenOpts.SanitizeCfiCrossDso)
1493 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1496 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1497 bool IsIncompleteFunction,
1503 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1507 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1509 if (!IsIncompleteFunction) {
1512 if (F->isDeclaration())
1519 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1521 assert(!F->arg_empty() &&
1522 F->arg_begin()->getType()
1523 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1524 "unexpected this return");
1525 F->addAttribute(1, llvm::Attribute::Returned);
1534 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
1535 F->setSection(CSA->getName());
1536 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
1537 F->setSection(SA->getName());
1542 F->addAttribute(llvm::AttributeList::FunctionIndex,
1543 llvm::Attribute::NoBuiltin);
1550 (
Kind == OO_New ||
Kind == OO_Array_New))
1551 F->addAttribute(llvm::AttributeList::ReturnIndex,
1552 llvm::Attribute::NoAlias);
1555 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1556 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1557 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1558 if (MD->isVirtual())
1559 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1563 if (!CodeGenOpts.SanitizeCfiCrossDso)
1571 assert(!GV->isDeclaration() &&
1572 "Only globals with definition can force usage.");
1573 LLVMUsed.emplace_back(GV);
1577 assert(!GV->isDeclaration() &&
1578 "Only globals with definition can force usage.");
1579 LLVMCompilerUsed.emplace_back(GV);
1583 std::vector<llvm::WeakTrackingVH> &List) {
1590 UsedArray.resize(List.size());
1591 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
1593 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1594 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
1597 if (UsedArray.empty())
1599 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1601 auto *GV =
new llvm::GlobalVariable(
1602 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1603 llvm::ConstantArray::get(ATy, UsedArray), Name);
1605 GV->setSection(
"llvm.metadata");
1608 void CodeGenModule::emitLLVMUsed() {
1609 emitUsed(*
this,
"llvm.used", LLVMUsed);
1610 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1615 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1622 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1627 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1628 C, {llvm::MDString::get(C,
"lib"), llvm::MDString::get(C, Lib)}));
1635 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1642 llvm::SmallPtrSet<Module *, 16> &Visited) {
1644 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1649 for (
unsigned I = Mod->
Imports.size(); I > 0; --I) {
1650 if (Visited.insert(Mod->
Imports[I - 1]).second)
1667 llvm::Metadata *Args[2] = {
1668 llvm::MDString::get(Context,
"-framework"),
1669 llvm::MDString::get(Context, Mod->
LinkLibraries[I - 1].Library)};
1671 Metadata.push_back(llvm::MDNode::get(Context, Args));
1679 auto *OptString = llvm::MDString::get(Context, Opt);
1680 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1684 void CodeGenModule::EmitModuleLinkOptions() {
1688 llvm::SetVector<clang::Module *> LinkModules;
1689 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1693 for (
Module *M : ImportedModules) {
1699 if (Visited.insert(M).second)
1705 while (!Stack.empty()) {
1708 bool AnyChildren =
false;
1713 Sub != SubEnd; ++Sub) {
1716 if ((*Sub)->IsExplicit)
1719 if (Visited.insert(*Sub).second) {
1720 Stack.push_back(*Sub);
1728 LinkModules.insert(Mod);
1737 for (
Module *M : LinkModules)
1738 if (Visited.insert(M).second)
1740 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1741 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1744 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
1745 for (
auto *MD : LinkerOptionsMetadata)
1746 NMD->addOperand(MD);
1749 void CodeGenModule::EmitDeferred() {
1754 if (!DeferredVTables.empty()) {
1755 EmitDeferredVTables();
1760 assert(DeferredVTables.empty());
1764 if (DeferredDeclsToEmit.empty())
1769 std::vector<GlobalDecl> CurDeclsToEmit;
1770 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1777 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1795 if (!GV->isDeclaration())
1799 EmitGlobalDefinition(D, GV);
1804 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1806 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1811 void CodeGenModule::EmitVTablesOpportunistically() {
1817 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1818 &&
"Only emit opportunistic vtables with optimizations");
1822 "This queue should only contain external vtables");
1823 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
1826 OpportunisticVTables.clear();
1830 if (Annotations.empty())
1834 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1835 Annotations[0]->getType(), Annotations.size()), Annotations);
1836 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
1837 llvm::GlobalValue::AppendingLinkage,
1838 Array,
"llvm.global.annotations");
1839 gv->setSection(AnnotationSection);
1843 llvm::Constant *&AStr = AnnotationStrings[Str];
1848 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
1850 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
1851 llvm::GlobalValue::PrivateLinkage, s,
".str");
1852 gv->setSection(AnnotationSection);
1853 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1871 return llvm::ConstantInt::get(
Int32Ty, LineNo);
1875 const AnnotateAttr *AA,
1883 llvm::Constant *Fields[4] = {
1884 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
1885 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
1886 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
1889 return llvm::ConstantStruct::getAnon(Fields);
1893 llvm::GlobalValue *GV) {
1894 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1905 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1914 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1924 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1925 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
1926 if (!EnabledAsanMask)
1929 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(),
Category))
1931 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1937 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
1938 Ty = AT->getElementType();
1943 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1952 if (!LangOpts.XRayInstrument)
1957 auto Attr = ImbueAttr::NONE;
1959 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1960 if (
Attr == ImbueAttr::NONE)
1961 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1963 case ImbueAttr::NONE:
1965 case ImbueAttr::ALWAYS:
1966 Fn->addFnAttr(
"function-instrument",
"xray-always");
1968 case ImbueAttr::ALWAYS_ARG1:
1969 Fn->addFnAttr(
"function-instrument",
"xray-always");
1970 Fn->addFnAttr(
"xray-log-args",
"1");
1972 case ImbueAttr::NEVER:
1973 Fn->addFnAttr(
"function-instrument",
"xray-never");
1979 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
1981 if (LangOpts.EmitAllDecls)
1987 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
1988 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
1993 if (
const auto *VD = dyn_cast<VarDecl>(Global))
2001 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2014 std::string Name =
"_GUID_" + Uuid.lower();
2015 std::replace(Name.begin(), Name.end(),
'-',
'_');
2021 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
2024 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2025 assert(Init &&
"failed to initialize as constant");
2027 auto *GV =
new llvm::GlobalVariable(
2029 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2031 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2037 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
2038 assert(AA &&
"No alias?");
2047 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2051 llvm::Constant *Aliasee;
2052 if (isa<llvm::FunctionType>(DeclTy))
2053 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2057 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2058 llvm::PointerType::getUnqual(DeclTy),
2061 auto *F = cast<llvm::GlobalValue>(Aliasee);
2062 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2063 WeakRefReferences.insert(F);
2069 const auto *Global = cast<ValueDecl>(GD.
getDecl());
2072 if (Global->
hasAttr<WeakRefAttr>())
2077 if (Global->
hasAttr<AliasAttr>())
2078 return EmitAliasDefinition(GD);
2081 if (Global->
hasAttr<IFuncAttr>())
2082 return emitIFuncDefinition(GD);
2085 if (Global->
hasAttr<CPUDispatchAttr>())
2086 return emitCPUDispatchDefinition(GD);
2089 if (LangOpts.CUDA) {
2090 if (LangOpts.CUDAIsDevice) {
2091 if (!Global->
hasAttr<CUDADeviceAttr>() &&
2092 !Global->
hasAttr<CUDAGlobalAttr>() &&
2093 !Global->
hasAttr<CUDAConstantAttr>() &&
2094 !Global->
hasAttr<CUDASharedAttr>())
2103 if (isa<FunctionDecl>(Global) && !Global->
hasAttr<CUDAHostAttr>() &&
2104 Global->
hasAttr<CUDADeviceAttr>())
2107 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2108 "Expected Variable or Function");
2112 if (LangOpts.OpenMP) {
2115 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2117 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2118 if (MustBeEmitted(Global))
2125 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2137 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
2142 const auto *VD = cast<VarDecl>(Global);
2143 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
2147 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2148 !VD->hasDefinition() &&
2149 (VD->hasAttr<CUDAConstantAttr>() ||
2150 VD->hasAttr<CUDADeviceAttr>());
2151 if (!MustEmitForCuda &&
2166 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2168 EmitGlobalDefinition(GD);
2175 cast<VarDecl>(Global)->hasInit()) {
2176 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2177 CXXGlobalInits.push_back(
nullptr);
2183 addDeferredDeclToEmit(GD);
2184 }
else if (MustBeEmitted(Global)) {
2186 assert(!MayBeEmittedEagerly(Global));
2187 addDeferredDeclToEmit(GD);
2192 DeferredDecls[MangledName] = GD;
2199 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2200 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2207 struct FunctionIsDirectlyRecursive :
2209 const StringRef Name;
2213 Name(N), BI(C), Result(
false) {
2217 bool TraverseCallExpr(
CallExpr *E) {
2222 if (Attr && Name == Attr->getLabel()) {
2229 StringRef BuiltinName = BI.
getName(BuiltinID);
2230 if (BuiltinName.startswith(
"__builtin_") &&
2231 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
2240 struct DLLImportFunctionVisitor
2242 bool SafeToInline =
true;
2244 bool shouldVisitImplicitCode()
const {
return true; }
2246 bool VisitVarDecl(
VarDecl *VD) {
2249 SafeToInline =
false;
2250 return SafeToInline;
2257 return SafeToInline;
2262 SafeToInline = D->
hasAttr<DLLImportAttr>();
2263 return SafeToInline;
2268 if (isa<FunctionDecl>(VD))
2269 SafeToInline = VD->
hasAttr<DLLImportAttr>();
2270 else if (
VarDecl *V = dyn_cast<VarDecl>(VD))
2271 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2272 return SafeToInline;
2277 return SafeToInline;
2284 SafeToInline =
true;
2286 SafeToInline = M->
hasAttr<DLLImportAttr>();
2288 return SafeToInline;
2293 return SafeToInline;
2298 return SafeToInline;
2307 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
2309 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2314 Name = Attr->getLabel();
2319 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
2320 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2321 return Walker.Result;
2324 bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
2327 const auto *F = cast<FunctionDecl>(GD.
getDecl());
2328 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2331 if (F->hasAttr<DLLImportAttr>()) {
2333 DLLImportFunctionVisitor Visitor;
2334 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2335 if (!Visitor.SafeToInline)
2341 for (
const Decl *Member : Dtor->getParent()->decls())
2342 if (isa<FieldDecl>(Member))
2356 return !isTriviallyRecursive(F);
2359 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2360 return CodeGenOpts.OptimizationLevel > 0;
2363 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
2364 const auto *D = cast<ValueDecl>(GD.
getDecl());
2368 "Generating code for declaration");
2370 if (isa<FunctionDecl>(D)) {
2373 if (!shouldEmitFunction(GD))
2376 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2379 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2381 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2384 EmitGlobalFunctionDefinition(GD, GV);
2386 if (Method->isVirtual())
2392 return EmitGlobalFunctionDefinition(GD, GV);
2395 if (
const auto *VD = dyn_cast<VarDecl>(D))
2396 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2398 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
2402 llvm::Function *NewFn);
2404 void CodeGenModule::emitMultiVersionFunctions() {
2416 EmitGlobalFunctionDefinition(CurGD,
nullptr);
2425 assert(Func &&
"This should have just been created");
2427 Options.emplace_back(
getTarget(), cast<llvm::Function>(Func),
2428 CurFD->
getAttr<TargetAttr>()->parse());
2431 llvm::Function *ResolverFunc = cast<llvm::Function>(
2434 ResolverFunc->setComdat(
2435 getModule().getOrInsertComdat(ResolverFunc->getName()));
2437 Options.begin(), Options.end(),
2438 std::greater<CodeGenFunction::TargetMultiVersionResolverOption>());
2444 void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
2445 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2446 assert(FD &&
"Not a FunctionDecl?");
2447 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
2448 assert(DD &&
"Not a cpu_dispatch Function?");
2452 llvm::Type *ResolverType = llvm::FunctionType::get(
2453 llvm::PointerType::get(DeclTy,
2456 auto *ResolverFunc = cast<llvm::Function>(
2457 GetOrCreateLLVMFunction(ResolverName, ResolverType,
GlobalDecl{},
2467 llvm::Constant *Func = GetOrCreateLLVMFunction(
2468 MangledName, DeclTy, GD,
false,
false,
2472 llvm::transform(Features, Features.begin(),
2473 [](StringRef Str) {
return Str.substr(1); });
2474 Features.erase(std::remove_if(
2475 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2477 }), Features.end());
2478 Options.emplace_back(cast<llvm::Function>(Func),
2483 Options.begin(), Options.end(),
2484 std::greater<CodeGenFunction::CPUDispatchMultiVersionResolverOption>());
2494 std::string MangledName =
2496 std::string IFuncName = MangledName +
".ifunc";
2504 MultiVersionFuncs.push_back(GD);
2506 std::string ResolverName = MangledName +
".resolver";
2507 llvm::Type *ResolverType = llvm::FunctionType::get(
2508 llvm::PointerType::get(DeclTy,
2511 llvm::Constant *Resolver =
2512 GetOrCreateLLVMFunction(ResolverName, ResolverType,
GlobalDecl{},
2516 GIF->setName(IFuncName);
2529 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2531 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
2537 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2539 if (
getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2540 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
2541 !DontDefer && !IsForDefinition) {
2545 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2547 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2551 addDeferredDeclToEmit(GDDef);
2556 const auto *TA = FD->
getAttr<TargetAttr>();
2557 if (TA && TA->isDefaultVersion())
2558 UpdateMultiVersionNames(GD, FD);
2559 if (!IsForDefinition)
2560 return GetOrCreateMultiVersionIFunc(GD, Ty, FD);
2567 if (WeakRefReferences.erase(Entry)) {
2568 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2569 if (FD && !FD->
hasAttr<WeakAttr>())
2574 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>()) {
2575 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2581 if (IsForDefinition && !Entry->isDeclaration()) {
2588 DiagnosedConflictingDefinitions.insert(GD).second) {
2592 diag::note_previous_definition);
2596 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2597 (Entry->getType()->getElementType() == Ty)) {
2604 if (!IsForDefinition)
2605 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2611 bool IsIncompleteFunction =
false;
2613 llvm::FunctionType *FTy;
2614 if (isa<llvm::FunctionType>(Ty)) {
2615 FTy = cast<llvm::FunctionType>(Ty);
2617 FTy = llvm::FunctionType::get(
VoidTy,
false);
2618 IsIncompleteFunction =
true;
2623 Entry ? StringRef() : MangledName, &
getModule());
2640 if (!Entry->use_empty()) {
2642 Entry->removeDeadConstantUsers();
2645 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2646 F, Entry->getType()->getElementType()->getPointerTo());
2650 assert(F->getName() == MangledName &&
"name was uniqued!");
2652 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2653 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2654 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2655 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2662 if (D && isa<CXXDestructorDecl>(D) &&
2663 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2665 addDeferredDeclToEmit(GD);
2670 auto DDI = DeferredDecls.find(MangledName);
2671 if (DDI != DeferredDecls.end()) {
2675 addDeferredDeclToEmit(DDI->second);
2676 DeferredDecls.erase(DDI);
2691 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2704 if (!IsIncompleteFunction) {
2705 assert(F->getType()->getElementType() == Ty);
2709 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2710 return llvm::ConstantExpr::getBitCast(F, PTy);
2723 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2731 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
2734 DD->getParent()->getNumVBases() == 0)
2739 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2740 false, llvm::AttributeList(),
2750 for (
const auto &Result : DC->
lookup(&CII))
2751 if (
const auto FD = dyn_cast<FunctionDecl>(Result))
2759 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
2763 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
2765 for (
const auto &Result : DC->
lookup(&NS)) {
2767 if (
auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2768 for (
const auto &Result : LSD->lookup(&NS))
2769 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2773 for (
const auto &Result : ND->
lookup(&CXXII))
2774 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
2786 llvm::AttributeList ExtraAttrs,
2789 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2793 if (
auto *F = dyn_cast<llvm::Function>(C)) {
2797 if (!Local &&
getTriple().isOSBinFormatCOFF() &&
2799 !
getTriple().isWindowsGNUEnvironment()) {
2801 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
2802 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2817 llvm::AttributeList ExtraAttrs) {
2834 return ExcludeCtor && !Record->hasMutableFields() &&
2835 Record->hasTrivialDestructor();
2853 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2854 llvm::PointerType *Ty,
2860 if (WeakRefReferences.erase(Entry)) {
2861 if (D && !D->
hasAttr<WeakAttr>())
2866 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
2867 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2869 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2872 if (Entry->getType() == Ty)
2877 if (IsForDefinition && !Entry->isDeclaration()) {
2885 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
2887 DiagnosedConflictingDefinitions.insert(D).second) {
2891 diag::note_previous_definition);
2896 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2897 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2901 if (!IsForDefinition)
2902 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2908 auto *GV =
new llvm::GlobalVariable(
2909 getModule(), Ty->getElementType(),
false,
2911 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2916 GV->takeName(Entry);
2918 if (!Entry->use_empty()) {
2919 llvm::Constant *NewPtrForOldDecl =
2920 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2921 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2924 Entry->eraseFromParent();
2930 auto DDI = DeferredDecls.find(MangledName);
2931 if (DDI != DeferredDecls.end()) {
2934 addDeferredDeclToEmit(DDI->second);
2935 DeferredDecls.erase(DDI);
2940 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2953 CXXThreadLocals.push_back(D);
2961 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
2962 EmitGlobalVarDefinition(D);
2967 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
2968 GV->setSection(SA->getName());
2972 if (
getTriple().getArch() == llvm::Triple::xcore &&
2976 GV->setSection(
".cp.rodata");
2981 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2984 const auto *Record =
2986 bool HasMutableFields = Record && Record->hasMutableFields();
2987 if (!HasMutableFields) {
2994 auto *InitType = Init->getType();
2995 if (GV->getType()->getElementType() != InitType) {
3000 GV->setName(StringRef());
3003 auto *NewGV = cast<llvm::GlobalVariable>(
3007 GV->eraseFromParent();
3010 GV->setInitializer(Init);
3011 GV->setConstant(
true);
3012 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3024 assert(
getContext().getTargetAddressSpace(ExpectedAS) ==
3025 Ty->getPointerAddressSpace());
3026 if (AddrSpace != ExpectedAS)
3037 if (isa<CXXConstructorDecl>(D))
3041 false, IsForDefinition);
3042 else if (isa<CXXDestructorDecl>(D))
3046 false, IsForDefinition);
3047 else if (isa<CXXMethodDecl>(D)) {
3049 cast<CXXMethodDecl>(D));
3053 }
else if (isa<FunctionDecl>(D)) {
3063 llvm::GlobalVariable *
3066 llvm::GlobalValue::LinkageTypes
Linkage) {
3067 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
3068 llvm::GlobalVariable *OldGV =
nullptr;
3072 if (GV->getType()->getElementType() == Ty)
3077 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
3082 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
3083 Linkage,
nullptr, Name);
3087 GV->takeName(OldGV);
3089 if (!OldGV->use_empty()) {
3090 llvm::Constant *NewPtrForOldDecl =
3091 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3092 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3095 OldGV->eraseFromParent();
3099 !GV->hasAvailableExternallyLinkage())
3100 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3119 llvm::PointerType *PTy =
3120 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
3123 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3132 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty),
nullptr);
3133 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3138 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
3146 if (GV && !GV->isDeclaration())
3151 if (!MustBeEmitted(D) && !GV) {
3152 DeferredDecls[MangledName] = D;
3157 EmitGlobalVarDefinition(D);
3167 if (LangOpts.OpenCL) {
3176 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3177 if (D && D->
hasAttr<CUDAConstantAttr>())
3179 else if (D && D->
hasAttr<CUDASharedAttr>())
3181 else if (D && D->
hasAttr<CUDADeviceAttr>())
3194 if (LangOpts.OpenCL)
3196 if (
auto AS =
getTarget().getConstantAddressSpace())
3197 return AS.getValue();
3209 static llvm::Constant *
3211 llvm::GlobalVariable *GV) {
3212 llvm::Constant *Cast = GV;
3218 GV->getValueType()->getPointerTo(
3225 template<
typename SomeDecl>
3227 llvm::GlobalValue *GV) {
3233 if (!D->template hasAttr<UsedAttr>())
3242 const SomeDecl *
First = D->getFirstDecl();
3243 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3249 std::pair<StaticExternCMap::iterator, bool> R =
3250 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3255 R.first->second =
nullptr;
3262 if (D.
hasAttr<SelectAnyAttr>())
3266 if (
auto *VD = dyn_cast<VarDecl>(&D))
3280 llvm_unreachable(
"No such linkage");
3284 llvm::GlobalObject &GO) {
3287 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3291 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
3301 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3302 OpenMPRuntime->emitTargetGlobalVariable(D))
3305 llvm::Constant *Init =
nullptr;
3307 bool NeedsGlobalCtor =
false;
3320 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
3321 else if (!InitExpr) {
3335 emitter.emplace(*
this);
3336 Init = emitter->tryEmitForInitializer(*InitDecl);
3345 NeedsGlobalCtor =
true;
3348 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
3355 DelayedCXXInitPosition.erase(D);
3360 llvm::Constant *Entry =
3364 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3365 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3366 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3368 CE->getOpcode() == llvm::Instruction::GetElementPtr);
3369 Entry = CE->getOperand(0);
3373 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3384 if (!GV || GV->getType()->getElementType() != InitType ||
3385 GV->getType()->getAddressSpace() !=
3389 Entry->setName(StringRef());
3392 GV = cast<llvm::GlobalVariable>(
3396 llvm::Constant *NewPtrForOldDecl =
3397 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3398 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3401 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3406 if (D->
hasAttr<AnnotateAttr>())
3410 llvm::GlobalValue::LinkageTypes
Linkage =
3420 if (GV && LangOpts.CUDA) {
3421 if (LangOpts.CUDAIsDevice) {
3422 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>())
3423 GV->setExternallyInitialized(
true);
3429 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>()) {
3437 if (D->
hasAttr<CUDAConstantAttr>())
3440 }
else if (D->
hasAttr<CUDASharedAttr>())
3450 GV->setInitializer(Init);
3451 if (emitter) emitter->finalize(GV);
3454 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3458 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
3461 GV->setConstant(
true);
3476 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3477 !llvm::GlobalVariable::isWeakLinkage(Linkage))
3480 GV->setLinkage(Linkage);
3481 if (D->
hasAttr<DLLImportAttr>())
3482 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3483 else if (D->
hasAttr<DLLExportAttr>())
3484 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3486 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3488 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3490 GV->setConstant(
false);
3495 if (!GV->getInitializer()->isNullValue())
3496 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3499 setNonAliasAttributes(D, GV);
3501 if (D->
getTLSKind() && !GV->isThreadLocal()) {
3503 CXXThreadLocals.push_back(D);
3510 if (NeedsGlobalCtor || NeedsGlobalDtor)
3511 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3513 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3518 DI->EmitGlobalVariable(GV, D);
3526 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
3537 if (D->
hasAttr<SectionAttr>())
3543 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
3544 D->
hasAttr<PragmaClangDataSectionAttr>() ||
3545 D->
hasAttr<PragmaClangRodataSectionAttr>())
3553 if (D->
hasAttr<WeakImportAttr>())
3563 if (D->
hasAttr<AlignedAttr>())
3572 if (FD->isBitField())
3574 if (FD->
hasAttr<AlignedAttr>())
3591 if (IsConstantVariable)
3592 return llvm::GlobalVariable::WeakODRLinkage;
3594 return llvm::GlobalVariable::WeakAnyLinkage;
3600 return llvm::GlobalValue::AvailableExternallyLinkage;
3614 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3631 return llvm::Function::WeakODRLinkage;
3636 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3638 CodeGenOpts.NoCommon))
3639 return llvm::GlobalVariable::CommonLinkage;
3645 if (D->
hasAttr<SelectAnyAttr>())
3646 return llvm::GlobalVariable::WeakODRLinkage;
3654 const VarDecl *VD,
bool IsConstant) {
3662 llvm::Function *newFn) {
3664 if (old->use_empty())
return;
3666 llvm::Type *newRetTy = newFn->getReturnType();
3670 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3672 llvm::Value::use_iterator use = ui++;
3673 llvm::User *user = use->getUser();
3677 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3678 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3684 llvm::CallSite callSite(user);
3685 if (!callSite)
continue;
3686 if (!callSite.isCallee(&*use))
continue;
3690 if (callSite->getType() != newRetTy && !callSite->use_empty())
3695 llvm::AttributeList oldAttrs = callSite.getAttributes();
3698 unsigned newNumArgs = newFn->arg_size();
3699 if (callSite.arg_size() < newNumArgs)
continue;
3704 bool dontTransform =
false;
3705 for (llvm::Argument &A : newFn->args()) {
3706 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3707 dontTransform =
true;
3712 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3720 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3723 callSite.getOperandBundlesAsDefs(newBundles);
3725 llvm::CallSite newCall;
3726 if (callSite.isCall()) {
3728 callSite.getInstruction());
3730 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3732 oldInvoke->getNormalDest(),
3733 oldInvoke->getUnwindDest(),
3734 newArgs, newBundles,
"",
3735 callSite.getInstruction());
3739 if (!newCall->getType()->isVoidTy())
3740 newCall->takeName(callSite.getInstruction());
3741 newCall.setAttributes(llvm::AttributeList::get(
3742 newFn->getContext(), oldAttrs.getFnAttributes(),
3743 oldAttrs.getRetAttributes(), newArgAttrs));
3744 newCall.setCallingConv(callSite.getCallingConv());
3747 if (!callSite->use_empty())
3748 callSite->replaceAllUsesWith(newCall.getInstruction());
3751 if (callSite->getDebugLoc())
3752 newCall->setDebugLoc(callSite->getDebugLoc());
3754 callSite->eraseFromParent();
3768 llvm::Function *NewFn) {
3770 if (!isa<llvm::Function>(Old))
return;
3789 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
3790 llvm::GlobalValue *GV) {
3791 const auto *D = cast<FunctionDecl>(GD.
getDecl());
3798 if (!GV || (GV->getType()->getElementType() != Ty))
3804 if (!GV->isDeclaration())
3811 auto *Fn = cast<llvm::Function>(GV);
3824 setNonAliasAttributes(GD, Fn);
3827 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
3828 AddGlobalCtor(Fn, CA->getPriority());
3829 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
3830 AddGlobalDtor(Fn, DA->getPriority());
3831 if (D->
hasAttr<AnnotateAttr>())
3834 if (D->isCPUSpecificMultiVersion()) {
3835 auto *Spec = D->
getAttr<CPUSpecificAttr>();
3837 if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
3838 ++Spec->ActiveArgIndex;
3839 EmitGlobalFunctionDefinition(GD,
nullptr);
3844 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
3845 const auto *D = cast<ValueDecl>(GD.
getDecl());
3846 const AliasAttr *AA = D->
getAttr<AliasAttr>();
3847 assert(AA &&
"Not an alias?");
3851 if (AA->getAliasee() == MangledName) {
3852 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3859 if (Entry && !Entry->isDeclaration())
3862 Aliases.push_back(GD);
3868 llvm::Constant *Aliasee;
3869 if (isa<llvm::FunctionType>(DeclTy))
3870 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3873 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3874 llvm::PointerType::getUnqual(DeclTy),
3882 if (GA->getAliasee() == Entry) {
3883 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3887 assert(Entry->isDeclaration());
3896 GA->takeName(Entry);
3898 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3900 Entry->eraseFromParent();
3902 GA->setName(MangledName);
3910 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3913 if (
const auto *VD = dyn_cast<VarDecl>(D))
3914 if (VD->getTLSKind())
3920 void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
3921 const auto *D = cast<ValueDecl>(GD.
getDecl());
3922 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
3923 assert(IFA &&
"Not an ifunc?");
3927 if (IFA->getResolver() == MangledName) {
3928 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3934 if (Entry && !Entry->isDeclaration()) {
3937 DiagnosedConflictingDefinitions.insert(GD).second) {
3938 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
3941 diag::note_previous_definition);
3946 Aliases.push_back(GD);
3949 llvm::Constant *Resolver =
3950 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3952 llvm::GlobalIFunc *GIF =
3956 if (GIF->getResolver() == Entry) {
3957 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3960 assert(Entry->isDeclaration());
3969 GIF->takeName(Entry);
3971 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3973 Entry->eraseFromParent();
3975 GIF->setName(MangledName);
3986 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3989 bool &IsUTF16,
unsigned &StringLength) {
3990 StringRef String = Literal->
getString();
3991 unsigned NumBytes = String.size();
3995 StringLength = NumBytes;
3996 return *Map.insert(std::make_pair(String,
nullptr)).first;
4003 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
4004 llvm::UTF16 *ToPtr = &ToBuf[0];
4006 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4007 ToPtr + NumBytes, llvm::strictConversion);
4010 StringLength = ToPtr - &ToBuf[0];
4014 return *Map.insert(std::make_pair(
4015 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4016 (StringLength + 1) * 2),
4022 unsigned StringLength = 0;
4023 bool isUTF16 =
false;
4024 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4029 if (
auto *C = Entry.second)
4032 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
4033 llvm::Constant *Zeros[] = { Zero, Zero };
4036 if (!CFConstantStringClassRef) {
4038 Ty = llvm::ArrayType::get(Ty, 0);
4039 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
4048 for (
const auto &Result : DC->
lookup(&II))
4049 if ((VD = dyn_cast<VarDecl>(Result)))
4052 if (!VD || !VD->
hasAttr<DLLExportAttr>()) {
4053 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4056 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4063 CFConstantStringClassRef =
4064 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
4072 auto Fields = Builder.beginStruct(STy);
4075 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4078 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4081 llvm::Constant *C =
nullptr;
4083 auto Arr = llvm::makeArrayRef(
4084 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4085 Entry.first().size() / 2);
4086 C = llvm::ConstantDataArray::get(VMContext, Arr);
4088 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4094 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
4095 llvm::GlobalValue::PrivateLinkage, C,
".str");
4096 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4108 GV->setSection(isUTF16 ?
"__TEXT,__ustring" 4109 :
"__TEXT,__cstring,cstring_literals");
4112 llvm::Constant *Str =
4113 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4117 Str = llvm::ConstantExpr::getBitCast(Str,
Int8PtrTy);
4122 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
4127 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
4129 llvm::GlobalVariable::PrivateLinkage);
4130 switch (
getTriple().getObjectFormat()) {
4131 case llvm::Triple::UnknownObjectFormat:
4132 llvm_unreachable(
"unknown file format");
4133 case llvm::Triple::COFF:
4134 case llvm::Triple::ELF:
4135 case llvm::Triple::Wasm:
4136 GV->setSection(
"cfstring");
4138 case llvm::Triple::MachO:
4139 GV->setSection(
"__DATA,__cfstring");
4148 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4152 if (ObjCFastEnumerationStateType.isNull()) {
4164 for (
size_t i = 0; i < 4; ++i) {
4169 FieldTypes[i],
nullptr,
4181 return ObjCFastEnumerationStateType;
4195 Str.resize(CAT->getSize().getZExtValue());
4196 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
4200 llvm::Type *ElemTy = AType->getElementType();
4201 unsigned NumElements = AType->getNumElements();
4204 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4206 Elements.reserve(NumElements);
4208 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
4210 Elements.resize(NumElements);
4211 return llvm::ConstantDataArray::get(VMContext, Elements);
4214 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4216 Elements.reserve(NumElements);
4218 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
4220 Elements.resize(NumElements);
4221 return llvm::ConstantDataArray::get(VMContext, Elements);
4224 static llvm::GlobalVariable *
4233 auto *GV =
new llvm::GlobalVariable(
4234 M, C->getType(), !CGM.
getLangOpts().WritableStrings, LT, C, GlobalName,
4235 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4237 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4238 if (GV->isWeakForLinker()) {
4239 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
4240 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4255 llvm::GlobalVariable **Entry =
nullptr;
4256 if (!LangOpts.WritableStrings) {
4257 Entry = &ConstantStringMap[C];
4258 if (
auto GV = *Entry) {
4266 StringRef GlobalVariableName;
4267 llvm::GlobalValue::LinkageTypes LT;
4272 if (!LangOpts.WritableStrings &&
4273 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4275 llvm::raw_svector_ostream Out(MangledNameBuffer);
4278 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4279 GlobalVariableName = MangledNameBuffer;
4281 LT = llvm::GlobalValue::PrivateLinkage;
4282 GlobalVariableName = Name;
4289 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
4310 const std::string &Str,
const char *GlobalName) {
4311 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4316 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
4319 llvm::GlobalVariable **Entry =
nullptr;
4320 if (!LangOpts.WritableStrings) {
4321 Entry = &ConstantStringMap[C];
4322 if (
auto GV = *Entry) {
4323 if (Alignment.getQuantity() > GV->getAlignment())
4324 GV->setAlignment(Alignment.getQuantity());
4331 GlobalName =
".str";
4334 GlobalName, Alignment);
4352 MaterializedType = E->
getType();
4356 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4363 llvm::raw_svector_ostream Out(Name);
4365 VD, E->getManglingNumber(), Out);
4368 if (E->getStorageDuration() ==
SD_Static) {
4382 Value = &EvalResult.
Val;
4388 llvm::Constant *InitialValue =
nullptr;
4389 bool Constant =
false;
4393 emitter.emplace(*
this);
4394 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4397 Type = InitialValue->getType();
4405 llvm::GlobalValue::LinkageTypes
Linkage =
4409 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4413 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4421 auto *GV =
new llvm::GlobalVariable(
4422 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4423 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4424 if (emitter) emitter->finalize(GV);
4428 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4429 if (VD->getTLSKind())
4431 llvm::Constant *CV = GV;
4437 MaterializedGlobalTemporaryMap[E] = CV;
4443 void CodeGenModule::EmitObjCPropertyImplementations(
const 4457 const_cast<ObjCImplementationDecl *>(D), PID);
4461 const_cast<ObjCImplementationDecl *>(D), PID);
4470 if (ivar->getType().isDestructedType())
4540 EmitDeclContext(LSD);
4543 void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
4544 for (
auto *I : DC->
decls()) {
4550 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4551 for (
auto *M : OID->methods())
4566 case Decl::CXXConversion:
4567 case Decl::CXXMethod:
4575 case Decl::CXXDeductionGuide:
4580 case Decl::Decomposition:
4581 case Decl::VarTemplateSpecialization:
4583 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
4584 for (
auto *B : DD->bindings())
4585 if (
auto *HD = B->getHoldingVar())
4591 case Decl::IndirectField:
4595 case Decl::Namespace:
4596 EmitDeclContext(cast<NamespaceDecl>(D));
4598 case Decl::ClassTemplateSpecialization: {
4599 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4602 Spec->hasDefinition())
4603 DebugInfo->completeTemplateDefinition(*Spec);
4605 case Decl::CXXRecord:
4609 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4612 for (
auto *I : cast<CXXRecordDecl>(D)->decls())
4613 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4617 case Decl::UsingShadow:
4618 case Decl::ClassTemplate:
4619 case Decl::VarTemplate:
4620 case Decl::VarTemplatePartialSpecialization:
4621 case Decl::FunctionTemplate:
4622 case Decl::TypeAliasTemplate:
4628 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4630 case Decl::NamespaceAlias:
4632 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4634 case Decl::UsingDirective:
4636 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4638 case Decl::CXXConstructor:
4641 case Decl::CXXDestructor:
4645 case Decl::StaticAssert:
4652 case Decl::ObjCInterface:
4653 case Decl::ObjCCategory:
4656 case Decl::ObjCProtocol: {
4657 auto *Proto = cast<ObjCProtocolDecl>(D);
4658 if (Proto->isThisDeclarationADefinition())
4663 case Decl::ObjCCategoryImpl:
4666 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4669 case Decl::ObjCImplementation: {
4670 auto *OMD = cast<ObjCImplementationDecl>(D);
4671 EmitObjCPropertyImplementations(OMD);
4672 EmitObjCIvarInitializations(OMD);
4677 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
4678 OMD->getClassInterface()), OMD->getLocation());
4681 case Decl::ObjCMethod: {
4682 auto *OMD = cast<ObjCMethodDecl>(D);
4688 case Decl::ObjCCompatibleAlias:
4689 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4692 case Decl::PragmaComment: {
4693 const auto *PCD = cast<PragmaCommentDecl>(D);
4694 switch (PCD->getCommentKind()) {
4696 llvm_unreachable(
"unexpected pragma comment kind");
4715 case Decl::PragmaDetectMismatch: {
4716 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4721 case Decl::LinkageSpec:
4722 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4725 case Decl::FileScopeAsm: {
4727 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4730 if (LangOpts.OpenMPIsDevice)
4732 auto *AD = cast<FileScopeAsmDecl>(D);
4733 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4737 case Decl::Import: {
4738 auto *Import = cast<ImportDecl>(D);
4741 if (!ImportedModules.insert(Import->getImportedModule()))
4745 if (!Import->getImportedOwningModule()) {
4747 DI->EmitImportDecl(*Import);
4751 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4753 Visited.insert(Import->getImportedModule());
4754 Stack.push_back(Import->getImportedModule());
4756 while (!Stack.empty()) {
4758 if (!EmittedModuleInitializers.insert(Mod).second)
4767 Sub != SubEnd; ++Sub) {
4770 if ((*Sub)->IsExplicit)
4773 if (Visited.insert(*Sub).second)
4774 Stack.push_back(*Sub);
4781 EmitDeclContext(cast<ExportDecl>(D));
4784 case Decl::OMPThreadPrivate:
4788 case Decl::OMPDeclareReduction:
4796 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
4803 if (!CodeGenOpts.CoverageMapping)
4806 case Decl::CXXConversion:
4807 case Decl::CXXMethod:
4809 case Decl::ObjCMethod:
4810 case Decl::CXXConstructor:
4811 case Decl::CXXDestructor: {
4812 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4817 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4818 if (I == DeferredEmptyCoverageMappingDecls.end())
4819 DeferredEmptyCoverageMappingDecls[D] =
true;
4829 if (!CodeGenOpts.CoverageMapping)
4831 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4832 if (Fn->isTemplateInstantiation())
4835 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4836 if (I == DeferredEmptyCoverageMappingDecls.end())
4837 DeferredEmptyCoverageMappingDecls[D] =
false;
4847 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4850 const Decl *D = Entry.first;
4852 case Decl::CXXConversion:
4853 case Decl::CXXMethod:
4855 case Decl::ObjCMethod: {
4862 case Decl::CXXConstructor: {
4869 case Decl::CXXDestructor: {
4886 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4887 return llvm::ConstantInt::get(i64, PtrInt);
4891 llvm::NamedMDNode *&GlobalMetadata,
4893 llvm::GlobalValue *Addr) {
4894 if (!GlobalMetadata)
4896 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
4899 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4902 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
4910 void CodeGenModule::EmitStaticExternCAliases() {
4913 for (
auto &I : StaticExternCValues) {
4915 llvm::GlobalValue *Val = I.second;
4923 auto Res = Manglings.find(MangledName);
4924 if (Res == Manglings.end())
4926 Result = Res->getValue();
4937 void CodeGenModule::EmitDeclMetadata() {
4938 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4940 for (
auto &I : MangledDeclNames) {
4941 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
4951 void CodeGenFunction::EmitDeclMetadata() {
4952 if (LocalDeclMap.empty())
return;
4957 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
4959 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4961 for (
auto &I : LocalDeclMap) {
4962 const Decl *D = I.first;
4964 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4966 Alloca->setMetadata(
4967 DeclPtrKind, llvm::MDNode::get(
4968 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4969 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4976 void CodeGenModule::EmitVersionIdentMetadata() {
4977 llvm::NamedMDNode *IdentMetadata =
4978 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
4980 llvm::LLVMContext &Ctx = TheModule.getContext();
4982 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4983 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4986 void CodeGenModule::EmitTargetMetadata() {
4993 for (
unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4994 auto Val = *(MangledDeclNames.begin() + I);
5001 void CodeGenModule::EmitCoverageFile() {
5006 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
5010 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
5011 llvm::LLVMContext &Ctx = TheModule.getContext();
5012 auto *CoverageDataFile =
5014 auto *CoverageNotesFile =
5016 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5017 llvm::MDNode *CU = CUNode->getOperand(i);
5018 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5019 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5023 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5026 assert(Uuid.size() == 36);
5027 for (
unsigned i = 0; i < 36; ++i) {
5028 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] ==
'-');
5033 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5035 llvm::Constant *Field3[8];
5036 for (
unsigned Idx = 0; Idx < 8; ++Idx)
5037 Field3[Idx] = llvm::ConstantInt::get(
5038 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5040 llvm::Constant *Fields[4] = {
5041 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
5042 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
5043 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
5044 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
5047 return llvm::ConstantStruct::getAnon(Fields);
5056 return llvm::Constant::getNullValue(
Int8PtrTy);
5059 LangOpts.ObjCRuntime.isGNUFamily())
5067 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5069 for (
auto RefExpr : D->
varlists()) {
5070 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5072 VD->getAnyInitializer() &&
5073 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
5078 VD, Addr, RefExpr->getLocStart(), PerformInit))
5079 CXXGlobalInits.push_back(InitFunction);
5084 CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
5091 std::string OutName;
5092 llvm::raw_string_ostream Out(OutName);
5106 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
5111 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
5131 for (
auto &Param : FnType->param_types())
5136 GeneralizedParams, FnType->getExtProtoInfo());
5143 llvm_unreachable(
"Encountered unknown FunctionType");
5148 GeneralizedMetadataIdMap,
".generalized");
5155 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5156 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5157 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5158 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5159 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5160 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5161 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5162 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5168 llvm::Metadata *MD =
5170 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
5172 if (CodeGenOpts.SanitizeCfiCrossDso)
5175 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5178 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
5179 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
5184 assert(TD !=
nullptr);
5185 TargetAttr::ParsedTargetAttr
ParsedAttr = TD->parse();
5187 ParsedAttr.Features.erase(
5188 llvm::remove_if(ParsedAttr.Features,
5189 [&](
const std::string &Feat) {
5190 return !Target.isValidFeatureName(
5191 StringRef{Feat}.substr(1));
5202 StringRef TargetCPU = Target.getTargetOpts().CPU;
5203 if (
const auto *TD = FD->
getAttr<TargetAttr>()) {
5208 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5209 Target.getTargetOpts().FeaturesAsWritten.begin(),
5210 Target.getTargetOpts().FeaturesAsWritten.end());
5212 if (ParsedAttr.Architecture !=
"" &&
5213 Target.isValidCPUName(ParsedAttr.Architecture))
5214 TargetCPU = ParsedAttr.Architecture;
5220 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU,
5221 ParsedAttr.Features);
5222 }
else if (
const auto *SD = FD->
getAttr<CPUSpecificAttr>()) {
5224 Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5226 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5227 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU, Features);
5229 Target.initFeatureMap(FeatureMap,
getDiags(), TargetCPU,
5230 Target.getTargetOpts().Features);
5236 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&
getModule());
5245 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()},
false);
5247 "__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.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
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 EmitTargetMultiVersionResolver(llvm::Function *Resolver, ArrayRef< TargetMultiVersionResolverOption > Options)
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...
llvm::LLVMContext & getLLVMContext()
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
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
Decl - This represents one declaration (or definition), e.g.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
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.
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.
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...
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...
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 ...
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.
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...
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
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, 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.
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
StructorType getFromDtorType(CXXDtorType T)
void startDefinition()
Starts the definition of this tag declaration.
bool isReferenceType() const
SanitizerMask Mask
Bitmask of enabled sanitizers.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
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
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...
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 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.
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)
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.
void AddELFLibDirective(StringRef Lib)
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.
The iOS ABI is a partial implementation of the ARM ABI.
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.
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
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
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.
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
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
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
Exposes information about the current target.
void SetLLVMFunctionAttributes(const Decl *D, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
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.
Pepresents 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 ...
Expr - 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...
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...
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)
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)
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.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, raw_ostream &Out)
CXXMethodDecl * getMethodDecl() const
Retrieves 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
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.
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
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::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage)
Will return a global variable of the given type.
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.
SourceLocation getLocStart() const LLVM_READONLY
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)
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.
virtual bool shouldMangleStringLiteral(const StringLiteral *SL)=0
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.
SourceLocation getLocStart() const LLVM_READONLY
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
llvm::IntegerType * Int16Ty
const Decl * getDecl() const
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
ParsedAttr - Represents a syntactic attribute.
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
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.
llvm::Constant * CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList())
Create a new compiler builtin function with the specified type and name.
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.
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.
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.
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
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
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.
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
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
Returns 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.
virtual void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags)=0
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...
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...
StructorType getFromCtorType(CXXCtorType T)
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)
llvm::Type * ConvertFunctionType(QualType FT, const FunctionDecl *FD=nullptr)
Converts the GlobalDecl into an llvm::Type.
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.
virtual unsigned multiVersionSortPriority(StringRef Name) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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 EmitCPUDispatchMultiVersionResolver(llvm::Function *Resolver, ArrayRef< CPUDispatchMultiVersionResolverOption > Options)
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)
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
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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).
TranslationUnitDecl * getTranslationUnitDecl() const
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
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.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
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.
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...
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
__DEVICE__ int max(int __a, int __b)
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()
static uint32_t GetX86CpuSupportsMask(ArrayRef< StringRef > FeatureStrs)
GVALinkage
A more specific kind of linkage than enum Linkage.
bool isPointerType() const
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)
void setGlobalVisibilityAndLocal(llvm::GlobalValue *GV, const NamedDecl *D) const
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 "llvm.linker.options" 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...
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