;
79using namespaceCodeGen;
82 "limited-coverage-experimental", llvm::cl::Hidden,
83llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
89 caseTargetCXXABI::AppleARM64:
90 caseTargetCXXABI::Fuchsia:
91 caseTargetCXXABI::GenericAArch64:
92 caseTargetCXXABI::GenericARM:
93 caseTargetCXXABI::iOS:
94 caseTargetCXXABI::WatchOS:
95 caseTargetCXXABI::GenericMIPS:
96 caseTargetCXXABI::GenericItanium:
97 caseTargetCXXABI::WebAssembly:
98 caseTargetCXXABI::XL:
100 caseTargetCXXABI::Microsoft:
104llvm_unreachable(
"invalid C++ ABI kind");
107staticstd::unique_ptr<TargetCodeGenInfo>
113 switch(Triple.getArch()) {
117 casellvm::Triple::m68k:
119 casellvm::Triple::mips:
120 casellvm::Triple::mipsel:
121 if(Triple.getOS() == llvm::Triple::NaCl)
123 else if(Triple.getOS() == llvm::Triple::Win32)
127 casellvm::Triple::mips64:
128 casellvm::Triple::mips64el:
131 casellvm::Triple::avr: {
135 unsignedNPR =
Target.getABI() ==
"avrtiny"? 6 : 18;
136 unsignedNRR =
Target.getABI() ==
"avrtiny"? 4 : 8;
140 casellvm::Triple::aarch64:
141 casellvm::Triple::aarch64_32:
142 casellvm::Triple::aarch64_be: {
144 if(
Target.getABI() ==
"darwinpcs")
145Kind = AArch64ABIKind::DarwinPCS;
146 else if(Triple.isOSWindows())
148 else if(
Target.getABI() ==
"aapcs-soft")
149Kind = AArch64ABIKind::AAPCSSoft;
150 else if(
Target.getABI() ==
"pauthtest")
151Kind = AArch64ABIKind::PAuthTest;
156 casellvm::Triple::wasm32:
157 casellvm::Triple::wasm64: {
159 if(
Target.getABI() ==
"experimental-mv")
160Kind = WebAssemblyABIKind::ExperimentalMV;
164 casellvm::Triple::arm:
165 casellvm::Triple::armeb:
166 casellvm::Triple::thumb:
167 casellvm::Triple::thumbeb: {
168 if(Triple.getOS() == llvm::Triple::Win32)
172StringRef ABIStr =
Target.getABI();
173 if(ABIStr ==
"apcs-gnu")
174Kind = ARMABIKind::APCS;
175 else if(ABIStr ==
"aapcs16")
176Kind = ARMABIKind::AAPCS16_VFP;
177 else if(CodeGenOpts.
FloatABI==
"hard"||
178(CodeGenOpts.
FloatABI!=
"soft"&& Triple.isHardFloatABI()))
179Kind = ARMABIKind::AAPCS_VFP;
184 casellvm::Triple::ppc: {
185 if(Triple.isOSAIX())
192 casellvm::Triple::ppcle: {
193 boolIsSoftFloat = CodeGenOpts.
FloatABI==
"soft";
196 casellvm::Triple::ppc64:
197 if(Triple.isOSAIX())
200 if(Triple.isOSBinFormatELF()) {
202 if(
Target.getABI() ==
"elfv2")
203Kind = PPC64_SVR4_ABIKind::ELFv2;
204 boolIsSoftFloat = CodeGenOpts.
FloatABI==
"soft";
209 casellvm::Triple::ppc64le: {
210assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
212 if(
Target.getABI() ==
"elfv1")
213Kind = PPC64_SVR4_ABIKind::ELFv1;
214 boolIsSoftFloat = CodeGenOpts.
FloatABI==
"soft";
219 casellvm::Triple::nvptx:
220 casellvm::Triple::nvptx64:
223 casellvm::Triple::msp430:
226 casellvm::Triple::riscv32:
227 casellvm::Triple::riscv64: {
228StringRef ABIStr =
Target.getABI();
229 unsignedXLen =
Target.getPointerWidth(LangAS::Default);
230 unsignedABIFLen = 0;
231 if(ABIStr.ends_with(
"f"))
233 else if(ABIStr.ends_with(
"d"))
235 boolEABI = ABIStr.ends_with(
"e");
239 casellvm::Triple::systemz: {
240 boolSoftFloat = CodeGenOpts.
FloatABI==
"soft";
241 boolHasVector = !SoftFloat &&
Target.getABI() ==
"vector";
245 casellvm::Triple::tce:
246 casellvm::Triple::tcele:
249 casellvm::Triple::x86: {
250 boolIsDarwinVectorABI = Triple.isOSDarwin();
251 boolIsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
253 if(Triple.getOS() == llvm::Triple::Win32) {
255CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
256CodeGenOpts.NumRegisterParameters);
259CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
260CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI==
"soft");
263 casellvm::Triple::x86_64: {
264StringRef ABI =
Target.getABI();
265 X86AVXABILevelAVXLevel = (ABI ==
"avx512"? X86AVXABILevel::AVX512
266: ABI ==
"avx"? X86AVXABILevel::AVX
267: X86AVXABILevel::None);
269 switch(Triple.getOS()) {
270 casellvm::Triple::Win32:
276 casellvm::Triple::hexagon:
278 casellvm::Triple::lanai:
280 casellvm::Triple::r600:
282 casellvm::Triple::amdgcn:
284 casellvm::Triple::sparc:
286 casellvm::Triple::sparcv9:
288 casellvm::Triple::xcore:
290 casellvm::Triple::arc:
292 casellvm::Triple::spir:
293 casellvm::Triple::spir64:
295 casellvm::Triple::spirv32:
296 casellvm::Triple::spirv64:
297 casellvm::Triple::spirv:
299 casellvm::Triple::dxil:
301 casellvm::Triple::ve:
303 casellvm::Triple::csky: {
304 boolIsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
306 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
311 casellvm::Triple::bpfeb:
312 casellvm::Triple::bpfel:
314 casellvm::Triple::loongarch32:
315 casellvm::Triple::loongarch64: {
316StringRef ABIStr =
Target.getABI();
317 unsignedABIFRLen = 0;
318 if(ABIStr.ends_with(
"f"))
320 else if(ABIStr.ends_with(
"d"))
323CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
329 if(!TheTargetCodeGenInfo)
331 return*TheTargetCodeGenInfo;
341: Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
342PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
344VMContext(M.getContext()), VTables(*this), StackHandler(diags),
349llvm::LLVMContext &LLVMContext = M.getContext();
350 VoidTy= llvm::Type::getVoidTy(LLVMContext);
351 Int8Ty= llvm::Type::getInt8Ty(LLVMContext);
352 Int16Ty= llvm::Type::getInt16Ty(LLVMContext);
353 Int32Ty= llvm::Type::getInt32Ty(LLVMContext);
354 Int64Ty= llvm::Type::getInt64Ty(LLVMContext);
355 HalfTy= llvm::Type::getHalfTy(LLVMContext);
356 BFloatTy= llvm::Type::getBFloatTy(LLVMContext);
357 FloatTy= llvm::Type::getFloatTy(LLVMContext);
358 DoubleTy= llvm::Type::getDoubleTy(LLVMContext);
364 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
366 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
368llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
369 IntTy= llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
370 IntPtrTy= llvm::IntegerType::get(LLVMContext,
371 C.getTargetInfo().getMaxPointerWidth());
372 Int8PtrTy= llvm::PointerType::get(LLVMContext,
374 constllvm::DataLayout &DL = M.getDataLayout();
376llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
378llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
395createOpenCLRuntime();
397createOpenMPRuntime();
404 if(LangOpts.
Sanitize.
hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
405(!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
411 if(CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
416Block.GlobalUniqueCount = 0;
418 if(
C.getLangOpts().ObjC)
422 autoReaderOrErr = llvm::IndexedInstrProfReader::create(
429PGOReader = std::move(ReaderOrErr.get());
434 if(CodeGenOpts.CoverageMapping)
438 if(CodeGenOpts.UniqueInternalLinkageNames &&
439!
getModule().getSourceFileName().empty()) {
443 if(
Path.rfind(Entry.first, 0) != std::string::npos) {
444 Path= Entry.second +
Path.substr(Entry.first.size());
447ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(
Path);
452 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
453CodeGenOpts.NumRegisterParameters);
458voidCodeGenModule::createObjCRuntime() {
475llvm_unreachable(
"bad runtime kind");
478voidCodeGenModule::createOpenCLRuntime() {
482voidCodeGenModule::createOpenMPRuntime() {
486 casellvm::Triple::nvptx:
487 casellvm::Triple::nvptx64:
488 casellvm::Triple::amdgcn:
490 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
494 if(LangOpts.OpenMPSimd)
502voidCodeGenModule::createCUDARuntime() {
506voidCodeGenModule::createHLSLRuntime() {
511Replacements[Name] =
C;
514voidCodeGenModule::applyReplacements() {
515 for(
auto&I : Replacements) {
516StringRef MangledName = I.first;
517llvm::Constant *Replacement = I.second;
521 auto*OldF = cast<llvm::Function>(Entry);
522 auto*NewF = dyn_cast<llvm::Function>(Replacement);
524 if(
auto*Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
525NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
527 auto*CE = cast<llvm::ConstantExpr>(Replacement);
528assert(CE->getOpcode() == llvm::Instruction::BitCast ||
529CE->getOpcode() == llvm::Instruction::GetElementPtr);
530NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
535OldF->replaceAllUsesWith(Replacement);
537NewF->removeFromParent();
538OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
541OldF->eraseFromParent();
546GlobalValReplacements.push_back(std::make_pair(GV,
C));
549voidCodeGenModule::applyGlobalValReplacements() {
550 for(
auto&I : GlobalValReplacements) {
551llvm::GlobalValue *GV = I.first;
552llvm::Constant *
C= I.second;
554GV->replaceAllUsesWith(
C);
555GV->eraseFromParent();
562 constllvm::Constant *
C;
563 if(
auto*GA = dyn_cast<llvm::GlobalAlias>(GV))
564 C= GA->getAliasee();
565 else if(
auto*GI = dyn_cast<llvm::GlobalIFunc>(GV))
566 C= GI->getResolver();
570 const auto*AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
574 constllvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
583 boolIsIFunc,
constllvm::GlobalValue *Alias,
constllvm::GlobalValue *&GV,
584 constllvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
588Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
592 if(GV->hasCommonLinkage()) {
594 if(Triple.getObjectFormat() == llvm::Triple::XCOFF) {
595Diags.
Report(Location, diag::err_alias_to_common);
600 if(GV->isDeclaration()) {
601Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
602Diags.
Report(Location, diag::note_alias_requires_mangled_name)
603<< IsIFunc << IsIFunc;
606 for(
const auto&[
Decl, Name] : MangledDeclNames) {
607 if(
const auto*ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
609 if(II && II->
getName() == GV->getName()) {
610Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
614(Twine(IsIFunc ?
"ifunc":
"alias") +
"(\""+ Name +
"\")")
624 const auto*F = dyn_cast<llvm::Function>(GV);
626Diags.
Report(Location, diag::err_alias_to_undefined)
627<< IsIFunc << IsIFunc;
631llvm::FunctionType *FTy = F->getFunctionType();
632 if(!FTy->getReturnType()->isPointerTy()) {
633Diags.
Report(Location, diag::err_ifunc_resolver_return);
647 if(GVar->hasAttribute(
"toc-data")) {
648 autoGVId = GVar->getName();
651Diags.
Report(Location, diag::warn_toc_unsupported_type)
652<< GVId <<
"the variable has an alias";
654llvm::AttributeSet CurrAttributes = GVar->getAttributes();
655llvm::AttributeSet NewAttributes =
656CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
657GVar->setAttributes(NewAttributes);
661voidCodeGenModule::checkAliases() {
668 const auto*
D= cast<ValueDecl>(GD.getDecl());
671 boolIsIFunc =
D->
hasAttr<IFuncAttr>();
673Location = A->getLocation();
674 Range= A->getRange();
676llvm_unreachable(
"Not an alias or ifunc?");
680 constllvm::GlobalValue *GV =
nullptr;
682MangledDeclNames,
Range)) {
688 if(
constllvm::GlobalVariable *GVar =
689dyn_cast<const llvm::GlobalVariable>(GV))
693llvm::Constant *Aliasee =
694IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
695: cast<llvm::GlobalAlias>(Alias)->getAliasee();
697llvm::GlobalValue *AliaseeGV;
698 if(
autoCE = dyn_cast<llvm::ConstantExpr>(Aliasee))
699AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
701AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
703 if(
constSectionAttr *SA =
D->
getAttr<SectionAttr>()) {
704StringRef AliasSection = SA->getName();
705 if(AliasSection != AliaseeGV->getSection())
706Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
707<< AliasSection << IsIFunc << IsIFunc;
715 if(
auto*GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
716 if(GA->isInterposable()) {
717Diags.
Report(Location, diag::warn_alias_to_weak_alias)
718<< GV->getName() << GA->getName() << IsIFunc;
719Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
720GA->getAliasee(), Alias->getType());
723cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
725cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
731cast<llvm::Function>(Aliasee)->addFnAttr(
732llvm::Attribute::DisableSanitizerInstrumentation);
740Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
741Alias->eraseFromParent();
746DeferredDeclsToEmit.clear();
747EmittedDeferredDecls.clear();
748DeferredAnnotations.clear();
750OpenMPRuntime->clear();
754StringRef MainFile) {
757 if(VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
758 if(MainFile.empty())
759MainFile =
"<stdin>";
760Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
763Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
766Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
770staticstd::optional<llvm::GlobalValue::VisibilityTypes>
777 returnllvm::GlobalValue::DefaultVisibility;
779 returnllvm::GlobalValue::HiddenVisibility;
781 returnllvm::GlobalValue::ProtectedVisibility;
783llvm_unreachable(
"unknown option value!");
788std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
797GV.setDSOLocal(
false);
798GV.setVisibility(*
V);
803 if(!LO.VisibilityFromDLLStorageClass)
806std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
809std::optional<llvm::GlobalValue::VisibilityTypes>
810NoDLLStorageClassVisibility =
813std::optional<llvm::GlobalValue::VisibilityTypes>
814ExternDeclDLLImportVisibility =
817std::optional<llvm::GlobalValue::VisibilityTypes>
818ExternDeclNoDLLStorageClassVisibility =
821 for(llvm::GlobalValue &GV : M.global_values()) {
822 if(GV.hasAppendingLinkage() || GV.hasLocalLinkage())
825 if(GV.isDeclarationForLinker())
827llvm::GlobalValue::DLLImportStorageClass
828? ExternDeclDLLImportVisibility
829: ExternDeclNoDLLStorageClassVisibility);
832llvm::GlobalValue::DLLExportStorageClass
833? DLLExportVisibility
834: NoDLLStorageClassVisibility);
836GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
841 constllvm::Triple &Triple,
843 if(Triple.isAMDGPU() || Triple.isNVPTX())
845 returnLangOpts.getStackProtector() == Mode;
851EmitModuleInitializers(Primary);
853DeferredDecls.insert(EmittedDeferredDecls.begin(),
854EmittedDeferredDecls.end());
855EmittedDeferredDecls.clear();
856EmitVTablesOpportunistically();
857applyGlobalValReplacements();
859emitMultiVersionFunctions();
861 if(Context.
getLangOpts().IncrementalExtensions &&
862GlobalTopLevelStmtBlockInFlight.first) {
864GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
865GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
871EmitCXXModuleInitFunc(Primary);
873EmitCXXGlobalInitFunc();
874EmitCXXGlobalCleanUpFunc();
875registerGlobalDtorsWithAtExit();
876EmitCXXThreadLocalInitFunc();
878 if(llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
881 if(llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
885OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
886OpenMPRuntime->clear();
890PGOReader->getSummary(
false).getMD(VMContext),
891llvm::ProfileSummary::PSK_Instr);
898EmitCtorList(GlobalCtors,
"llvm.global_ctors");
899EmitCtorList(GlobalDtors,
"llvm.global_dtors");
901EmitStaticExternCAliases();
907CoverageMapping->emit();
908 if(CodeGenOpts.SanitizeCfiCrossDso) {
912 if(LangOpts.
Sanitize.
has(SanitizerKind::KCFI))
914emitAtAvailableLinkGuard();
922 if(
getTarget().getTargetOpts().CodeObjectVersion !=
923llvm::CodeObjectVersionKind::COV_None) {
924 getModule().addModuleFlag(llvm::Module::Error,
925 "amdhsa_code_object_version",
926 getTarget().getTargetOpts().CodeObjectVersion);
931 auto*MDStr = llvm::MDString::get(
936 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
949 if(
auto*FD = dyn_cast<FunctionDecl>(
D))
953UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
957llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
959 auto*GV =
newllvm::GlobalVariable(
960 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
961llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
964 if(LangOpts.HIP && !
getLangOpts().OffloadingNewDriver) {
967 auto*GV =
newllvm::GlobalVariable(
969llvm::Constant::getNullValue(
Int8Ty),
977 if(CodeGenOpts.Autolink &&
978(Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
979EmitModuleLinkOptions();
994 if(!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
995 auto*NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
996 for(
auto*MD : ELFDependentLibraries)
1000 if(CodeGenOpts.DwarfVersion) {
1001 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1002CodeGenOpts.DwarfVersion);
1005 if(CodeGenOpts.Dwarf64)
1006 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1008 if(Context.
getLangOpts().SemanticInterposition)
1010 getModule().setSemanticInterposition(
true);
1012 if(CodeGenOpts.EmitCodeView) {
1014 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1016 if(CodeGenOpts.CodeViewGHash) {
1017 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1019 if(CodeGenOpts.ControlFlowGuard) {
1021 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1022}
else if(CodeGenOpts.ControlFlowGuardNoChecks) {
1024 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1026 if(CodeGenOpts.EHContGuard) {
1028 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1032 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1034 if(CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1039 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1041llvm::Metadata *Ops[2] = {
1042llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1043llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1044llvm::Type::getInt32Ty(VMContext), 1))};
1046 getModule().addModuleFlag(llvm::Module::Require,
1047 "StrictVTablePointersRequirement",
1048llvm::MDNode::get(VMContext, Ops));
1054 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1055llvm::DEBUG_METADATA_VERSION);
1060uint64_t WCharWidth =
1062 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1065 getModule().addModuleFlag(llvm::Module::Warning,
1066 "zos_product_major_version",
1067uint32_t(CLANG_VERSION_MAJOR));
1068 getModule().addModuleFlag(llvm::Module::Warning,
1069 "zos_product_minor_version",
1070uint32_t(CLANG_VERSION_MINOR));
1071 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1072uint32_t(CLANG_VERSION_PATCHLEVEL));
1074 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1075llvm::MDString::get(VMContext, ProductId));
1080 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1081llvm::MDString::get(VMContext, lang_str));
1085: std::time(
nullptr);
1086 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1087 static_cast<uint64_t
>(TT));
1090 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1091llvm::MDString::get(VMContext,
"ascii"));
1095 if(
T.isARM() ||
T.isThumb()) {
1097uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1098 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1101 if(
T.isRISCV()) {
1102StringRef ABIStr =
Target.getABI();
1103llvm::LLVMContext &Ctx = TheModule.getContext();
1104 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1105llvm::MDString::get(Ctx, ABIStr));
1110 conststd::vector<std::string> &Features =
1113llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1114 if(!errorToBool(ParseResult.takeError()))
1116llvm::Module::AppendUnique,
"riscv-isa",
1118Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1121 if(CodeGenOpts.SanitizeCfiCrossDso) {
1123 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1126 if(CodeGenOpts.WholeProgramVTables) {
1130 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1131CodeGenOpts.VirtualFunctionElimination);
1134 if(LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1135 getModule().addModuleFlag(llvm::Module::Override,
1136 "CFI Canonical Jump Tables",
1137CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1140 if(CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1141 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1145 if(LangOpts.
Sanitize.
has(SanitizerKind::KCFI)) {
1146 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1149 if(CodeGenOpts.PatchableFunctionEntryOffset)
1150 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1151CodeGenOpts.PatchableFunctionEntryOffset);
1154 if(CodeGenOpts.CFProtectionReturn &&
1157 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1161 if(CodeGenOpts.CFProtectionBranch &&
1164 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1167 autoScheme = CodeGenOpts.getCFBranchLabelScheme();
1168 if(
Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1170Scheme =
Target.getDefaultCFBranchLabelScheme();
1172llvm::Module::Error,
"cf-branch-label-scheme",
1178 if(CodeGenOpts.FunctionReturnThunks)
1179 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1181 if(CodeGenOpts.IndirectBranchCSPrefix)
1182 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1194LangOpts.getSignReturnAddressScope() !=
1196 getModule().addModuleFlag(llvm::Module::Override,
1197 "sign-return-address-buildattr", 1);
1198 if(LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1199 getModule().addModuleFlag(llvm::Module::Override,
1200 "tag-stack-memory-buildattr", 1);
1202 if(
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1203 if(LangOpts.BranchTargetEnforcement)
1204 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1206 if(LangOpts.BranchProtectionPAuthLR)
1207 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1209 if(LangOpts.GuardedControlStack)
1210 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1212 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1214 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1217 getModule().addModuleFlag(llvm::Module::Min,
1218 "sign-return-address-with-bkey", 1);
1220 if(LangOpts.PointerAuthELFGOT)
1221 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1224 if(LangOpts.PointerAuthCalls)
1225 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1227assert(
getTriple().isOSBinFormatELF());
1228 using namespacellvm::ELF;
1229uint64_t PAuthABIVersion =
1230(LangOpts.PointerAuthIntrinsics
1231<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1232(LangOpts.PointerAuthCalls
1233<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1234(LangOpts.PointerAuthReturns
1235<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1236(LangOpts.PointerAuthAuthTraps
1237<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1238(LangOpts.PointerAuthVTPtrAddressDiscrimination
1239<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1240(LangOpts.PointerAuthVTPtrTypeDiscrimination
1241<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1242(LangOpts.PointerAuthInitFini
1243<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1244(LangOpts.PointerAuthInitFiniAddressDiscrimination
1245<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1246(LangOpts.PointerAuthELFGOT
1247<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1248(LangOpts.PointerAuthIndirectGotos
1249<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1250(LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1251<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1252(LangOpts.PointerAuthFunctionTypeDiscrimination
1253<< AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1254 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1255AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1256 "Update when new enum items are defined");
1257 if(PAuthABIVersion != 0) {
1258 getModule().addModuleFlag(llvm::Module::Error,
1259 "aarch64-elf-pauthabi-platform",
1260AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1261 getModule().addModuleFlag(llvm::Module::Error,
1262 "aarch64-elf-pauthabi-version",
1268 if(CodeGenOpts.StackClashProtector)
1270llvm::Module::Override,
"probe-stack",
1271llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1273 if(CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1274 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1275CodeGenOpts.StackProbeSize);
1278llvm::LLVMContext &Ctx = TheModule.getContext();
1280llvm::Module::Error,
"MemProfProfileFilename",
1284 if(LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1288 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1290llvm::DenormalMode::IEEE);
1293 if(LangOpts.EHAsynch)
1294 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1297 if(CodeGenOpts.ImportCallOptimization)
1298 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1303 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1305 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1309 if(LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1310EmitOpenCLMetadata();
1318llvm::Metadata *SPIRVerElts[] = {
1319llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1321llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1322 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1323llvm::NamedMDNode *SPIRVerMD =
1324TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1325llvm::LLVMContext &Ctx = TheModule.getContext();
1326SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1334 if(uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1335assert(PLevel < 3 &&
"Invalid PIC Level");
1336 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1338 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1342 unsignedCM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1343.Case(
"tiny", llvm::CodeModel::Tiny)
1344.Case(
"small", llvm::CodeModel::Small)
1345.Case(
"kernel", llvm::CodeModel::Kernel)
1346.Case(
"medium", llvm::CodeModel::Medium)
1347.Case(
"large", llvm::CodeModel::Large)
1350llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1353 if((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1355llvm::Triple::x86_64) {
1361 if(CodeGenOpts.NoPLT)
1364CodeGenOpts.DirectAccessExternalData !=
1365 getModule().getDirectAccessExternalData()) {
1366 getModule().setDirectAccessExternalData(
1367CodeGenOpts.DirectAccessExternalData);
1369 if(CodeGenOpts.UnwindTables)
1370 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1372 switch(CodeGenOpts.getFramePointer()) {
1377 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1380 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1383 getModule().setFramePointer(llvm::FramePointerKind::All);
1387SimplifyPersonality();
1400EmitVersionIdentMetadata();
1403EmitCommandLineMetadata();
1411 getModule().setStackProtectorGuardSymbol(
1414 getModule().setStackProtectorGuardOffset(
1419 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1421 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1423 if(
getContext().getTargetInfo().getMaxTLSAlign())
1424 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1425 getContext().getTargetInfo().getMaxTLSAlign());
1443 if(
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1444 for(
auto&I : MustTailCallUndefinedGlobals) {
1445 if(!I.first->isDefined())
1446 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1450 if(!Entry || Entry->isWeakForLinker() ||
1451Entry->isDeclarationForLinker())
1452 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1458voidCodeGenModule::EmitOpenCLMetadata() {
1464 autoEmitVersion = [
this](StringRef MDName,
intVersion) {
1465llvm::Metadata *OCLVerElts[] = {
1466llvm::ConstantAsMetadata::get(
1467llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1468llvm::ConstantAsMetadata::get(
1469llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1470llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1471llvm::LLVMContext &Ctx = TheModule.getContext();
1472OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1475EmitVersion(
"opencl.ocl.version", CLVersion);
1476 if(LangOpts.OpenCLCPlusPlus) {
1478EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1482voidCodeGenModule::EmitBackendOptionsMetadata(
1485 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1486CodeGenOpts.SmallDataLimit);
1503 returnTBAA->getTypeInfo(QTy);
1522 returnTBAA->getAccessInfo(AccessType);
1529 returnTBAA->getVTablePtrAccessInfo(VTablePtrType);
1535 returnTBAA->getTBAAStructInfo(QTy);
1541 returnTBAA->getBaseTypeInfo(QTy);
1547 returnTBAA->getAccessTagInfo(Info);
1554 returnTBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1562 returnTBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1570 returnTBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1576Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1581I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1594 "cannot compile this %0 yet");
1595std::string Msg =
Type;
1597<< Msg << S->getSourceRange();
1604 "cannot compile this %0 yet");
1605std::string Msg =
Type;
1610llvm::function_ref<
void()> Fn) {
1621 if(GV->hasLocalLinkage()) {
1622GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1636Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(
D) &&
1637 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1638 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1639OMPDeclareTargetDeclAttr::DT_NoHost &&
1641GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1645 if(GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1649 if(GV->hasDLLExportStorageClass()) {
1652diag::err_hidden_visibility_dllexport);
1655diag::err_non_default_visibility_dllimport);
1661!GV->isDeclarationForLinker())
1666llvm::GlobalValue *GV) {
1667 if(GV->hasLocalLinkage())
1670 if(!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1674 if(GV->hasDLLImportStorageClass())
1677 constllvm::Triple &TT = CGM.
getTriple();
1679 if(TT.isWindowsGNUEnvironment()) {
1688 if(GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1697 if(TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1705 if(TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1709 if(!TT.isOSBinFormatELF())
1715 if(RM != llvm::Reloc::Static && !LOpts.PIE) {
1721 if(!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1723 return!(CGM.
getLangOpts().SemanticInterposition ||
1728 if(!GV->isDeclarationForLinker())
1734 if(RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1741 if(CGOpts.DirectAccessExternalData) {
1747 if(
auto*Var = dyn_cast<llvm::GlobalVariable>(GV))
1748 if(!Var->isThreadLocal())
1757 if(isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1773 const auto*
D= dyn_cast<NamedDecl>(GD.
getDecl());
1775 if(
const auto*Dtor = dyn_cast_or_null<CXXDestructorDecl>(
D)) {
1784 if(
D&&
D->isExternallyVisible()) {
1785 if(
D->
hasAttr<DLLImportAttr>())
1786GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1787 else if((
D->
hasAttr<DLLExportAttr>() ||
1789!GV->isDeclarationForLinker())
1790GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1814 returnllvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1815.Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1816.Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1817.Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1818.Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1821llvm::GlobalVariable::ThreadLocalMode
1823 switch(CodeGenOpts.getDefaultTLSModel()) {
1825 returnllvm::GlobalVariable::GeneralDynamicTLSModel;
1827 returnllvm::GlobalVariable::LocalDynamicTLSModel;
1829 returnllvm::GlobalVariable::InitialExecTLSModel;
1831 returnllvm::GlobalVariable::LocalExecTLSModel;
1833llvm_unreachable(
"Invalid TLS model!");
1837assert(
D.getTLSKind() &&
"setting TLS mode on non-TLS var!");
1839llvm::GlobalValue::ThreadLocalMode TLM;
1843 if(
constTLSModelAttr *
Attr=
D.
getAttr<TLSModelAttr>()) {
1847GV->setThreadLocalMode(TLM);
1853 return(Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1857 constCPUSpecificAttr *
Attr,
1865Out <<
".resolver";
1879 boolOmitMultiVersionMangling =
false) {
1881llvm::raw_svector_ostream Out(Buffer);
1890assert(II &&
"Attempt to mangle unnamed decl.");
1891 const auto*FD = dyn_cast<FunctionDecl>(ND);
1896Out <<
"__regcall4__"<< II->
getName();
1898Out <<
"__regcall3__"<< II->
getName();
1899}
else if(FD && FD->hasAttr<CUDAGlobalAttr>() &&
1901Out <<
"__device_stub__"<< II->
getName();
1917 "Hash computed when not explicitly requested");
1921 if(
const auto*FD = dyn_cast<FunctionDecl>(ND))
1922 if(FD->isMultiVersion() && !OmitMultiVersionMangling) {
1923 switch(FD->getMultiVersionKind()) {
1927FD->getAttr<CPUSpecificAttr>(),
1931 auto*
Attr= FD->getAttr<TargetAttr>();
1932assert(
Attr&&
"Expected TargetAttr to be present " 1933 "for attribute mangling");
1939 auto*
Attr= FD->getAttr<TargetVersionAttr>();
1940assert(
Attr&&
"Expected TargetVersionAttr to be present " 1941 "for attribute mangling");
1947 auto*
Attr= FD->getAttr<TargetClonesAttr>();
1948assert(
Attr&&
"Expected TargetClonesAttr to be present " 1949 "for attribute mangling");
1956llvm_unreachable(
"None multiversion type isn't valid here");
1966 returnstd::string(Out.str());
1969voidCodeGenModule::UpdateMultiVersionNames(
GlobalDeclGD,
1971StringRef &CurName) {
1978std::string NonTargetName =
1986 "Other GD should now be a multiversioned function");
1996 if(OtherName != NonTargetName) {
1999 const autoExistingRecord = Manglings.find(NonTargetName);
2000 if(ExistingRecord != std::end(Manglings))
2001Manglings.remove(&(*ExistingRecord));
2002 auto Result= Manglings.insert(std::make_pair(OtherName, OtherGD));
2007CurName = OtherNameRef;
2009Entry->setName(OtherName);
2019 if(
const auto*CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2033 autoFoundName = MangledDeclNames.find(CanonicalGD);
2034 if(FoundName != MangledDeclNames.end())
2035 returnFoundName->second;
2039 const auto*ND = cast<NamedDecl>(GD.
getDecl());
2051assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2071 auto Result= Manglings.insert(std::make_pair(MangledName, GD));
2072 returnMangledDeclNames[CanonicalGD] =
Result.first->first();
2081llvm::raw_svector_ostream Out(Buffer);
2084dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
2085 else if(
const auto*CD = dyn_cast<CXXConstructorDecl>(
D))
2087 else if(
const auto*DD = dyn_cast<CXXDestructorDecl>(
D))
2090MangleCtx.
mangleBlock(cast<DeclContext>(
D), BD, Out);
2092 auto Result= Manglings.insert(std::make_pair(Out.str(), BD));
2093 return Result.first->first();
2097 autoit = MangledDeclNames.begin();
2098 while(it != MangledDeclNames.end()) {
2099 if(it->second == Name)
2107 return getModule().getNamedValue(Name);
2114llvm::Constant *AssociatedData) {
2116GlobalCtors.push_back(
Structor(
Priority, LexOrder, Ctor, AssociatedData));
2122 boolIsDtorAttrFunc) {
2123 if(CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2125DtorsUsingAtExit[
Priority].push_back(Dtor);
2133voidCodeGenModule::EmitCtorList(CtorList &Fns,
const char*GlobalName) {
2134 if(Fns.empty())
return;
2140llvm::PointerType *PtrTy = llvm::PointerType::get(
2141 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2144llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2148 autoCtors = Builder.beginArray(CtorStructTy);
2149 for(
const auto&I : Fns) {
2150 autoCtor = Ctors.beginStruct(CtorStructTy);
2151Ctor.addInt(
Int32Ty, I.Priority);
2152 if(InitFiniAuthSchema) {
2153llvm::Constant *StorageAddress =
2155? llvm::ConstantExpr::getIntToPtr(
2156llvm::ConstantInt::get(
2158llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2162I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2163llvm::ConstantInt::get(
2165Ctor.add(SignedCtorPtr);
2167Ctor.add(I.Initializer);
2169 if(I.AssociatedData)
2170Ctor.add(I.AssociatedData);
2172Ctor.addNullPointer(PtrTy);
2173Ctor.finishAndAddTo(Ctors);
2176 autoList = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2178llvm::GlobalValue::AppendingLinkage);
2182List->setAlignment(std::nullopt);
2187llvm::GlobalValue::LinkageTypes
2189 const auto*
D= cast<FunctionDecl>(GD.
getDecl());
2193 if(
const auto*Dtor = dyn_cast<CXXDestructorDecl>(
D))
2200llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2201 if(!MDS)
return nullptr;
2203 returnllvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2209FnType->getReturnType(), FnType->getParamTypes(),
2210FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2212std::string OutName;
2213llvm::raw_string_ostream Out(OutName);
2218Out <<
".normalized";
2220 returnllvm::ConstantInt::get(
Int32Ty,
2221 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2226llvm::Function *F,
boolIsThunk) {
2228llvm::AttributeList PAL;
2231 if(
CallingConv== llvm::CallingConv::X86_VectorCall &&
2237Error(
Loc,
"__vectorcall calling convention is not currently supported");
2239F->setAttributes(PAL);
2240F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2244std::string ReadOnlyQual(
"__read_only");
2245std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2246 if(ReadOnlyPos != std::string::npos)
2248TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2250std::string WriteOnlyQual(
"__write_only");
2251std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2252 if(WriteOnlyPos != std::string::npos)
2253TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2255std::string ReadWriteQual(
"__read_write");
2256std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2257 if(ReadWritePos != std::string::npos)
2258TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2291assert(((FD && CGF) || (!FD && !CGF)) &&
2292 "Incorrect use - FD and CGF should either be both null or not!");
2318 for(
unsignedi = 0, e = FD->
getNumParams(); i != e; ++i) {
2321argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2326std::string typeQuals;
2330 const Decl*PDecl = parm;
2332PDecl = TD->getDecl();
2333 constOpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2334 if(A && A->isWriteOnly())
2335accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2336 else if(A && A->isReadWrite())
2337accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2339accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2341accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2343 autogetTypeSpelling = [&](
QualTypeTy) {
2344 autotypeName = Ty.getUnqualifiedType().getAsString(Policy);
2346 if(Ty.isCanonical()) {
2347StringRef typeNameRef = typeName;
2349 if(typeNameRef.consume_front(
"unsigned "))
2350 returnstd::string(
"u") + typeNameRef.str();
2351 if(typeNameRef.consume_front(
"signed "))
2352 returntypeNameRef.str();
2362addressQuals.push_back(
2363llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2367std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2368std::string baseTypeName =
2370argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2371argBaseTypeNames.push_back(
2372llvm::MDString::get(VMContext, baseTypeName));
2376typeQuals =
"restrict";
2379typeQuals += typeQuals.empty() ?
"const":
" const";
2381typeQuals += typeQuals.empty() ?
"volatile":
" volatile";
2383uint32_t AddrSpc = 0;
2388addressQuals.push_back(
2389llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2393std::string typeName = getTypeSpelling(ty);
2405argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2406argBaseTypeNames.push_back(
2407llvm::MDString::get(VMContext, baseTypeName));
2410typeQuals =
"pipe";
2412argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2416Fn->setMetadata(
"kernel_arg_addr_space",
2417llvm::MDNode::get(VMContext, addressQuals));
2418Fn->setMetadata(
"kernel_arg_access_qual",
2419llvm::MDNode::get(VMContext, accessQuals));
2420Fn->setMetadata(
"kernel_arg_type",
2421llvm::MDNode::get(VMContext, argTypeNames));
2422Fn->setMetadata(
"kernel_arg_base_type",
2423llvm::MDNode::get(VMContext, argBaseTypeNames));
2424Fn->setMetadata(
"kernel_arg_type_qual",
2425llvm::MDNode::get(VMContext, argTypeQuals));
2429Fn->setMetadata(
"kernel_arg_name",
2430llvm::MDNode::get(VMContext, argNames));
2440 if(!LangOpts.Exceptions)
return false;
2443 if(LangOpts.CXXExceptions)
return true;
2446 if(LangOpts.ObjCExceptions) {
2463!isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2468llvm::SetVector<const CXXRecordDecl *> MostBases;
2470std::function<void (
const CXXRecordDecl*)> CollectMostBases;
2473MostBases.insert(RD);
2475CollectMostBases(B.getType()->getAsCXXRecordDecl());
2477CollectMostBases(RD);
2478 returnMostBases.takeVector();
2482llvm::Function *F) {
2483llvm::AttrBuilder B(F->getContext());
2485 if((!
D|| !
D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2486B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2488 if(CodeGenOpts.StackClashProtector)
2489B.addAttribute(
"probe-stack",
"inline-asm");
2491 if(CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2492B.addAttribute(
"stack-probe-size",
2493std::to_string(CodeGenOpts.StackProbeSize));
2496B.addAttribute(llvm::Attribute::NoUnwind);
2498 if(
D&&
D->
hasAttr<NoStackProtectorAttr>())
2500 else if(
D&&
D->
hasAttr<StrictGuardStackCheckAttr>() &&
2502B.addAttribute(llvm::Attribute::StackProtectStrong);
2504B.addAttribute(llvm::Attribute::StackProtect);
2506B.addAttribute(llvm::Attribute::StackProtectStrong);
2508B.addAttribute(llvm::Attribute::StackProtectReq);
2512 if(
getLangOpts().
HLSL&& !F->hasFnAttribute(llvm::Attribute::NoInline))
2513B.addAttribute(llvm::Attribute::AlwaysInline);
2517 else if(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2519B.addAttribute(llvm::Attribute::NoInline);
2527 if(
D->
hasAttr<ArmLocallyStreamingAttr>())
2528B.addAttribute(
"aarch64_pstate_sm_body");
2531 if(
Attr->isNewZA())
2532B.addAttribute(
"aarch64_new_za");
2533 if(
Attr->isNewZT0())
2534B.addAttribute(
"aarch64_new_zt0");
2539 boolShouldAddOptNone =
2540!CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2542ShouldAddOptNone &= !
D->
hasAttr<MinSizeAttr>();
2543ShouldAddOptNone &= !
D->
hasAttr<AlwaysInlineAttr>();
2546 if(
getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2548B.addAttribute(llvm::Attribute::AlwaysInline);
2549}
else if((ShouldAddOptNone ||
D->
hasAttr<OptimizeNoneAttr>()) &&
2550!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2552B.addAttribute(llvm::Attribute::OptimizeNone);
2555B.addAttribute(llvm::Attribute::NoInline);
2560B.addAttribute(llvm::Attribute::Naked);
2563F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2564F->removeFnAttr(llvm::Attribute::MinSize);
2565}
else if(
D->
hasAttr<NakedAttr>()) {
2567B.addAttribute(llvm::Attribute::Naked);
2568B.addAttribute(llvm::Attribute::NoInline);
2569}
else if(
D->
hasAttr<NoDuplicateAttr>()) {
2570B.addAttribute(llvm::Attribute::NoDuplicate);
2571}
else if(
D->
hasAttr<NoInlineAttr>() &&
2572!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2574B.addAttribute(llvm::Attribute::NoInline);
2575}
else if(
D->
hasAttr<AlwaysInlineAttr>() &&
2576!F->hasFnAttribute(llvm::Attribute::NoInline)) {
2578B.addAttribute(llvm::Attribute::AlwaysInline);
2582 if(!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2583B.addAttribute(llvm::Attribute::NoInline);
2587 if(
auto*FD = dyn_cast<FunctionDecl>(
D)) {
2590 autoCheckRedeclForInline = [](
const FunctionDecl*Redecl) {
2591 returnRedecl->isInlineSpecified();
2593 if(any_of(FD->
redecls(), CheckRedeclForInline))
2598 returnany_of(Pattern->
redecls(), CheckRedeclForInline);
2600 if(CheckForInline(FD)) {
2601B.addAttribute(llvm::Attribute::InlineHint);
2602}
else if(CodeGenOpts.getInlining() ==
2605!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2606B.addAttribute(llvm::Attribute::NoInline);
2613 if(!
D->
hasAttr<OptimizeNoneAttr>()) {
2615 if(!ShouldAddOptNone)
2616B.addAttribute(llvm::Attribute::OptimizeForSize);
2617B.addAttribute(llvm::Attribute::Cold);
2620B.addAttribute(llvm::Attribute::Hot);
2622B.addAttribute(llvm::Attribute::MinSize);
2629F->setAlignment(llvm::Align(alignment));
2631 if(!
D->
hasAttr<AlignedAttr>())
2632 if(LangOpts.FunctionAlignment)
2633F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2640 if(isa<CXXMethodDecl>(
D) && F->getPointerAlignment(
getDataLayout()) < 2)
2641F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2646 if(CodeGenOpts.SanitizeCfiCrossDso &&
2647CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2648 if(
auto*FD = dyn_cast<FunctionDecl>(
D)) {
2659 auto*MD = dyn_cast<CXXMethodDecl>(
D);
2662llvm::Metadata *
Id=
2665F->addTypeMetadata(0,
Id);
2672 if(isa_and_nonnull<NamedDecl>(
D))
2675GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2680 if(
const auto*VD = dyn_cast_if_present<VarDecl>(
D);
2682((CodeGenOpts.KeepPersistentStorageVariables &&
2683(VD->getStorageDuration() ==
SD_Static||
2684VD->getStorageDuration() ==
SD_Thread)) ||
2685(CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static&&
2686VD->getType().isConstQualified())))
2690boolCodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDeclGD,
2691llvm::AttrBuilder &Attrs,
2692 boolSetTargetFeatures) {
2698std::vector<std::string> Features;
2699 const auto*FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2701 const auto*TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2702 const auto*TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2703assert((!TD || !TV) &&
"both target_version and target specified");
2704 const auto*SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2705 const auto*TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2706 boolAddedAttr =
false;
2707 if(TD || TV || SD || TC) {
2708llvm::StringMap<bool> FeatureMap;
2712 for(
constllvm::StringMap<bool>::value_type &Entry : FeatureMap)
2713Features.push_back((Entry.getValue() ?
"+":
"-") + Entry.getKey().str());
2721 Target.parseTargetAttr(TD->getFeaturesStr());
2743 if(!TargetCPU.empty()) {
2744Attrs.addAttribute(
"target-cpu", TargetCPU);
2747 if(!TuneCPU.empty()) {
2748Attrs.addAttribute(
"tune-cpu", TuneCPU);
2751 if(!Features.empty() && SetTargetFeatures) {
2752llvm::erase_if(Features, [&](
conststd::string& F) {
2755llvm::sort(Features);
2756Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2762 boolIsDefault =
false;
2764IsDefault = TV->isDefaultVersion();
2765TV->getFeatures(Feats);
2771Attrs.addAttribute(
"fmv-features");
2773}
else if(!Feats.empty()) {
2775std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
2776std::string FMVFeatures;
2777 for(StringRef F : OrderedFeats)
2778FMVFeatures.append(
","+ F.str());
2779Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
2786voidCodeGenModule::setNonAliasAttributes(
GlobalDeclGD,
2787llvm::GlobalObject *GO) {
2792 if(
auto*GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2795 if(
auto*SA =
D->
getAttr<PragmaClangBSSSectionAttr>())
2796GV->addAttribute(
"bss-section", SA->getName());
2797 if(
auto*SA =
D->
getAttr<PragmaClangDataSectionAttr>())
2798GV->addAttribute(
"data-section", SA->getName());
2799 if(
auto*SA =
D->
getAttr<PragmaClangRodataSectionAttr>())
2800GV->addAttribute(
"rodata-section", SA->getName());
2801 if(
auto*SA =
D->
getAttr<PragmaClangRelroSectionAttr>())
2802GV->addAttribute(
"relro-section", SA->getName());
2805 if(
auto*F = dyn_cast<llvm::Function>(GO)) {
2808 if(
auto*SA =
D->
getAttr<PragmaClangTextSectionAttr>())
2809 if(!
D->
getAttr<SectionAttr>())
2810F->setSection(SA->getName());
2812llvm::AttrBuilder Attrs(F->getContext());
2813 if(GetCPUAndFeaturesAttributes(GD, Attrs)) {
2817llvm::AttributeMask RemoveAttrs;
2818RemoveAttrs.addAttribute(
"target-cpu");
2819RemoveAttrs.addAttribute(
"target-features");
2820RemoveAttrs.addAttribute(
"fmv-features");
2821RemoveAttrs.addAttribute(
"tune-cpu");
2822F->removeFnAttrs(RemoveAttrs);
2823F->addFnAttrs(Attrs);
2827 if(
const auto*CSA =
D->
getAttr<CodeSegAttr>())
2828GO->setSection(CSA->getName());
2829 else if(
const auto*SA =
D->
getAttr<SectionAttr>())
2830GO->setSection(SA->getName());
2843F->setLinkage(llvm::Function::InternalLinkage);
2845setNonAliasAttributes(GD, F);
2856GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2860llvm::Function *F) {
2862 if(!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
2867 if(isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2871F->addTypeMetadata(0, MD);
2875 if(CodeGenOpts.SanitizeCfiCrossDso)
2877F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2881llvm::LLVMContext &Ctx = F->getContext();
2882llvm::MDBuilder MDB(Ctx);
2883F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2892 returnllvm::all_of(Name, [](
const char&
C) {
2893 returnllvm::isAlnum(
C) ||
C==
'_'||
C==
'.';
2899 for(
auto&F : M.functions()) {
2901 boolAddressTaken = F.hasAddressTaken();
2902 if(!AddressTaken && F.hasLocalLinkage())
2903F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2908 if(!AddressTaken || !F.isDeclaration())
2911 constllvm::ConstantInt *
Type;
2912 if(
constllvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2913 Type= llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2917StringRef Name = F.getName();
2921std::string
Asm= (
".weak __kcfi_typeid_"+ Name +
"\n.set __kcfi_typeid_"+
2922Name +
", "+ Twine(
Type->getZExtValue()) +
"\n")
2924M.appendModuleInlineAsm(
Asm);
2928voidCodeGenModule::SetFunctionAttributes(
GlobalDeclGD, llvm::Function *F,
2929 boolIsIncompleteFunction,
2932 if(llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2935F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
2939 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
2941 if(!IsIncompleteFunction)
2948 if(!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
2950assert(!F->arg_empty() &&
2951F->arg_begin()->getType()
2952->canLosslesslyBitCastTo(F->getReturnType()) &&
2953 "unexpected this return");
2954F->addParamAttr(0, llvm::Attribute::Returned);
2964 if(!IsIncompleteFunction && F->isDeclaration())
2967 if(
const auto*CSA = FD->
getAttr<CodeSegAttr>())
2968F->setSection(CSA->getName());
2969 else if(
const auto*SA = FD->
getAttr<SectionAttr>())
2970F->setSection(SA->getName());
2972 if(
const auto*EA = FD->
getAttr<ErrorAttr>()) {
2974F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
2975 else if(EA->isWarning())
2976F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
2982 boolHasBody = FD->
hasBody(FDBody);
2984assert(HasBody &&
"Inline builtin declarations should always have an " 2985 "available body!");
2986 if(shouldEmitFunction(FDBody))
2987F->addFnAttr(llvm::Attribute::NoBuiltin);
2993F->addFnAttr(llvm::Attribute::NoBuiltin);
2996 if(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2997F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2998 else if(
const auto*MD = dyn_cast<CXXMethodDecl>(FD))
2999 if(MD->isVirtual())
3000F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3006 if(!CodeGenOpts.SanitizeCfiCrossDso ||
3007!CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3010 if(LangOpts.
Sanitize.
has(SanitizerKind::KCFI))
3016 if(CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3017F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3019 if(
const auto*CB = FD->
getAttr<CallbackAttr>()) {
3023llvm::LLVMContext &Ctx = F->getContext();
3024llvm::MDBuilder MDB(Ctx);
3028 intCalleeIdx = *CB->encoding_begin();
3029 ArrayRef<int>PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3030F->addMetadata(llvm::LLVMContext::MD_callback,
3031*llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3032CalleeIdx, PayloadIndices,
3038assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3039 "Only globals with definition can force usage.");
3040LLVMUsed.emplace_back(GV);
3044assert(!GV->isDeclaration() &&
3045 "Only globals with definition can force usage.");
3046LLVMCompilerUsed.emplace_back(GV);
3050assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3051 "Only globals with definition can force usage.");
3053LLVMCompilerUsed.emplace_back(GV);
3055LLVMUsed.emplace_back(GV);
3059std::vector<llvm::WeakTrackingVH> &List) {
3066UsedArray.resize(List.size());
3067 for(
unsignedi = 0, e = List.size(); i != e; ++i) {
3069llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3070cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
3073 if(UsedArray.empty())
3075llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3077 auto*GV =
newllvm::GlobalVariable(
3078CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3079llvm::ConstantArray::get(ATy, UsedArray), Name);
3081GV->setSection(
"llvm.metadata");
3084voidCodeGenModule::emitLLVMUsed() {
3085 emitUsed(*
this,
"llvm.used", LLVMUsed);
3086 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3091LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3100LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3106ELFDependentLibraries.push_back(
3107llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3114LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3129 if(
Visited.insert(Import).second)
3146 if(LL.IsFramework) {
3147llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3148llvm::MDString::get(Context, LL.Library)};
3150Metadata.push_back(llvm::MDNode::get(Context, Args));
3156llvm::Metadata *Args[2] = {
3157llvm::MDString::get(Context,
"lib"),
3158llvm::MDString::get(Context, LL.Library),
3160Metadata.push_back(llvm::MDNode::get(Context, Args));
3164 auto*OptString = llvm::MDString::get(Context, Opt);
3165Metadata.push_back(llvm::MDNode::get(Context, OptString));
3170voidCodeGenModule::EmitModuleInitializers(
clang::Module*Primary) {
3172 "We should only emit module initializers for named modules.");
3178 if(isa<ImportDecl>(
D))
3180assert(isa<VarDecl>(
D) &&
"GMF initializer decl is not a var?");
3187 if(isa<ImportDecl>(
D))
3195 if(isa<ImportDecl>(
D))
3197assert(isa<VarDecl>(
D) &&
"PMF initializer decl is not a var?");
3203voidCodeGenModule::EmitModuleLinkOptions() {
3207llvm::SetVector<clang::Module *> LinkModules;
3212 for(
Module*M : ImportedModules) {
3215 if(M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3218 if(
Visited.insert(M).second)
3224 while(!Stack.empty()) {
3227 boolAnyChildren =
false;
3233 if(
SM->IsExplicit)
3237Stack.push_back(
SM);
3238AnyChildren =
true;
3245LinkModules.insert(Mod);
3254 for(
Module*M : LinkModules)
3255 if(
Visited.insert(M).second)
3257std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3258LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3261 auto*NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3262 for(
auto*MD : LinkerOptionsMetadata)
3263NMD->addOperand(MD);
3266voidCodeGenModule::EmitDeferred() {
3275 if(!DeferredVTables.empty()) {
3276EmitDeferredVTables();
3281assert(DeferredVTables.empty());
3288llvm::append_range(DeferredDeclsToEmit,
3292 if(DeferredDeclsToEmit.empty())
3297std::vector<GlobalDecl> CurDeclsToEmit;
3298CurDeclsToEmit.swap(DeferredDeclsToEmit);
3305llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3323 if(!GV->isDeclaration())
3327 if(LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(
D))
3331EmitGlobalDefinition(
D, GV);
3336 if(!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3338assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3343voidCodeGenModule::EmitVTablesOpportunistically() {
3349assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3350&&
"Only emit opportunistic vtables with optimizations");
3353assert(
getVTables().isVTableExternal(RD) &&
3354 "This queue should only contain external vtables");
3355 if(
getCXXABI().canSpeculativelyEmitVTable(RD))
3358OpportunisticVTables.clear();
3362 for(
const auto& [MangledName, VD] : DeferredAnnotations) {
3367DeferredAnnotations.clear();
3369 if(Annotations.empty())
3373llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3374Annotations[0]->getType(), Annotations.size()), Annotations);
3375 auto*gv =
newllvm::GlobalVariable(
getModule(), Array->getType(),
false,
3376llvm::GlobalValue::AppendingLinkage,
3377Array,
"llvm.global.annotations");
3382llvm::Constant *&AStr = AnnotationStrings[Str];
3387llvm::Constant *
s= llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3388 auto*gv =
newllvm::GlobalVariable(
3389 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3390 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3393gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3410 SM.getExpansionLineNumber(L);
3411 returnllvm::ConstantInt::get(
Int32Ty, LineNo);
3419llvm::FoldingSetNodeID ID;
3420 for(
Expr*
E: Exprs) {
3421ID.Add(cast<clang::ConstantExpr>(
E)->getAPValueResult());
3423llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3428LLVMArgs.reserve(Exprs.size());
3430llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr*
E) {
3431 const auto*CE = cast<clang::ConstantExpr>(
E);
3432 returnConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3435 auto*
Struct= llvm::ConstantStruct::getAnon(LLVMArgs);
3436 auto*GV =
newllvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3437llvm::GlobalValue::PrivateLinkage,
Struct,
3440GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3447 constAnnotateAttr *AA,
3455llvm::Constant *GVInGlobalsAS = GV;
3456 if(GV->getAddressSpace() !=
3458GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3460llvm::PointerType::get(
3461GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3465llvm::Constant *Fields[] = {
3466GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3468 returnllvm::ConstantStruct::getAnon(Fields);
3472llvm::GlobalValue *GV) {
3473assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3483 if(NoSanitizeL.containsFunction(Kind, Fn->getName()))
3488 if(NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3493 returnNoSanitizeL.containsLocation(Kind,
Loc);
3496 returnNoSanitizeL.containsFile(Kind, MainFile.
getName());
3500llvm::GlobalVariable *GV,
3504 if(NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3507 if(NoSanitizeL.containsMainFile(
3508Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3511 if(NoSanitizeL.containsLocation(Kind,
Loc,
Category))
3518 while(
autoAT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3519Ty = AT->getElementType();
3524 if(NoSanitizeL.containsType(Kind, TypeStr,
Category))
3535 auto Attr= ImbueAttr::NONE;
3538 if(
Attr== ImbueAttr::NONE)
3539 Attr= XRayFilter.shouldImbueFunction(Fn->getName());
3541 caseImbueAttr::NONE:
3543 caseImbueAttr::ALWAYS:
3544Fn->addFnAttr(
"function-instrument",
"xray-always");
3546 caseImbueAttr::ALWAYS_ARG1:
3547Fn->addFnAttr(
"function-instrument",
"xray-always");
3548Fn->addFnAttr(
"xray-log-args",
"1");
3550 caseImbueAttr::NEVER:
3551Fn->addFnAttr(
"function-instrument",
"xray-never");
3575 if(
autoMainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3589 if(NumGroups > 1) {
3590 autoGroup = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3599 if(LangOpts.EmitAllDecls)
3602 const auto*VD = dyn_cast<VarDecl>(
Global);
3604((CodeGenOpts.KeepPersistentStorageVariables &&
3605(VD->getStorageDuration() ==
SD_Static||
3606VD->getStorageDuration() ==
SD_Thread)) ||
3607(CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static&&
3608VD->getType().isConstQualified())))
3621 if(LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3622std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3623OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3624 if(!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3628 if(
const auto*FD = dyn_cast<FunctionDecl>(
Global)) {
3637 if(
const auto*VD = dyn_cast<VarDecl>(
Global)) {
3643 if(CXX20ModuleInits && VD->getOwningModule() &&
3644!VD->getOwningModule()->isModuleMapModule()) {
3653 if(LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3654 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(
Global) &&
3656!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3669 if(llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3673llvm::Constant *
Init;
3676 if(!
V.isAbsent()) {
3687llvm::Constant *Fields[4] = {
3691llvm::ConstantDataArray::getRaw(
3692StringRef(
reinterpret_cast<char*
>(Parts.
Part4And5), 8), 8,
3694 Init= llvm::ConstantStruct::getAnon(Fields);
3697 auto*GV =
newllvm::GlobalVariable(
3699 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3701GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3704 if(!
V.isAbsent()) {
3717llvm::GlobalVariable **Entry =
nullptr;
3718Entry = &UnnamedGlobalConstantDeclMap[GCD];
3723llvm::Constant *
Init;
3727assert(!
V.isAbsent());
3731 auto*GV =
newllvm::GlobalVariable(
getModule(),
Init->getType(),
3733llvm::GlobalValue::PrivateLinkage,
Init,
3735GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3749 if(llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3753llvm::Constant *
Init=
Emitter.emitForInitializer(
3761llvm::GlobalValue::LinkageTypes
Linkage=
3763? llvm::GlobalValue::LinkOnceODRLinkage
3764: llvm::GlobalValue::InternalLinkage;
3765 auto*GV =
newllvm::GlobalVariable(
getModule(),
Init->getType(),
3769GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3776 constAliasAttr *AA = VD->
getAttr<AliasAttr>();
3777assert(AA &&
"No alias?");
3787llvm::Constant *Aliasee;
3788 if(isa<llvm::FunctionType>(DeclTy))
3789Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3796 auto*F = cast<llvm::GlobalValue>(Aliasee);
3797F->setLinkage(llvm::Function::ExternalWeakLinkage);
3798WeakRefReferences.insert(F);
3806 if(
auto*A =
D->
getAttr<AttrT>())
3807 returnA->isImplicit();
3811boolCodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl*
Global)
const{
3812assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
3817 return!LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
3818 Global->hasAttr<CUDAConstantAttr>() ||
3819 Global->hasAttr<CUDASharedAttr>() ||
3820 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3821 Global->getType()->isCUDADeviceBuiltinTextureType();
3828 if(
Global->hasAttr<WeakRefAttr>())
3833 if(
Global->hasAttr<AliasAttr>())
3834 returnEmitAliasDefinition(GD);
3837 if(
Global->hasAttr<IFuncAttr>())
3838 returnemitIFuncDefinition(GD);
3841 if(
Global->hasAttr<CPUDispatchAttr>())
3842 returnemitCPUDispatchDefinition(GD);
3847 if(LangOpts.CUDA) {
3848assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
3849 "Expected Variable or Function");
3850 if(
const auto*VD = dyn_cast<VarDecl>(
Global)) {
3851 if(!shouldEmitCUDAGlobalVar(VD))
3853}
else if(LangOpts.CUDAIsDevice) {
3854 const auto*FD = dyn_cast<FunctionDecl>(
Global);
3855 if((!
Global->hasAttr<CUDADeviceAttr>() ||
3856(LangOpts.OffloadImplicitHostDeviceTemplates &&
3857hasImplicitAttr<CUDAHostAttr>(FD) &&
3858hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
3860!
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3861!
Global->hasAttr<CUDAGlobalAttr>() &&
3862!(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
3863!
Global->hasAttr<CUDAHostAttr>()))
3866}
else if(!
Global->hasAttr<CUDAHostAttr>() &&
3867 Global->hasAttr<CUDADeviceAttr>())
3871 if(LangOpts.OpenMP) {
3873 if(OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3875 if(
auto*DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
3876 if(MustBeEmitted(
Global))
3880 if(
auto*DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
3881 if(MustBeEmitted(
Global))
3888 if(
const auto*FD = dyn_cast<FunctionDecl>(
Global)) {
3891 if(FD->
hasAttr<AnnotateAttr>()) {
3894DeferredAnnotations[MangledName] = FD;
3909GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
3914 const auto*VD = cast<VarDecl>(
Global);
3915assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
3918 if(LangOpts.OpenMP) {
3920 if(std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3921OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3925 if(VD->hasExternalStorage() &&
3926Res != OMPDeclareTargetDeclAttr::MT_Link)
3929 boolUnifiedMemoryEnabled =
3931 if((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3932*Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3933!UnifiedMemoryEnabled) {
3936assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3937((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3938*Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3939UnifiedMemoryEnabled)) &&
3940 "Link clause or to clause with unified memory expected.");
3959 if(MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
3961EmitGlobalDefinition(GD);
3962addEmittedDeferredDecl(GD);
3969cast<VarDecl>(
Global)->hasInit()) {
3970DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
3971CXXGlobalInits.push_back(
nullptr);
3977addDeferredDeclToEmit(GD);
3978}
else if(MustBeEmitted(
Global)) {
3980assert(!MayBeEmittedEagerly(
Global));
3981addDeferredDeclToEmit(GD);
3986DeferredDecls[MangledName] = GD;
3993 if(
CXXRecordDecl*RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3994 if(RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4001 structFunctionIsDirectlyRecursive
4003 constStringRef Name;
4006: Name(N), BI(
C) {}
4008 boolVisitCallExpr(
const CallExpr*
E) {
4012AsmLabelAttr *
Attr= FD->
getAttr<AsmLabelAttr>();
4013 if(
Attr&& Name ==
Attr->getLabel())
4018StringRef BuiltinName = BI.
getName(BuiltinID);
4019 if(BuiltinName.starts_with(
"__builtin_") &&
4020Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
4026 boolVisitStmt(
const Stmt*S) {
4027 for(
const Stmt*Child : S->children())
4028 if(Child && this->Visit(Child))
4035 structDLLImportFunctionVisitor
4037 boolSafeToInline =
true;
4039 boolshouldVisitImplicitCode()
const{
return true; }
4041 boolVisitVarDecl(
VarDecl*VD) {
4044SafeToInline =
false;
4045 returnSafeToInline;
4052 returnSafeToInline;
4056 if(
const auto*
D=
E->getTemporary()->getDestructor())
4057SafeToInline =
D->
hasAttr<DLLImportAttr>();
4058 returnSafeToInline;
4063 if(isa<FunctionDecl>(VD))
4064SafeToInline = VD->
hasAttr<DLLImportAttr>();
4065 else if(
VarDecl*
V= dyn_cast<VarDecl>(VD))
4066SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4067 returnSafeToInline;
4071SafeToInline =
E->getConstructor()->hasAttr<DLLImportAttr>();
4072 returnSafeToInline;
4079SafeToInline =
true;
4081SafeToInline = M->
hasAttr<DLLImportAttr>();
4083 returnSafeToInline;
4087SafeToInline =
E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4088 returnSafeToInline;
4092SafeToInline =
E->getOperatorNew()->hasAttr<DLLImportAttr>();
4093 returnSafeToInline;
4102CodeGenModule::isTriviallyRecursive(
const FunctionDecl*FD) {
4104 if(
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4106AsmLabelAttr *
Attr= FD->
getAttr<AsmLabelAttr>();
4109Name =
Attr->getLabel();
4114FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
4116 returnBody ? Walker.Visit(Body) :
false;
4119boolCodeGenModule::shouldEmitFunction(
GlobalDeclGD) {
4123 const auto*F = cast<FunctionDecl>(GD.
getDecl());
4126 if(F->isInlineBuiltinDeclaration())
4129 if(CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4134 if(
const Module*M = F->getOwningModule();
4135M && M->getTopLevelModule()->isNamedModule() &&
4136 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4146 if(!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4151 if(F->hasAttr<NoInlineAttr>())
4154 if(F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4156DLLImportFunctionVisitor Visitor;
4157Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4158 if(!Visitor.SafeToInline)
4164 for(
const Decl*
Member: Dtor->getParent()->decls())
4165 if(isa<FieldDecl>(
Member))
4179 return!isTriviallyRecursive(F);
4182boolCodeGenModule::shouldOpportunisticallyEmitVTables() {
4183 returnCodeGenOpts.OptimizationLevel > 0;
4186voidCodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDeclGD,
4187llvm::GlobalValue *GV) {
4188 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
4191 auto*Spec = FD->
getAttr<CPUSpecificAttr>();
4192 for(
unsignedI = 0; I < Spec->cpus_size(); ++I)
4194}
else if(
auto*TC = FD->
getAttr<TargetClonesAttr>()) {
4195 for(
unsignedI = 0; I < TC->featuresStrs_size(); ++I)
4198TC->isFirstOfVersion(I))
4201GetOrCreateMultiVersionResolver(GD);
4203EmitGlobalFunctionDefinition(GD, GV);
4208AddDeferredMultiVersionResolverToEmit(GD);
4211voidCodeGenModule::EmitGlobalDefinition(
GlobalDeclGD, llvm::GlobalValue *GV) {
4212 const auto*
D= cast<ValueDecl>(GD.
getDecl());
4216 "Generating code for declaration");
4218 if(
const auto*FD = dyn_cast<FunctionDecl>(
D)) {
4221 if(!shouldEmitFunction(GD))
4224llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4226llvm::raw_string_ostream OS(Name);
4232 if(
const auto*Method = dyn_cast<CXXMethodDecl>(
D)) {
4235 if(isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4236ABI->emitCXXStructor(GD);
4238EmitMultiVersionFunctionDefinition(GD, GV);
4240EmitGlobalFunctionDefinition(GD, GV);
4242 if(Method->isVirtual())
4249 returnEmitMultiVersionFunctionDefinition(GD, GV);
4250 returnEmitGlobalFunctionDefinition(GD, GV);
4253 if(
const auto*VD = dyn_cast<VarDecl>(
D))
4254 returnEmitGlobalVarDefinition(VD, !VD->hasDefinition());
4256llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4260llvm::Function *NewFn);
4263 constCodeGenFunction::FMVResolverOption &RO) {
4265 if(RO.Architecture)
4266Features.push_back(*RO.Architecture);
4275staticllvm::GlobalValue::LinkageTypes
4279 returnllvm::GlobalValue::InternalLinkage;
4280 returnllvm::GlobalValue::WeakODRLinkage;
4283voidCodeGenModule::emitMultiVersionFunctions() {
4284std::vector<GlobalDecl> MVFuncsToEmit;
4285MultiVersionFuncs.swap(MVFuncsToEmit);
4287 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
4288assert(FD &&
"Expected a FunctionDecl");
4290 autocreateFunction = [&](
const FunctionDecl*
Decl,
unsignedMVIdx = 0) {
4295 if(
Decl->isDefined()) {
4296EmitGlobalFunctionDefinition(CurGD,
nullptr);
4304assert(
Func&&
"This should have just been created");
4306 returncast<llvm::Function>(
Func);
4320 if(
const auto*TA = CurFD->
getAttr<TargetAttr>()) {
4321assert(getTarget().getTriple().isX86() &&
"Unsupported target");
4322TA->getX86AddedFeatures(Feats);
4323llvm::Function *Func = createFunction(CurFD);
4324Options.emplace_back(Func, Feats, TA->getX86Architecture());
4325}
else if(
const auto*TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4326if (TVA->isDefaultVersion() && IsDefined)
4327ShouldEmitResolver = true;
4328llvm::Function *Func = createFunction(CurFD);
4329char Delim = getTarget().getTriple().isAArch64() ?
'+':
',';
4330TVA->getFeatures(Feats, Delim);
4331Options.emplace_back(Func, Feats);
4332}
else if(
const auto*TC = CurFD->
getAttr<TargetClonesAttr>()) {
4334ShouldEmitResolver = true;
4335for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4336if (!TC->isFirstOfVersion(I))
4339llvm::Function *Func = createFunction(CurFD, I);
4341if (getTarget().getTriple().isX86()) {
4342TC->getX86Feature(Feats, I);
4343Options.emplace_back(Func, Feats, TC->getX86Architecture(I));
4345char Delim = getTarget().getTriple().isAArch64() ?
'+':
',';
4346TC->getFeatures(Feats, I, Delim);
4347Options.emplace_back(Func, Feats);
4351llvm_unreachable(
"unexpected MultiVersionKind");
4354 if(!ShouldEmitResolver)
4357llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4358 if(
auto*IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4359ResolverConstant = IFunc->getResolver();
4363*
this, GD, FD,
true);
4370 auto*Alias = llvm::GlobalAlias::create(
4372MangledName +
".ifunc", IFunc, &
getModule());
4377llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4382ResolverFunc->setComdat(
4383 getModule().getOrInsertComdat(ResolverFunc->getName()));
4387Options, [&TI](
constCodeGenFunction::FMVResolverOption &LHS,
4388 constCodeGenFunction::FMVResolverOption &RHS) {
4392CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4398 if(!MVFuncsToEmit.empty())
4403 if(!MultiVersionFuncs.empty())
4404emitMultiVersionFunctions();
4408llvm::Constant *New) {
4409assert(cast<llvm::Function>(Old)->isDeclaration() &&
"Not a declaration");
4411Old->replaceAllUsesWith(New);
4412Old->eraseFromParent();
4415voidCodeGenModule::emitCPUDispatchDefinition(
GlobalDeclGD) {
4416 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
4417assert(FD &&
"Not a FunctionDecl?");
4419 const auto*DD = FD->
getAttr<CPUDispatchAttr>();
4420assert(DD &&
"Not a cpu_dispatch Function?");
4426UpdateMultiVersionNames(GD, FD, ResolverName);
4428llvm::Type *ResolverType;
4431ResolverType = llvm::FunctionType::get(
4432llvm::PointerType::get(DeclTy,
4441 auto*ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4442ResolverName, ResolverType, ResolverGD,
false));
4445ResolverFunc->setComdat(
4446 getModule().getOrInsertComdat(ResolverFunc->getName()));
4459 GlobalDeclExistingDecl = Manglings.lookup(MangledName);
4460 if(ExistingDecl.
getDecl() &&
4462EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4465 if(!ExistingDecl.
getDecl())
4468 Func= GetOrCreateLLVMFunction(
4469MangledName, DeclTy, ExistingDecl,
4476 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4477llvm::transform(Features, Features.begin(),
4478[](StringRef Str) { return Str.substr(1); });
4479llvm::erase_if(Features, [&
Target](StringRef Feat) {
4480 return!
Target.validateCpuSupports(Feat);
4482Options.emplace_back(cast<llvm::Function>(
Func), Features);
4486llvm::stable_sort(Options, [](
constCodeGenFunction::FMVResolverOption &LHS,
4487 constCodeGenFunction::FMVResolverOption &RHS) {
4488 returnllvm::X86::getCpuSupportsMask(LHS.Features) >
4489llvm::X86::getCpuSupportsMask(RHS.Features);
4496 while(Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4497(Options.end() - 2)->Features),
4498[](
auto X) { return X == 0; })) {
4499StringRef LHSName = (Options.end() - 2)->
Function->getName();
4500StringRef RHSName = (Options.end() - 1)->
Function->getName();
4501 if(LHSName.compare(RHSName) < 0)
4502Options.erase(Options.end() - 2);
4504Options.erase(Options.end() - 1);
4508CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4512 auto*IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4513 unsignedAS = IFunc->getType()->getPointerAddressSpace();
4517 if(!isa<llvm::GlobalIFunc>(IFunc)) {
4518 auto*GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4525*
this, GD, FD,
true);
4528 auto*GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4536voidCodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDeclGD) {
4537 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
4538assert(FD &&
"Not a FunctionDecl?");
4541std::string MangledName =
4543 if(!DeferredResolversToEmit.insert(MangledName).second)
4546MultiVersionFuncs.push_back(GD);
4552llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDeclGD) {
4553 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
4554assert(FD &&
"Not a FunctionDecl?");
4556std::string MangledName =
4561std::string ResolverName = MangledName;
4565llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4569ResolverName +=
".ifunc";
4576ResolverName +=
".resolver";
4579 boolShouldReturnIFunc =
4589 if(ResolverGV && (isa<llvm::GlobalIFunc>(ResolverGV) || !ShouldReturnIFunc))
4598AddDeferredMultiVersionResolverToEmit(GD);
4602 if(ShouldReturnIFunc) {
4604llvm::Type *ResolverType =
4605llvm::FunctionType::get(llvm::PointerType::get(DeclTy, AS),
false);
4606llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4607MangledName +
".resolver", ResolverType,
GlobalDecl{},
4609llvm::GlobalIFunc *GIF =
4612GIF->setName(ResolverName);
4619llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4620ResolverName, DeclTy,
GlobalDecl{},
false);
4621assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV &&
4622 "Resolver should be created for the first time");
4627boolCodeGenModule::shouldDropDLLAttribute(
const Decl*
D,
4628 constllvm::GlobalValue *GV)
const{
4629 autoSC = GV->getDLLStorageClass();
4630 if(SC == llvm::GlobalValue::DefaultStorageClass)
4633 return(((SC == llvm::GlobalValue::DLLImportStorageClass &&
4634!MRD->
hasAttr<DLLImportAttr>()) ||
4635(SC == llvm::GlobalValue::DLLExportStorageClass &&
4636!MRD->
hasAttr<DLLExportAttr>())) &&
4647llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4648StringRef MangledName, llvm::Type *Ty,
GlobalDeclGD,
boolForVTable,
4649 boolDontDefer,
boolIsThunk, llvm::AttributeList ExtraAttrs,
4653std::string NameWithoutMultiVersionMangling;
4656 if(
const FunctionDecl*FD = cast_or_null<FunctionDecl>(
D)) {
4658 if(
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4659!OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4660!DontDefer && !IsForDefinition) {
4663 if(
const auto*CD = dyn_cast<CXXConstructorDecl>(FDDef))
4665 else if(
const auto*DD = dyn_cast<CXXDestructorDecl>(FDDef))
4674UpdateMultiVersionNames(GD, FD, MangledName);
4675 if(!IsForDefinition) {
4681AddDeferredMultiVersionResolverToEmit(GD);
4683*
this, GD, FD,
true);
4685 returnGetOrCreateMultiVersionResolver(GD);
4690 if(!NameWithoutMultiVersionMangling.empty())
4691MangledName = NameWithoutMultiVersionMangling;
4696 if(WeakRefReferences.erase(Entry)) {
4698 if(FD && !FD->
hasAttr<WeakAttr>())
4699Entry->setLinkage(llvm::Function::ExternalLinkage);
4703 if(
D&& shouldDropDLLAttribute(
D, Entry)) {
4704Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4710 if(IsForDefinition && !Entry->isDeclaration()) {
4717DiagnosedConflictingDefinitions.insert(GD).second) {
4721diag::note_previous_definition);
4725 if((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4726(Entry->getValueType() == Ty)) {
4733 if(!IsForDefinition)
4740 boolIsIncompleteFunction =
false;
4742llvm::FunctionType *FTy;
4743 if(isa<llvm::FunctionType>(Ty)) {
4744FTy = cast<llvm::FunctionType>(Ty);
4746FTy = llvm::FunctionType::get(
VoidTy,
false);
4747IsIncompleteFunction =
true;
4751llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4752Entry ? StringRef() : MangledName, &
getModule());
4756 if(
D&&
D->
hasAttr<AnnotateAttr>())
4757DeferredAnnotations[MangledName] = cast<ValueDecl>(
D);
4774 if(!Entry->use_empty()) {
4776Entry->removeDeadConstantUsers();
4782assert(F->getName() == MangledName &&
"name was uniqued!");
4784SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4785 if(ExtraAttrs.hasFnAttrs()) {
4786llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4794 if(isa_and_nonnull<CXXDestructorDecl>(
D) &&
4795 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(
D),
4797addDeferredDeclToEmit(GD);
4802 autoDDI = DeferredDecls.find(MangledName);
4803 if(DDI != DeferredDecls.end()) {
4807addDeferredDeclToEmit(DDI->second);
4808DeferredDecls.erase(DDI);
4823 for(
const auto*FD = cast<FunctionDecl>(
D)->getMostRecentDecl(); FD;
4836 if(!IsIncompleteFunction) {
4837assert(F->getFunctionType() == Ty);
4853 const auto*FD = cast<FunctionDecl>(GD.
getDecl());
4860 if(
const auto*DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
4863DD->getParent()->getNumVBases() == 0)
4868 auto*F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4869 false, llvm::AttributeList(),
4872 if(LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4873cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
4875cast<llvm::Function>(F->stripPointerCasts()), GD);
4876 if(IsForDefinition)
4884llvm::GlobalValue *F =
4887 returnllvm::NoCFIValue::get(F);
4897 if(
const auto*FD = dyn_cast<FunctionDecl>(
Result))
4900 if(!
C.getLangOpts().CPlusPlus)
4905(Name ==
"_ZSt9terminatev"|| Name ==
"?terminate@@YAXXZ")
4906?
C.Idents.get(
"terminate")
4907:
C.Idents.get(Name);
4909 for(
const auto&N : {
"__cxxabiv1",
"std"}) {
4913 if(
auto*LSD = dyn_cast<LinkageSpecDecl>(
Result))
4914 for(
const auto*
Result: LSD->lookup(&NS))
4915 if((ND = dyn_cast<NamespaceDecl>(
Result)))
4920 if(
const auto*FD = dyn_cast<FunctionDecl>(
Result))
4929llvm::Function *F, StringRef Name) {
4935 if(!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
4938 if(!FD || FD->
hasAttr<DLLImportAttr>()) {
4939F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4940F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4947llvm::AttributeList ExtraAttrs,
boolLocal,
boolAssumeConvergent) {
4948 if(AssumeConvergent) {
4950ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4958llvm::Constant *
C= GetOrCreateLLVMFunction(
4960 false,
false, ExtraAttrs);
4962 if(
auto*F = dyn_cast<llvm::Function>(
C)) {
4971 return{ConvTy,
C};
4976llvm::FunctionCallee
4978llvm::AttributeList ExtraAttrs,
boolLocal,
4979 boolAssumeConvergent) {
4980 if(AssumeConvergent) {
4982ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4985llvm::Constant *
C=
4986GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
4990 if(
auto*F = dyn_cast<llvm::Function>(
C)) {
4999markRegisterParameterAttributes(F);
5025 if(WeakRefReferences.erase(Entry)) {
5027Entry->setLinkage(llvm::Function::ExternalLinkage);
5031 if(
D&& shouldDropDLLAttribute(
D, Entry))
5032Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5034 if(LangOpts.OpenMP && !LangOpts.OpenMPSimd &&
D)
5037 if(Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5042 if(IsForDefinition && !Entry->isDeclaration()) {
5050(OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5052DiagnosedConflictingDefinitions.insert(
D).second) {
5056diag::note_previous_definition);
5061 if(Entry->getType()->getAddressSpace() != TargetAS)
5062 returnllvm::ConstantExpr::getAddrSpaceCast(
5063Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5067 if(!IsForDefinition)
5073 auto*GV =
newllvm::GlobalVariable(
5074 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5075MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5076 getContext().getTargetAddressSpace(DAddrSpace));
5081GV->takeName(Entry);
5083 if(!Entry->use_empty()) {
5084Entry->replaceAllUsesWith(GV);
5087Entry->eraseFromParent();
5093 autoDDI = DeferredDecls.find(MangledName);
5094 if(DDI != DeferredDecls.end()) {
5097addDeferredDeclToEmit(DDI->second);
5098DeferredDecls.erase(DDI);
5103 if(LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5108GV->setConstant(
D->getType().isConstantStorage(
getContext(),
false,
false));
5110GV->setAlignment(
getContext().getDeclAlign(
D).getAsAlign());
5114 if(
D->getTLSKind()) {
5116CXXThreadLocals.push_back(
D);
5124 if(
getContext().isMSStaticDataMemberInlineDefinition(
D)) {
5125EmitGlobalVarDefinition(
D);
5129 if(
D->hasExternalStorage()) {
5130 if(
constSectionAttr *SA =
D->
getAttr<SectionAttr>())
5131GV->setSection(SA->getName());
5135 if(
getTriple().getArch() == llvm::Triple::xcore &&
5137 D->getType().isConstant(Context) &&
5139GV->setSection(
".cp.rodata");
5142 if(
const auto*CMA =
D->
getAttr<CodeModelAttr>())
5143GV->setCodeModel(CMA->getModel());
5148 if(Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5149 D->getType().isConstQualified() && !GV->hasInitializer() &&
5150!
D->hasDefinition() &&
D->hasInit() && !
D->
hasAttr<DLLImportAttr>()) {
5154 if(!HasMutableFields) {
5156 const Expr*InitExpr =
D->getAnyInitializer(InitDecl);
5161 auto*InitType =
Init->getType();
5162 if(GV->getValueType() != InitType) {
5167GV->setName(StringRef());
5170 auto*NewGV = cast<llvm::GlobalVariable>(
5172->stripPointerCasts());
5175GV->eraseFromParent();
5178GV->setInitializer(
Init);
5179GV->setConstant(
true);
5180GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5195 D->hasExternalStorage())
5200SanitizerMD->reportGlobal(GV, *
D);
5203 D?
D->getType().getAddressSpace()
5205assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5206 if(DAddrSpace != ExpectedAS) {
5208*
this, GV, DAddrSpace, ExpectedAS,
5219 if(isa<CXXConstructorDecl>(
D) || isa<CXXDestructorDecl>(
D))
5221 false, IsForDefinition);
5223 if(isa<CXXMethodDecl>(
D)) {
5231 if(isa<FunctionDecl>(
D)) {
5242StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5243llvm::Align Alignment) {
5244llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5245llvm::GlobalVariable *OldGV =
nullptr;
5249 if(GV->getValueType() == Ty)
5254assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5259GV =
newllvm::GlobalVariable(
getModule(), Ty,
true,
5264GV->takeName(OldGV);
5266 if(!OldGV->use_empty()) {
5267OldGV->replaceAllUsesWith(GV);
5270OldGV->eraseFromParent();
5274!GV->hasAvailableExternallyLinkage())
5275GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5277GV->setAlignment(Alignment);
5291assert(
D->hasGlobalStorage() &&
"Not a global variable");
5309 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5314assert(!
D->getInit() &&
"Cannot emit definite definitions here!");
5322 if(GV && !GV->isDeclaration())
5327 if(!MustBeEmitted(
D) && !GV) {
5328DeferredDecls[MangledName] =
D;
5333EmitGlobalVarDefinition(
D);
5337 if(
auto const*
V= dyn_cast<const VarDecl>(
D))
5338EmitExternalVarDeclaration(
V);
5339 if(
auto const*FD = dyn_cast<const FunctionDecl>(
D))
5340EmitExternalFunctionDeclaration(FD);
5349 if(LangOpts.OpenCL) {
5360 if(LangOpts.SYCLIsDevice &&
5364 if(LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5366 if(
D->
hasAttr<CUDAConstantAttr>())
5368 if(
D->
hasAttr<CUDASharedAttr>())
5370 if(
D->
hasAttr<CUDADeviceAttr>())
5372 if(
D->getType().isConstQualified())
5378 if(LangOpts.OpenMP) {
5380 if(OpenMPRuntime->hasAllocateAttributeForGlobalVar(
D, AS))
5388 if(LangOpts.OpenCL)
5390 if(LangOpts.SYCLIsDevice)
5392 if(LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5400 if(
autoAS =
getTarget().getConstantAddressSpace())
5413staticllvm::Constant *
5415llvm::GlobalVariable *GV) {
5416llvm::Constant *Cast = GV;
5422llvm::PointerType::get(
5429template<
typenameSomeDecl>
5431llvm::GlobalValue *GV) {
5437 if(!
D->template hasAttr<UsedAttr>())
5446 constSomeDecl *
First=
D->getFirstDecl();
5447 if(
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5453std::pair<StaticExternCMap::iterator, bool> R =
5454StaticExternCValues.insert(std::make_pair(
D->getIdentifier(), GV));
5459R.first->second =
nullptr;
5466 if(
D.
hasAttr<SelectAnyAttr>())
5470 if(
auto*VD = dyn_cast<VarDecl>(&
D))
5484llvm_unreachable(
"No such linkage");
5492llvm::GlobalObject &GO) {
5495GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5503voidCodeGenModule::EmitGlobalVarDefinition(
const VarDecl*
D,
5513 if(LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5514OpenMPRuntime->emitTargetGlobalVariable(
D))
5517llvm::TrackingVH<llvm::Constant>
Init;
5518 boolNeedsGlobalCtor =
false;
5522 boolIsDefinitionAvailableExternally =
5524 boolNeedsGlobalDtor =
5525!IsDefinitionAvailableExternally &&
5532 if(IsDefinitionAvailableExternally &&
5533(!
D->hasConstantInitialization() ||
5537!
D->getType().isConstantStorage(
getContext(),
true,
true)))
5541 const Expr*InitExpr =
D->getAnyInitializer(InitDecl);
5543std::optional<ConstantEmitter> emitter;
5548 boolIsCUDASharedVar =
5553 boolIsCUDAShadowVar =
5557 boolIsCUDADeviceShadowVar =
5559(
D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5560 D->getType()->isCUDADeviceBuiltinTextureType());
5562(IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5563 Init= llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5564 else if(
D->
hasAttr<LoaderUninitializedAttr>())
5565 Init= llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5566 else if(!InitExpr) {
5580emitter.emplace(*
this);
5581llvm::Constant *
Initializer= emitter->tryEmitForInitializer(*InitDecl);
5584 if(
D->getType()->isReferenceType())
5589 if(!IsDefinitionAvailableExternally)
5590NeedsGlobalCtor =
true;
5594NeedsGlobalCtor =
false;
5598 Init= llvm::PoisonValue::get(
getTypes().ConvertType(
T));
5606DelayedCXXInitPosition.erase(
D);
5613assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5618llvm::Type* InitType =
Init->getType();
5619llvm::Constant *Entry =
5623Entry = Entry->stripPointerCasts();
5626 auto*GV = dyn_cast<llvm::GlobalVariable>(Entry);
5637 if(!GV || GV->getValueType() != InitType ||
5638GV->getType()->getAddressSpace() !=
5642Entry->setName(StringRef());
5645GV = cast<llvm::GlobalVariable>(
5647->stripPointerCasts());
5650llvm::Constant *NewPtrForOldDecl =
5651llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5653Entry->replaceAllUsesWith(NewPtrForOldDecl);
5656cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5661 if(
D->
hasAttr<AnnotateAttr>())
5674 if(LangOpts.CUDA) {
5675 if(LangOpts.CUDAIsDevice) {
5676 if(
Linkage!= llvm::GlobalValue::InternalLinkage &&
5678 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5679 D->getType()->isCUDADeviceBuiltinTextureType()))
5680GV->setExternallyInitialized(
true);
5690GV->setInitializer(
Init);
5692emitter->finalize(GV);
5695GV->setConstant((
D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
5696(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5697 D->getType().isConstantStorage(
getContext(),
true,
true)));
5700 if(
constSectionAttr *SA =
D->
getAttr<SectionAttr>()) {
5703GV->setConstant(
true);
5708 if(std::optional<CharUnits> AlignValFromAllocate =
5710AlignVal = *AlignValFromAllocate;
5728 Linkage== llvm::GlobalValue::ExternalLinkage &&
5731 Linkage= llvm::GlobalValue::InternalLinkage;
5734 if(
D->
hasAttr<DLLImportAttr>())
5735GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5736 else if(
D->
hasAttr<DLLExportAttr>())
5737GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5739GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5741 if(
Linkage== llvm::GlobalVariable::CommonLinkage) {
5743GV->setConstant(
false);
5748 if(!GV->getInitializer()->isNullValue())
5749GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5752setNonAliasAttributes(
D, GV);
5754 if(
D->getTLSKind() && !GV->isThreadLocal()) {
5756CXXThreadLocals.push_back(
D);
5763 if(NeedsGlobalCtor || NeedsGlobalDtor)
5764EmitCXXGlobalVarDeclInitFunc(
D, GV, NeedsGlobalCtor);
5766SanitizerMD->reportGlobal(GV, *
D, NeedsGlobalCtor);
5771DI->EmitGlobalVariable(GV,
D);
5774voidCodeGenModule::EmitExternalVarDeclaration(
const VarDecl*
D) {
5779llvm::Constant *GV =
5781DI->EmitExternalVariable(
5782cast<llvm::GlobalVariable>(GV->stripPointerCasts()),
D);
5786voidCodeGenModule::EmitExternalFunctionDeclaration(
const FunctionDecl*FD) {
5791 auto*
Fn= cast<llvm::Function>(
5792GetOrCreateLLVMFunction(MangledName, Ty, FD,
false));
5793 if(!
Fn->getSubprogram())
5803 if((NoCommon ||
D->
hasAttr<NoCommonAttr>()) && !
D->
hasAttr<CommonAttr>())
5810 if(
D->getInit() ||
D->hasExternalStorage())
5820 if(
D->
hasAttr<PragmaClangBSSSectionAttr>() ||
5821 D->
hasAttr<PragmaClangDataSectionAttr>() ||
5822 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
5823 D->
hasAttr<PragmaClangRodataSectionAttr>())
5827 if(
D->getTLSKind())
5831 if(
D->
hasAttr<WeakImportAttr>())
5850 if(FD->isBitField())
5852 if(FD->
hasAttr<AlignedAttr>())
5874llvm::GlobalValue::LinkageTypes
5878 returnllvm::Function::InternalLinkage;
5881 returnllvm::GlobalVariable::WeakAnyLinkage;
5885 returnllvm::GlobalVariable::LinkOnceAnyLinkage;
5890 returnllvm::GlobalValue::AvailableExternallyLinkage;
5904 return!Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5905: llvm::Function::InternalLinkage;
5919 returnllvm::Function::ExternalLinkage;
5922 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5923: llvm::Function::InternalLinkage;
5924 returnllvm::Function::WeakODRLinkage;
5931CodeGenOpts.NoCommon))
5932 returnllvm::GlobalVariable::CommonLinkage;
5938 if(
D->
hasAttr<SelectAnyAttr>())
5939 returnllvm::GlobalVariable::WeakODRLinkage;
5943 returnllvm::GlobalVariable::ExternalLinkage;
5946llvm::GlobalValue::LinkageTypes
5955llvm::Function *newFn) {
5957 if(old->use_empty())
5960llvm::Type *newRetTy = newFn->getReturnType();
5965 for(llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5967llvm::User *user = ui->getUser();
5971 if(
auto*bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5972 if(bitcast->getOpcode() == llvm::Instruction::BitCast)
5978llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5981 if(!callSite->isCallee(&*ui))
5986 if(callSite->getType() != newRetTy && !callSite->use_empty())
5991llvm::AttributeList oldAttrs = callSite->getAttributes();
5994 unsignednewNumArgs = newFn->arg_size();
5995 if(callSite->arg_size() < newNumArgs)
6001 booldontTransform =
false;
6002 for(llvm::Argument &A : newFn->args()) {
6003 if(callSite->getArgOperand(argNo)->getType() != A.getType()) {
6004dontTransform =
true;
6009newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6017newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6021callSite->getOperandBundlesAsDefs(newBundles);
6023llvm::CallBase *newCall;
6024 if(isa<llvm::CallInst>(callSite)) {
6025newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6026callSite->getIterator());
6028 auto*oldInvoke = cast<llvm::InvokeInst>(callSite);
6029newCall = llvm::InvokeInst::Create(
6030newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6031newArgs, newBundles,
"", callSite->getIterator());
6035 if(!newCall->getType()->isVoidTy())
6036newCall->takeName(callSite);
6037newCall->setAttributes(
6038llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6039oldAttrs.getRetAttrs(), newArgAttrs));
6040newCall->setCallingConv(callSite->getCallingConv());
6043 if(!callSite->use_empty())
6044callSite->replaceAllUsesWith(newCall);
6047 if(callSite->getDebugLoc())
6048newCall->setDebugLoc(callSite->getDebugLoc());
6050callSitesToBeRemovedFromParent.push_back(callSite);
6053 for(
auto*callSite : callSitesToBeRemovedFromParent) {
6054callSite->eraseFromParent();
6068llvm::Function *NewFn) {
6070 if(!isa<llvm::Function>(Old))
return;
6078(LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6090voidCodeGenModule::EmitGlobalFunctionDefinition(
GlobalDeclGD,
6091llvm::GlobalValue *GV) {
6092 const auto*
D= cast<FunctionDecl>(GD.
getDecl());
6099 if(!GV || (GV->getValueType() != Ty))
6105 if(!GV->isDeclaration())
6112 auto*Fn = cast<llvm::Function>(GV);
6124setNonAliasAttributes(GD, Fn);
6127 if(
constConstructorAttr *CA =
D->
getAttr<ConstructorAttr>())
6129 if(
constDestructorAttr *DA =
D->
getAttr<DestructorAttr>())
6135voidCodeGenModule::EmitAliasDefinition(
GlobalDeclGD) {
6136 const auto*
D= cast<ValueDecl>(GD.
getDecl());
6137 constAliasAttr *AA =
D->
getAttr<AliasAttr>();
6138assert(AA &&
"Not an alias?");
6142 if(AA->getAliasee() == MangledName) {
6143Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6150 if(Entry && !Entry->isDeclaration())
6153Aliases.push_back(GD);
6159llvm::Constant *Aliasee;
6160llvm::GlobalValue::LinkageTypes
LT;
6161 if(isa<llvm::FunctionType>(DeclTy)) {
6162Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6168 if(
const auto*VD = dyn_cast<VarDecl>(GD.
getDecl()))
6175 unsignedAS = Aliasee->getType()->getPointerAddressSpace();
6177llvm::GlobalAlias::create(DeclTy, AS,
LT,
"", Aliasee, &
getModule());
6180 if(GA->getAliasee() == Entry) {
6181Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6185assert(Entry->isDeclaration());
6194GA->takeName(Entry);
6196Entry->replaceAllUsesWith(GA);
6197Entry->eraseFromParent();
6199GA->setName(MangledName);
6207GA->setLinkage(llvm::Function::WeakAnyLinkage);
6210 if(
const auto*VD = dyn_cast<VarDecl>(
D))
6211 if(VD->getTLSKind())
6217 if(isa<VarDecl>(
D))
6219DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6222voidCodeGenModule::emitIFuncDefinition(
GlobalDeclGD) {
6223 const auto*
D= cast<ValueDecl>(GD.
getDecl());
6224 constIFuncAttr *IFA =
D->
getAttr<IFuncAttr>();
6225assert(IFA &&
"Not an ifunc?");
6229 if(IFA->getResolver() == MangledName) {
6230Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6236 if(Entry && !Entry->isDeclaration()) {
6239DiagnosedConflictingDefinitions.insert(GD).second) {
6243diag::note_previous_definition);
6248Aliases.push_back(GD);
6254llvm::Constant *Resolver =
6255GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6259llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6260DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6262 if(GIF->getResolver() == Entry) {
6263Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6266assert(Entry->isDeclaration());
6275GIF->takeName(Entry);
6277Entry->replaceAllUsesWith(GIF);
6278Entry->eraseFromParent();
6280GIF->setName(MangledName);
6286 returnllvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6287(llvm::Intrinsic::ID)IID, Tys);
6290staticllvm::StringMapEntry<llvm::GlobalVariable *> &
6293 bool&IsUTF16,
unsigned&StringLength) {
6294StringRef String = Literal->getString();
6295 unsignedNumBytes = String.size();
6298 if(!Literal->containsNonAsciiOrNull()) {
6299StringLength = NumBytes;
6300 return*Map.insert(std::make_pair(String,
nullptr)).first;
6307 constllvm::UTF8 *FromPtr = (
constllvm::UTF8 *)String.data();
6308llvm::UTF16 *ToPtr = &ToBuf[0];
6310(void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6311ToPtr + NumBytes, llvm::strictConversion);
6314StringLength = ToPtr - &ToBuf[0];
6318 return*Map.insert(std::make_pair(
6319StringRef(
reinterpret_cast<const char*
>(ToBuf.data()),
6320(StringLength + 1) * 2),
6326 unsignedStringLength = 0;
6327 boolisUTF16 =
false;
6328llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6333 if(
auto*
C= Entry.second)
6338 constllvm::Triple &Triple =
getTriple();
6341 const boolIsSwiftABI =
6342 static_cast<unsigned>(CFRuntime) >=
6347 if(!CFConstantStringClassRef) {
6348 const char*CFConstantStringClassName =
"__CFConstantStringClassReference";
6350Ty = llvm::ArrayType::get(Ty, 0);
6352 switch(CFRuntime) {
6356CFConstantStringClassName =
6357Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN" 6358:
"$s10Foundation19_NSCFConstantStringCN";
6362CFConstantStringClassName =
6363Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN" 6364:
"$S10Foundation19_NSCFConstantStringCN";
6368CFConstantStringClassName =
6369Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN" 6370:
"__T010Foundation19_NSCFConstantStringCN";
6377 if(Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6378llvm::GlobalValue *GV =
nullptr;
6380 if((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6387 if((VD = dyn_cast<VarDecl>(
Result)))
6390 if(Triple.isOSBinFormatELF()) {
6392GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6394GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6395 if(!VD || !VD->
hasAttr<DLLExportAttr>())
6396GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6398GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6406CFConstantStringClassRef =
6407IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6412 auto*STy = cast<llvm::StructType>(
getTypes().ConvertType(CFTy));
6415 autoFields = Builder.beginStruct(STy);
6418Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6422Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6423Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6425Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6429llvm::Constant *
C=
nullptr;
6432 reinterpret_cast<uint16_t *
>(
const_cast<char*
>(Entry.first().data())),
6433Entry.first().size() / 2);
6434 C= llvm::ConstantDataArray::get(VMContext, Arr);
6436 C= llvm::ConstantDataArray::getString(VMContext, Entry.first());
6442 newllvm::GlobalVariable(
getModule(),
C->getType(),
true,
6443llvm::GlobalValue::PrivateLinkage,
C,
".str");
6444GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6454 if(Triple.isOSBinFormatMachO())
6455GV->setSection(isUTF16 ?
"__TEXT,__ustring" 6456:
"__TEXT,__cstring,cstring_literals");
6459 else if(Triple.isOSBinFormatELF())
6460GV->setSection(
".rodata");
6466llvm::IntegerType *LengthTy =
6476Fields.addInt(LengthTy, StringLength);
6484GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6486llvm::GlobalVariable::PrivateLinkage);
6487GV->addAttribute(
"objc_arc_inert");
6488 switch(Triple.getObjectFormat()) {
6489 casellvm::Triple::UnknownObjectFormat:
6490llvm_unreachable(
"unknown file format");
6491 casellvm::Triple::DXContainer:
6492 casellvm::Triple::GOFF:
6493 casellvm::Triple::SPIRV:
6494 casellvm::Triple::XCOFF:
6495llvm_unreachable(
"unimplemented");
6496 casellvm::Triple::COFF:
6497 casellvm::Triple::ELF:
6498 casellvm::Triple::Wasm:
6499GV->setSection(
"cfstring");
6501 casellvm::Triple::MachO:
6502GV->setSection(
"__DATA,__cfstring");
6511 return!CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6515 if(ObjCFastEnumerationStateType.
isNull()) {
6517 D->startDefinition();
6525 for(
size_ti = 0; i < 4; ++i) {
6530FieldTypes[i],
nullptr,
6538 D->completeDefinition();
6542 returnObjCFastEnumerationStateType;
6551 if(
E->getCharByteWidth() == 1) {
6556assert(CAT &&
"String literal not of constant array type!");
6558 returnllvm::ConstantDataArray::getString(VMContext, Str,
false);
6561 auto*AType = cast<llvm::ArrayType>(
getTypes().ConvertType(
E->
getType()));
6562llvm::Type *ElemTy = AType->getElementType();
6563 unsignedNumElements = AType->getNumElements();
6566 if(ElemTy->getPrimitiveSizeInBits() == 16) {
6568Elements.reserve(NumElements);
6570 for(
unsignedi = 0, e =
E->getLength(); i != e; ++i)
6571Elements.push_back(
E->getCodeUnit(i));
6572Elements.resize(NumElements);
6573 returnllvm::ConstantDataArray::get(VMContext, Elements);
6576assert(ElemTy->getPrimitiveSizeInBits() == 32);
6578Elements.reserve(NumElements);
6580 for(
unsignedi = 0, e =
E->getLength(); i != e; ++i)
6581Elements.push_back(
E->getCodeUnit(i));
6582Elements.resize(NumElements);
6583 returnllvm::ConstantDataArray::get(VMContext, Elements);
6586staticllvm::GlobalVariable *
6595 auto*GV =
newllvm::GlobalVariable(
6596M,
C->getType(), !CGM.
getLangOpts().WritableStrings,
LT,
C, GlobalName,
6597 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6599GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6600 if(GV->isWeakForLinker()) {
6601assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6602GV->setComdat(M.getOrInsertComdat(GV->getName()));
6618llvm::GlobalVariable **Entry =
nullptr;
6619 if(!LangOpts.WritableStrings) {
6620Entry = &ConstantStringMap[
C];
6621 if(
autoGV = *Entry) {
6622 if(uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6625GV->getValueType(), Alignment);
6630StringRef GlobalVariableName;
6631llvm::GlobalValue::LinkageTypes
LT;
6636 if(
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6637!LangOpts.WritableStrings) {
6638llvm::raw_svector_ostream Out(MangledNameBuffer);
6640 LT= llvm::GlobalValue::LinkOnceODRLinkage;
6641GlobalVariableName = MangledNameBuffer;
6643 LT= llvm::GlobalValue::PrivateLinkage;
6644GlobalVariableName = Name;
6656SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0),
"<string literal>");
6659GV->getValueType(), Alignment);
6676 conststd::string &Str,
const char*GlobalName) {
6677StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6681llvm::Constant *
C=
6682llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6685llvm::GlobalVariable **Entry =
nullptr;
6686 if(!LangOpts.WritableStrings) {
6687Entry = &ConstantStringMap[
C];
6688 if(
autoGV = *Entry) {
6689 if(uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6692GV->getValueType(), Alignment);
6698GlobalName =
".str";
6701GlobalName, Alignment);
6706GV->getValueType(), Alignment);
6711assert((
E->getStorageDuration() ==
SD_Static||
6712 E->getStorageDuration() ==
SD_Thread) &&
"not a global temporary");
6713 const auto*VD = cast<VarDecl>(
E->getExtendingDecl());
6718 if(
Init==
E->getSubExpr())
6719MaterializedType =
E->
getType();
6723 autoInsertResult = MaterializedGlobalTemporaryMap.insert({
E,
nullptr});
6724 if(!InsertResult.second) {
6727 if(!InsertResult.first->second) {
6732InsertResult.first->second =
newllvm::GlobalVariable(
6733 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
6737llvm::cast<llvm::GlobalVariable>(
6738InsertResult.first->second->stripPointerCasts())
6747llvm::raw_svector_ostream Out(Name);
6749VD,
E->getManglingNumber(), Out);
6752 if(
E->getStorageDuration() ==
SD_Static&& VD->evaluateValue()) {
6758 Value=
E->getOrCreateValue(
false);
6769std::optional<ConstantEmitter> emitter;
6770llvm::Constant *InitialValue =
nullptr;
6771 boolConstant =
false;
6775emitter.emplace(*
this);
6776InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
6781 Type= InitialValue->getType();
6790 if(
Linkage== llvm::GlobalVariable::ExternalLinkage) {
6792 if(VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6796 Linkage= llvm::GlobalVariable::LinkOnceODRLinkage;
6800 Linkage= llvm::GlobalVariable::InternalLinkage;
6804 auto*GV =
newllvm::GlobalVariable(
6806 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6807 if(emitter) emitter->finalize(GV);
6809 if(!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
6811 if(GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6813GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6817GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6818 if(VD->getTLSKind())
6820llvm::Constant *CV = GV;
6824llvm::PointerType::get(
6830llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[
E];
6832Entry->replaceAllUsesWith(CV);
6833llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6842voidCodeGenModule::EmitObjCPropertyImplementations(
const 6844 for(
const auto*PID :
D->property_impls()) {
6855 if(!Getter || Getter->isSynthesizedAccessorStub())
6858 auto*Setter = PID->getSetterMethodDecl();
6859 if(!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6870 if(ivar->getType().isDestructedType())
6880 E=
D->init_end(); B !=
E; ++B) {
6903 D->addInstanceMethod(DTORMethod);
6905 D->setHasDestructors(
true);
6910 if(
D->getNumIvarInitializers() == 0 ||
6919 getContext().getObjCIdType(),
nullptr,
D,
true,
6924 D->addInstanceMethod(CTORMethod);
6926 D->setHasNonZeroConstructors(
true);
6937EmitDeclContext(LSD);
6942 if(LangOpts.CUDA && LangOpts.CUDAIsDevice)
6945std::unique_ptr<CodeGenFunction> &CurCGF =
6946GlobalTopLevelStmtBlockInFlight.first;
6950 if(CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6958std::string Name =
"__stmts__"+ llvm::utostr(CXXGlobalInits.size());
6964llvm::Function *
Fn= llvm::Function::Create(
6965FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
6968GlobalTopLevelStmtBlockInFlight.second =
D;
6969CurCGF->StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
6971CXXGlobalInits.push_back(Fn);
6974CurCGF->EmitStmt(
D->getStmt());
6977voidCodeGenModule::EmitDeclContext(
const DeclContext*DC) {
6978 for(
auto*I : DC->
decls()) {
6984 if(
auto*OID = dyn_cast<ObjCImplDecl>(I)) {
6985 for(
auto*M : OID->methods())
7004 caseDecl::CXXConversion:
7005 caseDecl::CXXMethod:
7006 caseDecl::Function:
7013 caseDecl::CXXDeductionGuide:
7018 caseDecl::Decomposition:
7019 caseDecl::VarTemplateSpecialization:
7021 if(
auto*DD = dyn_cast<DecompositionDecl>(
D))
7022 for(
auto*B : DD->flat_bindings())
7023 if(
auto*HD = B->getHoldingVar())
7030 caseDecl::IndirectField:
7034 caseDecl::Namespace:
7035EmitDeclContext(cast<NamespaceDecl>(
D));
7037 caseDecl::ClassTemplateSpecialization: {
7038 const auto*Spec = cast<ClassTemplateSpecializationDecl>(
D);
7040 if(Spec->getSpecializationKind() ==
7042Spec->hasDefinition())
7043DI->completeTemplateDefinition(*Spec);
7045 caseDecl::CXXRecord: {
7052DI->completeUnusedClass(*CRD);
7055 for(
auto*I : CRD->
decls())
7056 if(isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
7061 caseDecl::UsingShadow:
7062 caseDecl::ClassTemplate:
7063 caseDecl::VarTemplate:
7065 caseDecl::VarTemplatePartialSpecialization:
7066 caseDecl::FunctionTemplate:
7067 caseDecl::TypeAliasTemplate:
7074DI->EmitUsingDecl(cast<UsingDecl>(*
D));
7076 caseDecl::UsingEnum:
7078DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*
D));
7080 caseDecl::NamespaceAlias:
7082DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*
D));
7084 caseDecl::UsingDirective:
7086DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*
D));
7088 caseDecl::CXXConstructor:
7091 caseDecl::CXXDestructor:
7095 caseDecl::StaticAssert:
7102 caseDecl::ObjCInterface:
7103 caseDecl::ObjCCategory:
7106 caseDecl::ObjCProtocol: {
7107 auto*Proto = cast<ObjCProtocolDecl>(
D);
7108 if(Proto->isThisDeclarationADefinition())
7113 caseDecl::ObjCCategoryImpl:
7116 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(
D));
7119 caseDecl::ObjCImplementation: {
7120 auto*OMD = cast<ObjCImplementationDecl>(
D);
7121EmitObjCPropertyImplementations(OMD);
7122EmitObjCIvarInitializations(OMD);
7127DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7128OMD->getClassInterface()), OMD->getLocation());
7131 caseDecl::ObjCMethod: {
7132 auto*OMD = cast<ObjCMethodDecl>(
D);
7138 caseDecl::ObjCCompatibleAlias:
7139 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(
D));
7142 caseDecl::PragmaComment: {
7143 const auto*PCD = cast<PragmaCommentDecl>(
D);
7144 switch(PCD->getCommentKind()) {
7146llvm_unreachable(
"unexpected pragma comment kind");
7161 caseDecl::PragmaDetectMismatch: {
7162 const auto*PDMD = cast<PragmaDetectMismatchDecl>(
D);
7167 caseDecl::LinkageSpec:
7168EmitLinkageSpec(cast<LinkageSpecDecl>(
D));
7171 caseDecl::FileScopeAsm: {
7173 if(LangOpts.CUDA && LangOpts.CUDAIsDevice)
7176 if(LangOpts.OpenMPIsTargetDevice)
7179 if(LangOpts.SYCLIsDevice)
7181 auto*AD = cast<FileScopeAsmDecl>(
D);
7182 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
7186 caseDecl::TopLevelStmt:
7187EmitTopLevelStmt(cast<TopLevelStmtDecl>(
D));
7190 caseDecl::Import: {
7191 auto*Import = cast<ImportDecl>(
D);
7194 if(!ImportedModules.insert(Import->getImportedModule()))
7198 if(!Import->getImportedOwningModule()) {
7200DI->EmitImportDecl(*Import);
7206 if(CXX20ModuleInits && Import->getImportedModule() &&
7207Import->getImportedModule()->isNamedModule())
7216 Visited.insert(Import->getImportedModule());
7217Stack.push_back(Import->getImportedModule());
7219 while(!Stack.empty()) {
7221 if(!EmittedModuleInitializers.insert(Mod).second)
7228 for(
auto*Submodule : Mod->
submodules()) {
7231 if(Submodule->IsExplicit)
7234 if(
Visited.insert(Submodule).second)
7235Stack.push_back(Submodule);
7242EmitDeclContext(cast<ExportDecl>(
D));
7245 caseDecl::OMPThreadPrivate:
7249 caseDecl::OMPAllocate:
7253 caseDecl::OMPDeclareReduction:
7257 caseDecl::OMPDeclareMapper:
7261 caseDecl::OMPRequires:
7266 caseDecl::TypeAlias:
7268DI->EmitAndRetainType(
7269 getContext().getTypedefType(cast<TypedefNameDecl>(
D)));
7281DI->EmitAndRetainType(
getContext().getEnumType(cast<EnumDecl>(
D)));
7284 caseDecl::HLSLBuffer:
7292assert(isa<TypeDecl>(
D) &&
"Unsupported decl kind");
7299 if(!CodeGenOpts.CoverageMapping)
7302 caseDecl::CXXConversion:
7303 caseDecl::CXXMethod:
7304 caseDecl::Function:
7305 caseDecl::ObjCMethod:
7306 caseDecl::CXXConstructor:
7307 caseDecl::CXXDestructor: {
7308 if(!cast<FunctionDecl>(
D)->doesThisDeclarationHaveABody())
7316DeferredEmptyCoverageMappingDecls.try_emplace(
D,
true);
7326 if(!CodeGenOpts.CoverageMapping)
7328 if(
const auto*Fn = dyn_cast<FunctionDecl>(
D)) {
7329 if(Fn->isTemplateInstantiation())
7332DeferredEmptyCoverageMappingDecls.insert_or_assign(
D,
false);
7340 for(
const auto&Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7343 const Decl*
D= Entry.first;
7345 caseDecl::CXXConversion:
7346 caseDecl::CXXMethod:
7347 caseDecl::Function:
7348 caseDecl::ObjCMethod: {
7355 caseDecl::CXXConstructor: {
7362 caseDecl::CXXDestructor: {
7379 if(llvm::Function *F =
getModule().getFunction(
"main")) {
7380 if(!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7382 auto*GA = llvm::GlobalAlias::create(
"__main_void", F);
7383GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7392llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7393 returnllvm::ConstantInt::get(i64, PtrInt);
7397llvm::NamedMDNode *&GlobalMetadata,
7399llvm::GlobalValue *Addr) {
7400 if(!GlobalMetadata)
7402CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7405llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7408GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7411boolCodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7412llvm::GlobalValue *CppFunc) {
7420 if(Elem == CppFunc)
7426 for(llvm::User *User : Elem->users()) {
7430 if(
auto*ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7431 if(ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7434 for(llvm::User *CEUser : ConstExpr->users()) {
7435 if(
auto*IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7436IFuncs.push_back(IFunc);
7441CEs.push_back(ConstExpr);
7442}
else if(
auto*IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7443IFuncs.push_back(IFunc);
7455 for(llvm::GlobalIFunc *IFunc : IFuncs)
7456IFunc->setResolver(
nullptr);
7457 for(llvm::ConstantExpr *ConstExpr : CEs)
7458ConstExpr->destroyConstant();
7462Elem->eraseFromParent();
7464 for(llvm::GlobalIFunc *IFunc : IFuncs) {
7469llvm::FunctionType::get(IFunc->getType(),
false);
7470llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7471CppFunc->getName(), ResolverTy, {},
false);
7472IFunc->setResolver(Resolver);
7482voidCodeGenModule::EmitStaticExternCAliases() {
7485 for(
auto&I : StaticExternCValues) {
7487llvm::GlobalValue *Val = I.second;
7495llvm::GlobalValue *ExistingElem =
7496 getModule().getNamedValue(Name->getName());
7500 if(!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7507 autoRes = Manglings.find(MangledName);
7508 if(Res == Manglings.end())
7510 Result= Res->getValue();
7521voidCodeGenModule::EmitDeclMetadata() {
7522llvm::NamedMDNode *GlobalMetadata =
nullptr;
7524 for(
auto&I : MangledDeclNames) {
7525llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
7535voidCodeGenFunction::EmitDeclMetadata() {
7536 if(LocalDeclMap.empty())
return;
7541 unsignedDeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7543llvm::NamedMDNode *GlobalMetadata =
nullptr;
7545 for(
auto&I : LocalDeclMap) {
7546 const Decl*
D= I.first;
7547llvm::Value *Addr = I.second.emitRawPointer(*
this);
7548 if(
auto*Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7550Alloca->setMetadata(
7551DeclPtrKind, llvm::MDNode::get(
7552Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7553}
else if(
auto*GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7560voidCodeGenModule::EmitVersionIdentMetadata() {
7561llvm::NamedMDNode *IdentMetadata =
7562TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7564llvm::LLVMContext &Ctx = TheModule.getContext();
7566llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7567IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7570voidCodeGenModule::EmitCommandLineMetadata() {
7571llvm::NamedMDNode *CommandLineMetadata =
7572TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7574llvm::LLVMContext &Ctx = TheModule.getContext();
7576llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7577CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7580voidCodeGenModule::EmitCoverageFile() {
7581llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7585llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7586llvm::LLVMContext &Ctx = TheModule.getContext();
7587 auto*CoverageDataFile =
7589 auto*CoverageNotesFile =
7591 for(
inti = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7592llvm::MDNode *CU = CUNode->getOperand(i);
7593llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7594GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7615 if(LangOpts.OpenMP && LangOpts.OpenMPSimd)
7617 for(
autoRefExpr :
D->varlist()) {
7618 auto*VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7620VD->getAnyInitializer() &&
7621!VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7627 if(
autoInitFunction =
getOpenMPRuntime().emitThreadPrivateVarDefinition(
7628VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7629CXXGlobalInits.push_back(InitFunction);
7634CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7638FnType->getReturnType(), FnType->getParamTypes(),
7639FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7641llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7646std::string OutName;
7647llvm::raw_string_ostream Out(OutName);
7652Out <<
".normalized";
7666 returnCreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7671 returnCreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
7691 for(
auto&Param : FnType->param_types())
7696GeneralizedParams, FnType->getExtProtoInfo());
7703llvm_unreachable(
"Encountered unknown FunctionType");
7708GeneralizedMetadataIdMap,
".generalized");
7715 return((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
7717(LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
7719(LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
7721(LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
7728llvm::Metadata *MD =
7730VTable->addTypeMetadata(Offset.getQuantity(), MD);
7732 if(CodeGenOpts.SanitizeCfiCrossDso)
7734VTable->addTypeMetadata(Offset.getQuantity(),
7735llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7738llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
7739VTable->addTypeMetadata(Offset.getQuantity(), MD);
7745SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
7755 auto*FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
7770 boolforPointeeType) {
7781 if(
autoAlign = TT->getDecl()->getMaxAlignment()) {
7811 if(
T.getQualifiers().hasUnaligned()) {
7813}
else if(forPointeeType && !AlignForArray &&
7825 if(
unsignedMaxAlign =
getLangOpts().MaxTypeAlign) {
7838 if(NumAutoVarInit >= StopAfter) {
7841 if(!NumAutoVarInit) {
7844 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 7845 "number of times ftrivial-auto-var-init=%1 gets applied.");
7859 const Decl*
D)
const{
7863OS << (isa<VarDecl>(
D) ?
".static.":
".intern.");
7865OS << (isa<VarDecl>(
D) ?
"__static__":
"__intern__");
7871assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7875llvm::MD5::MD5Result
Result;
7876 for(
const auto&Arg : PreprocessorOpts.
Macros)
7877Hash.update(Arg.first);
7881llvm::sys::fs::UniqueID ID;
7882 if(llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
7884assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7885 if(
autoEC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
7886 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7889OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
7890<<
"_"<< llvm::utohexstr(
Result.low(),
true,
8);
7897assert(DeferredDeclsToEmit.empty() &&
7898 "Should have emitted all decls deferred to emit.");
7899assert(NewBuilder->DeferredDecls.empty() &&
7900 "Newly created module should not have deferred decls");
7901NewBuilder->DeferredDecls = std::move(DeferredDecls);
7902assert(EmittedDeferredDecls.empty() &&
7903 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7905assert(NewBuilder->DeferredVTables.empty() &&
7906 "Newly created module should not have deferred vtables");
7907NewBuilder->DeferredVTables = std::move(DeferredVTables);
7909assert(NewBuilder->MangledDeclNames.empty() &&
7910 "Newly created module should not have mangled decl names");
7911assert(NewBuilder->Manglings.empty() &&
7912 "Newly created module should not have manglings");
7913NewBuilder->Manglings = std::move(Manglings);
7915NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7917NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
Defines the clang::ASTContext interface.
ASTImporterLookupTable & LT
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static bool hasImplicitAttr(const ValueDecl *D)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local, llvm::Function *F, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
static bool allowKCFIIdentifier(StringRef Name)
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, llvm::GlobalValue *GV)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static uint64_t getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
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...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, const NamedDecl *ND, bool OmitMultiVersionMangling=false)
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
llvm::DenseSet< const void * > Visited
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
llvm::StringMap< SectionInfo > SectionInfos
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
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 ...
QualType getRecordType(const RecordDecl *Decl) const
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.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
FullSourceLoc getFullLoc(SourceLocation Loc) const
const XRayFunctionFilter & getXRayFilter() const
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
Builtin::Context & BuiltinInfo
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType UnsignedLongTy
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const clang::PrintingPolicy & getPrintingPolicy() const
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
QualType getObjCIdType() const
Represents the Objective-CC id type.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
Represents binding an expression to a temporary.
Represents a call to a C++ constructor.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
Represents a delete expression for memory deallocation and destructor calls, e.g.
Represents a C++ destructor within a class.
Represents a call to a member function that may be written either with member call syntax (e....
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Represents a C++ struct/union/class.
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
CanProxy< U > castAs() const
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
std::string CoverageDataFile
The filename with path we use for coverage data files.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasProfileClangUse() const
Check if Clang profile use is on.
std::string SymbolPartition
The name of the partition that symbols are assigned to, specified with -fsymbol-partition (see https:...
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
CGFunctionInfo - Class to encapsulate the information about a function definition.
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
Class supports emissionof SIMD-only code.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
llvm::LLVMContext & getLLVMContext()
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CGDebugInfo * getModuleDebugInfo()
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
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 setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
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.
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
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.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
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.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::ConstantInt * CreateKCFITypeId(QualType T)
Generate a KCFI type identifier for T.
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
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.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
const T & getABIInfo() 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.
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 LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
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.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
Represents a member of a struct/union/class.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isSignReturnAddressWithAKey() const
Check if return address signing uses AKey.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
bool hasSignReturnAddress() const
Check if return address signing is enabled.
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
LangStandard::Kind LangStd
The used language standard.
bool isSignReturnAddressScopeAll() const
Check if leaf functions are also signed.
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
Represents a linkage specification.
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Represent a C++ namespace.
This represents '#pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
const ObjCInterfaceDecl * getClassInterface() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
ObjCMethodDecl - Represents an instance or class method declaration.
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 isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
std::vector< std::pair< std::string, bool > > Macros
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, CodeGenOptions::ProfileInstrKind Kind) const
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, CodeGenOptions::ProfileInstrKind Kind) const
ExclusionType
Represents if an how something should be excluded from profiling.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
ExclusionType getDefault(CodeGenOptions::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, CodeGenOptions::ProfileInstrKind Kind) const
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Stmt - This represents one statement.
StringLiteral - This represents a string literal expression, e.g.
Represents the declaration of a struct/union/class/enum.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual uint64_t getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
std::vector< std::string > Features
The list of target specific features to enable or disable â this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const Type * getTypeForDecl() const
The base class of the type hierarchy.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPNaClTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
const FunctionProtoType * T
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
@ EST_None
no exception specification
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
cl::opt< bool > SystemHeadersCoverage
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
llvm::CallingConv::ID RuntimeCC
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
Parts of a decomposed MSGuidDecl.
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
Contains information gathered from parsing the contents of TargetAttr.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4