50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/Analysis/TargetLibraryInfo.h"
54#include "llvm/BinaryFormat/ELF.h"
55#include "llvm/IR/AttributeMask.h"
56#include "llvm/IR/CallingConv.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ProfileSummary.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/ProfileData/SampleProf.h"
64#include "llvm/Support/CRC.h"
65#include "llvm/Support/CodeGen.h"
66#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/xxhash.h"
71#include "llvm/TargetParser/RISCVISAInfo.h"
72#include "llvm/TargetParser/Triple.h"
73#include "llvm/TargetParser/X86TargetParser.h"
74#include "llvm/Transforms/Utils/BuildLibCalls.h"
82 "limited-coverage-experimental", llvm::cl::Hidden,
83 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
89 case TargetCXXABI::AppleARM64:
90 case TargetCXXABI::Fuchsia:
91 case TargetCXXABI::GenericAArch64:
92 case TargetCXXABI::GenericARM:
93 case TargetCXXABI::iOS:
94 case TargetCXXABI::WatchOS:
95 case TargetCXXABI::GenericMIPS:
96 case TargetCXXABI::GenericItanium:
97 case TargetCXXABI::WebAssembly:
98 case TargetCXXABI::XL:
100 case TargetCXXABI::Microsoft:
104 llvm_unreachable(
"invalid C++ ABI kind");
107static std::unique_ptr<TargetCodeGenInfo>
110 const llvm::Triple &Triple =
Target.getTriple();
113 switch (Triple.getArch()) {
117 case llvm::Triple::m68k:
119 case llvm::Triple::mips:
120 case llvm::Triple::mipsel:
121 if (Triple.getOS() == llvm::Triple::Win32)
125 case llvm::Triple::mips64:
126 case llvm::Triple::mips64el:
129 case llvm::Triple::avr: {
133 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
134 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
138 case llvm::Triple::aarch64:
139 case llvm::Triple::aarch64_32:
140 case llvm::Triple::aarch64_be: {
142 if (
Target.getABI() ==
"darwinpcs")
143 Kind = AArch64ABIKind::DarwinPCS;
144 else if (Triple.isOSWindows())
146 else if (
Target.getABI() ==
"aapcs-soft")
147 Kind = AArch64ABIKind::AAPCSSoft;
148 else if (
Target.getABI() ==
"pauthtest")
149 Kind = AArch64ABIKind::PAuthTest;
154 case llvm::Triple::wasm32:
155 case llvm::Triple::wasm64: {
157 if (
Target.getABI() ==
"experimental-mv")
158 Kind = WebAssemblyABIKind::ExperimentalMV;
162 case llvm::Triple::arm:
163 case llvm::Triple::armeb:
164 case llvm::Triple::thumb:
165 case llvm::Triple::thumbeb: {
166 if (Triple.getOS() == llvm::Triple::Win32)
170 StringRef ABIStr =
Target.getABI();
171 if (ABIStr ==
"apcs-gnu")
172 Kind = ARMABIKind::APCS;
173 else if (ABIStr ==
"aapcs16")
174 Kind = ARMABIKind::AAPCS16_VFP;
175 else if (CodeGenOpts.
FloatABI ==
"hard" ||
176 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
177 Kind = ARMABIKind::AAPCS_VFP;
182 case llvm::Triple::ppc: {
183 if (Triple.isOSAIX())
190 case llvm::Triple::ppcle: {
195 case llvm::Triple::ppc64:
196 if (Triple.isOSAIX())
199 if (Triple.isOSBinFormatELF()) {
201 if (
Target.getABI() ==
"elfv2")
202 Kind = PPC64_SVR4_ABIKind::ELFv2;
203 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
208 case llvm::Triple::ppc64le: {
209 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
211 if (
Target.getABI() ==
"elfv1")
212 Kind = PPC64_SVR4_ABIKind::ELFv1;
213 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
218 case llvm::Triple::nvptx:
219 case llvm::Triple::nvptx64:
222 case llvm::Triple::msp430:
225 case llvm::Triple::riscv32:
226 case llvm::Triple::riscv64: {
227 StringRef ABIStr =
Target.getABI();
229 unsigned ABIFLen = 0;
230 if (ABIStr.ends_with(
"f"))
232 else if (ABIStr.ends_with(
"d"))
234 bool EABI = ABIStr.ends_with(
"e");
238 case llvm::Triple::systemz: {
239 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
240 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
244 case llvm::Triple::tce:
245 case llvm::Triple::tcele:
248 case llvm::Triple::x86: {
249 bool IsDarwinVectorABI = Triple.isOSDarwin();
250 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
252 if (Triple.getOS() == llvm::Triple::Win32) {
254 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
255 CodeGenOpts.NumRegisterParameters);
258 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
259 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
262 case llvm::Triple::x86_64: {
263 StringRef ABI =
Target.getABI();
264 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
265 : ABI ==
"avx" ? X86AVXABILevel::AVX
266 : X86AVXABILevel::None);
268 switch (Triple.getOS()) {
269 case llvm::Triple::UEFI:
270 case llvm::Triple::Win32:
276 case llvm::Triple::hexagon:
278 case llvm::Triple::lanai:
280 case llvm::Triple::r600:
282 case llvm::Triple::amdgcn:
284 case llvm::Triple::sparc:
286 case llvm::Triple::sparcv9:
288 case llvm::Triple::xcore:
290 case llvm::Triple::arc:
292 case llvm::Triple::spir:
293 case llvm::Triple::spir64:
295 case llvm::Triple::spirv32:
296 case llvm::Triple::spirv64:
297 case llvm::Triple::spirv:
299 case llvm::Triple::dxil:
301 case llvm::Triple::ve:
303 case llvm::Triple::csky: {
304 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
306 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
311 case llvm::Triple::bpfeb:
312 case llvm::Triple::bpfel:
314 case llvm::Triple::loongarch32:
315 case llvm::Triple::loongarch64: {
316 StringRef ABIStr =
Target.getABI();
317 unsigned ABIFRLen = 0;
318 if (ABIStr.ends_with(
"f"))
320 else if (ABIStr.ends_with(
"d"))
329 if (!TheTargetCodeGenInfo)
331 return *TheTargetCodeGenInfo;
335 llvm::LLVMContext &Context,
339 if (Opts.AlignDouble || Opts.OpenCL || Opts.HLSL)
342 llvm::Triple Triple =
Target.getTriple();
343 llvm::DataLayout DL(
Target.getDataLayoutString());
344 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
345 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
346 llvm::Align ClangAlign(Alignment / 8);
347 if (DLAlign != ClangAlign) {
348 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
349 <<
" mapping to " << *Ty <<
" has data layout alignment "
350 << DLAlign.value() <<
" while clang specifies "
351 << ClangAlign.value() <<
"\n";
356 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
358 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
360 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
362 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
365 if (Triple.getArch() != llvm::Triple::m68k)
366 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
369 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
370 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
371 Triple.getArch() != llvm::Triple::ve)
372 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
374 if (
Target.hasFloat16Type())
375 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
377 if (
Target.hasBFloat16Type())
378 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
379 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
382 if (!Triple.isOSAIX()) {
384 llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
387 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
390 if (
Target.hasFloat128Type())
391 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
392 if (
Target.hasIbm128Type())
393 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
395 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
406 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
407 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
409 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
415 llvm::LLVMContext &LLVMContext = M.getContext();
416 VoidTy = llvm::Type::getVoidTy(LLVMContext);
417 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
418 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
419 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
420 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
421 HalfTy = llvm::Type::getHalfTy(LLVMContext);
422 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
423 FloatTy = llvm::Type::getFloatTy(LLVMContext);
424 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
430 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
432 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
434 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
435 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
436 IntPtrTy = llvm::IntegerType::get(LLVMContext,
437 C.getTargetInfo().getMaxPointerWidth());
438 Int8PtrTy = llvm::PointerType::get(LLVMContext,
440 const llvm::DataLayout &DL = M.getDataLayout();
442 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
444 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
461 createOpenCLRuntime();
463 createOpenMPRuntime();
470 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
471 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
477 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
478 CodeGenOpts.CoverageNotesFile.size() ||
479 CodeGenOpts.CoverageDataFile.size())
487 Block.GlobalUniqueCount = 0;
489 if (
C.getLangOpts().ObjC)
492 if (CodeGenOpts.hasProfileClangUse()) {
493 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
494 CodeGenOpts.ProfileInstrumentUsePath, *FS,
495 CodeGenOpts.ProfileRemappingFile);
500 PGOReader = std::move(ReaderOrErr.get());
505 if (CodeGenOpts.CoverageMapping)
509 if (CodeGenOpts.UniqueInternalLinkageNames &&
510 !
getModule().getSourceFileName().empty()) {
511 std::string Path =
getModule().getSourceFileName();
513 for (
const auto &Entry : LangOpts.MacroPrefixMap)
514 if (Path.rfind(Entry.first, 0) != std::string::npos) {
515 Path = Entry.second + Path.substr(Entry.first.size());
518 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
522 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
523 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
524 CodeGenOpts.NumRegisterParameters);
533 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
534 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
536 this->MSHotPatchFunctions.push_back(std::string{*I});
538 auto &DE = Context.getDiagnostics();
541 "failed to open hotpatch functions file "
542 "(-fms-hotpatch-functions-file): %0 : %1");
544 << BufOrErr.getError().message();
549 this->MSHotPatchFunctions.push_back(FuncName);
551 llvm::sort(this->MSHotPatchFunctions);
554 if (!Context.getAuxTargetInfo())
560void CodeGenModule::createObjCRuntime() {
577 llvm_unreachable(
"bad runtime kind");
580void CodeGenModule::createOpenCLRuntime() {
584void CodeGenModule::createOpenMPRuntime() {
585 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
586 Diags.Report(diag::err_omp_host_ir_file_not_found)
587 << LangOpts.OMPHostIRFile;
592 case llvm::Triple::nvptx:
593 case llvm::Triple::nvptx64:
594 case llvm::Triple::amdgcn:
595 case llvm::Triple::spirv64:
598 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
599 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
602 if (LangOpts.OpenMPSimd)
603 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
605 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
610void CodeGenModule::createCUDARuntime() {
614void CodeGenModule::createHLSLRuntime() {
615 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
619 Replacements[Name] =
C;
622void CodeGenModule::applyReplacements() {
623 for (
auto &I : Replacements) {
624 StringRef MangledName = I.first;
625 llvm::Constant *Replacement = I.second;
630 auto *NewF = dyn_cast<llvm::Function>(Replacement);
632 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
633 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
636 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
637 CE->getOpcode() == llvm::Instruction::GetElementPtr);
638 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
643 OldF->replaceAllUsesWith(Replacement);
645 NewF->removeFromParent();
646 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
649 OldF->eraseFromParent();
654 GlobalValReplacements.push_back(std::make_pair(GV,
C));
657void CodeGenModule::applyGlobalValReplacements() {
658 for (
auto &I : GlobalValReplacements) {
659 llvm::GlobalValue *GV = I.first;
660 llvm::Constant *
C = I.second;
662 GV->replaceAllUsesWith(
C);
663 GV->eraseFromParent();
670 const llvm::Constant *
C;
671 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
672 C = GA->getAliasee();
673 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
674 C = GI->getResolver();
678 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
682 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
691 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
692 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
696 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
700 if (GV->hasCommonLinkage()) {
701 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
702 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
703 Diags.
Report(Location, diag::err_alias_to_common);
708 if (GV->isDeclaration()) {
709 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
710 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
711 << IsIFunc << IsIFunc;
714 for (
const auto &[
Decl, Name] : MangledDeclNames) {
715 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
717 if (II && II->
getName() == GV->getName()) {
718 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
722 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
732 const auto *F = dyn_cast<llvm::Function>(GV);
734 Diags.
Report(Location, diag::err_alias_to_undefined)
735 << IsIFunc << IsIFunc;
739 llvm::FunctionType *FTy = F->getFunctionType();
740 if (!FTy->getReturnType()->isPointerTy()) {
741 Diags.
Report(Location, diag::err_ifunc_resolver_return);
755 if (GVar->hasAttribute(
"toc-data")) {
756 auto GVId = GVar->getName();
759 Diags.
Report(Location, diag::warn_toc_unsupported_type)
760 << GVId <<
"the variable has an alias";
762 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
763 llvm::AttributeSet NewAttributes =
764 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
765 GVar->setAttributes(NewAttributes);
769void CodeGenModule::checkAliases() {
774 DiagnosticsEngine &Diags =
getDiags();
775 for (
const GlobalDecl &GD : Aliases) {
777 SourceLocation Location;
779 bool IsIFunc = D->hasAttr<IFuncAttr>();
780 if (
const Attr *A = D->getDefiningAttr()) {
781 Location = A->getLocation();
782 Range = A->getRange();
784 llvm_unreachable(
"Not an alias or ifunc?");
788 const llvm::GlobalValue *GV =
nullptr;
790 MangledDeclNames, Range)) {
796 if (
const llvm::GlobalVariable *GVar =
797 dyn_cast<const llvm::GlobalVariable>(GV))
801 llvm::Constant *Aliasee =
805 llvm::GlobalValue *AliaseeGV;
806 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
811 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
812 StringRef AliasSection = SA->getName();
813 if (AliasSection != AliaseeGV->getSection())
814 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
815 << AliasSection << IsIFunc << IsIFunc;
823 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
824 if (GA->isInterposable()) {
825 Diags.Report(Location, diag::warn_alias_to_weak_alias)
826 << GV->getName() << GA->getName() << IsIFunc;
827 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
828 GA->getAliasee(), Alias->getType());
840 llvm::Attribute::DisableSanitizerInstrumentation);
845 for (
const GlobalDecl &GD : Aliases) {
848 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
849 Alias->eraseFromParent();
854 DeferredDeclsToEmit.clear();
855 EmittedDeferredDecls.clear();
856 DeferredAnnotations.clear();
858 OpenMPRuntime->clear();
862 StringRef MainFile) {
865 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
866 if (MainFile.empty())
867 MainFile =
"<stdin>";
868 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
871 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
874 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
878static std::optional<llvm::GlobalValue::VisibilityTypes>
885 return llvm::GlobalValue::DefaultVisibility;
887 return llvm::GlobalValue::HiddenVisibility;
889 return llvm::GlobalValue::ProtectedVisibility;
891 llvm_unreachable(
"unknown option value!");
896 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
905 GV.setDSOLocal(
false);
906 GV.setVisibility(*
V);
911 if (!LO.VisibilityFromDLLStorageClass)
914 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
917 std::optional<llvm::GlobalValue::VisibilityTypes>
918 NoDLLStorageClassVisibility =
921 std::optional<llvm::GlobalValue::VisibilityTypes>
922 ExternDeclDLLImportVisibility =
925 std::optional<llvm::GlobalValue::VisibilityTypes>
926 ExternDeclNoDLLStorageClassVisibility =
929 for (llvm::GlobalValue &GV : M.global_values()) {
930 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
933 if (GV.isDeclarationForLinker())
935 llvm::GlobalValue::DLLImportStorageClass
936 ? ExternDeclDLLImportVisibility
937 : ExternDeclNoDLLStorageClassVisibility);
940 llvm::GlobalValue::DLLExportStorageClass
941 ? DLLExportVisibility
942 : NoDLLStorageClassVisibility);
944 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
949 const llvm::Triple &Triple,
953 return LangOpts.getStackProtector() == Mode;
959 EmitModuleInitializers(Primary);
961 DeferredDecls.insert_range(EmittedDeferredDecls);
962 EmittedDeferredDecls.clear();
963 EmitVTablesOpportunistically();
964 applyGlobalValReplacements();
966 emitMultiVersionFunctions();
968 if (Context.getLangOpts().IncrementalExtensions &&
969 GlobalTopLevelStmtBlockInFlight.first) {
971 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
972 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
978 EmitCXXModuleInitFunc(Primary);
980 EmitCXXGlobalInitFunc();
981 EmitCXXGlobalCleanUpFunc();
982 registerGlobalDtorsWithAtExit();
983 EmitCXXThreadLocalInitFunc();
985 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
987 if (Context.getLangOpts().CUDA && CUDARuntime) {
988 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
992 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
993 OpenMPRuntime->clear();
997 PGOReader->getSummary(
false).getMD(VMContext),
998 llvm::ProfileSummary::PSK_Instr);
999 if (PGOStats.hasDiagnostics())
1005 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1006 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1008 EmitStaticExternCAliases();
1013 if (CoverageMapping)
1014 CoverageMapping->emit();
1015 if (CodeGenOpts.SanitizeCfiCrossDso) {
1019 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1021 emitAtAvailableLinkGuard();
1022 if (Context.getTargetInfo().getTriple().isWasm())
1029 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1030 llvm::CodeObjectVersionKind::COV_None) {
1031 getModule().addModuleFlag(llvm::Module::Error,
1032 "amdhsa_code_object_version",
1033 getTarget().getTargetOpts().CodeObjectVersion);
1038 auto *MDStr = llvm::MDString::get(
1043 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1052 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1054 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1056 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1060 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1064 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1066 auto *GV =
new llvm::GlobalVariable(
1067 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1068 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1074 auto *GV =
new llvm::GlobalVariable(
1076 llvm::Constant::getNullValue(
Int8Ty),
1085 if (CodeGenOpts.Autolink &&
1086 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1087 EmitModuleLinkOptions();
1102 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1103 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1104 for (
auto *MD : ELFDependentLibraries)
1105 NMD->addOperand(MD);
1108 if (CodeGenOpts.DwarfVersion) {
1109 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1110 CodeGenOpts.DwarfVersion);
1113 if (CodeGenOpts.Dwarf64)
1114 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1116 if (Context.getLangOpts().SemanticInterposition)
1118 getModule().setSemanticInterposition(
true);
1120 if (CodeGenOpts.EmitCodeView) {
1122 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1124 if (CodeGenOpts.CodeViewGHash) {
1125 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1127 if (CodeGenOpts.ControlFlowGuard) {
1129 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1130 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1132 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1134 if (CodeGenOpts.EHContGuard) {
1136 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1138 if (Context.getLangOpts().Kernel) {
1140 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1142 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1147 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1149 llvm::Metadata *Ops[2] = {
1150 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1151 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1152 llvm::Type::getInt32Ty(VMContext), 1))};
1154 getModule().addModuleFlag(llvm::Module::Require,
1155 "StrictVTablePointersRequirement",
1156 llvm::MDNode::get(VMContext, Ops));
1162 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1163 llvm::DEBUG_METADATA_VERSION);
1168 uint64_t WCharWidth =
1169 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1170 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1173 getModule().addModuleFlag(llvm::Module::Warning,
1174 "zos_product_major_version",
1175 uint32_t(CLANG_VERSION_MAJOR));
1176 getModule().addModuleFlag(llvm::Module::Warning,
1177 "zos_product_minor_version",
1178 uint32_t(CLANG_VERSION_MINOR));
1179 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1180 uint32_t(CLANG_VERSION_PATCHLEVEL));
1182 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1183 llvm::MDString::get(VMContext, ProductId));
1188 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1189 llvm::MDString::get(VMContext, lang_str));
1191 time_t TT = PreprocessorOpts.SourceDateEpoch
1192 ? *PreprocessorOpts.SourceDateEpoch
1193 : std::time(
nullptr);
1194 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1195 static_cast<uint64_t
>(TT));
1198 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1199 llvm::MDString::get(VMContext,
"ascii"));
1202 llvm::Triple
T = Context.getTargetInfo().getTriple();
1203 if (
T.isARM() ||
T.isThumb()) {
1205 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1206 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1210 StringRef ABIStr = Target.getABI();
1211 llvm::LLVMContext &Ctx = TheModule.getContext();
1212 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1213 llvm::MDString::get(Ctx, ABIStr));
1218 const std::vector<std::string> &Features =
1221 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1222 if (!errorToBool(ParseResult.takeError()))
1224 llvm::Module::AppendUnique,
"riscv-isa",
1226 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1229 if (CodeGenOpts.SanitizeCfiCrossDso) {
1231 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1234 if (CodeGenOpts.WholeProgramVTables) {
1238 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1239 CodeGenOpts.VirtualFunctionElimination);
1242 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1243 getModule().addModuleFlag(llvm::Module::Override,
1244 "CFI Canonical Jump Tables",
1245 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1248 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1249 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1253 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1255 llvm::Module::Append,
"Unique Source File Identifier",
1257 TheModule.getContext(),
1258 llvm::MDString::get(TheModule.getContext(),
1259 CodeGenOpts.UniqueSourceFileIdentifier)));
1262 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1263 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1266 if (CodeGenOpts.PatchableFunctionEntryOffset)
1267 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1268 CodeGenOpts.PatchableFunctionEntryOffset);
1269 if (CodeGenOpts.SanitizeKcfiArity)
1270 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1273 if (CodeGenOpts.CFProtectionReturn &&
1274 Target.checkCFProtectionReturnSupported(
getDiags())) {
1276 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1280 if (CodeGenOpts.CFProtectionBranch &&
1281 Target.checkCFProtectionBranchSupported(
getDiags())) {
1283 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1286 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1287 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1289 Scheme = Target.getDefaultCFBranchLabelScheme();
1291 llvm::Module::Error,
"cf-branch-label-scheme",
1297 if (CodeGenOpts.FunctionReturnThunks)
1298 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1300 if (CodeGenOpts.IndirectBranchCSPrefix)
1301 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1312 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1313 LangOpts.getSignReturnAddressScope() !=
1315 getModule().addModuleFlag(llvm::Module::Override,
1316 "sign-return-address-buildattr", 1);
1317 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1318 getModule().addModuleFlag(llvm::Module::Override,
1319 "tag-stack-memory-buildattr", 1);
1321 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1322 if (LangOpts.BranchTargetEnforcement)
1323 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1325 if (LangOpts.BranchProtectionPAuthLR)
1326 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1328 if (LangOpts.GuardedControlStack)
1329 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1330 if (LangOpts.hasSignReturnAddress())
1331 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1332 if (LangOpts.isSignReturnAddressScopeAll())
1333 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1335 if (!LangOpts.isSignReturnAddressWithAKey())
1336 getModule().addModuleFlag(llvm::Module::Min,
1337 "sign-return-address-with-bkey", 1);
1339 if (LangOpts.PointerAuthELFGOT)
1340 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1343 if (LangOpts.PointerAuthCalls)
1344 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1347 using namespace llvm::ELF;
1348 uint64_t PAuthABIVersion =
1349 (LangOpts.PointerAuthIntrinsics
1350 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1351 (LangOpts.PointerAuthCalls
1352 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1353 (LangOpts.PointerAuthReturns
1354 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1355 (LangOpts.PointerAuthAuthTraps
1356 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1357 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1358 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1359 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1360 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1361 (LangOpts.PointerAuthInitFini
1362 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1363 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1364 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1365 (LangOpts.PointerAuthELFGOT
1366 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1367 (LangOpts.PointerAuthIndirectGotos
1368 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1369 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1370 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1371 (LangOpts.PointerAuthFunctionTypeDiscrimination
1372 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1373 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1374 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1375 "Update when new enum items are defined");
1376 if (PAuthABIVersion != 0) {
1377 getModule().addModuleFlag(llvm::Module::Error,
1378 "aarch64-elf-pauthabi-platform",
1379 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1380 getModule().addModuleFlag(llvm::Module::Error,
1381 "aarch64-elf-pauthabi-version",
1387 if (CodeGenOpts.StackClashProtector)
1389 llvm::Module::Override,
"probe-stack",
1390 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1392 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1393 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1394 CodeGenOpts.StackProbeSize);
1396 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1397 llvm::LLVMContext &Ctx = TheModule.getContext();
1399 llvm::Module::Error,
"MemProfProfileFilename",
1400 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1403 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1407 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1408 CodeGenOpts.FP32DenormalMode.Output !=
1409 llvm::DenormalMode::IEEE);
1412 if (LangOpts.EHAsynch)
1413 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1416 if (CodeGenOpts.ImportCallOptimization)
1417 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1421 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1423 llvm::Module::Warning,
"winx64-eh-unwindv2",
1424 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1428 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1430 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1434 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1435 EmitOpenCLMetadata();
1442 auto Version = LangOpts.getOpenCLCompatibleVersion();
1443 llvm::Metadata *SPIRVerElts[] = {
1444 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1446 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1447 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1448 llvm::NamedMDNode *SPIRVerMD =
1449 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1450 llvm::LLVMContext &Ctx = TheModule.getContext();
1451 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1459 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1460 assert(PLevel < 3 &&
"Invalid PIC Level");
1461 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1462 if (Context.getLangOpts().PIE)
1463 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1467 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1468 .Case(
"tiny", llvm::CodeModel::Tiny)
1469 .Case(
"small", llvm::CodeModel::Small)
1470 .Case(
"kernel", llvm::CodeModel::Kernel)
1471 .Case(
"medium", llvm::CodeModel::Medium)
1472 .Case(
"large", llvm::CodeModel::Large)
1475 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1478 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1479 Context.getTargetInfo().getTriple().getArch() ==
1480 llvm::Triple::x86_64) {
1486 if (CodeGenOpts.NoPLT)
1489 CodeGenOpts.DirectAccessExternalData !=
1490 getModule().getDirectAccessExternalData()) {
1491 getModule().setDirectAccessExternalData(
1492 CodeGenOpts.DirectAccessExternalData);
1494 if (CodeGenOpts.UnwindTables)
1495 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1497 switch (CodeGenOpts.getFramePointer()) {
1502 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1505 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1508 getModule().setFramePointer(llvm::FramePointerKind::All);
1512 SimplifyPersonality();
1525 EmitVersionIdentMetadata();
1528 EmitCommandLineMetadata();
1536 getModule().setStackProtectorGuardSymbol(
1539 getModule().setStackProtectorGuardOffset(
1544 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1546 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1548 if (
getContext().getTargetInfo().getMaxTLSAlign())
1549 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1550 getContext().getTargetInfo().getMaxTLSAlign());
1568 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1569 for (
auto &I : MustTailCallUndefinedGlobals) {
1570 if (!I.first->isDefined())
1571 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1575 if (!Entry || Entry->isWeakForLinker() ||
1576 Entry->isDeclarationForLinker())
1577 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1583void CodeGenModule::EmitOpenCLMetadata() {
1589 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1590 llvm::Metadata *OCLVerElts[] = {
1591 llvm::ConstantAsMetadata::get(
1592 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1593 llvm::ConstantAsMetadata::get(
1594 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1595 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1596 llvm::LLVMContext &Ctx = TheModule.getContext();
1597 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1600 EmitVersion(
"opencl.ocl.version", CLVersion);
1601 if (LangOpts.OpenCLCPlusPlus) {
1603 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1607void CodeGenModule::EmitBackendOptionsMetadata(
1608 const CodeGenOptions &CodeGenOpts) {
1610 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1611 CodeGenOpts.SmallDataLimit);
1628 return TBAA->getTypeInfo(QTy);
1647 return TBAA->getAccessInfo(AccessType);
1654 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1660 return TBAA->getTBAAStructInfo(QTy);
1666 return TBAA->getBaseTypeInfo(QTy);
1672 return TBAA->getAccessTagInfo(Info);
1679 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1687 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1695 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1701 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1706 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1719 "cannot compile this %0 yet");
1720 std::string Msg =
Type;
1729 "cannot compile this %0 yet");
1730 std::string Msg =
Type;
1735 llvm::function_ref<
void()> Fn) {
1736 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1746 if (GV->hasLocalLinkage()) {
1747 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1760 if (Context.getLangOpts().OpenMP &&
1761 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
1762 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1763 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1764 OMPDeclareTargetDeclAttr::DT_NoHost &&
1766 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1771 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1775 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1779 if (GV->hasDLLExportStorageClass()) {
1782 diag::err_hidden_visibility_dllexport);
1785 diag::err_non_default_visibility_dllimport);
1791 !GV->isDeclarationForLinker())
1796 llvm::GlobalValue *GV) {
1797 if (GV->hasLocalLinkage())
1800 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1804 if (GV->hasDLLImportStorageClass())
1807 const llvm::Triple &TT = CGM.
getTriple();
1809 if (TT.isOSCygMing()) {
1827 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1835 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1839 if (!TT.isOSBinFormatELF())
1845 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1853 return !(CGM.
getLangOpts().SemanticInterposition ||
1858 if (!GV->isDeclarationForLinker())
1864 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1871 if (CGOpts.DirectAccessExternalData) {
1877 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1878 if (!Var->isThreadLocal())
1903 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
1905 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1915 if (D->
hasAttr<DLLImportAttr>())
1916 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1917 else if ((D->
hasAttr<DLLExportAttr>() ||
1919 !GV->isDeclarationForLinker())
1920 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1940 GV->setPartition(CodeGenOpts.SymbolPartition);
1944 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1945 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1946 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1947 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1948 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1951llvm::GlobalVariable::ThreadLocalMode
1953 switch (CodeGenOpts.getDefaultTLSModel()) {
1955 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1957 return llvm::GlobalVariable::LocalDynamicTLSModel;
1959 return llvm::GlobalVariable::InitialExecTLSModel;
1961 return llvm::GlobalVariable::LocalExecTLSModel;
1963 llvm_unreachable(
"Invalid TLS model!");
1967 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
1969 llvm::GlobalValue::ThreadLocalMode TLM;
1973 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
1977 GV->setThreadLocalMode(TLM);
1983 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1987 const CPUSpecificAttr *
Attr,
2009 bool OmitMultiVersionMangling =
false) {
2011 llvm::raw_svector_ostream Out(Buffer);
2020 assert(II &&
"Attempt to mangle unnamed decl.");
2021 const auto *FD = dyn_cast<FunctionDecl>(ND);
2026 Out <<
"__regcall4__" << II->
getName();
2028 Out <<
"__regcall3__" << II->
getName();
2029 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2031 Out <<
"__device_stub__" << II->
getName();
2033 DeviceKernelAttr::isOpenCLSpelling(
2034 FD->getAttr<DeviceKernelAttr>()) &&
2036 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2052 "Hash computed when not explicitly requested");
2056 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2057 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2058 switch (FD->getMultiVersionKind()) {
2062 FD->getAttr<CPUSpecificAttr>(),
2066 auto *
Attr = FD->getAttr<TargetAttr>();
2067 assert(
Attr &&
"Expected TargetAttr to be present "
2068 "for attribute mangling");
2074 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2075 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2076 "for attribute mangling");
2082 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2083 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2084 "for attribute mangling");
2091 llvm_unreachable(
"None multiversion type isn't valid here");
2101 return std::string(Out.str());
2104void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2105 const FunctionDecl *FD,
2106 StringRef &CurName) {
2113 std::string NonTargetName =
2121 "Other GD should now be a multiversioned function");
2131 if (OtherName != NonTargetName) {
2134 const auto ExistingRecord = Manglings.find(NonTargetName);
2135 if (ExistingRecord != std::end(Manglings))
2136 Manglings.remove(&(*ExistingRecord));
2137 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2142 CurName = OtherNameRef;
2144 Entry->setName(OtherName);
2154 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2168 auto FoundName = MangledDeclNames.find(CanonicalGD);
2169 if (FoundName != MangledDeclNames.end())
2170 return FoundName->second;
2207 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2208 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2217 llvm::raw_svector_ostream Out(Buffer);
2220 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2221 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2223 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2228 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2229 return Result.first->first();
2233 auto it = MangledDeclNames.begin();
2234 while (it != MangledDeclNames.end()) {
2235 if (it->second == Name)
2250 llvm::Constant *AssociatedData) {
2252 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2258 bool IsDtorAttrFunc) {
2259 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2261 DtorsUsingAtExit[Priority].push_back(Dtor);
2266 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2269void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2270 if (Fns.empty())
return;
2276 llvm::PointerType *PtrTy = llvm::PointerType::get(
2277 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2280 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2284 auto Ctors = Builder.beginArray(CtorStructTy);
2285 for (
const auto &I : Fns) {
2286 auto Ctor = Ctors.beginStruct(CtorStructTy);
2287 Ctor.addInt(
Int32Ty, I.Priority);
2288 if (InitFiniAuthSchema) {
2289 llvm::Constant *StorageAddress =
2291 ? llvm::ConstantExpr::getIntToPtr(
2292 llvm::ConstantInt::get(
2294 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2298 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2299 llvm::ConstantInt::get(
2301 Ctor.add(SignedCtorPtr);
2303 Ctor.add(I.Initializer);
2305 if (I.AssociatedData)
2306 Ctor.add(I.AssociatedData);
2308 Ctor.addNullPointer(PtrTy);
2309 Ctor.finishAndAddTo(Ctors);
2312 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2314 llvm::GlobalValue::AppendingLinkage);
2318 List->setAlignment(std::nullopt);
2323llvm::GlobalValue::LinkageTypes
2329 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2336 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2337 if (!MDS)
return nullptr;
2339 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2346 const RecordDecl *UD = UT->getOriginalDecl()->getDefinitionOrSelf();
2347 if (!UD->
hasAttr<TransparentUnionAttr>())
2349 for (
const auto *it : UD->
fields()) {
2350 return it->getType();
2360 bool GeneralizePointers) {
2373 bool GeneralizePointers) {
2376 for (
auto &Param : FnType->param_types())
2377 GeneralizedParams.push_back(
2381 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2382 GeneralizedParams, FnType->getExtProtoInfo());
2387 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2389 llvm_unreachable(
"Encountered unknown FunctionType");
2397 FnType->getReturnType(), FnType->getParamTypes(),
2398 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2400 std::string OutName;
2401 llvm::raw_string_ostream Out(OutName);
2409 Out <<
".normalized";
2411 Out <<
".generalized";
2413 return llvm::ConstantInt::get(
Int32Ty,
2414 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2419 llvm::Function *F,
bool IsThunk) {
2421 llvm::AttributeList PAL;
2424 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2428 Loc = D->getLocation();
2430 Error(Loc,
"__vectorcall calling convention is not currently supported");
2432 F->setAttributes(PAL);
2433 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2437 std::string ReadOnlyQual(
"__read_only");
2438 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2439 if (ReadOnlyPos != std::string::npos)
2441 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2443 std::string WriteOnlyQual(
"__write_only");
2444 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2445 if (WriteOnlyPos != std::string::npos)
2446 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2448 std::string ReadWriteQual(
"__read_write");
2449 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2450 if (ReadWritePos != std::string::npos)
2451 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2484 assert(((FD && CGF) || (!FD && !CGF)) &&
2485 "Incorrect use - FD and CGF should either be both null or not!");
2511 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2514 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2519 std::string typeQuals;
2523 const Decl *PDecl = parm;
2525 PDecl = TD->getDecl();
2526 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2527 if (A && A->isWriteOnly())
2528 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2529 else if (A && A->isReadWrite())
2530 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2532 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2534 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2536 auto getTypeSpelling = [&](
QualType Ty) {
2537 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2539 if (Ty.isCanonical()) {
2540 StringRef typeNameRef = typeName;
2542 if (typeNameRef.consume_front(
"unsigned "))
2543 return std::string(
"u") + typeNameRef.str();
2544 if (typeNameRef.consume_front(
"signed "))
2545 return typeNameRef.str();
2555 addressQuals.push_back(
2556 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2560 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2561 std::string baseTypeName =
2563 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2564 argBaseTypeNames.push_back(
2565 llvm::MDString::get(VMContext, baseTypeName));
2569 typeQuals =
"restrict";
2572 typeQuals += typeQuals.empty() ?
"const" :
" const";
2574 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2576 uint32_t AddrSpc = 0;
2581 addressQuals.push_back(
2582 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2586 std::string typeName = getTypeSpelling(ty);
2598 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2599 argBaseTypeNames.push_back(
2600 llvm::MDString::get(VMContext, baseTypeName));
2605 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2609 Fn->setMetadata(
"kernel_arg_addr_space",
2610 llvm::MDNode::get(VMContext, addressQuals));
2611 Fn->setMetadata(
"kernel_arg_access_qual",
2612 llvm::MDNode::get(VMContext, accessQuals));
2613 Fn->setMetadata(
"kernel_arg_type",
2614 llvm::MDNode::get(VMContext, argTypeNames));
2615 Fn->setMetadata(
"kernel_arg_base_type",
2616 llvm::MDNode::get(VMContext, argBaseTypeNames));
2617 Fn->setMetadata(
"kernel_arg_type_qual",
2618 llvm::MDNode::get(VMContext, argTypeQuals));
2622 Fn->setMetadata(
"kernel_arg_name",
2623 llvm::MDNode::get(VMContext, argNames));
2633 if (!LangOpts.Exceptions)
return false;
2636 if (LangOpts.CXXExceptions)
return true;
2639 if (LangOpts.ObjCExceptions) {
2659SmallVector<const CXXRecordDecl *, 0>
2661 llvm::SetVector<const CXXRecordDecl *> MostBases;
2666 MostBases.insert(RD);
2668 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2670 CollectMostBases(RD);
2671 return MostBases.takeVector();
2675 llvm::Function *F) {
2676 llvm::AttrBuilder B(F->getContext());
2678 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2679 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2681 if (CodeGenOpts.StackClashProtector)
2682 B.addAttribute(
"probe-stack",
"inline-asm");
2684 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2685 B.addAttribute(
"stack-probe-size",
2686 std::to_string(CodeGenOpts.StackProbeSize));
2689 B.addAttribute(llvm::Attribute::NoUnwind);
2691 if (D && D->
hasAttr<NoStackProtectorAttr>())
2693 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
2695 B.addAttribute(llvm::Attribute::StackProtectStrong);
2697 B.addAttribute(llvm::Attribute::StackProtect);
2699 B.addAttribute(llvm::Attribute::StackProtectStrong);
2701 B.addAttribute(llvm::Attribute::StackProtectReq);
2705 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2706 B.addAttribute(llvm::Attribute::AlwaysInline);
2710 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2712 B.addAttribute(llvm::Attribute::NoInline);
2720 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2721 B.addAttribute(
"aarch64_pstate_sm_body");
2724 if (
Attr->isNewZA())
2725 B.addAttribute(
"aarch64_new_za");
2726 if (
Attr->isNewZT0())
2727 B.addAttribute(
"aarch64_new_zt0");
2732 bool ShouldAddOptNone =
2733 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2735 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2736 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2739 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2740 !D->
hasAttr<NoInlineAttr>()) {
2741 B.addAttribute(llvm::Attribute::AlwaysInline);
2742 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
2743 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2745 B.addAttribute(llvm::Attribute::OptimizeNone);
2748 B.addAttribute(llvm::Attribute::NoInline);
2753 B.addAttribute(llvm::Attribute::Naked);
2756 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2757 F->removeFnAttr(llvm::Attribute::MinSize);
2758 }
else if (D->
hasAttr<NakedAttr>()) {
2760 B.addAttribute(llvm::Attribute::Naked);
2761 B.addAttribute(llvm::Attribute::NoInline);
2762 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
2763 B.addAttribute(llvm::Attribute::NoDuplicate);
2764 }
else if (D->
hasAttr<NoInlineAttr>() &&
2765 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2767 B.addAttribute(llvm::Attribute::NoInline);
2768 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
2769 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2771 B.addAttribute(llvm::Attribute::AlwaysInline);
2775 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2776 B.addAttribute(llvm::Attribute::NoInline);
2780 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2783 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2784 return Redecl->isInlineSpecified();
2786 if (any_of(FD->
redecls(), CheckRedeclForInline))
2791 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2793 if (CheckForInline(FD)) {
2794 B.addAttribute(llvm::Attribute::InlineHint);
2795 }
else if (CodeGenOpts.getInlining() ==
2798 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2799 B.addAttribute(llvm::Attribute::NoInline);
2806 if (!D->
hasAttr<OptimizeNoneAttr>()) {
2808 if (!ShouldAddOptNone)
2809 B.addAttribute(llvm::Attribute::OptimizeForSize);
2810 B.addAttribute(llvm::Attribute::Cold);
2813 B.addAttribute(llvm::Attribute::Hot);
2814 if (D->
hasAttr<MinSizeAttr>())
2815 B.addAttribute(llvm::Attribute::MinSize);
2822 F->setAlignment(llvm::Align(alignment));
2824 if (!D->
hasAttr<AlignedAttr>())
2825 if (LangOpts.FunctionAlignment)
2826 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2834 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2839 if (CodeGenOpts.SanitizeCfiCrossDso &&
2840 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2841 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2852 auto *MD = dyn_cast<CXXMethodDecl>(D);
2855 llvm::Metadata *Id =
2857 MD->getType(), std::nullopt,
Base));
2858 F->addTypeMetadata(0, Id);
2865 if (isa_and_nonnull<NamedDecl>(D))
2868 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2870 if (D && D->
hasAttr<UsedAttr>())
2873 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
2875 ((CodeGenOpts.KeepPersistentStorageVariables &&
2876 (VD->getStorageDuration() ==
SD_Static ||
2877 VD->getStorageDuration() ==
SD_Thread)) ||
2878 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2879 VD->getType().isConstQualified())))
2883bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2884 llvm::AttrBuilder &Attrs,
2885 bool SetTargetFeatures) {
2891 std::vector<std::string> Features;
2892 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2895 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2896 assert((!TD || !TV) &&
"both target_version and target specified");
2899 bool AddedAttr =
false;
2900 if (TD || TV || SD || TC) {
2901 llvm::StringMap<bool> FeatureMap;
2905 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2906 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2914 Target.parseTargetAttr(TD->getFeaturesStr());
2936 if (!TargetCPU.empty()) {
2937 Attrs.addAttribute(
"target-cpu", TargetCPU);
2940 if (!TuneCPU.empty()) {
2941 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2944 if (!Features.empty() && SetTargetFeatures) {
2945 llvm::erase_if(Features, [&](
const std::string& F) {
2948 llvm::sort(Features);
2949 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2954 llvm::SmallVector<StringRef, 8> Feats;
2955 bool IsDefault =
false;
2957 IsDefault = TV->isDefaultVersion();
2958 TV->getFeatures(Feats);
2964 Attrs.addAttribute(
"fmv-features");
2966 }
else if (!Feats.empty()) {
2968 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
2969 std::string FMVFeatures;
2970 for (StringRef F : OrderedFeats)
2971 FMVFeatures.append(
"," + F.str());
2972 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
2979void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2980 llvm::GlobalObject *GO) {
2985 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2988 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
2989 GV->addAttribute(
"bss-section", SA->getName());
2990 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
2991 GV->addAttribute(
"data-section", SA->getName());
2992 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
2993 GV->addAttribute(
"rodata-section", SA->getName());
2994 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
2995 GV->addAttribute(
"relro-section", SA->getName());
2998 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3001 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3002 if (!D->
getAttr<SectionAttr>())
3003 F->setSection(SA->getName());
3005 llvm::AttrBuilder Attrs(F->getContext());
3006 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3010 llvm::AttributeMask RemoveAttrs;
3011 RemoveAttrs.addAttribute(
"target-cpu");
3012 RemoveAttrs.addAttribute(
"target-features");
3013 RemoveAttrs.addAttribute(
"fmv-features");
3014 RemoveAttrs.addAttribute(
"tune-cpu");
3015 F->removeFnAttrs(RemoveAttrs);
3016 F->addFnAttrs(Attrs);
3020 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3021 GO->setSection(CSA->getName());
3022 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3023 GO->setSection(SA->getName());
3036 F->setLinkage(llvm::Function::InternalLinkage);
3038 setNonAliasAttributes(GD, F);
3049 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3053 llvm::Function *F) {
3055 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3066 F->addTypeMetadata(0, MD);
3073 if (CodeGenOpts.SanitizeCfiCrossDso)
3075 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3079 llvm::LLVMContext &Ctx = F->getContext();
3080 llvm::MDBuilder MDB(Ctx);
3081 llvm::StringRef Salt;
3084 if (
const auto &Info = FP->getExtraAttributeInfo())
3085 Salt = Info.CFISalt;
3087 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3096 return llvm::all_of(Name, [](
const char &
C) {
3097 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3103 for (
auto &F : M.functions()) {
3105 bool AddressTaken = F.hasAddressTaken();
3106 if (!AddressTaken && F.hasLocalLinkage())
3107 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3112 if (!AddressTaken || !F.isDeclaration())
3115 const llvm::ConstantInt *
Type;
3116 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3117 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3121 StringRef Name = F.getName();
3125 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3126 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
3128 M.appendModuleInlineAsm(
Asm);
3132void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3133 bool IsIncompleteFunction,
3136 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3144 if (!IsIncompleteFunction)
3151 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3153 assert(!F->arg_empty() &&
3154 F->arg_begin()->getType()
3155 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3156 "unexpected this return");
3157 F->addParamAttr(0, llvm::Attribute::Returned);
3167 if (!IsIncompleteFunction && F->isDeclaration())
3170 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3171 F->setSection(CSA->getName());
3172 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3173 F->setSection(SA->getName());
3175 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3177 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3178 else if (EA->isWarning())
3179 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3184 const FunctionDecl *FDBody;
3185 bool HasBody = FD->
hasBody(FDBody);
3187 assert(HasBody &&
"Inline builtin declarations should always have an "
3189 if (shouldEmitFunction(FDBody))
3190 F->addFnAttr(llvm::Attribute::NoBuiltin);
3196 F->addFnAttr(llvm::Attribute::NoBuiltin);
3200 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3201 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3202 if (MD->isVirtual())
3203 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3209 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3210 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3213 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3219 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3220 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3222 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3226 llvm::LLVMContext &Ctx = F->getContext();
3227 llvm::MDBuilder MDB(Ctx);
3231 int CalleeIdx = *CB->encoding_begin();
3232 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3233 F->addMetadata(llvm::LLVMContext::MD_callback,
3234 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3235 CalleeIdx, PayloadIndices,
3242 "Only globals with definition can force usage.");
3243 LLVMUsed.emplace_back(GV);
3247 assert(!GV->isDeclaration() &&
3248 "Only globals with definition can force usage.");
3249 LLVMCompilerUsed.emplace_back(GV);
3254 "Only globals with definition can force usage.");
3256 LLVMCompilerUsed.emplace_back(GV);
3258 LLVMUsed.emplace_back(GV);
3262 std::vector<llvm::WeakTrackingVH> &List) {
3269 UsedArray.resize(List.size());
3270 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3272 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3276 if (UsedArray.empty())
3278 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3280 auto *GV =
new llvm::GlobalVariable(
3281 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3282 llvm::ConstantArray::get(ATy, UsedArray), Name);
3284 GV->setSection(
"llvm.metadata");
3287void CodeGenModule::emitLLVMUsed() {
3288 emitUsed(*
this,
"llvm.used", LLVMUsed);
3289 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3294 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3303 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3309 ELFDependentLibraries.push_back(
3310 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3317 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3326 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3332 if (Visited.insert(Import).second)
3349 if (LL.IsFramework) {
3350 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3351 llvm::MDString::get(Context, LL.Library)};
3353 Metadata.push_back(llvm::MDNode::get(Context, Args));
3359 llvm::Metadata *Args[2] = {
3360 llvm::MDString::get(Context,
"lib"),
3361 llvm::MDString::get(Context, LL.Library),
3363 Metadata.push_back(llvm::MDNode::get(Context, Args));
3367 auto *OptString = llvm::MDString::get(Context, Opt);
3368 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3373void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3375 "We should only emit module initializers for named modules.");
3383 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3400 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3406void CodeGenModule::EmitModuleLinkOptions() {
3410 llvm::SetVector<clang::Module *> LinkModules;
3411 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3412 SmallVector<clang::Module *, 16> Stack;
3415 for (
Module *M : ImportedModules) {
3418 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3421 if (Visited.insert(M).second)
3427 while (!Stack.empty()) {
3430 bool AnyChildren =
false;
3439 if (Visited.insert(
SM).second) {
3440 Stack.push_back(
SM);
3448 LinkModules.insert(Mod);
3455 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3457 for (
Module *M : LinkModules)
3458 if (Visited.insert(M).second)
3460 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3461 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3464 if (!LinkerOptionsMetadata.empty()) {
3465 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3466 for (
auto *MD : LinkerOptionsMetadata)
3467 NMD->addOperand(MD);
3471void CodeGenModule::EmitDeferred() {
3480 if (!DeferredVTables.empty()) {
3481 EmitDeferredVTables();
3486 assert(DeferredVTables.empty());
3493 llvm::append_range(DeferredDeclsToEmit,
3497 if (DeferredDeclsToEmit.empty())
3502 std::vector<GlobalDecl> CurDeclsToEmit;
3503 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3505 for (GlobalDecl &D : CurDeclsToEmit) {
3511 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3515 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3531 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3549 if (!GV->isDeclaration())
3553 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3557 EmitGlobalDefinition(D, GV);
3562 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3564 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3569void CodeGenModule::EmitVTablesOpportunistically() {
3575 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3576 &&
"Only emit opportunistic vtables with optimizations");
3578 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
3580 "This queue should only contain external vtables");
3581 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3582 VTables.GenerateClassData(RD);
3584 OpportunisticVTables.clear();
3588 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3593 DeferredAnnotations.clear();
3595 if (Annotations.empty())
3599 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3600 Annotations[0]->
getType(), Annotations.size()), Annotations);
3601 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3602 llvm::GlobalValue::AppendingLinkage,
3603 Array,
"llvm.global.annotations");
3608 llvm::Constant *&AStr = AnnotationStrings[Str];
3613 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3614 auto *gv =
new llvm::GlobalVariable(
3615 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3616 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3619 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3636 SM.getExpansionLineNumber(L);
3637 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3645 llvm::FoldingSetNodeID ID;
3646 for (
Expr *E : Exprs) {
3649 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3654 LLVMArgs.reserve(Exprs.size());
3656 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
3658 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3661 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3662 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3663 llvm::GlobalValue::PrivateLinkage,
Struct,
3666 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3673 const AnnotateAttr *AA,
3681 llvm::Constant *GVInGlobalsAS = GV;
3682 if (GV->getAddressSpace() !=
3684 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3686 llvm::PointerType::get(
3687 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3691 llvm::Constant *Fields[] = {
3692 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3694 return llvm::ConstantStruct::getAnon(Fields);
3698 llvm::GlobalValue *GV) {
3699 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3709 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3712 auto &
SM = Context.getSourceManager();
3714 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3719 return NoSanitizeL.containsLocation(Kind, Loc);
3722 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3726 llvm::GlobalVariable *GV,
3728 StringRef Category)
const {
3730 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3732 auto &
SM = Context.getSourceManager();
3733 if (NoSanitizeL.containsMainFile(
3734 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3737 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3744 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3745 Ty = AT->getElementType();
3750 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3758 StringRef Category)
const {
3761 auto Attr = ImbueAttr::NONE;
3763 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3764 if (
Attr == ImbueAttr::NONE)
3765 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3767 case ImbueAttr::NONE:
3769 case ImbueAttr::ALWAYS:
3770 Fn->addFnAttr(
"function-instrument",
"xray-always");
3772 case ImbueAttr::ALWAYS_ARG1:
3773 Fn->addFnAttr(
"function-instrument",
"xray-always");
3774 Fn->addFnAttr(
"xray-log-args",
"1");
3776 case ImbueAttr::NEVER:
3777 Fn->addFnAttr(
"function-instrument",
"xray-never");
3790 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
3800 auto &
SM = Context.getSourceManager();
3801 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3815 if (NumGroups > 1) {
3816 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3825 if (LangOpts.EmitAllDecls)
3828 const auto *VD = dyn_cast<VarDecl>(
Global);
3830 ((CodeGenOpts.KeepPersistentStorageVariables &&
3831 (VD->getStorageDuration() ==
SD_Static ||
3832 VD->getStorageDuration() ==
SD_Thread)) ||
3833 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3834 VD->getType().isConstQualified())))
3847 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3848 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3849 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3850 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3854 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3864 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
3867 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3868 if (Context.getInlineVariableDefinitionKind(VD) ==
3873 if (CXX20ModuleInits && VD->getOwningModule() &&
3874 !VD->getOwningModule()->isModuleMapModule()) {
3883 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3886 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3899 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3903 llvm::Constant *
Init;
3906 if (!
V.isAbsent()) {
3917 llvm::Constant *Fields[4] = {
3921 llvm::ConstantDataArray::getRaw(
3922 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3924 Init = llvm::ConstantStruct::getAnon(Fields);
3927 auto *GV =
new llvm::GlobalVariable(
3929 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3931 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3934 if (!
V.isAbsent()) {
3947 llvm::GlobalVariable **Entry =
nullptr;
3948 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3953 llvm::Constant *
Init;
3957 assert(!
V.isAbsent());
3961 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3963 llvm::GlobalValue::PrivateLinkage,
Init,
3965 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3979 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3983 llvm::Constant *
Init =
Emitter.emitForInitializer(
3991 llvm::GlobalValue::LinkageTypes
Linkage =
3993 ? llvm::GlobalValue::LinkOnceODRLinkage
3994 : llvm::GlobalValue::InternalLinkage;
3995 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3999 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4006 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4007 assert(AA &&
"No alias?");
4017 llvm::Constant *Aliasee;
4019 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4027 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4028 WeakRefReferences.insert(F);
4036 if (
auto *A = D->
getAttr<AttrT>())
4037 return A->isImplicit();
4041bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4042 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4047 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4048 Global->hasAttr<CUDAConstantAttr>() ||
4049 Global->hasAttr<CUDASharedAttr>() ||
4050 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4051 Global->getType()->isCUDADeviceBuiltinTextureType();
4058 if (
Global->hasAttr<WeakRefAttr>())
4063 if (
Global->hasAttr<AliasAttr>())
4064 return EmitAliasDefinition(GD);
4067 if (
Global->hasAttr<IFuncAttr>())
4068 return emitIFuncDefinition(GD);
4071 if (
Global->hasAttr<CPUDispatchAttr>())
4072 return emitCPUDispatchDefinition(GD);
4077 if (LangOpts.CUDA) {
4079 "Expected Variable or Function");
4080 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4081 if (!shouldEmitCUDAGlobalVar(VD))
4083 }
else if (LangOpts.CUDAIsDevice) {
4084 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4085 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4086 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4090 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4091 !
Global->hasAttr<CUDAGlobalAttr>() &&
4093 !
Global->hasAttr<CUDAHostAttr>()))
4096 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4097 Global->hasAttr<CUDADeviceAttr>())
4101 if (LangOpts.OpenMP) {
4103 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4105 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4106 if (MustBeEmitted(
Global))
4110 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4111 if (MustBeEmitted(
Global))
4118 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4119 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4125 if (FD->
hasAttr<AnnotateAttr>()) {
4128 DeferredAnnotations[MangledName] = FD;
4143 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4149 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4151 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4152 if (LangOpts.OpenMP) {
4154 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4155 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4159 if (VD->hasExternalStorage() &&
4160 Res != OMPDeclareTargetDeclAttr::MT_Link)
4163 bool UnifiedMemoryEnabled =
4165 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4166 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4167 !UnifiedMemoryEnabled) {
4170 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4171 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4172 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4173 UnifiedMemoryEnabled)) &&
4174 "Link clause or to clause with unified memory expected.");
4183 if (Context.getInlineVariableDefinitionKind(VD) ==
4193 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4195 EmitGlobalDefinition(GD);
4196 addEmittedDeferredDecl(GD);
4204 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4205 CXXGlobalInits.push_back(
nullptr);
4211 addDeferredDeclToEmit(GD);
4212 }
else if (MustBeEmitted(
Global)) {
4214 assert(!MayBeEmittedEagerly(
Global));
4215 addDeferredDeclToEmit(GD);
4220 DeferredDecls[MangledName] = GD;
4226 if (
const auto *RT =
4227 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4228 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getOriginalDecl())) {
4229 RD = RD->getDefinitionOrSelf();
4230 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4238 struct FunctionIsDirectlyRecursive
4239 :
public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4240 const StringRef Name;
4241 const Builtin::Context &BI;
4242 FunctionIsDirectlyRecursive(StringRef N,
const Builtin::Context &
C)
4245 bool VisitCallExpr(
const CallExpr *E) {
4249 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4250 if (Attr && Name == Attr->getLabel())
4255 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4256 StringRef BuiltinName = BuiltinNameStr;
4257 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4260 bool VisitStmt(
const Stmt *S) {
4261 for (
const Stmt *Child : S->
children())
4262 if (Child && this->Visit(Child))
4269 struct DLLImportFunctionVisitor
4270 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4271 bool SafeToInline =
true;
4273 bool shouldVisitImplicitCode()
const {
return true; }
4275 bool VisitVarDecl(VarDecl *VD) {
4278 SafeToInline =
false;
4279 return SafeToInline;
4286 return SafeToInline;
4289 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4291 SafeToInline = D->
hasAttr<DLLImportAttr>();
4292 return SafeToInline;
4295 bool VisitDeclRefExpr(DeclRefExpr *E) {
4298 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4299 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4300 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4301 return SafeToInline;
4304 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4306 return SafeToInline;
4309 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4313 SafeToInline =
true;
4315 SafeToInline = M->
hasAttr<DLLImportAttr>();
4317 return SafeToInline;
4320 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4322 return SafeToInline;
4325 bool VisitCXXNewExpr(CXXNewExpr *E) {
4327 return SafeToInline;
4336CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4338 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4340 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4343 Name = Attr->getLabel();
4348 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4349 const Stmt *Body = FD->
getBody();
4350 return Body ? Walker.Visit(Body) :
false;
4353bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4360 if (F->isInlineBuiltinDeclaration())
4363 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4368 if (
const Module *M = F->getOwningModule();
4369 M && M->getTopLevelModule()->isNamedModule() &&
4370 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4380 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4385 if (F->hasAttr<NoInlineAttr>())
4388 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4390 DLLImportFunctionVisitor Visitor;
4391 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4392 if (!Visitor.SafeToInline)
4395 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4398 for (
const Decl *
Member : Dtor->getParent()->decls())
4402 for (
const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4413 return !isTriviallyRecursive(F);
4416bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4417 return CodeGenOpts.OptimizationLevel > 0;
4420void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4421 llvm::GlobalValue *GV) {
4425 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4426 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4428 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4429 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4430 if (TC->isFirstOfVersion(I))
4433 EmitGlobalFunctionDefinition(GD, GV);
4439 AddDeferredMultiVersionResolverToEmit(GD);
4441 GetOrCreateMultiVersionResolver(GD);
4445void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4448 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4449 Context.getSourceManager(),
4450 "Generating code for declaration");
4452 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4455 if (!shouldEmitFunction(GD))
4458 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4460 llvm::raw_string_ostream
OS(Name);
4466 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4470 ABI->emitCXXStructor(GD);
4472 EmitMultiVersionFunctionDefinition(GD, GV);
4474 EmitGlobalFunctionDefinition(GD, GV);
4483 return EmitMultiVersionFunctionDefinition(GD, GV);
4484 return EmitGlobalFunctionDefinition(GD, GV);
4487 if (
const auto *VD = dyn_cast<VarDecl>(D))
4488 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4490 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4494 llvm::Function *NewFn);
4510static llvm::GlobalValue::LinkageTypes
4514 return llvm::GlobalValue::InternalLinkage;
4515 return llvm::GlobalValue::WeakODRLinkage;
4518void CodeGenModule::emitMultiVersionFunctions() {
4519 std::vector<GlobalDecl> MVFuncsToEmit;
4520 MultiVersionFuncs.swap(MVFuncsToEmit);
4521 for (GlobalDecl GD : MVFuncsToEmit) {
4523 assert(FD &&
"Expected a FunctionDecl");
4525 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4526 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4530 if (
Decl->isDefined()) {
4531 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4539 assert(
Func &&
"This should have just been created");
4548 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4551 FD, [&](
const FunctionDecl *CurFD) {
4552 llvm::SmallVector<StringRef, 8> Feats;
4555 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4557 TA->getX86AddedFeatures(Feats);
4558 llvm::Function *
Func = createFunction(CurFD);
4559 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
4560 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4561 if (TVA->isDefaultVersion() && IsDefined)
4562 ShouldEmitResolver =
true;
4563 llvm::Function *
Func = createFunction(CurFD);
4565 TVA->getFeatures(Feats, Delim);
4566 Options.emplace_back(
Func, Feats);
4567 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4568 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4569 if (!TC->isFirstOfVersion(I))
4571 if (TC->isDefaultVersion(I) && IsDefined)
4572 ShouldEmitResolver =
true;
4573 llvm::Function *
Func = createFunction(CurFD, I);
4576 TC->getX86Feature(Feats, I);
4577 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
4580 TC->getFeatures(Feats, I, Delim);
4581 Options.emplace_back(
Func, Feats);
4585 llvm_unreachable(
"unexpected MultiVersionKind");
4588 if (!ShouldEmitResolver)
4591 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4592 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4593 ResolverConstant = IFunc->getResolver();
4597 *
this, GD, FD,
true);
4604 auto *Alias = llvm::GlobalAlias::create(
4606 MangledName +
".ifunc", IFunc, &
getModule());
4615 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4616 const CodeGenFunction::FMVResolverOption &RHS) {
4619 CodeGenFunction CGF(*
this);
4620 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4622 setMultiVersionResolverAttributes(ResolverFunc, GD);
4624 ResolverFunc->setComdat(
4625 getModule().getOrInsertComdat(ResolverFunc->getName()));
4631 if (!MVFuncsToEmit.empty())
4636 if (!MultiVersionFuncs.empty())
4637 emitMultiVersionFunctions();
4641 llvm::Constant *
New) {
4644 Old->replaceAllUsesWith(
New);
4645 Old->eraseFromParent();
4648void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4650 assert(FD &&
"Not a FunctionDecl?");
4652 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4653 assert(DD &&
"Not a cpu_dispatch Function?");
4659 UpdateMultiVersionNames(GD, FD, ResolverName);
4661 llvm::Type *ResolverType;
4662 GlobalDecl ResolverGD;
4664 ResolverType = llvm::FunctionType::get(
4675 ResolverName, ResolverType, ResolverGD,
false));
4678 ResolverFunc->setComdat(
4679 getModule().getOrInsertComdat(ResolverFunc->getName()));
4681 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4684 for (
const IdentifierInfo *II : DD->cpus()) {
4692 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4695 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4701 Func = GetOrCreateLLVMFunction(
4702 MangledName, DeclTy, ExistingDecl,
4708 llvm::SmallVector<StringRef, 32> Features;
4709 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4710 llvm::transform(Features, Features.begin(),
4711 [](StringRef Str) { return Str.substr(1); });
4712 llvm::erase_if(Features, [&Target](StringRef Feat) {
4713 return !Target.validateCpuSupports(Feat);
4719 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
4720 const CodeGenFunction::FMVResolverOption &RHS) {
4721 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
4722 llvm::X86::getCpuSupportsMask(RHS.
Features);
4729 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4730 (Options.end() - 2)->Features),
4731 [](
auto X) { return X == 0; })) {
4732 StringRef LHSName = (Options.end() - 2)->Function->getName();
4733 StringRef RHSName = (Options.end() - 1)->Function->getName();
4734 if (LHSName.compare(RHSName) < 0)
4735 Options.erase(Options.end() - 2);
4737 Options.erase(Options.end() - 1);
4740 CodeGenFunction CGF(*
this);
4741 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4742 setMultiVersionResolverAttributes(ResolverFunc, GD);
4747 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4752 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4759 *
this, GD, FD,
true);
4762 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4770void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4772 assert(FD &&
"Not a FunctionDecl?");
4775 std::string MangledName =
4777 if (!DeferredResolversToEmit.insert(MangledName).second)
4780 MultiVersionFuncs.push_back(GD);
4786llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4788 assert(FD &&
"Not a FunctionDecl?");
4790 std::string MangledName =
4795 std::string ResolverName = MangledName;
4799 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4803 ResolverName +=
".ifunc";
4810 ResolverName +=
".resolver";
4813 bool ShouldReturnIFunc =
4832 AddDeferredMultiVersionResolverToEmit(GD);
4836 if (ShouldReturnIFunc) {
4838 llvm::Type *ResolverType = llvm::FunctionType::get(
4840 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4841 MangledName +
".resolver", ResolverType, GlobalDecl{},
4843 llvm::GlobalIFunc *GIF =
4846 GIF->setName(ResolverName);
4853 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4854 ResolverName, DeclTy, GlobalDecl{},
false);
4856 "Resolver should be created for the first time");
4861void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
4863 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
4881bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
4882 const llvm::GlobalValue *GV)
const {
4883 auto SC = GV->getDLLStorageClass();
4884 if (SC == llvm::GlobalValue::DefaultStorageClass)
4887 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4888 !MRD->
hasAttr<DLLImportAttr>()) ||
4889 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4890 !MRD->
hasAttr<DLLExportAttr>())) &&
4901llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4902 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
4903 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4907 std::string NameWithoutMultiVersionMangling;
4908 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4910 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4911 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4912 !DontDefer && !IsForDefinition) {
4915 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4917 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4920 GDDef = GlobalDecl(FDDef);
4928 UpdateMultiVersionNames(GD, FD, MangledName);
4929 if (!IsForDefinition) {
4935 AddDeferredMultiVersionResolverToEmit(GD);
4937 *
this, GD, FD,
true);
4939 return GetOrCreateMultiVersionResolver(GD);
4944 if (!NameWithoutMultiVersionMangling.empty())
4945 MangledName = NameWithoutMultiVersionMangling;
4950 if (WeakRefReferences.erase(Entry)) {
4951 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4952 if (FD && !FD->
hasAttr<WeakAttr>())
4953 Entry->setLinkage(llvm::Function::ExternalLinkage);
4957 if (D && shouldDropDLLAttribute(D, Entry)) {
4958 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4964 if (IsForDefinition && !Entry->isDeclaration()) {
4971 DiagnosedConflictingDefinitions.insert(GD).second) {
4975 diag::note_previous_definition);
4980 (Entry->getValueType() == Ty)) {
4987 if (!IsForDefinition)
4994 bool IsIncompleteFunction =
false;
4996 llvm::FunctionType *FTy;
5000 FTy = llvm::FunctionType::get(
VoidTy,
false);
5001 IsIncompleteFunction =
true;
5005 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5006 Entry ? StringRef() : MangledName, &
getModule());
5010 if (D && D->
hasAttr<AnnotateAttr>())
5028 if (!Entry->use_empty()) {
5030 Entry->removeDeadConstantUsers();
5036 assert(F->getName() == MangledName &&
"name was uniqued!");
5038 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5039 if (ExtraAttrs.hasFnAttrs()) {
5040 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5048 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5051 addDeferredDeclToEmit(GD);
5056 auto DDI = DeferredDecls.find(MangledName);
5057 if (DDI != DeferredDecls.end()) {
5061 addDeferredDeclToEmit(DDI->second);
5062 DeferredDecls.erase(DDI);
5090 if (!IsIncompleteFunction) {
5091 assert(F->getFunctionType() == Ty);
5109 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5119 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5122 DD->getParent()->getNumVBases() == 0)
5127 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5128 false, llvm::AttributeList(),
5131 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5135 if (IsForDefinition)
5143 llvm::GlobalValue *F =
5146 return llvm::NoCFIValue::get(F);
5155 for (
const auto *Result : DC->
lookup(&CII))
5156 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5159 if (!
C.getLangOpts().CPlusPlus)
5164 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5165 ?
C.Idents.get(
"terminate")
5166 :
C.Idents.get(Name);
5168 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5170 for (
const auto *Result : DC->
lookup(&NS)) {
5172 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
5173 for (
const auto *Result : LSD->lookup(&NS))
5174 if ((ND = dyn_cast<NamespaceDecl>(Result)))
5178 for (
const auto *Result : ND->
lookup(&CXXII))
5179 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5188 llvm::Function *F, StringRef Name) {
5194 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5197 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5198 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5199 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5206 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5207 if (AssumeConvergent) {
5209 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5212 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5217 llvm::Constant *
C = GetOrCreateLLVMFunction(
5219 false,
false, ExtraAttrs);
5221 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5237 llvm::AttributeList ExtraAttrs,
bool Local,
5238 bool AssumeConvergent) {
5239 if (AssumeConvergent) {
5241 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5245 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5249 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5258 markRegisterParameterAttributes(F);
5284 if (WeakRefReferences.erase(Entry)) {
5285 if (D && !D->
hasAttr<WeakAttr>())
5286 Entry->setLinkage(llvm::Function::ExternalLinkage);
5290 if (D && shouldDropDLLAttribute(D, Entry))
5291 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5293 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5296 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5301 if (IsForDefinition && !Entry->isDeclaration()) {
5309 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5311 DiagnosedConflictingDefinitions.insert(D).second) {
5315 diag::note_previous_definition);
5320 if (Entry->getType()->getAddressSpace() != TargetAS)
5321 return llvm::ConstantExpr::getAddrSpaceCast(
5322 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5326 if (!IsForDefinition)
5332 auto *GV =
new llvm::GlobalVariable(
5333 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5334 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5335 getContext().getTargetAddressSpace(DAddrSpace));
5340 GV->takeName(Entry);
5342 if (!Entry->use_empty()) {
5343 Entry->replaceAllUsesWith(GV);
5346 Entry->eraseFromParent();
5352 auto DDI = DeferredDecls.find(MangledName);
5353 if (DDI != DeferredDecls.end()) {
5356 addDeferredDeclToEmit(DDI->second);
5357 DeferredDecls.erase(DDI);
5362 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5369 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5375 CXXThreadLocals.push_back(D);
5383 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5384 EmitGlobalVarDefinition(D);
5389 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5390 GV->setSection(SA->getName());
5394 if (
getTriple().getArch() == llvm::Triple::xcore &&
5398 GV->setSection(
".cp.rodata");
5401 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5402 GV->setCodeModel(CMA->getModel());
5407 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5411 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5412 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5413 if (!HasMutableFields) {
5420 auto *InitType =
Init->getType();
5421 if (GV->getValueType() != InitType) {
5426 GV->setName(StringRef());
5431 ->stripPointerCasts());
5434 GV->eraseFromParent();
5437 GV->setInitializer(
Init);
5438 GV->setConstant(
true);
5439 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5459 SanitizerMD->reportGlobal(GV, *D);
5464 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5465 if (DAddrSpace != ExpectedAS) {
5467 *
this, GV, DAddrSpace,
5480 false, IsForDefinition);
5501 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5502 llvm::Align Alignment) {
5503 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5504 llvm::GlobalVariable *OldGV =
nullptr;
5508 if (GV->getValueType() == Ty)
5513 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5518 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5523 GV->takeName(OldGV);
5525 if (!OldGV->use_empty()) {
5526 OldGV->replaceAllUsesWith(GV);
5529 OldGV->eraseFromParent();
5533 !GV->hasAvailableExternallyLinkage())
5534 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5536 GV->setAlignment(Alignment);
5573 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
5581 if (GV && !GV->isDeclaration())
5586 if (!MustBeEmitted(D) && !GV) {
5587 DeferredDecls[MangledName] = D;
5592 EmitGlobalVarDefinition(D);
5597 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
5599 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
5614 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
5617 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5619 if (!Fn->getSubprogram())
5625 return Context.toCharUnitsFromBits(
5630 if (LangOpts.OpenCL) {
5641 if (LangOpts.SYCLIsDevice &&
5645 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5647 if (D->
hasAttr<CUDAConstantAttr>())
5649 if (D->
hasAttr<CUDASharedAttr>())
5651 if (D->
hasAttr<CUDADeviceAttr>())
5659 if (LangOpts.OpenMP) {
5661 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5669 if (LangOpts.OpenCL)
5671 if (LangOpts.SYCLIsDevice)
5673 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5681 if (
auto AS =
getTarget().getConstantAddressSpace())
5694static llvm::Constant *
5696 llvm::GlobalVariable *GV) {
5697 llvm::Constant *Cast = GV;
5703 llvm::PointerType::get(
5710template<
typename SomeDecl>
5712 llvm::GlobalValue *GV) {
5727 const SomeDecl *
First = D->getFirstDecl();
5728 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5734 std::pair<StaticExternCMap::iterator, bool> R =
5735 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5740 R.first->second =
nullptr;
5747 if (D.
hasAttr<SelectAnyAttr>())
5751 if (
auto *VD = dyn_cast<VarDecl>(&D))
5765 llvm_unreachable(
"No such linkage");
5773 llvm::GlobalObject &GO) {
5776 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5784void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
5799 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5800 OpenMPRuntime->emitTargetGlobalVariable(D))
5803 llvm::TrackingVH<llvm::Constant>
Init;
5804 bool NeedsGlobalCtor =
false;
5808 bool IsDefinitionAvailableExternally =
5810 bool NeedsGlobalDtor =
5811 !IsDefinitionAvailableExternally &&
5818 if (IsDefinitionAvailableExternally &&
5829 std::optional<ConstantEmitter> emitter;
5834 bool IsCUDASharedVar =
5839 bool IsCUDAShadowVar =
5841 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
5842 D->
hasAttr<CUDASharedAttr>());
5843 bool IsCUDADeviceShadowVar =
5848 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
5849 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5853 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
5855 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
5856 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5857 }
else if (!InitExpr) {
5870 initializedGlobalDecl = GlobalDecl(D);
5871 emitter.emplace(*
this);
5872 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5880 if (!IsDefinitionAvailableExternally)
5881 NeedsGlobalCtor =
true;
5885 NeedsGlobalCtor =
false;
5897 DelayedCXXInitPosition.erase(D);
5904 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5909 llvm::Type* InitType =
Init->getType();
5910 llvm::Constant *Entry =
5914 Entry = Entry->stripPointerCasts();
5917 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5928 if (!GV || GV->getValueType() != InitType ||
5929 GV->getType()->getAddressSpace() !=
5933 Entry->setName(StringRef());
5938 ->stripPointerCasts());
5941 llvm::Constant *NewPtrForOldDecl =
5942 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5944 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5952 if (D->
hasAttr<AnnotateAttr>())
5965 if (LangOpts.CUDA) {
5966 if (LangOpts.CUDAIsDevice) {
5967 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
5968 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
5971 GV->setExternallyInitialized(
true);
5981 GV->setExternallyInitialized(
true);
5983 GV->setInitializer(
Init);
5990 emitter->finalize(GV);
5993 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
5994 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
5998 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
5999 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6001 GV->setConstant(
true);
6006 if (std::optional<CharUnits> AlignValFromAllocate =
6008 AlignVal = *AlignValFromAllocate;
6026 Linkage == llvm::GlobalValue::ExternalLinkage &&
6027 Context.getTargetInfo().getTriple().isOSDarwin() &&
6029 Linkage = llvm::GlobalValue::InternalLinkage;
6035 Linkage = llvm::GlobalValue::ExternalLinkage;
6038 if (D->
hasAttr<DLLImportAttr>())
6039 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6040 else if (D->
hasAttr<DLLExportAttr>())
6041 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6043 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6045 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6047 GV->setConstant(
false);
6052 if (!GV->getInitializer()->isNullValue())
6053 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6056 setNonAliasAttributes(D, GV);
6058 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6060 CXXThreadLocals.push_back(D);
6067 if (NeedsGlobalCtor || NeedsGlobalDtor)
6068 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6070 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6075 DI->EmitGlobalVariable(GV, D);
6083 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6094 if (D->
hasAttr<SectionAttr>())
6100 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6101 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6102 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6103 D->
hasAttr<PragmaClangRodataSectionAttr>())
6111 if (D->
hasAttr<WeakImportAttr>())
6120 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6121 if (D->
hasAttr<AlignedAttr>())
6124 if (Context.isAlignmentRequired(VarType))
6128 for (
const FieldDecl *FD : RD->fields()) {
6129 if (FD->isBitField())
6131 if (FD->
hasAttr<AlignedAttr>())
6133 if (Context.isAlignmentRequired(FD->
getType()))
6145 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6146 Context.getTypeAlignIfKnown(D->
getType()) >
6153llvm::GlobalValue::LinkageTypes
6157 return llvm::Function::InternalLinkage;
6160 return llvm::GlobalVariable::WeakAnyLinkage;
6164 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6169 return llvm::GlobalValue::AvailableExternallyLinkage;
6183 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6184 : llvm::Function::InternalLinkage;
6198 return llvm::Function::ExternalLinkage;
6201 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6202 : llvm::Function::InternalLinkage;
6203 return llvm::Function::WeakODRLinkage;
6210 CodeGenOpts.NoCommon))
6211 return llvm::GlobalVariable::CommonLinkage;
6217 if (D->
hasAttr<SelectAnyAttr>())
6218 return llvm::GlobalVariable::WeakODRLinkage;
6222 return llvm::GlobalVariable::ExternalLinkage;
6225llvm::GlobalValue::LinkageTypes
6234 llvm::Function *newFn) {
6236 if (old->use_empty())
6239 llvm::Type *newRetTy = newFn->getReturnType();
6244 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6246 llvm::User *user = ui->getUser();
6250 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6251 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6257 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6260 if (!callSite->isCallee(&*ui))
6265 if (callSite->getType() != newRetTy && !callSite->use_empty())
6270 llvm::AttributeList oldAttrs = callSite->getAttributes();
6273 unsigned newNumArgs = newFn->arg_size();
6274 if (callSite->arg_size() < newNumArgs)
6280 bool dontTransform =
false;
6281 for (llvm::Argument &A : newFn->args()) {
6282 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6283 dontTransform =
true;
6288 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6296 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6300 callSite->getOperandBundlesAsDefs(newBundles);
6302 llvm::CallBase *newCall;
6304 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6305 callSite->getIterator());
6308 newCall = llvm::InvokeInst::Create(
6309 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6310 newArgs, newBundles,
"", callSite->getIterator());
6314 if (!newCall->getType()->isVoidTy())
6315 newCall->takeName(callSite);
6316 newCall->setAttributes(
6317 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6318 oldAttrs.getRetAttrs(), newArgAttrs));
6319 newCall->setCallingConv(callSite->getCallingConv());
6322 if (!callSite->use_empty())
6323 callSite->replaceAllUsesWith(newCall);
6326 if (callSite->getDebugLoc())
6327 newCall->setDebugLoc(callSite->getDebugLoc());
6329 callSitesToBeRemovedFromParent.push_back(callSite);
6332 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6333 callSite->eraseFromParent();
6347 llvm::Function *NewFn) {
6357 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6369void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6370 llvm::GlobalValue *GV) {
6378 if (!GV || (GV->getValueType() != Ty))
6384 if (!GV->isDeclaration())
6403 setNonAliasAttributes(GD, Fn);
6405 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6406 (CodeGenOpts.OptimizationLevel == 0) &&
6409 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6411 !D->
hasAttr<NoInlineAttr>() &&
6412 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6413 !D->
hasAttr<OptimizeNoneAttr>() &&
6414 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6415 !ShouldAddOptNone) {
6416 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6422 auto GetPriority = [
this](
const auto *
Attr) ->
int {
6427 return Attr->DefaultPriority;
6430 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6432 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
6438void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6440 const AliasAttr *AA = D->
getAttr<AliasAttr>();
6441 assert(AA &&
"Not an alias?");
6445 if (AA->getAliasee() == MangledName) {
6446 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6453 if (Entry && !Entry->isDeclaration())
6456 Aliases.push_back(GD);
6462 llvm::Constant *Aliasee;
6463 llvm::GlobalValue::LinkageTypes
LT;
6465 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6471 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6478 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6480 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
6483 if (GA->getAliasee() == Entry) {
6484 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6488 assert(Entry->isDeclaration());
6497 GA->takeName(Entry);
6499 Entry->replaceAllUsesWith(GA);
6500 Entry->eraseFromParent();
6502 GA->setName(MangledName);
6510 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6513 if (
const auto *VD = dyn_cast<VarDecl>(D))
6514 if (VD->getTLSKind())
6525void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6527 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
6528 assert(IFA &&
"Not an ifunc?");
6532 if (IFA->getResolver() == MangledName) {
6533 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6539 if (Entry && !Entry->isDeclaration()) {
6542 DiagnosedConflictingDefinitions.insert(GD).second) {
6543 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
6546 diag::note_previous_definition);
6551 Aliases.push_back(GD);
6557 llvm::Constant *Resolver =
6558 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6562 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6563 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6565 if (GIF->getResolver() == Entry) {
6566 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6569 assert(Entry->isDeclaration());
6578 GIF->takeName(Entry);
6580 Entry->replaceAllUsesWith(GIF);
6581 Entry->eraseFromParent();
6583 GIF->setName(MangledName);
6589 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6590 (llvm::Intrinsic::ID)IID, Tys);
6593static llvm::StringMapEntry<llvm::GlobalVariable *> &
6596 bool &IsUTF16,
unsigned &StringLength) {
6597 StringRef String = Literal->getString();
6598 unsigned NumBytes = String.size();
6601 if (!Literal->containsNonAsciiOrNull()) {
6602 StringLength = NumBytes;
6603 return *Map.insert(std::make_pair(String,
nullptr)).first;
6610 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6611 llvm::UTF16 *ToPtr = &ToBuf[0];
6613 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6614 ToPtr + NumBytes, llvm::strictConversion);
6617 StringLength = ToPtr - &ToBuf[0];
6621 return *Map.insert(std::make_pair(
6622 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6623 (StringLength + 1) * 2),
6629 unsigned StringLength = 0;
6630 bool isUTF16 =
false;
6631 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6636 if (
auto *
C = Entry.second)
6641 const llvm::Triple &Triple =
getTriple();
6644 const bool IsSwiftABI =
6645 static_cast<unsigned>(CFRuntime) >=
6650 if (!CFConstantStringClassRef) {
6651 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6653 Ty = llvm::ArrayType::get(Ty, 0);
6655 switch (CFRuntime) {
6659 CFConstantStringClassName =
6660 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6661 :
"$s10Foundation19_NSCFConstantStringCN";
6665 CFConstantStringClassName =
6666 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6667 :
"$S10Foundation19_NSCFConstantStringCN";
6671 CFConstantStringClassName =
6672 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6673 :
"__T010Foundation19_NSCFConstantStringCN";
6680 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6681 llvm::GlobalValue *GV =
nullptr;
6683 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6690 if ((VD = dyn_cast<VarDecl>(
Result)))
6693 if (Triple.isOSBinFormatELF()) {
6695 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6697 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6698 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6699 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6701 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6709 CFConstantStringClassRef =
6710 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6713 QualType CFTy = Context.getCFConstantStringType();
6718 auto Fields = Builder.beginStruct(STy);
6727 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6728 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6730 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6734 llvm::Constant *
C =
nullptr;
6737 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6738 Entry.first().size() / 2);
6739 C = llvm::ConstantDataArray::get(VMContext, Arr);
6741 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6747 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6748 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6749 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6752 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6753 : Context.getTypeAlignInChars(Context.CharTy);
6759 if (Triple.isOSBinFormatMachO())
6760 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6761 :
"__TEXT,__cstring,cstring_literals");
6764 else if (Triple.isOSBinFormatELF())
6765 GV->setSection(
".rodata");
6771 llvm::IntegerType *LengthTy =
6781 Fields.addInt(LengthTy, StringLength);
6789 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6791 llvm::GlobalVariable::PrivateLinkage);
6792 GV->addAttribute(
"objc_arc_inert");
6793 switch (Triple.getObjectFormat()) {
6794 case llvm::Triple::UnknownObjectFormat:
6795 llvm_unreachable(
"unknown file format");
6796 case llvm::Triple::DXContainer:
6797 case llvm::Triple::GOFF:
6798 case llvm::Triple::SPIRV:
6799 case llvm::Triple::XCOFF:
6800 llvm_unreachable(
"unimplemented");
6801 case llvm::Triple::COFF:
6802 case llvm::Triple::ELF:
6803 case llvm::Triple::Wasm:
6804 GV->setSection(
"cfstring");
6806 case llvm::Triple::MachO:
6807 GV->setSection(
"__DATA,__cfstring");
6816 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6820 if (ObjCFastEnumerationStateType.isNull()) {
6821 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
6825 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
6826 Context.getPointerType(Context.UnsignedLongTy),
6827 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6830 for (
size_t i = 0; i < 4; ++i) {
6835 FieldTypes[i],
nullptr,
6844 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
6847 return ObjCFastEnumerationStateType;
6861 assert(CAT &&
"String literal not of constant array type!");
6863 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6867 llvm::Type *ElemTy = AType->getElementType();
6868 unsigned NumElements = AType->getNumElements();
6871 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6873 Elements.reserve(NumElements);
6875 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
6877 Elements.resize(NumElements);
6878 return llvm::ConstantDataArray::get(VMContext, Elements);
6881 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6883 Elements.reserve(NumElements);
6885 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
6887 Elements.resize(NumElements);
6888 return llvm::ConstantDataArray::get(VMContext, Elements);
6891static llvm::GlobalVariable *
6900 auto *GV =
new llvm::GlobalVariable(
6901 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
6902 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6904 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6905 if (GV->isWeakForLinker()) {
6906 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6907 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6923 llvm::GlobalVariable **Entry =
nullptr;
6924 if (!LangOpts.WritableStrings) {
6925 Entry = &ConstantStringMap[
C];
6926 if (
auto GV = *Entry) {
6927 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6930 GV->getValueType(), Alignment);
6935 StringRef GlobalVariableName;
6936 llvm::GlobalValue::LinkageTypes LT;
6941 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6942 !LangOpts.WritableStrings) {
6943 llvm::raw_svector_ostream Out(MangledNameBuffer);
6945 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6946 GlobalVariableName = MangledNameBuffer;
6948 LT = llvm::GlobalValue::PrivateLinkage;
6949 GlobalVariableName = Name;
6961 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
6964 GV->getValueType(), Alignment);
6981 StringRef GlobalName) {
6982 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6987 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6990 llvm::GlobalVariable **Entry =
nullptr;
6991 if (!LangOpts.WritableStrings) {
6992 Entry = &ConstantStringMap[
C];
6993 if (
auto GV = *Entry) {
6994 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6997 GV->getValueType(), Alignment);
7003 GlobalName, Alignment);
7008 GV->getValueType(), Alignment);
7021 MaterializedType = E->
getType();
7025 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7026 if (!InsertResult.second) {
7029 if (!InsertResult.first->second) {
7034 InsertResult.first->second =
new llvm::GlobalVariable(
7035 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7039 llvm::cast<llvm::GlobalVariable>(
7040 InsertResult.first->second->stripPointerCasts())
7049 llvm::raw_svector_ostream Out(Name);
7071 std::optional<ConstantEmitter> emitter;
7072 llvm::Constant *InitialValue =
nullptr;
7073 bool Constant =
false;
7077 emitter.emplace(*
this);
7078 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7083 Type = InitialValue->getType();
7092 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7094 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7098 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7102 Linkage = llvm::GlobalVariable::InternalLinkage;
7106 auto *GV =
new llvm::GlobalVariable(
7108 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7109 if (emitter) emitter->finalize(GV);
7111 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7113 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7115 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7119 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7120 if (VD->getTLSKind())
7122 llvm::Constant *CV = GV;
7125 *
this, GV, AddrSpace,
7126 llvm::PointerType::get(
7132 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7134 Entry->replaceAllUsesWith(CV);
7135 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7144void CodeGenModule::EmitObjCPropertyImplementations(
const
7157 if (!Getter || Getter->isSynthesizedAccessorStub())
7160 auto *Setter = PID->getSetterMethodDecl();
7161 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7172 if (ivar->getType().isDestructedType())
7193void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7206 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7221 getContext().getObjCIdType(),
nullptr, D,
true,
7227 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7232void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7239 EmitDeclContext(LSD);
7242void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7244 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7247 std::unique_ptr<CodeGenFunction> &CurCGF =
7248 GlobalTopLevelStmtBlockInFlight.first;
7252 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7260 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7261 FunctionArgList Args;
7263 const CGFunctionInfo &FnInfo =
7266 llvm::Function *
Fn = llvm::Function::Create(
7267 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7269 CurCGF.reset(
new CodeGenFunction(*
this));
7270 GlobalTopLevelStmtBlockInFlight.second = D;
7271 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7273 CXXGlobalInits.push_back(Fn);
7276 CurCGF->EmitStmt(D->
getStmt());
7279void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7280 for (
auto *I : DC->
decls()) {
7286 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7287 for (
auto *M : OID->methods())
7306 case Decl::CXXConversion:
7307 case Decl::CXXMethod:
7308 case Decl::Function:
7315 case Decl::CXXDeductionGuide:
7320 case Decl::Decomposition:
7321 case Decl::VarTemplateSpecialization:
7323 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7324 for (
auto *B : DD->flat_bindings())
7325 if (
auto *HD = B->getHoldingVar())
7332 case Decl::IndirectField:
7336 case Decl::Namespace:
7339 case Decl::ClassTemplateSpecialization: {
7342 if (Spec->getSpecializationKind() ==
7344 Spec->hasDefinition())
7345 DI->completeTemplateDefinition(*Spec);
7347 case Decl::CXXRecord: {
7351 DI->EmitAndRetainType(
7355 DI->completeUnusedClass(*CRD);
7358 for (
auto *I : CRD->
decls())
7364 case Decl::UsingShadow:
7365 case Decl::ClassTemplate:
7366 case Decl::VarTemplate:
7368 case Decl::VarTemplatePartialSpecialization:
7369 case Decl::FunctionTemplate:
7370 case Decl::TypeAliasTemplate:
7379 case Decl::UsingEnum:
7383 case Decl::NamespaceAlias:
7387 case Decl::UsingDirective:
7391 case Decl::CXXConstructor:
7394 case Decl::CXXDestructor:
7398 case Decl::StaticAssert:
7405 case Decl::ObjCInterface:
7406 case Decl::ObjCCategory:
7409 case Decl::ObjCProtocol: {
7411 if (Proto->isThisDeclarationADefinition())
7412 ObjCRuntime->GenerateProtocol(Proto);
7416 case Decl::ObjCCategoryImpl:
7422 case Decl::ObjCImplementation: {
7424 EmitObjCPropertyImplementations(OMD);
7425 EmitObjCIvarInitializations(OMD);
7426 ObjCRuntime->GenerateClass(OMD);
7430 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7431 OMD->getClassInterface()), OMD->getLocation());
7434 case Decl::ObjCMethod: {
7441 case Decl::ObjCCompatibleAlias:
7445 case Decl::PragmaComment: {
7447 switch (PCD->getCommentKind()) {
7449 llvm_unreachable(
"unexpected pragma comment kind");
7464 case Decl::PragmaDetectMismatch: {
7470 case Decl::LinkageSpec:
7474 case Decl::FileScopeAsm: {
7476 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7479 if (LangOpts.OpenMPIsTargetDevice)
7482 if (LangOpts.SYCLIsDevice)
7485 getModule().appendModuleInlineAsm(AD->getAsmString());
7489 case Decl::TopLevelStmt:
7493 case Decl::Import: {
7497 if (!ImportedModules.insert(Import->getImportedModule()))
7501 if (!Import->getImportedOwningModule()) {
7503 DI->EmitImportDecl(*Import);
7509 if (CXX20ModuleInits && Import->getImportedModule() &&
7510 Import->getImportedModule()->isNamedModule())
7519 Visited.insert(Import->getImportedModule());
7520 Stack.push_back(Import->getImportedModule());
7522 while (!Stack.empty()) {
7524 if (!EmittedModuleInitializers.insert(Mod).second)
7527 for (
auto *D : Context.getModuleInitializers(Mod))
7534 if (Submodule->IsExplicit)
7537 if (Visited.insert(Submodule).second)
7538 Stack.push_back(Submodule);
7548 case Decl::OMPThreadPrivate:
7552 case Decl::OMPAllocate:
7556 case Decl::OMPDeclareReduction:
7560 case Decl::OMPDeclareMapper:
7564 case Decl::OMPRequires:
7569 case Decl::TypeAlias:
7571 DI->EmitAndRetainType(
getContext().getTypedefType(
7579 DI->EmitAndRetainType(
7586 DI->EmitAndRetainType(
7590 case Decl::HLSLRootSignature:
7593 case Decl::HLSLBuffer:
7597 case Decl::OpenACCDeclare:
7600 case Decl::OpenACCRoutine:
7615 if (!CodeGenOpts.CoverageMapping)
7618 case Decl::CXXConversion:
7619 case Decl::CXXMethod:
7620 case Decl::Function:
7621 case Decl::ObjCMethod:
7622 case Decl::CXXConstructor:
7623 case Decl::CXXDestructor: {
7632 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
7642 if (!CodeGenOpts.CoverageMapping)
7644 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7645 if (Fn->isTemplateInstantiation())
7648 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
7656 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7659 const Decl *D = Entry.first;
7661 case Decl::CXXConversion:
7662 case Decl::CXXMethod:
7663 case Decl::Function:
7664 case Decl::ObjCMethod: {
7671 case Decl::CXXConstructor: {
7678 case Decl::CXXDestructor: {
7695 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7696 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7697 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7698 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7699 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7708 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7709 return llvm::ConstantInt::get(i64, PtrInt);
7713 llvm::NamedMDNode *&GlobalMetadata,
7715 llvm::GlobalValue *
Addr) {
7716 if (!GlobalMetadata)
7718 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7721 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
7724 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7727bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7728 llvm::GlobalValue *CppFunc) {
7730 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7733 llvm::SmallVector<llvm::ConstantExpr *> CEs;
7736 if (Elem == CppFunc)
7742 for (llvm::User *User : Elem->users()) {
7746 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7747 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7750 for (llvm::User *CEUser : ConstExpr->users()) {
7751 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7752 IFuncs.push_back(IFunc);
7757 CEs.push_back(ConstExpr);
7758 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7759 IFuncs.push_back(IFunc);
7771 for (llvm::GlobalIFunc *IFunc : IFuncs)
7772 IFunc->setResolver(
nullptr);
7773 for (llvm::ConstantExpr *ConstExpr : CEs)
7774 ConstExpr->destroyConstant();
7778 Elem->eraseFromParent();
7780 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7785 llvm::FunctionType::get(IFunc->getType(),
false);
7786 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7787 CppFunc->getName(), ResolverTy, {},
false);
7788 IFunc->setResolver(Resolver);
7798void CodeGenModule::EmitStaticExternCAliases() {
7801 for (
auto &I : StaticExternCValues) {
7802 const IdentifierInfo *Name = I.first;
7803 llvm::GlobalValue *Val = I.second;
7811 llvm::GlobalValue *ExistingElem =
7816 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7823 auto Res = Manglings.find(MangledName);
7824 if (Res == Manglings.end())
7826 Result = Res->getValue();
7837void CodeGenModule::EmitDeclMetadata() {
7838 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7840 for (
auto &I : MangledDeclNames) {
7841 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
7851void CodeGenFunction::EmitDeclMetadata() {
7852 if (LocalDeclMap.empty())
return;
7857 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7859 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7861 for (
auto &I : LocalDeclMap) {
7862 const Decl *D = I.first;
7863 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
7864 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
7866 Alloca->setMetadata(
7867 DeclPtrKind, llvm::MDNode::get(
7868 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7869 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
7876void CodeGenModule::EmitVersionIdentMetadata() {
7877 llvm::NamedMDNode *IdentMetadata =
7878 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7880 llvm::LLVMContext &Ctx = TheModule.getContext();
7882 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7883 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7886void CodeGenModule::EmitCommandLineMetadata() {
7887 llvm::NamedMDNode *CommandLineMetadata =
7888 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7890 llvm::LLVMContext &Ctx = TheModule.getContext();
7892 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7893 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7896void CodeGenModule::EmitCoverageFile() {
7897 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7901 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7902 llvm::LLVMContext &Ctx = TheModule.getContext();
7903 auto *CoverageDataFile =
7905 auto *CoverageNotesFile =
7907 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7908 llvm::MDNode *CU = CUNode->getOperand(i);
7909 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7910 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7923 LangOpts.ObjCRuntime.isGNUFamily())
7924 return ObjCRuntime->GetEHType(Ty);
7931 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7933 for (
auto RefExpr : D->
varlist()) {
7936 VD->getAnyInitializer() &&
7937 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7944 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
7945 CXXGlobalInits.push_back(InitFunction);
7950CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7954 FnType->getReturnType(), FnType->getParamTypes(),
7955 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7957 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7962 std::string OutName;
7963 llvm::raw_string_ostream Out(OutName);
7968 Out <<
".normalized";
7991 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7996 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8000 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8008 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8009 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8010 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8011 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8012 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8013 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8014 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8015 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8023 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8025 if (CodeGenOpts.SanitizeCfiCrossDso)
8027 VTable->addTypeMetadata(Offset.getQuantity(),
8028 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8031 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8032 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8038 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8048 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8063 bool forPointeeType) {
8074 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8081 bool AlignForArray =
T->isArrayType();
8087 if (
T->isIncompleteType()) {
8104 if (
T.getQualifiers().hasUnaligned()) {
8106 }
else if (forPointeeType && !AlignForArray &&
8107 (RD =
T->getAsCXXRecordDecl())) {
8118 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8131 if (NumAutoVarInit >= StopAfter) {
8134 if (!NumAutoVarInit) {
8137 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
8138 "number of times ftrivial-auto-var-init=%1 gets applied.");
8152 const Decl *D)
const {
8156 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8158 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8164 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8168 llvm::MD5::MD5Result
Result;
8169 for (
const auto &Arg : PreprocessorOpts.Macros)
8170 Hash.update(Arg.first);
8174 llvm::sys::fs::UniqueID ID;
8175 if (llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
8177 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8178 if (
auto EC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
8179 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8182 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8183 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8190 assert(DeferredDeclsToEmit.empty() &&
8191 "Should have emitted all decls deferred to emit.");
8192 assert(NewBuilder->DeferredDecls.empty() &&
8193 "Newly created module should not have deferred decls");
8194 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8195 assert(EmittedDeferredDecls.empty() &&
8196 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8198 assert(NewBuilder->DeferredVTables.empty() &&
8199 "Newly created module should not have deferred vtables");
8200 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8202 assert(NewBuilder->MangledDeclNames.empty() &&
8203 "Newly created module should not have mangled decl names");
8204 assert(NewBuilder->Manglings.empty() &&
8205 "Newly created module should not have manglings");
8206 NewBuilder->Manglings = std::move(Manglings);
8208 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8210 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
Defines the clang::ASTContext interface.
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 bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
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 GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
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 QualType GeneralizeTransparentUnion(QualType Ty)
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 bool allowKCFIIdentifier(StringRef Name)
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 void checkDataLayoutConsistency(const TargetInfo &Target, llvm::LLVMContext &Context, const LangOptions &Opts)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
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 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 llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
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 QualType GeneralizeType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
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::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
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()
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
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()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
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.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
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
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
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.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
CXXTemporary * getTemporary()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
FunctionDecl * getOperatorDelete() const
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
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.
FunctionDecl * getOperatorNew() const
Represents a C++ struct/union/class.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
const CXXDestructorDecl * getDestructor() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
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 MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
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::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
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 EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
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 addRootSignature(const HLSLRootSignatureDecl *D)
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...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
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.
llvm::LLVMContext & getLLVMContext()
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
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.
llvm::ConstantInt * CreateKCFITypeId(QualType T, StringRef Salt)
Generate a KCFI type identifier for T.
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.
void createFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
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.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
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.
SanitizerMetadata * getSanitizerMetadata()
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)
AtomicOptions getAtomicOpts()
Get the current Atomic options.
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 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 EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void addReplacement(StringRef Name, llvm::Constant *C)
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.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
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, StringRef GlobalName=".str")
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 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.
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, 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.
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.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
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.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
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.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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 isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
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 * 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.
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 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.
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
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...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
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
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.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
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.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents 'pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
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()
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?
@ 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...
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.
ExclusionType getDefault(llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, llvm::driver::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.
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, llvm::driver::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.
bool isConstant(const ASTContext &Ctx) const
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
virtual void completeDefinition()
Note that the definition of this type is now complete.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
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.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
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.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
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 RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
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.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() 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.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
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 > 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)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool LT(InterpState &S, CodePtr OpPC)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
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)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
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...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ 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.
const FunctionProtoType * T
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)
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.
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ 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
int const char * function
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
std::optional< StringRef > Architecture
llvm::SmallVector< StringRef, 8 > Features
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
Return true if the evaluated expression has side effects.
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
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.