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)"));
90 case TargetCXXABI::AppleARM64:
91 case TargetCXXABI::Fuchsia:
92 case TargetCXXABI::GenericAArch64:
93 case TargetCXXABI::GenericARM:
94 case TargetCXXABI::iOS:
95 case TargetCXXABI::WatchOS:
96 case TargetCXXABI::GenericMIPS:
97 case TargetCXXABI::GenericItanium:
98 case TargetCXXABI::WebAssembly:
99 case TargetCXXABI::XL:
101 case TargetCXXABI::Microsoft:
105 llvm_unreachable(
"invalid C++ ABI kind");
108static std::unique_ptr<TargetCodeGenInfo>
111 const llvm::Triple &Triple =
Target.getTriple();
114 switch (Triple.getArch()) {
118 case llvm::Triple::m68k:
120 case llvm::Triple::mips:
121 case llvm::Triple::mipsel:
122 if (Triple.getOS() == llvm::Triple::Win32)
126 case llvm::Triple::mips64:
127 case llvm::Triple::mips64el:
130 case llvm::Triple::avr: {
134 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
135 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
139 case llvm::Triple::aarch64:
140 case llvm::Triple::aarch64_32:
141 case llvm::Triple::aarch64_be: {
143 if (
Target.getABI() ==
"darwinpcs")
144 Kind = AArch64ABIKind::DarwinPCS;
145 else if (Triple.isOSWindows())
147 else if (
Target.getABI() ==
"aapcs-soft")
148 Kind = AArch64ABIKind::AAPCSSoft;
153 case llvm::Triple::wasm32:
154 case llvm::Triple::wasm64: {
156 if (
Target.getABI() ==
"experimental-mv")
157 Kind = WebAssemblyABIKind::ExperimentalMV;
161 case llvm::Triple::arm:
162 case llvm::Triple::armeb:
163 case llvm::Triple::thumb:
164 case llvm::Triple::thumbeb: {
165 if (Triple.getOS() == llvm::Triple::Win32)
169 StringRef ABIStr =
Target.getABI();
170 if (ABIStr ==
"apcs-gnu")
171 Kind = ARMABIKind::APCS;
172 else if (ABIStr ==
"aapcs16")
173 Kind = ARMABIKind::AAPCS16_VFP;
174 else if (CodeGenOpts.
FloatABI ==
"hard" ||
175 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
176 Kind = ARMABIKind::AAPCS_VFP;
181 case llvm::Triple::ppc: {
182 if (Triple.isOSAIX())
189 case llvm::Triple::ppcle: {
194 case llvm::Triple::ppc64:
195 if (Triple.isOSAIX())
198 if (Triple.isOSBinFormatELF()) {
200 if (
Target.getABI() ==
"elfv2")
201 Kind = PPC64_SVR4_ABIKind::ELFv2;
202 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
207 case llvm::Triple::ppc64le: {
208 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
210 if (
Target.getABI() ==
"elfv1")
211 Kind = PPC64_SVR4_ABIKind::ELFv1;
212 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
217 case llvm::Triple::nvptx:
218 case llvm::Triple::nvptx64:
221 case llvm::Triple::msp430:
224 case llvm::Triple::riscv32:
225 case llvm::Triple::riscv64: {
226 StringRef ABIStr =
Target.getABI();
228 unsigned ABIFLen = 0;
229 if (ABIStr.ends_with(
"f"))
231 else if (ABIStr.ends_with(
"d"))
233 bool EABI = ABIStr.ends_with(
"e");
237 case llvm::Triple::systemz: {
238 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
239 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
243 case llvm::Triple::tce:
244 case llvm::Triple::tcele:
247 case llvm::Triple::x86: {
248 bool IsDarwinVectorABI = Triple.isOSDarwin();
249 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
251 if (Triple.getOS() == llvm::Triple::Win32) {
253 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
254 CodeGenOpts.NumRegisterParameters);
257 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
258 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
261 case llvm::Triple::x86_64: {
262 StringRef ABI =
Target.getABI();
263 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
264 : ABI ==
"avx" ? X86AVXABILevel::AVX
265 : X86AVXABILevel::None);
267 switch (Triple.getOS()) {
268 case llvm::Triple::UEFI:
269 case llvm::Triple::Win32:
275 case llvm::Triple::hexagon:
277 case llvm::Triple::lanai:
279 case llvm::Triple::r600:
281 case llvm::Triple::amdgcn:
283 case llvm::Triple::sparc:
285 case llvm::Triple::sparcv9:
287 case llvm::Triple::xcore:
289 case llvm::Triple::arc:
291 case llvm::Triple::spir:
292 case llvm::Triple::spir64:
294 case llvm::Triple::spirv32:
295 case llvm::Triple::spirv64:
296 case llvm::Triple::spirv:
298 case llvm::Triple::dxil:
300 case llvm::Triple::ve:
302 case llvm::Triple::csky: {
303 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
305 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
310 case llvm::Triple::bpfeb:
311 case llvm::Triple::bpfel:
313 case llvm::Triple::loongarch32:
314 case llvm::Triple::loongarch64: {
315 StringRef ABIStr =
Target.getABI();
316 unsigned ABIFRLen = 0;
317 if (ABIStr.ends_with(
"f"))
319 else if (ABIStr.ends_with(
"d"))
328 if (!TheTargetCodeGenInfo)
330 return *TheTargetCodeGenInfo;
334 llvm::LLVMContext &Context,
338 if (Opts.AlignDouble || Opts.OpenCL || Opts.HLSL)
341 llvm::Triple Triple =
Target.getTriple();
342 llvm::DataLayout DL(
Target.getDataLayoutString());
343 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
344 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
345 llvm::Align ClangAlign(Alignment / 8);
346 if (DLAlign != ClangAlign) {
347 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
348 <<
" mapping to " << *Ty <<
" has data layout alignment "
349 << DLAlign.value() <<
" while clang specifies "
350 << ClangAlign.value() <<
"\n";
355 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
357 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
359 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
361 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
364 if (Triple.getArch() != llvm::Triple::m68k)
365 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
368 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
369 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
370 Triple.getArch() != llvm::Triple::ve)
371 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
373 if (
Target.hasFloat16Type())
374 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
376 if (
Target.hasBFloat16Type())
377 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
378 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
381 if (!Triple.isOSAIX()) {
383 llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
386 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
389 if (
Target.hasFloat128Type())
390 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
391 if (
Target.hasIbm128Type())
392 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
394 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
405 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
406 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
408 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
414 llvm::LLVMContext &LLVMContext = M.getContext();
415 VoidTy = llvm::Type::getVoidTy(LLVMContext);
416 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
417 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
418 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
419 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
420 HalfTy = llvm::Type::getHalfTy(LLVMContext);
421 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
422 FloatTy = llvm::Type::getFloatTy(LLVMContext);
423 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
429 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
431 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
433 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
434 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
435 IntPtrTy = llvm::IntegerType::get(LLVMContext,
436 C.getTargetInfo().getMaxPointerWidth());
437 Int8PtrTy = llvm::PointerType::get(LLVMContext,
439 const llvm::DataLayout &DL = M.getDataLayout();
441 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
443 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
460 createOpenCLRuntime();
462 createOpenMPRuntime();
469 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
470 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
476 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
477 CodeGenOpts.CoverageNotesFile.size() ||
478 CodeGenOpts.CoverageDataFile.size())
486 Block.GlobalUniqueCount = 0;
488 if (
C.getLangOpts().ObjC)
491 if (CodeGenOpts.hasProfileClangUse()) {
492 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
493 CodeGenOpts.ProfileInstrumentUsePath, *FS,
494 CodeGenOpts.ProfileRemappingFile);
495 if (
auto E = ReaderOrErr.takeError()) {
496 unsigned DiagID = Diags.getCustomDiagID(
498 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
500 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
504 PGOReader = std::move(ReaderOrErr.get());
509 if (CodeGenOpts.CoverageMapping)
513 if (CodeGenOpts.UniqueInternalLinkageNames &&
514 !
getModule().getSourceFileName().empty()) {
515 std::string Path =
getModule().getSourceFileName();
517 for (
const auto &Entry : LangOpts.MacroPrefixMap)
518 if (Path.rfind(Entry.first, 0) != std::string::npos) {
519 Path = Entry.second + Path.substr(Entry.first.size());
522 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
526 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
527 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
528 CodeGenOpts.NumRegisterParameters);
537 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
538 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
540 this->MSHotPatchFunctions.push_back(std::string{*I});
542 auto &DE = Context.getDiagnostics();
545 "failed to open hotpatch functions file "
546 "(-fms-hotpatch-functions-file): %0 : %1");
548 << BufOrErr.getError().message();
553 this->MSHotPatchFunctions.push_back(FuncName);
555 llvm::sort(this->MSHotPatchFunctions);
558 if (!Context.getAuxTargetInfo())
564void CodeGenModule::createObjCRuntime() {
581 llvm_unreachable(
"bad runtime kind");
584void CodeGenModule::createOpenCLRuntime() {
588void CodeGenModule::createOpenMPRuntime() {
589 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
590 Diags.Report(diag::err_omp_host_ir_file_not_found)
591 << LangOpts.OMPHostIRFile;
596 case llvm::Triple::nvptx:
597 case llvm::Triple::nvptx64:
598 case llvm::Triple::amdgcn:
599 case llvm::Triple::spirv64:
602 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
603 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
606 if (LangOpts.OpenMPSimd)
607 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
609 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
614void CodeGenModule::createCUDARuntime() {
618void CodeGenModule::createHLSLRuntime() {
619 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
623 Replacements[Name] =
C;
626void CodeGenModule::applyReplacements() {
627 for (
auto &I : Replacements) {
628 StringRef MangledName = I.first;
629 llvm::Constant *Replacement = I.second;
634 auto *NewF = dyn_cast<llvm::Function>(Replacement);
636 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
637 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
640 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
641 CE->getOpcode() == llvm::Instruction::GetElementPtr);
642 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
647 OldF->replaceAllUsesWith(Replacement);
649 NewF->removeFromParent();
650 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
653 OldF->eraseFromParent();
658 GlobalValReplacements.push_back(std::make_pair(GV,
C));
661void CodeGenModule::applyGlobalValReplacements() {
662 for (
auto &I : GlobalValReplacements) {
663 llvm::GlobalValue *GV = I.first;
664 llvm::Constant *
C = I.second;
666 GV->replaceAllUsesWith(
C);
667 GV->eraseFromParent();
674 const llvm::Constant *
C;
675 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
676 C = GA->getAliasee();
677 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
678 C = GI->getResolver();
682 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
686 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
695 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
696 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
700 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
704 if (GV->hasCommonLinkage()) {
705 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
706 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
707 Diags.
Report(Location, diag::err_alias_to_common);
712 if (GV->isDeclaration()) {
713 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
714 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
715 << IsIFunc << IsIFunc;
718 for (
const auto &[
Decl, Name] : MangledDeclNames) {
719 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
721 if (II && II->
getName() == GV->getName()) {
722 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
726 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
736 const auto *F = dyn_cast<llvm::Function>(GV);
738 Diags.
Report(Location, diag::err_alias_to_undefined)
739 << IsIFunc << IsIFunc;
743 llvm::FunctionType *FTy = F->getFunctionType();
744 if (!FTy->getReturnType()->isPointerTy()) {
745 Diags.
Report(Location, diag::err_ifunc_resolver_return);
759 if (GVar->hasAttribute(
"toc-data")) {
760 auto GVId = GVar->getName();
763 Diags.
Report(Location, diag::warn_toc_unsupported_type)
764 << GVId <<
"the variable has an alias";
766 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
767 llvm::AttributeSet NewAttributes =
768 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
769 GVar->setAttributes(NewAttributes);
773void CodeGenModule::checkAliases() {
778 DiagnosticsEngine &Diags =
getDiags();
779 for (
const GlobalDecl &GD : Aliases) {
781 SourceLocation Location;
783 bool IsIFunc = D->hasAttr<IFuncAttr>();
784 if (
const Attr *A = D->getDefiningAttr()) {
785 Location = A->getLocation();
786 Range = A->getRange();
788 llvm_unreachable(
"Not an alias or ifunc?");
792 const llvm::GlobalValue *GV =
nullptr;
794 MangledDeclNames, Range)) {
800 if (
const llvm::GlobalVariable *GVar =
801 dyn_cast<const llvm::GlobalVariable>(GV))
805 llvm::Constant *Aliasee =
809 llvm::GlobalValue *AliaseeGV;
810 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
815 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
816 StringRef AliasSection = SA->getName();
817 if (AliasSection != AliaseeGV->getSection())
818 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
819 << AliasSection << IsIFunc << IsIFunc;
827 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
828 if (GA->isInterposable()) {
829 Diags.Report(Location, diag::warn_alias_to_weak_alias)
830 << GV->getName() << GA->getName() << IsIFunc;
831 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
832 GA->getAliasee(), Alias->getType());
844 llvm::Attribute::DisableSanitizerInstrumentation);
849 for (
const GlobalDecl &GD : Aliases) {
852 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
853 Alias->eraseFromParent();
858 DeferredDeclsToEmit.clear();
859 EmittedDeferredDecls.clear();
860 DeferredAnnotations.clear();
862 OpenMPRuntime->clear();
866 StringRef MainFile) {
869 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
870 if (MainFile.empty())
871 MainFile =
"<stdin>";
872 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
875 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
878 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
882static std::optional<llvm::GlobalValue::VisibilityTypes>
889 return llvm::GlobalValue::DefaultVisibility;
891 return llvm::GlobalValue::HiddenVisibility;
893 return llvm::GlobalValue::ProtectedVisibility;
895 llvm_unreachable(
"unknown option value!");
900 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
909 GV.setDSOLocal(
false);
910 GV.setVisibility(*
V);
915 if (!LO.VisibilityFromDLLStorageClass)
918 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
921 std::optional<llvm::GlobalValue::VisibilityTypes>
922 NoDLLStorageClassVisibility =
925 std::optional<llvm::GlobalValue::VisibilityTypes>
926 ExternDeclDLLImportVisibility =
929 std::optional<llvm::GlobalValue::VisibilityTypes>
930 ExternDeclNoDLLStorageClassVisibility =
933 for (llvm::GlobalValue &GV : M.global_values()) {
934 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
937 if (GV.isDeclarationForLinker())
939 llvm::GlobalValue::DLLImportStorageClass
940 ? ExternDeclDLLImportVisibility
941 : ExternDeclNoDLLStorageClassVisibility);
944 llvm::GlobalValue::DLLExportStorageClass
945 ? DLLExportVisibility
946 : NoDLLStorageClassVisibility);
948 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
953 const llvm::Triple &Triple,
957 return LangOpts.getStackProtector() == Mode;
963 EmitModuleInitializers(Primary);
965 DeferredDecls.insert_range(EmittedDeferredDecls);
966 EmittedDeferredDecls.clear();
967 EmitVTablesOpportunistically();
968 applyGlobalValReplacements();
970 emitMultiVersionFunctions();
972 if (Context.getLangOpts().IncrementalExtensions &&
973 GlobalTopLevelStmtBlockInFlight.first) {
975 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
976 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
982 EmitCXXModuleInitFunc(Primary);
984 EmitCXXGlobalInitFunc();
985 EmitCXXGlobalCleanUpFunc();
986 registerGlobalDtorsWithAtExit();
987 EmitCXXThreadLocalInitFunc();
989 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
991 if (Context.getLangOpts().CUDA && CUDARuntime) {
992 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
996 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
997 OpenMPRuntime->clear();
1001 PGOReader->getSummary(
false).getMD(VMContext),
1002 llvm::ProfileSummary::PSK_Instr);
1003 if (PGOStats.hasDiagnostics())
1009 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1010 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1012 EmitStaticExternCAliases();
1017 if (CoverageMapping)
1018 CoverageMapping->emit();
1019 if (CodeGenOpts.SanitizeCfiCrossDso) {
1023 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1025 emitAtAvailableLinkGuard();
1026 if (Context.getTargetInfo().getTriple().isWasm())
1033 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1034 llvm::CodeObjectVersionKind::COV_None) {
1035 getModule().addModuleFlag(llvm::Module::Error,
1036 "amdhsa_code_object_version",
1037 getTarget().getTargetOpts().CodeObjectVersion);
1042 auto *MDStr = llvm::MDString::get(
1047 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1056 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1058 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1060 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1064 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1068 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1070 auto *GV =
new llvm::GlobalVariable(
1071 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1072 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1078 auto *GV =
new llvm::GlobalVariable(
1080 llvm::Constant::getNullValue(
Int8Ty),
1089 if (CodeGenOpts.Autolink &&
1090 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1091 EmitModuleLinkOptions();
1106 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1107 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1108 for (
auto *MD : ELFDependentLibraries)
1109 NMD->addOperand(MD);
1112 if (CodeGenOpts.DwarfVersion) {
1113 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1114 CodeGenOpts.DwarfVersion);
1117 if (CodeGenOpts.Dwarf64)
1118 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1120 if (Context.getLangOpts().SemanticInterposition)
1122 getModule().setSemanticInterposition(
true);
1124 if (CodeGenOpts.EmitCodeView) {
1126 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1128 if (CodeGenOpts.CodeViewGHash) {
1129 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1131 if (CodeGenOpts.ControlFlowGuard) {
1133 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1134 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1136 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1138 if (CodeGenOpts.EHContGuard) {
1140 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1142 if (Context.getLangOpts().Kernel) {
1144 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1146 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1151 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1153 llvm::Metadata *Ops[2] = {
1154 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1155 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1156 llvm::Type::getInt32Ty(VMContext), 1))};
1158 getModule().addModuleFlag(llvm::Module::Require,
1159 "StrictVTablePointersRequirement",
1160 llvm::MDNode::get(VMContext, Ops));
1166 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1167 llvm::DEBUG_METADATA_VERSION);
1172 uint64_t WCharWidth =
1173 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1174 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1177 getModule().addModuleFlag(llvm::Module::Warning,
1178 "zos_product_major_version",
1179 uint32_t(CLANG_VERSION_MAJOR));
1180 getModule().addModuleFlag(llvm::Module::Warning,
1181 "zos_product_minor_version",
1182 uint32_t(CLANG_VERSION_MINOR));
1183 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1184 uint32_t(CLANG_VERSION_PATCHLEVEL));
1186 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1187 llvm::MDString::get(VMContext, ProductId));
1192 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1193 llvm::MDString::get(VMContext, lang_str));
1195 time_t TT = PreprocessorOpts.SourceDateEpoch
1196 ? *PreprocessorOpts.SourceDateEpoch
1197 : std::time(
nullptr);
1198 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1199 static_cast<uint64_t
>(TT));
1202 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1203 llvm::MDString::get(VMContext,
"ascii"));
1206 llvm::Triple
T = Context.getTargetInfo().getTriple();
1207 if (
T.isARM() ||
T.isThumb()) {
1209 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1210 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1214 StringRef ABIStr = Target.getABI();
1215 llvm::LLVMContext &Ctx = TheModule.getContext();
1216 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1217 llvm::MDString::get(Ctx, ABIStr));
1222 const std::vector<std::string> &Features =
1225 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1226 if (!errorToBool(ParseResult.takeError()))
1228 llvm::Module::AppendUnique,
"riscv-isa",
1230 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1233 if (CodeGenOpts.SanitizeCfiCrossDso) {
1235 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1238 if (CodeGenOpts.WholeProgramVTables) {
1242 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1243 CodeGenOpts.VirtualFunctionElimination);
1246 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1247 getModule().addModuleFlag(llvm::Module::Override,
1248 "CFI Canonical Jump Tables",
1249 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1252 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1253 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1257 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1259 llvm::Module::Append,
"Unique Source File Identifier",
1261 TheModule.getContext(),
1262 llvm::MDString::get(TheModule.getContext(),
1263 CodeGenOpts.UniqueSourceFileIdentifier)));
1266 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1267 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1270 if (CodeGenOpts.PatchableFunctionEntryOffset)
1271 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1272 CodeGenOpts.PatchableFunctionEntryOffset);
1273 if (CodeGenOpts.SanitizeKcfiArity)
1274 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1277 if (CodeGenOpts.CFProtectionReturn &&
1278 Target.checkCFProtectionReturnSupported(
getDiags())) {
1280 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1284 if (CodeGenOpts.CFProtectionBranch &&
1285 Target.checkCFProtectionBranchSupported(
getDiags())) {
1287 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1290 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1291 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1293 Scheme = Target.getDefaultCFBranchLabelScheme();
1295 llvm::Module::Error,
"cf-branch-label-scheme",
1301 if (CodeGenOpts.FunctionReturnThunks)
1302 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1304 if (CodeGenOpts.IndirectBranchCSPrefix)
1305 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1316 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1317 LangOpts.getSignReturnAddressScope() !=
1319 getModule().addModuleFlag(llvm::Module::Override,
1320 "sign-return-address-buildattr", 1);
1321 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1322 getModule().addModuleFlag(llvm::Module::Override,
1323 "tag-stack-memory-buildattr", 1);
1325 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1333 if (LangOpts.BranchTargetEnforcement)
1334 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1336 if (LangOpts.BranchProtectionPAuthLR)
1337 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1339 if (LangOpts.GuardedControlStack)
1340 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1341 if (LangOpts.hasSignReturnAddress())
1342 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1343 if (LangOpts.isSignReturnAddressScopeAll())
1344 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1346 if (!LangOpts.isSignReturnAddressWithAKey())
1347 getModule().addModuleFlag(llvm::Module::Min,
1348 "sign-return-address-with-bkey", 2);
1350 if (LangOpts.PointerAuthELFGOT)
1351 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1354 if (LangOpts.PointerAuthCalls)
1355 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1358 using namespace llvm::ELF;
1359 uint64_t PAuthABIVersion =
1360 (LangOpts.PointerAuthIntrinsics
1361 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1362 (LangOpts.PointerAuthCalls
1363 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1364 (LangOpts.PointerAuthReturns
1365 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1366 (LangOpts.PointerAuthAuthTraps
1367 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1368 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1369 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1370 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1371 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1372 (LangOpts.PointerAuthInitFini
1373 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1374 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1375 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1376 (LangOpts.PointerAuthELFGOT
1377 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1378 (LangOpts.PointerAuthIndirectGotos
1379 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1380 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1381 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1382 (LangOpts.PointerAuthFunctionTypeDiscrimination
1383 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1384 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1385 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1386 "Update when new enum items are defined");
1387 if (PAuthABIVersion != 0) {
1388 getModule().addModuleFlag(llvm::Module::Error,
1389 "aarch64-elf-pauthabi-platform",
1390 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1391 getModule().addModuleFlag(llvm::Module::Error,
1392 "aarch64-elf-pauthabi-version",
1398 if (CodeGenOpts.StackClashProtector)
1400 llvm::Module::Override,
"probe-stack",
1401 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1403 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1404 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1405 CodeGenOpts.StackProbeSize);
1407 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1408 llvm::LLVMContext &Ctx = TheModule.getContext();
1410 llvm::Module::Error,
"MemProfProfileFilename",
1411 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1414 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1418 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1419 CodeGenOpts.FP32DenormalMode.Output !=
1420 llvm::DenormalMode::IEEE);
1423 if (LangOpts.EHAsynch)
1424 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1427 if (CodeGenOpts.ImportCallOptimization)
1428 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1432 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1434 llvm::Module::Warning,
"winx64-eh-unwindv2",
1435 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1439 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1441 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1445 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1446 EmitOpenCLMetadata();
1453 auto Version = LangOpts.getOpenCLCompatibleVersion();
1454 llvm::Metadata *SPIRVerElts[] = {
1455 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1457 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1458 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1459 llvm::NamedMDNode *SPIRVerMD =
1460 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1461 llvm::LLVMContext &Ctx = TheModule.getContext();
1462 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1470 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1471 assert(PLevel < 3 &&
"Invalid PIC Level");
1472 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1473 if (Context.getLangOpts().PIE)
1474 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1478 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1479 .Case(
"tiny", llvm::CodeModel::Tiny)
1480 .Case(
"small", llvm::CodeModel::Small)
1481 .Case(
"kernel", llvm::CodeModel::Kernel)
1482 .Case(
"medium", llvm::CodeModel::Medium)
1483 .Case(
"large", llvm::CodeModel::Large)
1486 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1489 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1490 Context.getTargetInfo().getTriple().getArch() ==
1491 llvm::Triple::x86_64) {
1497 if (CodeGenOpts.NoPLT)
1500 CodeGenOpts.DirectAccessExternalData !=
1501 getModule().getDirectAccessExternalData()) {
1502 getModule().setDirectAccessExternalData(
1503 CodeGenOpts.DirectAccessExternalData);
1505 if (CodeGenOpts.UnwindTables)
1506 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1508 switch (CodeGenOpts.getFramePointer()) {
1513 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1516 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1519 getModule().setFramePointer(llvm::FramePointerKind::All);
1523 SimplifyPersonality();
1536 EmitVersionIdentMetadata();
1539 EmitCommandLineMetadata();
1547 getModule().setStackProtectorGuardSymbol(
1550 getModule().setStackProtectorGuardOffset(
1555 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1557 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1559 if (
getContext().getTargetInfo().getMaxTLSAlign())
1560 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1561 getContext().getTargetInfo().getMaxTLSAlign());
1579 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1580 for (
auto &I : MustTailCallUndefinedGlobals) {
1581 if (!I.first->isDefined())
1582 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1586 if (!Entry || Entry->isWeakForLinker() ||
1587 Entry->isDeclarationForLinker())
1588 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1599 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1600 ErrnoTBAAMD->addOperand(IntegerNode);
1605void CodeGenModule::EmitOpenCLMetadata() {
1611 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1612 llvm::Metadata *OCLVerElts[] = {
1613 llvm::ConstantAsMetadata::get(
1614 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1615 llvm::ConstantAsMetadata::get(
1616 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1617 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1618 llvm::LLVMContext &Ctx = TheModule.getContext();
1619 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1622 EmitVersion(
"opencl.ocl.version", CLVersion);
1623 if (LangOpts.OpenCLCPlusPlus) {
1625 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1629void CodeGenModule::EmitBackendOptionsMetadata(
1630 const CodeGenOptions &CodeGenOpts) {
1632 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1633 CodeGenOpts.SmallDataLimit);
1650 return TBAA->getTypeInfo(QTy);
1669 return TBAA->getAccessInfo(AccessType);
1676 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1682 return TBAA->getTBAAStructInfo(QTy);
1688 return TBAA->getBaseTypeInfo(QTy);
1694 return TBAA->getAccessTagInfo(Info);
1701 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1709 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1717 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1723 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1728 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1741 "cannot compile this %0 yet");
1742 std::string Msg =
Type;
1751 "cannot compile this %0 yet");
1752 std::string Msg =
Type;
1757 llvm::function_ref<
void()> Fn) {
1758 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1768 if (GV->hasLocalLinkage()) {
1769 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1782 if (Context.getLangOpts().OpenMP &&
1783 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
1784 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1785 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1786 OMPDeclareTargetDeclAttr::DT_NoHost &&
1788 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1793 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1797 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1801 if (GV->hasDLLExportStorageClass()) {
1804 diag::err_hidden_visibility_dllexport);
1807 diag::err_non_default_visibility_dllimport);
1813 !GV->isDeclarationForLinker())
1818 llvm::GlobalValue *GV) {
1819 if (GV->hasLocalLinkage())
1822 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1826 if (GV->hasDLLImportStorageClass())
1829 const llvm::Triple &TT = CGM.
getTriple();
1831 if (TT.isOSCygMing()) {
1849 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1857 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1861 if (!TT.isOSBinFormatELF())
1867 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1875 return !(CGM.
getLangOpts().SemanticInterposition ||
1880 if (!GV->isDeclarationForLinker())
1886 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1893 if (CGOpts.DirectAccessExternalData) {
1899 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1900 if (!Var->isThreadLocal())
1925 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
1927 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1937 if (D->
hasAttr<DLLImportAttr>())
1938 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1939 else if ((D->
hasAttr<DLLExportAttr>() ||
1941 !GV->isDeclarationForLinker())
1942 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1962 GV->setPartition(CodeGenOpts.SymbolPartition);
1966 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1967 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1968 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1969 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1970 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1973llvm::GlobalVariable::ThreadLocalMode
1975 switch (CodeGenOpts.getDefaultTLSModel()) {
1977 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1979 return llvm::GlobalVariable::LocalDynamicTLSModel;
1981 return llvm::GlobalVariable::InitialExecTLSModel;
1983 return llvm::GlobalVariable::LocalExecTLSModel;
1985 llvm_unreachable(
"Invalid TLS model!");
1989 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
1991 llvm::GlobalValue::ThreadLocalMode TLM;
1995 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
1999 GV->setThreadLocalMode(TLM);
2005 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2009 const CPUSpecificAttr *
Attr,
2031 bool OmitMultiVersionMangling =
false) {
2033 llvm::raw_svector_ostream Out(Buffer);
2042 assert(II &&
"Attempt to mangle unnamed decl.");
2043 const auto *FD = dyn_cast<FunctionDecl>(ND);
2048 Out <<
"__regcall4__" << II->
getName();
2050 Out <<
"__regcall3__" << II->
getName();
2051 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2053 Out <<
"__device_stub__" << II->
getName();
2055 DeviceKernelAttr::isOpenCLSpelling(
2056 FD->getAttr<DeviceKernelAttr>()) &&
2058 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2074 "Hash computed when not explicitly requested");
2078 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2079 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2080 switch (FD->getMultiVersionKind()) {
2084 FD->getAttr<CPUSpecificAttr>(),
2088 auto *
Attr = FD->getAttr<TargetAttr>();
2089 assert(
Attr &&
"Expected TargetAttr to be present "
2090 "for attribute mangling");
2096 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2097 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2098 "for attribute mangling");
2104 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2105 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2106 "for attribute mangling");
2113 llvm_unreachable(
"None multiversion type isn't valid here");
2123 return std::string(Out.str());
2126void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2127 const FunctionDecl *FD,
2128 StringRef &CurName) {
2135 std::string NonTargetName =
2143 "Other GD should now be a multiversioned function");
2153 if (OtherName != NonTargetName) {
2156 const auto ExistingRecord = Manglings.find(NonTargetName);
2157 if (ExistingRecord != std::end(Manglings))
2158 Manglings.remove(&(*ExistingRecord));
2159 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2164 CurName = OtherNameRef;
2166 Entry->setName(OtherName);
2176 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2190 auto FoundName = MangledDeclNames.find(CanonicalGD);
2191 if (FoundName != MangledDeclNames.end())
2192 return FoundName->second;
2229 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2230 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2239 llvm::raw_svector_ostream Out(Buffer);
2242 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2243 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2245 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2250 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2251 return Result.first->first();
2255 auto it = MangledDeclNames.begin();
2256 while (it != MangledDeclNames.end()) {
2257 if (it->second == Name)
2272 llvm::Constant *AssociatedData) {
2274 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2280 bool IsDtorAttrFunc) {
2281 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2283 DtorsUsingAtExit[Priority].push_back(Dtor);
2288 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2291void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2292 if (Fns.empty())
return;
2298 llvm::PointerType *PtrTy = llvm::PointerType::get(
2299 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2302 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2306 auto Ctors = Builder.beginArray(CtorStructTy);
2307 for (
const auto &I : Fns) {
2308 auto Ctor = Ctors.beginStruct(CtorStructTy);
2309 Ctor.addInt(
Int32Ty, I.Priority);
2310 if (InitFiniAuthSchema) {
2311 llvm::Constant *StorageAddress =
2313 ? llvm::ConstantExpr::getIntToPtr(
2314 llvm::ConstantInt::get(
2316 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2320 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2321 llvm::ConstantInt::get(
2323 Ctor.add(SignedCtorPtr);
2325 Ctor.add(I.Initializer);
2327 if (I.AssociatedData)
2328 Ctor.add(I.AssociatedData);
2330 Ctor.addNullPointer(PtrTy);
2331 Ctor.finishAndAddTo(Ctors);
2334 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2336 llvm::GlobalValue::AppendingLinkage);
2340 List->setAlignment(std::nullopt);
2345llvm::GlobalValue::LinkageTypes
2351 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2358 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2359 if (!MDS)
return nullptr;
2361 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2368 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2369 if (!UD->
hasAttr<TransparentUnionAttr>())
2371 if (!UD->
fields().empty())
2372 return UD->
fields().begin()->getType();
2381 bool GeneralizePointers) {
2394 bool GeneralizePointers) {
2397 for (
auto &Param : FnType->param_types())
2398 GeneralizedParams.push_back(
2402 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2403 GeneralizedParams, FnType->getExtProtoInfo());
2408 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2410 llvm_unreachable(
"Encountered unknown FunctionType");
2418 FnType->getReturnType(), FnType->getParamTypes(),
2419 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2421 std::string OutName;
2422 llvm::raw_string_ostream Out(OutName);
2430 Out <<
".normalized";
2432 Out <<
".generalized";
2434 return llvm::ConstantInt::get(
Int32Ty,
2435 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2440 llvm::Function *F,
bool IsThunk) {
2442 llvm::AttributeList PAL;
2445 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2449 Loc = D->getLocation();
2451 Error(Loc,
"__vectorcall calling convention is not currently supported");
2453 F->setAttributes(PAL);
2454 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2458 std::string ReadOnlyQual(
"__read_only");
2459 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2460 if (ReadOnlyPos != std::string::npos)
2462 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2464 std::string WriteOnlyQual(
"__write_only");
2465 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2466 if (WriteOnlyPos != std::string::npos)
2467 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2469 std::string ReadWriteQual(
"__read_write");
2470 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2471 if (ReadWritePos != std::string::npos)
2472 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2505 assert(((FD && CGF) || (!FD && !CGF)) &&
2506 "Incorrect use - FD and CGF should either be both null or not!");
2532 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2535 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2540 std::string typeQuals;
2544 const Decl *PDecl = parm;
2546 PDecl = TD->getDecl();
2547 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2548 if (A && A->isWriteOnly())
2549 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2550 else if (A && A->isReadWrite())
2551 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2553 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2555 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2557 auto getTypeSpelling = [&](
QualType Ty) {
2558 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2560 if (Ty.isCanonical()) {
2561 StringRef typeNameRef = typeName;
2563 if (typeNameRef.consume_front(
"unsigned "))
2564 return std::string(
"u") + typeNameRef.str();
2565 if (typeNameRef.consume_front(
"signed "))
2566 return typeNameRef.str();
2576 addressQuals.push_back(
2577 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2581 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2582 std::string baseTypeName =
2584 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2585 argBaseTypeNames.push_back(
2586 llvm::MDString::get(VMContext, baseTypeName));
2590 typeQuals =
"restrict";
2593 typeQuals += typeQuals.empty() ?
"const" :
" const";
2595 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2597 uint32_t AddrSpc = 0;
2602 addressQuals.push_back(
2603 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2607 std::string typeName = getTypeSpelling(ty);
2619 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2620 argBaseTypeNames.push_back(
2621 llvm::MDString::get(VMContext, baseTypeName));
2626 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2630 Fn->setMetadata(
"kernel_arg_addr_space",
2631 llvm::MDNode::get(VMContext, addressQuals));
2632 Fn->setMetadata(
"kernel_arg_access_qual",
2633 llvm::MDNode::get(VMContext, accessQuals));
2634 Fn->setMetadata(
"kernel_arg_type",
2635 llvm::MDNode::get(VMContext, argTypeNames));
2636 Fn->setMetadata(
"kernel_arg_base_type",
2637 llvm::MDNode::get(VMContext, argBaseTypeNames));
2638 Fn->setMetadata(
"kernel_arg_type_qual",
2639 llvm::MDNode::get(VMContext, argTypeQuals));
2643 Fn->setMetadata(
"kernel_arg_name",
2644 llvm::MDNode::get(VMContext, argNames));
2654 if (!LangOpts.Exceptions)
return false;
2657 if (LangOpts.CXXExceptions)
return true;
2660 if (LangOpts.ObjCExceptions) {
2680SmallVector<const CXXRecordDecl *, 0>
2682 llvm::SetVector<const CXXRecordDecl *> MostBases;
2687 MostBases.insert(RD);
2689 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2691 CollectMostBases(RD);
2692 return MostBases.takeVector();
2696 llvm::Function *F) {
2697 llvm::AttrBuilder B(F->getContext());
2699 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2700 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2702 if (CodeGenOpts.StackClashProtector)
2703 B.addAttribute(
"probe-stack",
"inline-asm");
2705 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2706 B.addAttribute(
"stack-probe-size",
2707 std::to_string(CodeGenOpts.StackProbeSize));
2710 B.addAttribute(llvm::Attribute::NoUnwind);
2712 if (D && D->
hasAttr<NoStackProtectorAttr>())
2714 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
2716 B.addAttribute(llvm::Attribute::StackProtectStrong);
2718 B.addAttribute(llvm::Attribute::StackProtect);
2720 B.addAttribute(llvm::Attribute::StackProtectStrong);
2722 B.addAttribute(llvm::Attribute::StackProtectReq);
2726 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2727 B.addAttribute(llvm::Attribute::AlwaysInline);
2731 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2733 B.addAttribute(llvm::Attribute::NoInline);
2741 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2742 B.addAttribute(
"aarch64_pstate_sm_body");
2745 if (
Attr->isNewZA())
2746 B.addAttribute(
"aarch64_new_za");
2747 if (
Attr->isNewZT0())
2748 B.addAttribute(
"aarch64_new_zt0");
2753 bool ShouldAddOptNone =
2754 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2756 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2757 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2760 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2761 !D->
hasAttr<NoInlineAttr>()) {
2762 B.addAttribute(llvm::Attribute::AlwaysInline);
2763 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
2764 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2766 B.addAttribute(llvm::Attribute::OptimizeNone);
2769 B.addAttribute(llvm::Attribute::NoInline);
2774 B.addAttribute(llvm::Attribute::Naked);
2777 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2778 F->removeFnAttr(llvm::Attribute::MinSize);
2779 }
else if (D->
hasAttr<NakedAttr>()) {
2781 B.addAttribute(llvm::Attribute::Naked);
2782 B.addAttribute(llvm::Attribute::NoInline);
2783 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
2784 B.addAttribute(llvm::Attribute::NoDuplicate);
2785 }
else if (D->
hasAttr<NoInlineAttr>() &&
2786 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2788 B.addAttribute(llvm::Attribute::NoInline);
2789 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
2790 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2792 B.addAttribute(llvm::Attribute::AlwaysInline);
2796 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2797 B.addAttribute(llvm::Attribute::NoInline);
2801 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2804 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2805 return Redecl->isInlineSpecified();
2807 if (any_of(FD->
redecls(), CheckRedeclForInline))
2812 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2814 if (CheckForInline(FD)) {
2815 B.addAttribute(llvm::Attribute::InlineHint);
2816 }
else if (CodeGenOpts.getInlining() ==
2819 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2820 B.addAttribute(llvm::Attribute::NoInline);
2827 if (!D->
hasAttr<OptimizeNoneAttr>()) {
2829 if (!ShouldAddOptNone)
2830 B.addAttribute(llvm::Attribute::OptimizeForSize);
2831 B.addAttribute(llvm::Attribute::Cold);
2834 B.addAttribute(llvm::Attribute::Hot);
2835 if (D->
hasAttr<MinSizeAttr>())
2836 B.addAttribute(llvm::Attribute::MinSize);
2843 F->setAlignment(llvm::Align(alignment));
2845 if (!D->
hasAttr<AlignedAttr>())
2846 if (LangOpts.FunctionAlignment)
2847 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2855 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2860 if (CodeGenOpts.SanitizeCfiCrossDso &&
2861 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2862 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2870 if (CodeGenOpts.CallGraphSection) {
2871 if (
auto *FD = dyn_cast<FunctionDecl>(D))
2878 auto *MD = dyn_cast<CXXMethodDecl>(D);
2881 llvm::Metadata *Id =
2883 MD->getType(), std::nullopt,
Base));
2884 F->addTypeMetadata(0, Id);
2891 if (isa_and_nonnull<NamedDecl>(D))
2894 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2896 if (D && D->
hasAttr<UsedAttr>())
2899 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
2901 ((CodeGenOpts.KeepPersistentStorageVariables &&
2902 (VD->getStorageDuration() ==
SD_Static ||
2903 VD->getStorageDuration() ==
SD_Thread)) ||
2904 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2905 VD->getType().isConstQualified())))
2909bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2910 llvm::AttrBuilder &Attrs,
2911 bool SetTargetFeatures) {
2917 std::vector<std::string> Features;
2918 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2921 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2922 assert((!TD || !TV) &&
"both target_version and target specified");
2925 bool AddedAttr =
false;
2926 if (TD || TV || SD || TC) {
2927 llvm::StringMap<bool> FeatureMap;
2931 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2932 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2940 Target.parseTargetAttr(TD->getFeaturesStr());
2962 if (!TargetCPU.empty()) {
2963 Attrs.addAttribute(
"target-cpu", TargetCPU);
2966 if (!TuneCPU.empty()) {
2967 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2970 if (!Features.empty() && SetTargetFeatures) {
2971 llvm::erase_if(Features, [&](
const std::string& F) {
2974 llvm::sort(Features);
2975 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2980 llvm::SmallVector<StringRef, 8> Feats;
2981 bool IsDefault =
false;
2983 IsDefault = TV->isDefaultVersion();
2984 TV->getFeatures(Feats);
2990 Attrs.addAttribute(
"fmv-features");
2992 }
else if (!Feats.empty()) {
2994 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
2995 std::string FMVFeatures;
2996 for (StringRef F : OrderedFeats)
2997 FMVFeatures.append(
"," + F.str());
2998 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3005void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3006 llvm::GlobalObject *GO) {
3011 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3014 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3015 GV->addAttribute(
"bss-section", SA->getName());
3016 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3017 GV->addAttribute(
"data-section", SA->getName());
3018 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3019 GV->addAttribute(
"rodata-section", SA->getName());
3020 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3021 GV->addAttribute(
"relro-section", SA->getName());
3024 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3027 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3028 if (!D->
getAttr<SectionAttr>())
3029 F->setSection(SA->getName());
3031 llvm::AttrBuilder Attrs(F->getContext());
3032 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3036 llvm::AttributeMask RemoveAttrs;
3037 RemoveAttrs.addAttribute(
"target-cpu");
3038 RemoveAttrs.addAttribute(
"target-features");
3039 RemoveAttrs.addAttribute(
"fmv-features");
3040 RemoveAttrs.addAttribute(
"tune-cpu");
3041 F->removeFnAttrs(RemoveAttrs);
3042 F->addFnAttrs(Attrs);
3046 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3047 GO->setSection(CSA->getName());
3048 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3049 GO->setSection(SA->getName());
3062 F->setLinkage(llvm::Function::InternalLinkage);
3064 setNonAliasAttributes(GD, F);
3075 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3079 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3080 return MD && MD->hasGeneralizedMDString();
3084 llvm::Function *F) {
3091 if (!F->hasLocalLinkage() ||
3092 F->getFunction().hasAddressTaken(
nullptr,
true,
3099 llvm::Function *F) {
3101 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3112 F->addTypeMetadata(0, MD);
3121 if (CodeGenOpts.SanitizeCfiCrossDso)
3123 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3127 llvm::CallBase *CB) {
3129 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3133 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3134 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3137 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3138 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3142 llvm::LLVMContext &Ctx = F->getContext();
3143 llvm::MDBuilder MDB(Ctx);
3144 llvm::StringRef Salt;
3147 if (
const auto &Info = FP->getExtraAttributeInfo())
3148 Salt = Info.CFISalt;
3150 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3159 return llvm::all_of(Name, [](
const char &
C) {
3160 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3166 for (
auto &F : M.functions()) {
3168 bool AddressTaken = F.hasAddressTaken();
3169 if (!AddressTaken && F.hasLocalLinkage())
3170 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3175 if (!AddressTaken || !F.isDeclaration())
3178 const llvm::ConstantInt *
Type;
3179 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3180 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3184 StringRef Name = F.getName();
3188 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3189 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
3191 M.appendModuleInlineAsm(
Asm);
3195void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3196 bool IsIncompleteFunction,
3199 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3207 if (!IsIncompleteFunction)
3214 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3216 assert(!F->arg_empty() &&
3217 F->arg_begin()->getType()
3218 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3219 "unexpected this return");
3220 F->addParamAttr(0, llvm::Attribute::Returned);
3230 if (!IsIncompleteFunction && F->isDeclaration())
3233 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3234 F->setSection(CSA->getName());
3235 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3236 F->setSection(SA->getName());
3238 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3240 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3241 else if (EA->isWarning())
3242 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3247 const FunctionDecl *FDBody;
3248 bool HasBody = FD->
hasBody(FDBody);
3250 assert(HasBody &&
"Inline builtin declarations should always have an "
3252 if (shouldEmitFunction(FDBody))
3253 F->addFnAttr(llvm::Attribute::NoBuiltin);
3259 F->addFnAttr(llvm::Attribute::NoBuiltin);
3263 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3264 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3265 if (MD->isVirtual())
3266 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3272 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3273 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3276 if (CodeGenOpts.CallGraphSection)
3279 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3285 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3286 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3288 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3292 llvm::LLVMContext &Ctx = F->getContext();
3293 llvm::MDBuilder MDB(Ctx);
3297 int CalleeIdx = *CB->encoding_begin();
3298 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3299 F->addMetadata(llvm::LLVMContext::MD_callback,
3300 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3301 CalleeIdx, PayloadIndices,
3308 "Only globals with definition can force usage.");
3309 LLVMUsed.emplace_back(GV);
3313 assert(!GV->isDeclaration() &&
3314 "Only globals with definition can force usage.");
3315 LLVMCompilerUsed.emplace_back(GV);
3320 "Only globals with definition can force usage.");
3322 LLVMCompilerUsed.emplace_back(GV);
3324 LLVMUsed.emplace_back(GV);
3328 std::vector<llvm::WeakTrackingVH> &List) {
3335 UsedArray.resize(List.size());
3336 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3338 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3342 if (UsedArray.empty())
3344 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3346 auto *GV =
new llvm::GlobalVariable(
3347 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3348 llvm::ConstantArray::get(ATy, UsedArray), Name);
3350 GV->setSection(
"llvm.metadata");
3353void CodeGenModule::emitLLVMUsed() {
3354 emitUsed(*
this,
"llvm.used", LLVMUsed);
3355 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3360 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3369 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3375 ELFDependentLibraries.push_back(
3376 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3383 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3392 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3398 if (Visited.insert(Import).second)
3415 if (LL.IsFramework) {
3416 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3417 llvm::MDString::get(Context, LL.Library)};
3419 Metadata.push_back(llvm::MDNode::get(Context, Args));
3425 llvm::Metadata *Args[2] = {
3426 llvm::MDString::get(Context,
"lib"),
3427 llvm::MDString::get(Context, LL.Library),
3429 Metadata.push_back(llvm::MDNode::get(Context, Args));
3433 auto *OptString = llvm::MDString::get(Context, Opt);
3434 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3439void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3441 "We should only emit module initializers for named modules.");
3449 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3466 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3472void CodeGenModule::EmitModuleLinkOptions() {
3476 llvm::SetVector<clang::Module *> LinkModules;
3477 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3478 SmallVector<clang::Module *, 16> Stack;
3481 for (
Module *M : ImportedModules) {
3484 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3487 if (Visited.insert(M).second)
3493 while (!Stack.empty()) {
3496 bool AnyChildren =
false;
3505 if (Visited.insert(
SM).second) {
3506 Stack.push_back(
SM);
3514 LinkModules.insert(Mod);
3521 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3523 for (
Module *M : LinkModules)
3524 if (Visited.insert(M).second)
3526 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3527 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3530 if (!LinkerOptionsMetadata.empty()) {
3531 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3532 for (
auto *MD : LinkerOptionsMetadata)
3533 NMD->addOperand(MD);
3537void CodeGenModule::EmitDeferred() {
3546 if (!DeferredVTables.empty()) {
3547 EmitDeferredVTables();
3552 assert(DeferredVTables.empty());
3559 llvm::append_range(DeferredDeclsToEmit,
3563 if (DeferredDeclsToEmit.empty())
3568 std::vector<GlobalDecl> CurDeclsToEmit;
3569 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3571 for (GlobalDecl &D : CurDeclsToEmit) {
3577 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3581 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3597 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3615 if (!GV->isDeclaration())
3619 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3623 EmitGlobalDefinition(D, GV);
3628 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3630 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3635void CodeGenModule::EmitVTablesOpportunistically() {
3641 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3642 &&
"Only emit opportunistic vtables with optimizations");
3644 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
3646 "This queue should only contain external vtables");
3647 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3648 VTables.GenerateClassData(RD);
3650 OpportunisticVTables.clear();
3654 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3659 DeferredAnnotations.clear();
3661 if (Annotations.empty())
3665 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3666 Annotations[0]->
getType(), Annotations.size()), Annotations);
3667 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3668 llvm::GlobalValue::AppendingLinkage,
3669 Array,
"llvm.global.annotations");
3674 llvm::Constant *&AStr = AnnotationStrings[Str];
3679 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3680 auto *gv =
new llvm::GlobalVariable(
3681 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3682 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3685 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3702 SM.getExpansionLineNumber(L);
3703 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3711 llvm::FoldingSetNodeID ID;
3712 for (
Expr *E : Exprs) {
3715 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3720 LLVMArgs.reserve(Exprs.size());
3722 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
3724 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3727 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3728 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3729 llvm::GlobalValue::PrivateLinkage,
Struct,
3732 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3739 const AnnotateAttr *AA,
3747 llvm::Constant *GVInGlobalsAS = GV;
3748 if (GV->getAddressSpace() !=
3750 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3752 llvm::PointerType::get(
3753 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3757 llvm::Constant *Fields[] = {
3758 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3760 return llvm::ConstantStruct::getAnon(Fields);
3764 llvm::GlobalValue *GV) {
3765 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3775 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3778 auto &
SM = Context.getSourceManager();
3780 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3785 return NoSanitizeL.containsLocation(Kind, Loc);
3788 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3792 llvm::GlobalVariable *GV,
3794 StringRef Category)
const {
3796 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3798 auto &
SM = Context.getSourceManager();
3799 if (NoSanitizeL.containsMainFile(
3800 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3803 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3810 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3811 Ty = AT->getElementType();
3816 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3824 StringRef Category)
const {
3827 auto Attr = ImbueAttr::NONE;
3829 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3830 if (
Attr == ImbueAttr::NONE)
3831 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3833 case ImbueAttr::NONE:
3835 case ImbueAttr::ALWAYS:
3836 Fn->addFnAttr(
"function-instrument",
"xray-always");
3838 case ImbueAttr::ALWAYS_ARG1:
3839 Fn->addFnAttr(
"function-instrument",
"xray-always");
3840 Fn->addFnAttr(
"xray-log-args",
"1");
3842 case ImbueAttr::NEVER:
3843 Fn->addFnAttr(
"function-instrument",
"xray-never");
3856 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
3866 auto &
SM = Context.getSourceManager();
3867 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3881 if (NumGroups > 1) {
3882 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3891 if (LangOpts.EmitAllDecls)
3894 const auto *VD = dyn_cast<VarDecl>(
Global);
3896 ((CodeGenOpts.KeepPersistentStorageVariables &&
3897 (VD->getStorageDuration() ==
SD_Static ||
3898 VD->getStorageDuration() ==
SD_Thread)) ||
3899 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3900 VD->getType().isConstQualified())))
3913 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3914 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3915 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3916 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3920 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3930 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
3933 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3934 if (Context.getInlineVariableDefinitionKind(VD) ==
3939 if (CXX20ModuleInits && VD->getOwningModule() &&
3940 !VD->getOwningModule()->isModuleMapModule()) {
3949 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3952 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3965 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3969 llvm::Constant *
Init;
3972 if (!
V.isAbsent()) {
3983 llvm::Constant *Fields[4] = {
3987 llvm::ConstantDataArray::getRaw(
3988 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3990 Init = llvm::ConstantStruct::getAnon(Fields);
3993 auto *GV =
new llvm::GlobalVariable(
3995 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3997 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4000 if (!
V.isAbsent()) {
4013 llvm::GlobalVariable **Entry =
nullptr;
4014 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4019 llvm::Constant *
Init;
4023 assert(!
V.isAbsent());
4027 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4029 llvm::GlobalValue::PrivateLinkage,
Init,
4031 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4045 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4049 llvm::Constant *
Init =
Emitter.emitForInitializer(
4057 llvm::GlobalValue::LinkageTypes
Linkage =
4059 ? llvm::GlobalValue::LinkOnceODRLinkage
4060 : llvm::GlobalValue::InternalLinkage;
4061 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4065 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4072 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4073 assert(AA &&
"No alias?");
4083 llvm::Constant *Aliasee;
4085 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4093 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4094 WeakRefReferences.insert(F);
4102 if (
auto *A = D->
getAttr<AttrT>())
4103 return A->isImplicit();
4107bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4108 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4113 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4114 Global->hasAttr<CUDAConstantAttr>() ||
4115 Global->hasAttr<CUDASharedAttr>() ||
4116 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4117 Global->getType()->isCUDADeviceBuiltinTextureType();
4124 if (
Global->hasAttr<WeakRefAttr>())
4129 if (
Global->hasAttr<AliasAttr>())
4130 return EmitAliasDefinition(GD);
4133 if (
Global->hasAttr<IFuncAttr>())
4134 return emitIFuncDefinition(GD);
4137 if (
Global->hasAttr<CPUDispatchAttr>())
4138 return emitCPUDispatchDefinition(GD);
4143 if (LangOpts.CUDA) {
4145 "Expected Variable or Function");
4146 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4147 if (!shouldEmitCUDAGlobalVar(VD))
4149 }
else if (LangOpts.CUDAIsDevice) {
4150 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4151 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4152 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4156 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4157 !
Global->hasAttr<CUDAGlobalAttr>() &&
4159 !
Global->hasAttr<CUDAHostAttr>()))
4162 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4163 Global->hasAttr<CUDADeviceAttr>())
4167 if (LangOpts.OpenMP) {
4169 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4171 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4172 if (MustBeEmitted(
Global))
4176 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4177 if (MustBeEmitted(
Global))
4184 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4185 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4191 if (FD->
hasAttr<AnnotateAttr>()) {
4194 DeferredAnnotations[MangledName] = FD;
4209 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4215 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4217 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4218 if (LangOpts.OpenMP) {
4220 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4221 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4225 if (VD->hasExternalStorage() &&
4226 Res != OMPDeclareTargetDeclAttr::MT_Link)
4229 bool UnifiedMemoryEnabled =
4231 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4232 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4233 !UnifiedMemoryEnabled) {
4236 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4237 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4238 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4239 UnifiedMemoryEnabled)) &&
4240 "Link clause or to clause with unified memory expected.");
4249 if (Context.getInlineVariableDefinitionKind(VD) ==
4259 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4261 EmitGlobalDefinition(GD);
4262 addEmittedDeferredDecl(GD);
4270 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4271 CXXGlobalInits.push_back(
nullptr);
4277 addDeferredDeclToEmit(GD);
4278 }
else if (MustBeEmitted(
Global)) {
4280 assert(!MayBeEmittedEagerly(
Global));
4281 addDeferredDeclToEmit(GD);
4286 DeferredDecls[MangledName] = GD;
4292 if (
const auto *RT =
4293 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4294 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4295 RD = RD->getDefinitionOrSelf();
4296 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4304 struct FunctionIsDirectlyRecursive
4305 :
public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4306 const StringRef Name;
4307 const Builtin::Context &BI;
4308 FunctionIsDirectlyRecursive(StringRef N,
const Builtin::Context &
C)
4311 bool VisitCallExpr(
const CallExpr *E) {
4315 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4316 if (Attr && Name == Attr->getLabel())
4321 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4322 StringRef BuiltinName = BuiltinNameStr;
4323 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4326 bool VisitStmt(
const Stmt *S) {
4327 for (
const Stmt *Child : S->
children())
4328 if (Child && this->Visit(Child))
4335 struct DLLImportFunctionVisitor
4336 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4337 bool SafeToInline =
true;
4339 bool shouldVisitImplicitCode()
const {
return true; }
4341 bool VisitVarDecl(VarDecl *VD) {
4344 SafeToInline =
false;
4345 return SafeToInline;
4352 return SafeToInline;
4355 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4357 SafeToInline = D->
hasAttr<DLLImportAttr>();
4358 return SafeToInline;
4361 bool VisitDeclRefExpr(DeclRefExpr *E) {
4364 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4365 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4366 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4367 return SafeToInline;
4370 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4372 return SafeToInline;
4375 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4379 SafeToInline =
true;
4381 SafeToInline = M->
hasAttr<DLLImportAttr>();
4383 return SafeToInline;
4386 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4388 return SafeToInline;
4391 bool VisitCXXNewExpr(CXXNewExpr *E) {
4393 return SafeToInline;
4402CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4404 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4406 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4409 Name = Attr->getLabel();
4414 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4415 const Stmt *Body = FD->
getBody();
4416 return Body ? Walker.Visit(Body) :
false;
4419bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4426 if (F->isInlineBuiltinDeclaration())
4429 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4434 if (
const Module *M = F->getOwningModule();
4435 M && M->getTopLevelModule()->isNamedModule() &&
4436 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4446 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4451 if (F->hasAttr<NoInlineAttr>())
4454 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4456 DLLImportFunctionVisitor Visitor;
4457 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4458 if (!Visitor.SafeToInline)
4461 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4464 for (
const Decl *
Member : Dtor->getParent()->decls())
4468 for (
const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4479 return !isTriviallyRecursive(F);
4482bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4483 return CodeGenOpts.OptimizationLevel > 0;
4486void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4487 llvm::GlobalValue *GV) {
4491 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4492 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4494 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4495 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4496 if (TC->isFirstOfVersion(I))
4499 EmitGlobalFunctionDefinition(GD, GV);
4505 AddDeferredMultiVersionResolverToEmit(GD);
4507 GetOrCreateMultiVersionResolver(GD);
4511void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4514 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4515 Context.getSourceManager(),
4516 "Generating code for declaration");
4518 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4521 if (!shouldEmitFunction(GD))
4524 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4526 llvm::raw_string_ostream
OS(Name);
4532 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4536 ABI->emitCXXStructor(GD);
4538 EmitMultiVersionFunctionDefinition(GD, GV);
4540 EmitGlobalFunctionDefinition(GD, GV);
4549 return EmitMultiVersionFunctionDefinition(GD, GV);
4550 return EmitGlobalFunctionDefinition(GD, GV);
4553 if (
const auto *VD = dyn_cast<VarDecl>(D))
4554 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4556 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4560 llvm::Function *NewFn);
4576static llvm::GlobalValue::LinkageTypes
4580 return llvm::GlobalValue::InternalLinkage;
4581 return llvm::GlobalValue::WeakODRLinkage;
4584void CodeGenModule::emitMultiVersionFunctions() {
4585 std::vector<GlobalDecl> MVFuncsToEmit;
4586 MultiVersionFuncs.swap(MVFuncsToEmit);
4587 for (GlobalDecl GD : MVFuncsToEmit) {
4589 assert(FD &&
"Expected a FunctionDecl");
4591 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4592 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4596 if (
Decl->isDefined()) {
4597 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4605 assert(
Func &&
"This should have just been created");
4614 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4617 FD, [&](
const FunctionDecl *CurFD) {
4618 llvm::SmallVector<StringRef, 8> Feats;
4621 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4623 TA->getX86AddedFeatures(Feats);
4624 llvm::Function *
Func = createFunction(CurFD);
4625 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
4626 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4627 if (TVA->isDefaultVersion() && IsDefined)
4628 ShouldEmitResolver =
true;
4629 llvm::Function *
Func = createFunction(CurFD);
4631 TVA->getFeatures(Feats, Delim);
4632 Options.emplace_back(
Func, Feats);
4633 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4634 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4635 if (!TC->isFirstOfVersion(I))
4637 if (TC->isDefaultVersion(I) && IsDefined)
4638 ShouldEmitResolver =
true;
4639 llvm::Function *
Func = createFunction(CurFD, I);
4642 TC->getX86Feature(Feats, I);
4643 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
4646 TC->getFeatures(Feats, I, Delim);
4647 Options.emplace_back(
Func, Feats);
4651 llvm_unreachable(
"unexpected MultiVersionKind");
4654 if (!ShouldEmitResolver)
4657 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4658 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4659 ResolverConstant = IFunc->getResolver();
4663 *
this, GD, FD,
true);
4670 auto *Alias = llvm::GlobalAlias::create(
4672 MangledName +
".ifunc", IFunc, &
getModule());
4681 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4682 const CodeGenFunction::FMVResolverOption &RHS) {
4685 CodeGenFunction CGF(*
this);
4686 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4688 setMultiVersionResolverAttributes(ResolverFunc, GD);
4690 ResolverFunc->setComdat(
4691 getModule().getOrInsertComdat(ResolverFunc->getName()));
4697 if (!MVFuncsToEmit.empty())
4702 if (!MultiVersionFuncs.empty())
4703 emitMultiVersionFunctions();
4707 llvm::Constant *
New) {
4710 Old->replaceAllUsesWith(
New);
4711 Old->eraseFromParent();
4714void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4716 assert(FD &&
"Not a FunctionDecl?");
4718 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4719 assert(DD &&
"Not a cpu_dispatch Function?");
4725 UpdateMultiVersionNames(GD, FD, ResolverName);
4727 llvm::Type *ResolverType;
4728 GlobalDecl ResolverGD;
4730 ResolverType = llvm::FunctionType::get(
4741 ResolverName, ResolverType, ResolverGD,
false));
4744 ResolverFunc->setComdat(
4745 getModule().getOrInsertComdat(ResolverFunc->getName()));
4747 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4750 for (
const IdentifierInfo *II : DD->cpus()) {
4758 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4761 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4767 Func = GetOrCreateLLVMFunction(
4768 MangledName, DeclTy, ExistingDecl,
4774 llvm::SmallVector<StringRef, 32> Features;
4775 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4776 llvm::transform(Features, Features.begin(),
4777 [](StringRef Str) { return Str.substr(1); });
4778 llvm::erase_if(Features, [&Target](StringRef Feat) {
4779 return !Target.validateCpuSupports(Feat);
4785 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
4786 const CodeGenFunction::FMVResolverOption &RHS) {
4787 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
4788 llvm::X86::getCpuSupportsMask(RHS.
Features);
4795 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4796 (Options.end() - 2)->Features),
4797 [](
auto X) { return X == 0; })) {
4798 StringRef LHSName = (Options.end() - 2)->Function->getName();
4799 StringRef RHSName = (Options.end() - 1)->Function->getName();
4800 if (LHSName.compare(RHSName) < 0)
4801 Options.erase(Options.end() - 2);
4803 Options.erase(Options.end() - 1);
4806 CodeGenFunction CGF(*
this);
4807 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4808 setMultiVersionResolverAttributes(ResolverFunc, GD);
4813 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4818 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4825 *
this, GD, FD,
true);
4828 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4836void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4838 assert(FD &&
"Not a FunctionDecl?");
4841 std::string MangledName =
4843 if (!DeferredResolversToEmit.insert(MangledName).second)
4846 MultiVersionFuncs.push_back(GD);
4852llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4854 assert(FD &&
"Not a FunctionDecl?");
4856 std::string MangledName =
4861 std::string ResolverName = MangledName;
4865 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4869 ResolverName +=
".ifunc";
4876 ResolverName +=
".resolver";
4879 bool ShouldReturnIFunc =
4898 AddDeferredMultiVersionResolverToEmit(GD);
4902 if (ShouldReturnIFunc) {
4904 llvm::Type *ResolverType = llvm::FunctionType::get(
4906 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4907 MangledName +
".resolver", ResolverType, GlobalDecl{},
4909 llvm::GlobalIFunc *GIF =
4912 GIF->setName(ResolverName);
4919 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4920 ResolverName, DeclTy, GlobalDecl{},
false);
4922 "Resolver should be created for the first time");
4927void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
4929 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
4947bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
4948 const llvm::GlobalValue *GV)
const {
4949 auto SC = GV->getDLLStorageClass();
4950 if (SC == llvm::GlobalValue::DefaultStorageClass)
4953 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4954 !MRD->
hasAttr<DLLImportAttr>()) ||
4955 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4956 !MRD->
hasAttr<DLLExportAttr>())) &&
4967llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4968 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
4969 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4973 std::string NameWithoutMultiVersionMangling;
4974 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4976 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4977 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4978 !DontDefer && !IsForDefinition) {
4981 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4983 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4986 GDDef = GlobalDecl(FDDef);
4994 UpdateMultiVersionNames(GD, FD, MangledName);
4995 if (!IsForDefinition) {
5001 AddDeferredMultiVersionResolverToEmit(GD);
5003 *
this, GD, FD,
true);
5005 return GetOrCreateMultiVersionResolver(GD);
5010 if (!NameWithoutMultiVersionMangling.empty())
5011 MangledName = NameWithoutMultiVersionMangling;
5016 if (WeakRefReferences.erase(Entry)) {
5017 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5018 if (FD && !FD->
hasAttr<WeakAttr>())
5019 Entry->setLinkage(llvm::Function::ExternalLinkage);
5023 if (D && shouldDropDLLAttribute(D, Entry)) {
5024 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5030 if (IsForDefinition && !Entry->isDeclaration()) {
5037 DiagnosedConflictingDefinitions.insert(GD).second) {
5041 diag::note_previous_definition);
5046 (Entry->getValueType() == Ty)) {
5053 if (!IsForDefinition)
5060 bool IsIncompleteFunction =
false;
5062 llvm::FunctionType *FTy;
5066 FTy = llvm::FunctionType::get(
VoidTy,
false);
5067 IsIncompleteFunction =
true;
5071 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5072 Entry ? StringRef() : MangledName, &
getModule());
5076 if (D && D->
hasAttr<AnnotateAttr>())
5094 if (!Entry->use_empty()) {
5096 Entry->removeDeadConstantUsers();
5102 assert(F->getName() == MangledName &&
"name was uniqued!");
5104 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5105 if (ExtraAttrs.hasFnAttrs()) {
5106 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5114 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5117 addDeferredDeclToEmit(GD);
5122 auto DDI = DeferredDecls.find(MangledName);
5123 if (DDI != DeferredDecls.end()) {
5127 addDeferredDeclToEmit(DDI->second);
5128 DeferredDecls.erase(DDI);
5156 if (!IsIncompleteFunction) {
5157 assert(F->getFunctionType() == Ty);
5175 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5185 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5188 DD->getParent()->getNumVBases() == 0)
5193 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5194 false, llvm::AttributeList(),
5197 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5201 if (IsForDefinition)
5209 llvm::GlobalValue *F =
5212 return llvm::NoCFIValue::get(F);
5221 for (
const auto *Result : DC->
lookup(&CII))
5222 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5225 if (!
C.getLangOpts().CPlusPlus)
5230 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5231 ?
C.Idents.get(
"terminate")
5232 :
C.Idents.get(Name);
5234 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5236 for (
const auto *Result : DC->
lookup(&NS)) {
5238 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
5239 for (
const auto *Result : LSD->lookup(&NS))
5240 if ((ND = dyn_cast<NamespaceDecl>(Result)))
5244 for (
const auto *Result : ND->
lookup(&CXXII))
5245 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5254 llvm::Function *F, StringRef Name) {
5260 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5263 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5264 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5265 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5272 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5273 if (AssumeConvergent) {
5275 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5278 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5283 llvm::Constant *
C = GetOrCreateLLVMFunction(
5285 false,
false, ExtraAttrs);
5287 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5303 llvm::AttributeList ExtraAttrs,
bool Local,
5304 bool AssumeConvergent) {
5305 if (AssumeConvergent) {
5307 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5311 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5315 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5324 markRegisterParameterAttributes(F);
5350 if (WeakRefReferences.erase(Entry)) {
5351 if (D && !D->
hasAttr<WeakAttr>())
5352 Entry->setLinkage(llvm::Function::ExternalLinkage);
5356 if (D && shouldDropDLLAttribute(D, Entry))
5357 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5359 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5362 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5367 if (IsForDefinition && !Entry->isDeclaration()) {
5375 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5377 DiagnosedConflictingDefinitions.insert(D).second) {
5381 diag::note_previous_definition);
5386 if (Entry->getType()->getAddressSpace() != TargetAS)
5387 return llvm::ConstantExpr::getAddrSpaceCast(
5388 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5392 if (!IsForDefinition)
5398 auto *GV =
new llvm::GlobalVariable(
5399 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5400 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5401 getContext().getTargetAddressSpace(DAddrSpace));
5406 GV->takeName(Entry);
5408 if (!Entry->use_empty()) {
5409 Entry->replaceAllUsesWith(GV);
5412 Entry->eraseFromParent();
5418 auto DDI = DeferredDecls.find(MangledName);
5419 if (DDI != DeferredDecls.end()) {
5422 addDeferredDeclToEmit(DDI->second);
5423 DeferredDecls.erase(DDI);
5428 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5435 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5441 CXXThreadLocals.push_back(D);
5449 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5450 EmitGlobalVarDefinition(D);
5455 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5456 GV->setSection(SA->getName());
5460 if (
getTriple().getArch() == llvm::Triple::xcore &&
5464 GV->setSection(
".cp.rodata");
5467 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5468 GV->setCodeModel(CMA->getModel());
5473 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5477 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5478 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5479 if (!HasMutableFields) {
5486 auto *InitType =
Init->getType();
5487 if (GV->getValueType() != InitType) {
5492 GV->setName(StringRef());
5497 ->stripPointerCasts());
5500 GV->eraseFromParent();
5503 GV->setInitializer(
Init);
5504 GV->setConstant(
true);
5505 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5525 SanitizerMD->reportGlobal(GV, *D);
5530 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5531 if (DAddrSpace != ExpectedAS) {
5533 *
this, GV, DAddrSpace,
5546 false, IsForDefinition);
5567 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5568 llvm::Align Alignment) {
5569 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5570 llvm::GlobalVariable *OldGV =
nullptr;
5574 if (GV->getValueType() == Ty)
5579 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5584 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5589 GV->takeName(OldGV);
5591 if (!OldGV->use_empty()) {
5592 OldGV->replaceAllUsesWith(GV);
5595 OldGV->eraseFromParent();
5599 !GV->hasAvailableExternallyLinkage())
5600 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5602 GV->setAlignment(Alignment);
5639 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
5647 if (GV && !GV->isDeclaration())
5652 if (!MustBeEmitted(D) && !GV) {
5653 DeferredDecls[MangledName] = D;
5658 EmitGlobalVarDefinition(D);
5663 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
5665 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
5680 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
5683 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5685 if (!Fn->getSubprogram())
5691 return Context.toCharUnitsFromBits(
5696 if (LangOpts.OpenCL) {
5707 if (LangOpts.SYCLIsDevice &&
5711 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5713 if (D->
hasAttr<CUDAConstantAttr>())
5715 if (D->
hasAttr<CUDASharedAttr>())
5717 if (D->
hasAttr<CUDADeviceAttr>())
5725 if (LangOpts.OpenMP) {
5727 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5735 if (LangOpts.OpenCL)
5737 if (LangOpts.SYCLIsDevice)
5739 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5747 if (
auto AS =
getTarget().getConstantAddressSpace())
5760static llvm::Constant *
5762 llvm::GlobalVariable *GV) {
5763 llvm::Constant *Cast = GV;
5769 llvm::PointerType::get(
5776template<
typename SomeDecl>
5778 llvm::GlobalValue *GV) {
5793 const SomeDecl *
First = D->getFirstDecl();
5794 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5800 std::pair<StaticExternCMap::iterator, bool> R =
5801 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5806 R.first->second =
nullptr;
5813 if (D.
hasAttr<SelectAnyAttr>())
5817 if (
auto *VD = dyn_cast<VarDecl>(&D))
5831 llvm_unreachable(
"No such linkage");
5839 llvm::GlobalObject &GO) {
5842 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5850void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
5865 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5866 OpenMPRuntime->emitTargetGlobalVariable(D))
5869 llvm::TrackingVH<llvm::Constant>
Init;
5870 bool NeedsGlobalCtor =
false;
5874 bool IsDefinitionAvailableExternally =
5876 bool NeedsGlobalDtor =
5877 !IsDefinitionAvailableExternally &&
5884 if (IsDefinitionAvailableExternally &&
5895 std::optional<ConstantEmitter> emitter;
5900 bool IsCUDASharedVar =
5905 bool IsCUDAShadowVar =
5907 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
5908 D->
hasAttr<CUDASharedAttr>());
5909 bool IsCUDADeviceShadowVar =
5914 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
5915 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5919 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
5921 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
5922 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5923 }
else if (!InitExpr) {
5936 initializedGlobalDecl = GlobalDecl(D);
5937 emitter.emplace(*
this);
5938 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5946 if (!IsDefinitionAvailableExternally)
5947 NeedsGlobalCtor =
true;
5951 NeedsGlobalCtor =
false;
5963 DelayedCXXInitPosition.erase(D);
5970 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5975 llvm::Type* InitType =
Init->getType();
5976 llvm::Constant *Entry =
5980 Entry = Entry->stripPointerCasts();
5983 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5994 if (!GV || GV->getValueType() != InitType ||
5995 GV->getType()->getAddressSpace() !=
5999 Entry->setName(StringRef());
6004 ->stripPointerCasts());
6007 llvm::Constant *NewPtrForOldDecl =
6008 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6010 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6018 if (D->
hasAttr<AnnotateAttr>())
6031 if (LangOpts.CUDA) {
6032 if (LangOpts.CUDAIsDevice) {
6033 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
6034 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6037 GV->setExternallyInitialized(
true);
6047 GV->setExternallyInitialized(
true);
6049 GV->setInitializer(
Init);
6056 emitter->finalize(GV);
6059 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6060 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6064 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6065 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6067 GV->setConstant(
true);
6072 if (std::optional<CharUnits> AlignValFromAllocate =
6074 AlignVal = *AlignValFromAllocate;
6092 Linkage == llvm::GlobalValue::ExternalLinkage &&
6093 Context.getTargetInfo().getTriple().isOSDarwin() &&
6095 Linkage = llvm::GlobalValue::InternalLinkage;
6101 Linkage = llvm::GlobalValue::ExternalLinkage;
6104 if (D->
hasAttr<DLLImportAttr>())
6105 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6106 else if (D->
hasAttr<DLLExportAttr>())
6107 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6109 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6111 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6113 GV->setConstant(
false);
6118 if (!GV->getInitializer()->isNullValue())
6119 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6122 setNonAliasAttributes(D, GV);
6124 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6126 CXXThreadLocals.push_back(D);
6133 if (NeedsGlobalCtor || NeedsGlobalDtor)
6134 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6136 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6141 DI->EmitGlobalVariable(GV, D);
6149 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6160 if (D->
hasAttr<SectionAttr>())
6166 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6167 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6168 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6169 D->
hasAttr<PragmaClangRodataSectionAttr>())
6177 if (D->
hasAttr<WeakImportAttr>())
6186 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6187 if (D->
hasAttr<AlignedAttr>())
6190 if (Context.isAlignmentRequired(VarType))
6194 for (
const FieldDecl *FD : RD->fields()) {
6195 if (FD->isBitField())
6197 if (FD->
hasAttr<AlignedAttr>())
6199 if (Context.isAlignmentRequired(FD->
getType()))
6211 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6212 Context.getTypeAlignIfKnown(D->
getType()) >
6219llvm::GlobalValue::LinkageTypes
6223 return llvm::Function::InternalLinkage;
6226 return llvm::GlobalVariable::WeakAnyLinkage;
6230 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6235 return llvm::GlobalValue::AvailableExternallyLinkage;
6249 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6250 : llvm::Function::InternalLinkage;
6264 return llvm::Function::ExternalLinkage;
6267 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6268 : llvm::Function::InternalLinkage;
6269 return llvm::Function::WeakODRLinkage;
6276 CodeGenOpts.NoCommon))
6277 return llvm::GlobalVariable::CommonLinkage;
6283 if (D->
hasAttr<SelectAnyAttr>())
6284 return llvm::GlobalVariable::WeakODRLinkage;
6288 return llvm::GlobalVariable::ExternalLinkage;
6291llvm::GlobalValue::LinkageTypes
6300 llvm::Function *newFn) {
6302 if (old->use_empty())
6305 llvm::Type *newRetTy = newFn->getReturnType();
6310 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6312 llvm::User *user = ui->getUser();
6316 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6317 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6323 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6326 if (!callSite->isCallee(&*ui))
6331 if (callSite->getType() != newRetTy && !callSite->use_empty())
6336 llvm::AttributeList oldAttrs = callSite->getAttributes();
6339 unsigned newNumArgs = newFn->arg_size();
6340 if (callSite->arg_size() < newNumArgs)
6346 bool dontTransform =
false;
6347 for (llvm::Argument &A : newFn->args()) {
6348 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6349 dontTransform =
true;
6354 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6362 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6366 callSite->getOperandBundlesAsDefs(newBundles);
6368 llvm::CallBase *newCall;
6370 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6371 callSite->getIterator());
6374 newCall = llvm::InvokeInst::Create(
6375 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6376 newArgs, newBundles,
"", callSite->getIterator());
6380 if (!newCall->getType()->isVoidTy())
6381 newCall->takeName(callSite);
6382 newCall->setAttributes(
6383 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6384 oldAttrs.getRetAttrs(), newArgAttrs));
6385 newCall->setCallingConv(callSite->getCallingConv());
6388 if (!callSite->use_empty())
6389 callSite->replaceAllUsesWith(newCall);
6392 if (callSite->getDebugLoc())
6393 newCall->setDebugLoc(callSite->getDebugLoc());
6395 callSitesToBeRemovedFromParent.push_back(callSite);
6398 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6399 callSite->eraseFromParent();
6413 llvm::Function *NewFn) {
6423 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6435void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6436 llvm::GlobalValue *GV) {
6444 if (!GV || (GV->getValueType() != Ty))
6450 if (!GV->isDeclaration())
6469 setNonAliasAttributes(GD, Fn);
6471 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6472 (CodeGenOpts.OptimizationLevel == 0) &&
6475 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6477 !D->
hasAttr<NoInlineAttr>() &&
6478 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6479 !D->
hasAttr<OptimizeNoneAttr>() &&
6480 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6481 !ShouldAddOptNone) {
6482 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6488 auto GetPriority = [
this](
const auto *
Attr) ->
int {
6493 return Attr->DefaultPriority;
6496 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6498 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
6504void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6506 const AliasAttr *AA = D->
getAttr<AliasAttr>();
6507 assert(AA &&
"Not an alias?");
6511 if (AA->getAliasee() == MangledName) {
6512 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6519 if (Entry && !Entry->isDeclaration())
6522 Aliases.push_back(GD);
6528 llvm::Constant *Aliasee;
6529 llvm::GlobalValue::LinkageTypes
LT;
6531 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6537 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6544 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6546 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
6549 if (GA->getAliasee() == Entry) {
6550 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6554 assert(Entry->isDeclaration());
6563 GA->takeName(Entry);
6565 Entry->replaceAllUsesWith(GA);
6566 Entry->eraseFromParent();
6568 GA->setName(MangledName);
6576 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6579 if (
const auto *VD = dyn_cast<VarDecl>(D))
6580 if (VD->getTLSKind())
6591void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6593 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
6594 assert(IFA &&
"Not an ifunc?");
6598 if (IFA->getResolver() == MangledName) {
6599 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6605 if (Entry && !Entry->isDeclaration()) {
6608 DiagnosedConflictingDefinitions.insert(GD).second) {
6609 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
6612 diag::note_previous_definition);
6617 Aliases.push_back(GD);
6623 llvm::Constant *Resolver =
6624 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6628 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6629 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6631 if (GIF->getResolver() == Entry) {
6632 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6635 assert(Entry->isDeclaration());
6644 GIF->takeName(Entry);
6646 Entry->replaceAllUsesWith(GIF);
6647 Entry->eraseFromParent();
6649 GIF->setName(MangledName);
6655 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6656 (llvm::Intrinsic::ID)IID, Tys);
6659static llvm::StringMapEntry<llvm::GlobalVariable *> &
6662 bool &IsUTF16,
unsigned &StringLength) {
6663 StringRef String = Literal->getString();
6664 unsigned NumBytes = String.size();
6667 if (!Literal->containsNonAsciiOrNull()) {
6668 StringLength = NumBytes;
6669 return *Map.insert(std::make_pair(String,
nullptr)).first;
6676 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6677 llvm::UTF16 *ToPtr = &ToBuf[0];
6679 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6680 ToPtr + NumBytes, llvm::strictConversion);
6683 StringLength = ToPtr - &ToBuf[0];
6687 return *Map.insert(std::make_pair(
6688 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6689 (StringLength + 1) * 2),
6695 unsigned StringLength = 0;
6696 bool isUTF16 =
false;
6697 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6702 if (
auto *
C = Entry.second)
6707 const llvm::Triple &Triple =
getTriple();
6710 const bool IsSwiftABI =
6711 static_cast<unsigned>(CFRuntime) >=
6716 if (!CFConstantStringClassRef) {
6717 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6719 Ty = llvm::ArrayType::get(Ty, 0);
6721 switch (CFRuntime) {
6725 CFConstantStringClassName =
6726 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6727 :
"$s10Foundation19_NSCFConstantStringCN";
6731 CFConstantStringClassName =
6732 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6733 :
"$S10Foundation19_NSCFConstantStringCN";
6737 CFConstantStringClassName =
6738 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6739 :
"__T010Foundation19_NSCFConstantStringCN";
6746 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6747 llvm::GlobalValue *GV =
nullptr;
6749 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6756 if ((VD = dyn_cast<VarDecl>(
Result)))
6759 if (Triple.isOSBinFormatELF()) {
6761 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6763 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6764 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6765 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6767 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6775 CFConstantStringClassRef =
6776 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6779 QualType CFTy = Context.getCFConstantStringType();
6784 auto Fields = Builder.beginStruct(STy);
6793 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6794 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6796 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6800 llvm::Constant *
C =
nullptr;
6803 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6804 Entry.first().size() / 2);
6805 C = llvm::ConstantDataArray::get(VMContext, Arr);
6807 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6813 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6814 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6815 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6818 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6819 : Context.getTypeAlignInChars(Context.CharTy);
6825 if (Triple.isOSBinFormatMachO())
6826 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6827 :
"__TEXT,__cstring,cstring_literals");
6830 else if (Triple.isOSBinFormatELF())
6831 GV->setSection(
".rodata");
6837 llvm::IntegerType *LengthTy =
6847 Fields.addInt(LengthTy, StringLength);
6855 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6857 llvm::GlobalVariable::PrivateLinkage);
6858 GV->addAttribute(
"objc_arc_inert");
6859 switch (Triple.getObjectFormat()) {
6860 case llvm::Triple::UnknownObjectFormat:
6861 llvm_unreachable(
"unknown file format");
6862 case llvm::Triple::DXContainer:
6863 case llvm::Triple::GOFF:
6864 case llvm::Triple::SPIRV:
6865 case llvm::Triple::XCOFF:
6866 llvm_unreachable(
"unimplemented");
6867 case llvm::Triple::COFF:
6868 case llvm::Triple::ELF:
6869 case llvm::Triple::Wasm:
6870 GV->setSection(
"cfstring");
6872 case llvm::Triple::MachO:
6873 GV->setSection(
"__DATA,__cfstring");
6882 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6886 if (ObjCFastEnumerationStateType.isNull()) {
6887 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
6891 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
6892 Context.getPointerType(Context.UnsignedLongTy),
6893 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6896 for (
size_t i = 0; i < 4; ++i) {
6901 FieldTypes[i],
nullptr,
6910 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
6913 return ObjCFastEnumerationStateType;
6927 assert(CAT &&
"String literal not of constant array type!");
6929 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6933 llvm::Type *ElemTy = AType->getElementType();
6934 unsigned NumElements = AType->getNumElements();
6937 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6939 Elements.reserve(NumElements);
6941 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
6943 Elements.resize(NumElements);
6944 return llvm::ConstantDataArray::get(VMContext, Elements);
6947 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6949 Elements.reserve(NumElements);
6951 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
6953 Elements.resize(NumElements);
6954 return llvm::ConstantDataArray::get(VMContext, Elements);
6957static llvm::GlobalVariable *
6966 auto *GV =
new llvm::GlobalVariable(
6967 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
6968 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6970 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6971 if (GV->isWeakForLinker()) {
6972 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6973 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6989 llvm::GlobalVariable **Entry =
nullptr;
6990 if (!LangOpts.WritableStrings) {
6991 Entry = &ConstantStringMap[
C];
6992 if (
auto GV = *Entry) {
6993 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6996 GV->getValueType(), Alignment);
7001 StringRef GlobalVariableName;
7002 llvm::GlobalValue::LinkageTypes LT;
7007 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7008 !LangOpts.WritableStrings) {
7009 llvm::raw_svector_ostream Out(MangledNameBuffer);
7011 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7012 GlobalVariableName = MangledNameBuffer;
7014 LT = llvm::GlobalValue::PrivateLinkage;
7015 GlobalVariableName = Name;
7027 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7030 GV->getValueType(), Alignment);
7047 StringRef GlobalName) {
7048 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7053 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7056 llvm::GlobalVariable **Entry =
nullptr;
7057 if (!LangOpts.WritableStrings) {
7058 Entry = &ConstantStringMap[
C];
7059 if (
auto GV = *Entry) {
7060 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7063 GV->getValueType(), Alignment);
7069 GlobalName, Alignment);
7074 GV->getValueType(), Alignment);
7087 MaterializedType = E->
getType();
7091 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7092 if (!InsertResult.second) {
7095 if (!InsertResult.first->second) {
7100 InsertResult.first->second =
new llvm::GlobalVariable(
7101 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7105 llvm::cast<llvm::GlobalVariable>(
7106 InsertResult.first->second->stripPointerCasts())
7115 llvm::raw_svector_ostream Out(Name);
7137 std::optional<ConstantEmitter> emitter;
7138 llvm::Constant *InitialValue =
nullptr;
7139 bool Constant =
false;
7143 emitter.emplace(*
this);
7144 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7149 Type = InitialValue->getType();
7158 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7160 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7164 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7168 Linkage = llvm::GlobalVariable::InternalLinkage;
7172 auto *GV =
new llvm::GlobalVariable(
7174 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7175 if (emitter) emitter->finalize(GV);
7177 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7179 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7181 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7185 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7186 if (VD->getTLSKind())
7188 llvm::Constant *CV = GV;
7191 *
this, GV, AddrSpace,
7192 llvm::PointerType::get(
7198 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7200 Entry->replaceAllUsesWith(CV);
7201 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7210void CodeGenModule::EmitObjCPropertyImplementations(
const
7223 if (!Getter || Getter->isSynthesizedAccessorStub())
7226 auto *Setter = PID->getSetterMethodDecl();
7227 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7238 if (ivar->getType().isDestructedType())
7259void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7272 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7287 getContext().getObjCIdType(),
nullptr, D,
true,
7293 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7298void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7305 EmitDeclContext(LSD);
7308void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7310 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7313 std::unique_ptr<CodeGenFunction> &CurCGF =
7314 GlobalTopLevelStmtBlockInFlight.first;
7318 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7326 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7327 FunctionArgList Args;
7329 const CGFunctionInfo &FnInfo =
7332 llvm::Function *
Fn = llvm::Function::Create(
7333 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7335 CurCGF.reset(
new CodeGenFunction(*
this));
7336 GlobalTopLevelStmtBlockInFlight.second = D;
7337 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7339 CXXGlobalInits.push_back(Fn);
7342 CurCGF->EmitStmt(D->
getStmt());
7345void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7346 for (
auto *I : DC->
decls()) {
7352 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7353 for (
auto *M : OID->methods())
7372 case Decl::CXXConversion:
7373 case Decl::CXXMethod:
7374 case Decl::Function:
7381 case Decl::CXXDeductionGuide:
7386 case Decl::Decomposition:
7387 case Decl::VarTemplateSpecialization:
7389 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7390 for (
auto *B : DD->flat_bindings())
7391 if (
auto *HD = B->getHoldingVar())
7398 case Decl::IndirectField:
7402 case Decl::Namespace:
7405 case Decl::ClassTemplateSpecialization: {
7408 if (Spec->getSpecializationKind() ==
7410 Spec->hasDefinition())
7411 DI->completeTemplateDefinition(*Spec);
7413 case Decl::CXXRecord: {
7417 DI->EmitAndRetainType(
7421 DI->completeUnusedClass(*CRD);
7424 for (
auto *I : CRD->
decls())
7430 case Decl::UsingShadow:
7431 case Decl::ClassTemplate:
7432 case Decl::VarTemplate:
7434 case Decl::VarTemplatePartialSpecialization:
7435 case Decl::FunctionTemplate:
7436 case Decl::TypeAliasTemplate:
7445 case Decl::UsingEnum:
7449 case Decl::NamespaceAlias:
7453 case Decl::UsingDirective:
7457 case Decl::CXXConstructor:
7460 case Decl::CXXDestructor:
7464 case Decl::StaticAssert:
7471 case Decl::ObjCInterface:
7472 case Decl::ObjCCategory:
7475 case Decl::ObjCProtocol: {
7477 if (Proto->isThisDeclarationADefinition())
7478 ObjCRuntime->GenerateProtocol(Proto);
7482 case Decl::ObjCCategoryImpl:
7488 case Decl::ObjCImplementation: {
7490 EmitObjCPropertyImplementations(OMD);
7491 EmitObjCIvarInitializations(OMD);
7492 ObjCRuntime->GenerateClass(OMD);
7496 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7497 OMD->getClassInterface()), OMD->getLocation());
7500 case Decl::ObjCMethod: {
7507 case Decl::ObjCCompatibleAlias:
7511 case Decl::PragmaComment: {
7513 switch (PCD->getCommentKind()) {
7515 llvm_unreachable(
"unexpected pragma comment kind");
7530 case Decl::PragmaDetectMismatch: {
7536 case Decl::LinkageSpec:
7540 case Decl::FileScopeAsm: {
7542 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7545 if (LangOpts.OpenMPIsTargetDevice)
7548 if (LangOpts.SYCLIsDevice)
7551 getModule().appendModuleInlineAsm(AD->getAsmString());
7555 case Decl::TopLevelStmt:
7559 case Decl::Import: {
7563 if (!ImportedModules.insert(Import->getImportedModule()))
7567 if (!Import->getImportedOwningModule()) {
7569 DI->EmitImportDecl(*Import);
7575 if (CXX20ModuleInits && Import->getImportedModule() &&
7576 Import->getImportedModule()->isNamedModule())
7585 Visited.insert(Import->getImportedModule());
7586 Stack.push_back(Import->getImportedModule());
7588 while (!Stack.empty()) {
7590 if (!EmittedModuleInitializers.insert(Mod).second)
7593 for (
auto *D : Context.getModuleInitializers(Mod))
7600 if (Submodule->IsExplicit)
7603 if (Visited.insert(Submodule).second)
7604 Stack.push_back(Submodule);
7614 case Decl::OMPThreadPrivate:
7618 case Decl::OMPAllocate:
7622 case Decl::OMPDeclareReduction:
7626 case Decl::OMPDeclareMapper:
7630 case Decl::OMPRequires:
7635 case Decl::TypeAlias:
7637 DI->EmitAndRetainType(
getContext().getTypedefType(
7645 DI->EmitAndRetainType(
7652 DI->EmitAndRetainType(
7656 case Decl::HLSLRootSignature:
7659 case Decl::HLSLBuffer:
7663 case Decl::OpenACCDeclare:
7666 case Decl::OpenACCRoutine:
7681 if (!CodeGenOpts.CoverageMapping)
7684 case Decl::CXXConversion:
7685 case Decl::CXXMethod:
7686 case Decl::Function:
7687 case Decl::ObjCMethod:
7688 case Decl::CXXConstructor:
7689 case Decl::CXXDestructor: {
7698 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
7708 if (!CodeGenOpts.CoverageMapping)
7710 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7711 if (Fn->isTemplateInstantiation())
7714 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
7722 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7725 const Decl *D = Entry.first;
7727 case Decl::CXXConversion:
7728 case Decl::CXXMethod:
7729 case Decl::Function:
7730 case Decl::ObjCMethod: {
7737 case Decl::CXXConstructor: {
7744 case Decl::CXXDestructor: {
7761 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7762 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7763 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7764 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7765 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7774 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7775 return llvm::ConstantInt::get(i64, PtrInt);
7779 llvm::NamedMDNode *&GlobalMetadata,
7781 llvm::GlobalValue *
Addr) {
7782 if (!GlobalMetadata)
7784 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7787 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
7790 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7793bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7794 llvm::GlobalValue *CppFunc) {
7796 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7799 llvm::SmallVector<llvm::ConstantExpr *> CEs;
7802 if (Elem == CppFunc)
7808 for (llvm::User *User : Elem->users()) {
7812 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7813 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7816 for (llvm::User *CEUser : ConstExpr->users()) {
7817 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7818 IFuncs.push_back(IFunc);
7823 CEs.push_back(ConstExpr);
7824 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7825 IFuncs.push_back(IFunc);
7837 for (llvm::GlobalIFunc *IFunc : IFuncs)
7838 IFunc->setResolver(
nullptr);
7839 for (llvm::ConstantExpr *ConstExpr : CEs)
7840 ConstExpr->destroyConstant();
7844 Elem->eraseFromParent();
7846 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7851 llvm::FunctionType::get(IFunc->getType(),
false);
7852 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7853 CppFunc->getName(), ResolverTy, {},
false);
7854 IFunc->setResolver(Resolver);
7864void CodeGenModule::EmitStaticExternCAliases() {
7867 for (
auto &I : StaticExternCValues) {
7868 const IdentifierInfo *Name = I.first;
7869 llvm::GlobalValue *Val = I.second;
7877 llvm::GlobalValue *ExistingElem =
7882 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7889 auto Res = Manglings.find(MangledName);
7890 if (Res == Manglings.end())
7892 Result = Res->getValue();
7903void CodeGenModule::EmitDeclMetadata() {
7904 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7906 for (
auto &I : MangledDeclNames) {
7907 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
7917void CodeGenFunction::EmitDeclMetadata() {
7918 if (LocalDeclMap.empty())
return;
7923 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7925 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7927 for (
auto &I : LocalDeclMap) {
7928 const Decl *D = I.first;
7929 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
7930 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
7932 Alloca->setMetadata(
7933 DeclPtrKind, llvm::MDNode::get(
7934 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7935 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
7942void CodeGenModule::EmitVersionIdentMetadata() {
7943 llvm::NamedMDNode *IdentMetadata =
7944 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7946 llvm::LLVMContext &Ctx = TheModule.getContext();
7948 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7949 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7952void CodeGenModule::EmitCommandLineMetadata() {
7953 llvm::NamedMDNode *CommandLineMetadata =
7954 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7956 llvm::LLVMContext &Ctx = TheModule.getContext();
7958 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7959 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7962void CodeGenModule::EmitCoverageFile() {
7963 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7967 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7968 llvm::LLVMContext &Ctx = TheModule.getContext();
7969 auto *CoverageDataFile =
7971 auto *CoverageNotesFile =
7973 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7974 llvm::MDNode *CU = CUNode->getOperand(i);
7975 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7976 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7989 LangOpts.ObjCRuntime.isGNUFamily())
7990 return ObjCRuntime->GetEHType(Ty);
7997 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7999 for (
auto RefExpr : D->
varlist()) {
8002 VD->getAnyInitializer() &&
8003 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
8010 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8011 CXXGlobalInits.push_back(InitFunction);
8016CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8020 FnType->getReturnType(), FnType->getParamTypes(),
8021 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8023 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
8028 std::string OutName;
8029 llvm::raw_string_ostream Out(OutName);
8034 Out <<
".normalized";
8057 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
8062 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8066 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8074 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8075 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8076 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8077 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8078 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8079 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8080 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8081 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8089 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8091 if (CodeGenOpts.SanitizeCfiCrossDso)
8093 VTable->addTypeMetadata(Offset.getQuantity(),
8094 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8097 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8098 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8104 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8114 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8129 bool forPointeeType) {
8140 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8147 bool AlignForArray =
T->isArrayType();
8153 if (
T->isIncompleteType()) {
8170 if (
T.getQualifiers().hasUnaligned()) {
8172 }
else if (forPointeeType && !AlignForArray &&
8173 (RD =
T->getAsCXXRecordDecl())) {
8184 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8197 if (NumAutoVarInit >= StopAfter) {
8200 if (!NumAutoVarInit) {
8203 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
8204 "number of times ftrivial-auto-var-init=%1 gets applied.");
8218 const Decl *D)
const {
8222 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8224 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8230 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8234 llvm::MD5::MD5Result
Result;
8235 for (
const auto &Arg : PreprocessorOpts.Macros)
8236 Hash.update(Arg.first);
8240 llvm::sys::fs::UniqueID ID;
8244 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8248 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8249 << PLoc.
getFilename() << Status.getError().message();
8251 ID = Status->getUniqueID();
8253 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8254 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8261 assert(DeferredDeclsToEmit.empty() &&
8262 "Should have emitted all decls deferred to emit.");
8263 assert(NewBuilder->DeferredDecls.empty() &&
8264 "Newly created module should not have deferred decls");
8265 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8266 assert(EmittedDeferredDecls.empty() &&
8267 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8269 assert(NewBuilder->DeferredVTables.empty() &&
8270 "Newly created module should not have deferred vtables");
8271 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8273 assert(NewBuilder->MangledDeclNames.empty() &&
8274 "Newly created module should not have mangled decl names");
8275 assert(NewBuilder->Manglings.empty() &&
8276 "Newly created module should not have manglings");
8277 NewBuilder->Manglings = std::move(Manglings);
8279 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8281 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 bool hasExistingGeneralizedTypeMD(llvm::Function *F)
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 constexpr auto ErrnoTBAAMDName
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 IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() 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 createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata if the function is a potential indirect call target to support call g...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach type metadata to the given call.
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)
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
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
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.