53#include "llvm/ABI/IRTypeMapper.h"
54#include "llvm/ABI/TargetInfo.h"
55#include "llvm/ADT/APFloat.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/StringExtras.h"
58#include "llvm/ADT/StringSwitch.h"
59#include "llvm/Analysis/TargetLibraryInfo.h"
60#include "llvm/BinaryFormat/ELF.h"
61#include "llvm/IR/AttributeMask.h"
62#include "llvm/IR/CallingConv.h"
63#include "llvm/IR/DataLayout.h"
64#include "llvm/IR/Intrinsics.h"
65#include "llvm/IR/LLVMContext.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/ProfileSummary.h"
68#include "llvm/ProfileData/InstrProfReader.h"
69#include "llvm/ProfileData/SampleProf.h"
70#include "llvm/Support/ARMBuildAttributes.h"
71#include "llvm/Support/CRC.h"
72#include "llvm/Support/CodeGen.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/ConvertUTF.h"
75#include "llvm/Support/ErrorHandling.h"
76#include "llvm/Support/TimeProfiler.h"
77#include "llvm/Support/VirtualFileSystem.h"
78#include "llvm/TargetParser/AArch64TargetParser.h"
79#include "llvm/TargetParser/RISCVISAInfo.h"
80#include "llvm/TargetParser/Triple.h"
81#include "llvm/TargetParser/X86TargetParser.h"
82#include "llvm/Transforms/Instrumentation/KCFI.h"
83#include "llvm/Transforms/Utils/BuildLibCalls.h"
84#include "llvm/Transforms/Utils/KCFIHash.h"
85#include "llvm/Transforms/Utils/ModuleUtils.h"
93 "limited-coverage-experimental", llvm::cl::Hidden,
94 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
101 case TargetCXXABI::AppleARM64:
102 case TargetCXXABI::Fuchsia:
103 case TargetCXXABI::GenericAArch64:
104 case TargetCXXABI::GenericARM:
105 case TargetCXXABI::iOS:
106 case TargetCXXABI::WatchOS:
107 case TargetCXXABI::GenericMIPS:
108 case TargetCXXABI::GenericItanium:
109 case TargetCXXABI::WebAssembly:
110 case TargetCXXABI::XL:
112 case TargetCXXABI::Microsoft:
116 llvm_unreachable(
"invalid C++ ABI kind");
119static std::unique_ptr<TargetCodeGenInfo>
122 const llvm::Triple &Triple =
Target.getTriple();
125 switch (Triple.getArch()) {
129 case llvm::Triple::m68k:
131 case llvm::Triple::mips:
132 case llvm::Triple::mipsel:
133 if (Triple.getOS() == llvm::Triple::Win32)
137 case llvm::Triple::mips64:
138 case llvm::Triple::mips64el:
141 case llvm::Triple::avr: {
145 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
146 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
150 case llvm::Triple::aarch64:
151 case llvm::Triple::aarch64_32:
152 case llvm::Triple::aarch64_be: {
154 if (
Target.getABI() ==
"darwinpcs")
155 Kind = AArch64ABIKind::DarwinPCS;
156 else if (Triple.isOSWindowsOrUEFI())
158 else if (
Target.getABI() ==
"aapcs-soft")
159 Kind = AArch64ABIKind::AAPCSSoft;
164 case llvm::Triple::wasm32:
165 case llvm::Triple::wasm64: {
167 if (
Target.getABI() ==
"experimental-mv")
168 Kind = WebAssemblyABIKind::ExperimentalMV;
172 case llvm::Triple::arm:
173 case llvm::Triple::armeb:
174 case llvm::Triple::thumb:
175 case llvm::Triple::thumbeb: {
176 if (Triple.getOS() == llvm::Triple::Win32)
180 StringRef ABIStr =
Target.getABI();
181 if (ABIStr ==
"apcs-gnu")
182 Kind = ARMABIKind::APCS;
183 else if (ABIStr ==
"aapcs16")
184 Kind = ARMABIKind::AAPCS16_VFP;
185 else if (CodeGenOpts.
FloatABI ==
"hard" ||
186 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
187 Kind = ARMABIKind::AAPCS_VFP;
192 case llvm::Triple::ppc: {
193 if (Triple.isOSAIX())
200 case llvm::Triple::ppcle: {
205 case llvm::Triple::ppc64:
206 if (Triple.isOSAIX())
209 if (Triple.isOSBinFormatELF()) {
211 if (
Target.getABI() ==
"elfv2")
212 Kind = PPC64_SVR4_ABIKind::ELFv2;
213 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
218 case llvm::Triple::ppc64le: {
219 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
221 if (
Target.getABI() ==
"elfv1")
222 Kind = PPC64_SVR4_ABIKind::ELFv1;
223 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
228 case llvm::Triple::nvptx:
229 case llvm::Triple::nvptx64:
232 case llvm::Triple::msp430:
235 case llvm::Triple::riscv32:
236 case llvm::Triple::riscv64:
237 case llvm::Triple::riscv32be:
238 case llvm::Triple::riscv64be: {
239 StringRef ABIStr =
Target.getABI();
241 unsigned ABIFLen = 0;
242 if (ABIStr.ends_with(
"f"))
244 else if (ABIStr.ends_with(
"d"))
246 bool EABI = ABIStr.ends_with(
"e");
250 case llvm::Triple::systemz: {
251 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
252 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
253 if (Triple.getOS() == llvm::Triple::ZOS)
258 case llvm::Triple::tce:
259 case llvm::Triple::tcele:
260 case llvm::Triple::tcele64:
263 case llvm::Triple::x86: {
264 bool IsDarwinVectorABI = Triple.isOSDarwin();
265 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
267 if (Triple.getOS() == llvm::Triple::Win32) {
269 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
270 CodeGenOpts.NumRegisterParameters);
273 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
274 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
277 case llvm::Triple::x86_64: {
278 StringRef ABI =
Target.getABI();
279 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
280 : ABI ==
"avx" ? X86AVXABILevel::AVX
281 : X86AVXABILevel::None);
283 switch (Triple.getOS()) {
284 case llvm::Triple::UEFI:
285 case llvm::Triple::Win32:
291 case llvm::Triple::hexagon:
293 case llvm::Triple::lanai:
295 case llvm::Triple::r600:
297 case llvm::Triple::amdgpu:
299 case llvm::Triple::sparc:
301 case llvm::Triple::sparcv9:
303 case llvm::Triple::xcore:
305 case llvm::Triple::arc:
307 case llvm::Triple::spir:
308 case llvm::Triple::spir64:
310 case llvm::Triple::spirv32:
311 case llvm::Triple::spirv64:
312 case llvm::Triple::spirv:
314 case llvm::Triple::dxil:
316 case llvm::Triple::ve:
318 case llvm::Triple::csky: {
319 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
321 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
326 case llvm::Triple::bpfeb:
327 case llvm::Triple::bpfel:
329 case llvm::Triple::loongarch32:
330 case llvm::Triple::loongarch64: {
331 StringRef ABIStr =
Target.getABI();
332 unsigned ABIFRLen = 0;
333 if (ABIStr.ends_with(
"f"))
335 else if (ABIStr.ends_with(
"d"))
340 case llvm::Triple::xtensa:
346 if (!TheTargetCodeGenInfo)
348 return *TheTargetCodeGenInfo;
352 if (!CodeGenOpts.ExperimentalABILowering)
362 return T.getVendor() != llvm::Triple::AMD && !
getLangOpts().HLSL;
364 if (
T.getArch() == llvm::Triple::aarch64 ||
365 T.getArch() == llvm::Triple::aarch64_32 ||
366 T.getArch() == llvm::Triple::aarch64_be)
369 if (
T.getArch() == llvm::Triple::x86_64 && !
T.isOSWindows() && !
T.isUEFI() &&
370 !
T.isOSDarwin() && !
T.isOSCygMing()) {
372 case llvm::CallingConv::Win64:
373 case llvm::CallingConv::X86_RegCall:
374 case llvm::CallingConv::X86_FastCall:
375 case llvm::CallingConv::X86_VectorCall:
376 case llvm::CallingConv::X86_StdCall:
377 case llvm::CallingConv::X86_ThisCall:
381 case llvm::CallingConv::Intel_OCL_BI:
382 case llvm::CallingConv::PreserveMost:
383 case llvm::CallingConv::PreserveAll:
384 case llvm::CallingConv::PreserveNone:
395 CompatInfo.IsMatrixHA = Compat > LangOptions::ClangABI::Ver23;
399 const llvm::Triple &
T,
402 CompatInfo.ClassifyIntegerMMXAsSSE = Compat > LangOptions::ClangABI::Ver3_8 &&
403 !
T.isOSDarwin() && !
T.isPS() &&
405 CompatInfo.HonorsRevision98 = !
T.isOSDarwin();
406 CompatInfo.PassInt128VectorsInMem =
407 Compat > LangOptions::ClangABI::Ver9 && (
T.isOSLinux() ||
T.isOSNetBSD());
409 CompatInfo.ReturnCXXRecordGreaterThan128InMem =
410 Compat > LangOptions::ClangABI::Ver20 && !
T.isPS();
411 CompatInfo.Clang11Compat = Compat <= LangOptions::ClangABI::Ver11 ||
T.isPS();
412 CompatInfo.ClassifyUnnamedBitFields =
413 Compat > LangOptions::ClangABI::Ver23 && !
T.isPS();
416const llvm::abi::TargetInfo &
418 if (TheLLVMABITargetInfo)
419 return *TheLLVMABITargetInfo;
423 switch (
T.getArch()) {
425 llvm_unreachable(
"LLVMABI lowering requested for an unsupported target");
427 case llvm::Triple::aarch64:
428 case llvm::Triple::aarch64_32:
429 case llvm::Triple::aarch64_be: {
430 llvm::abi::AArch64ABIOptions Opts;
432 if (ABI ==
"darwinpcs")
433 Opts.Kind = llvm::abi::AArch64ABIKind::DarwinPCS;
434 else if (
T.isOSWindows())
435 Opts.Kind = llvm::abi::AArch64ABIKind::Win64;
436 else if (ABI ==
"aapcs-soft")
437 Opts.Kind = llvm::abi::AArch64ABIKind::AAPCSSoft;
439 Opts.Kind = llvm::abi::AArch64ABIKind::AAPCS;
441 Opts.IsILP32 =
T.getArch() == llvm::Triple::aarch64_32;
443 Opts.IsMachO =
T.isOSBinFormatMachO();
444 Opts.IsAndroidOrOHOS =
T.isAndroid() ||
T.isOHOSFamily();
445 Opts.IsWindowsArm64EC =
T.isWindowsArm64EC();
447 Opts.IsBigEndian = !
T.isLittleEndian();
452 TheLLVMABITargetInfo = llvm::abi::createAArch64TargetInfo(TB, Opts);
453 return *TheLLVMABITargetInfo;
456 case llvm::Triple::spirv:
457 case llvm::Triple::spirv32:
458 case llvm::Triple::spirv64:
459 TheLLVMABITargetInfo = llvm::abi::createSPIRVTargetInfo(
462 return *TheLLVMABITargetInfo;
464 case llvm::Triple::bpfeb:
465 case llvm::Triple::bpfel:
467 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
468 return *TheLLVMABITargetInfo;
470 case llvm::Triple::x86_64: {
472 llvm::abi::X86AVXABILevel AVXLevel =
473 ABI ==
"avx512" ? llvm::abi::X86AVXABILevel::AVX512
474 : ABI ==
"avx" ? llvm::abi::X86AVXABILevel::AVX
475 : llvm::abi::X86AVXABILevel::None;
477 llvm::abi::X86ABICompatInfo CompatInfo;
483 TheLLVMABITargetInfo = llvm::abi::createX86_64TargetInfo(
484 TB, AVXLevel, Has64BitPointers, CompatInfo);
485 return *TheLLVMABITargetInfo;
491 llvm::LLVMContext &Context,
495 if (Opts.AlignDouble || Opts.OpenCL)
498 llvm::Triple Triple =
Target.getTriple();
499 llvm::DataLayout DL(
Target.getDataLayoutString());
500 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
501 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
502 llvm::Align ClangAlign(Alignment / 8);
503 if (DLAlign != ClangAlign) {
504 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
505 <<
" mapping to " << *Ty <<
" has data layout alignment "
506 << DLAlign.value() <<
" while clang specifies "
507 << ClangAlign.value() <<
"\n";
512 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
514 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
516 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
518 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
521 if (Triple.getArch() != llvm::Triple::m68k)
522 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
525 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
526 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
527 Triple.getArch() != llvm::Triple::ve)
528 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
530 if (
Target.hasFloat16Type())
531 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
533 if (
Target.hasBFloat16Type())
534 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
535 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
537 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
540 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
542 if (
Target.hasFloat128Type())
543 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
544 if (
Target.hasIbm128Type())
545 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
547 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
549 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
550 llvm::errs() <<
"Datalayout for target " << Triple.str()
551 <<
" sets element-aligned vectors to '"
552 <<
Target.vectorsAreElementAligned()
553 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
567 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
568 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
570 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
574 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
575 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
576 M.getContext(), M.getDataLayout());
580 llvm::LLVMContext &LLVMContext = M.getContext();
581 VoidTy = llvm::Type::getVoidTy(LLVMContext);
582 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
583 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
584 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
585 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
586 HalfTy = llvm::Type::getHalfTy(LLVMContext);
587 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
588 FloatTy = llvm::Type::getFloatTy(LLVMContext);
589 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
595 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
597 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
599 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
600 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
601 IntPtrTy = llvm::IntegerType::get(LLVMContext,
602 C.getTargetInfo().getMaxPointerWidth());
603 Int8PtrTy = llvm::PointerType::get(LLVMContext,
605 const llvm::DataLayout &DL = M.getDataLayout();
607 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
609 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
611 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
627 createOpenCLRuntime();
629 createOpenMPRuntime();
636 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
637 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
643 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
644 CodeGenOpts.CoverageNotesFile.size() ||
645 CodeGenOpts.CoverageDataFile.size())
653 Block.GlobalUniqueCount = 0;
655 if (
C.getLangOpts().ObjC)
658 if (CodeGenOpts.hasProfileClangUse()) {
659 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
660 CodeGenOpts.ProfileInstrumentUsePath, *FS,
661 CodeGenOpts.ProfileRemappingFile);
662 if (
auto E = ReaderOrErr.takeError()) {
663 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
664 Diags.Report(diag::err_reading_profile)
665 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
669 PGOReader = std::move(ReaderOrErr.get());
674 if (CodeGenOpts.CoverageMapping)
678 if (CodeGenOpts.UniqueInternalLinkageNames &&
679 !
getModule().getSourceFileName().empty()) {
683 Context.getTargetInfo());
684 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
688 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
689 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
690 CodeGenOpts.NumRegisterParameters);
699 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
700 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
702 this->MSHotPatchFunctions.push_back(std::string{*I});
704 auto &DE = Context.getDiagnostics();
705 DE.Report(diag::err_open_hotpatch_file_failed)
707 << BufOrErr.getError().message();
712 this->MSHotPatchFunctions.push_back(FuncName);
714 llvm::sort(this->MSHotPatchFunctions);
717 if (!Context.getAuxTargetInfo())
723void CodeGenModule::createObjCRuntime() {
740 llvm_unreachable(
"bad runtime kind");
743void CodeGenModule::createOpenCLRuntime() {
747void CodeGenModule::createOpenMPRuntime() {
748 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
749 Diags.Report(diag::err_omp_host_ir_file_not_found)
750 << LangOpts.OMPHostIRFile;
755 case llvm::Triple::nvptx:
756 case llvm::Triple::nvptx64:
757 case llvm::Triple::amdgpu:
758 case llvm::Triple::spirv64:
761 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
762 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
765 if (LangOpts.OpenMPSimd)
766 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
768 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
773void CodeGenModule::createCUDARuntime() {
777void CodeGenModule::createHLSLRuntime() {
778 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
782 Replacements[Name] =
C;
785void CodeGenModule::applyReplacements() {
786 for (
auto &I : Replacements) {
787 StringRef MangledName = I.first;
788 llvm::Constant *Replacement = I.second;
793 auto *NewF = dyn_cast<llvm::Function>(Replacement);
795 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
796 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
799 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
800 CE->getOpcode() == llvm::Instruction::GetElementPtr);
801 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
806 OldF->replaceAllUsesWith(Replacement);
808 NewF->removeFromParent();
809 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
812 OldF->eraseFromParent();
817 GlobalValReplacements.push_back(std::make_pair(GV,
C));
820void CodeGenModule::applyGlobalValReplacements() {
821 for (
auto &I : GlobalValReplacements) {
822 llvm::GlobalValue *GV = I.first;
823 llvm::Constant *
C = I.second;
825 GV->replaceAllUsesWith(
C);
826 GV->eraseFromParent();
833 const llvm::Constant *
C;
834 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
835 C = GA->getAliasee();
836 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
837 C = GI->getResolver();
841 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
845 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
854 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
855 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
859 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
863 if (GV->hasCommonLinkage()) {
864 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
865 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
866 Diags.
Report(Location, diag::err_alias_to_common);
871 if (GV->isDeclaration()) {
872 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
873 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
874 << IsIFunc << IsIFunc;
877 for (
const auto &[
Decl, Name] : MangledDeclNames) {
878 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
880 if (II && II->
getName() == GV->getName()) {
881 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
885 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
895 const auto *F = dyn_cast<llvm::Function>(GV);
897 Diags.
Report(Location, diag::err_alias_to_undefined)
898 << IsIFunc << IsIFunc;
902 llvm::FunctionType *FTy = F->getFunctionType();
903 if (!FTy->getReturnType()->isPointerTy()) {
904 Diags.
Report(Location, diag::err_ifunc_resolver_return);
918 if (GVar->hasAttribute(
"toc-data")) {
919 auto GVId = GVar->getName();
922 Diags.
Report(Location, diag::warn_toc_unsupported_type)
923 << GVId <<
"the variable has an alias";
925 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
926 llvm::AttributeSet NewAttributes =
927 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
928 GVar->setAttributes(NewAttributes);
932void CodeGenModule::checkAliases() {
937 DiagnosticsEngine &Diags =
getDiags();
938 for (
const GlobalDecl &GD : Aliases) {
940 SourceLocation Location;
942 bool IsIFunc = D->hasAttr<IFuncAttr>();
943 if (
const Attr *A = D->getDefiningAttr()) {
944 Location = A->getLocation();
945 Range = A->getRange();
947 llvm_unreachable(
"Not an alias or ifunc?");
951 const llvm::GlobalValue *GV =
nullptr;
953 MangledDeclNames, Range)) {
959 GlobalDecl AliaseeGD;
962 Diags.Report(Location, diag::err_alias_to_undefined)
963 << IsIFunc << IsIFunc;
972 if (AliasIsFuncDecl != AliaseeIsFunc) {
973 Diags.Report(Location, diag::err_alias_between_function_and_variable)
976 diag::note_aliasee_declaration);
983 if (AliasIsFuncDecl && AliaseeIsFunc) {
984 QualType AliasTy = D->getType();
986 auto shouldReportTypeMismatch = [&]() {
987 const auto *AliasFTy =
989 const auto *AliaseeFTy =
991 assert(AliasFTy && AliaseeFTy);
992 if (!Context.typesAreCompatible(AliasFTy->getReturnType(),
995 const auto *AliasFPTy = dyn_cast<FunctionProtoType>(AliasFTy);
996 const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(AliaseeFTy);
998 if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) ||
999 (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy))
1002 if (!AliasFPTy || !AliaseeFPTy)
1006 if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() ||
1007 AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic())
1009 for (
unsigned i = 0; i < AliasFPTy->getNumParams(); ++i)
1010 if (!Context.typesAreCompatible(AliasFPTy->getParamType(i),
1011 AliaseeFPTy->getParamType(i)))
1015 if (shouldReportTypeMismatch()) {
1016 Diags.Report(Location, diag::warn_alias_type_mismatch)
1017 << AliasTy << AliaseeTy;
1019 diag::note_aliasee_declaration);
1025 if (
const llvm::GlobalVariable *GVar =
1026 dyn_cast<const llvm::GlobalVariable>(GV))
1030 llvm::Constant *Aliasee =
1034 llvm::GlobalValue *AliaseeGV;
1035 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
1040 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
1041 StringRef AliasSection = SA->getName();
1042 if (AliasSection != AliaseeGV->getSection())
1043 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
1044 << AliasSection << IsIFunc << IsIFunc;
1052 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
1053 if (GA->isInterposable()) {
1054 Diags.Report(Location, diag::warn_alias_to_weak_alias)
1055 << GV->getName() << GA->getName() << IsIFunc;
1056 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1057 GA->getAliasee(), Alias->getType());
1069 llvm::Attribute::DisableSanitizerInstrumentation);
1074 for (
const GlobalDecl &GD : Aliases) {
1077 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
1078 Alias->eraseFromParent();
1083 DeferredDeclsToEmit.clear();
1084 EmittedDeferredDecls.clear();
1085 DeferredAnnotations.clear();
1087 OpenMPRuntime->clear();
1091 StringRef MainFile) {
1094 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
1095 if (MainFile.empty())
1096 MainFile =
"<stdin>";
1097 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
1100 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
1103 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
1107static std::optional<llvm::GlobalValue::VisibilityTypes>
1112 return std::nullopt;
1114 return llvm::GlobalValue::DefaultVisibility;
1116 return llvm::GlobalValue::HiddenVisibility;
1118 return llvm::GlobalValue::ProtectedVisibility;
1120 llvm_unreachable(
"unknown option value!");
1125 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
1134 GV.setDSOLocal(
false);
1135 GV.setVisibility(*
V);
1140 if (!LO.VisibilityFromDLLStorageClass)
1143 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
1146 std::optional<llvm::GlobalValue::VisibilityTypes>
1147 NoDLLStorageClassVisibility =
1150 std::optional<llvm::GlobalValue::VisibilityTypes>
1151 ExternDeclDLLImportVisibility =
1154 std::optional<llvm::GlobalValue::VisibilityTypes>
1155 ExternDeclNoDLLStorageClassVisibility =
1158 for (llvm::GlobalValue &GV : M.global_values()) {
1159 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
1162 if (GV.isDeclarationForLinker())
1164 llvm::GlobalValue::DLLImportStorageClass
1165 ? ExternDeclDLLImportVisibility
1166 : ExternDeclNoDLLStorageClassVisibility);
1169 llvm::GlobalValue::DLLExportStorageClass
1170 ? DLLExportVisibility
1171 : NoDLLStorageClassVisibility);
1173 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1178 const llvm::Triple &Triple,
1182 return LangOpts.getStackProtector() == Mode;
1185std::optional<llvm::Attribute::AttrKind>
1187 if (D && D->
hasAttr<NoStackProtectorAttr>())
1189 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1191 return llvm::Attribute::StackProtectStrong;
1193 return llvm::Attribute::StackProtect;
1195 return llvm::Attribute::StackProtectStrong;
1197 return llvm::Attribute::StackProtectReq;
1198 return std::nullopt;
1204 EmitModuleInitializers(Primary);
1206 DeferredDecls.insert_range(EmittedDeferredDecls);
1207 EmittedDeferredDecls.clear();
1208 EmitVTablesOpportunistically();
1209 applyGlobalValReplacements();
1210 applyReplacements();
1211 emitMultiVersionFunctions();
1212 emitPFPFieldsWithEvaluatedOffset();
1215 if (Context.getLangOpts().IncrementalExtensions &&
1216 GlobalTopLevelStmtBlockInFlight.first) {
1218 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1219 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1225 EmitCXXModuleInitFunc(Primary);
1227 EmitCXXGlobalInitFunc();
1228 EmitCXXGlobalCleanUpFunc();
1229 registerGlobalDtorsWithAtExit();
1230 EmitCXXThreadLocalInitFunc();
1232 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1234 if (Context.getLangOpts().CUDA && CUDARuntime) {
1235 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1238 if (LangOpts.SYCLIsHost && !CodeGenOpts.OffloadBinaryToEmbedFile.empty()) {
1239 if (llvm::Function *SYCLCtorFunction = embedSYCLDeviceBinary())
1244 if (OpenMPRuntime) {
1245 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1246 OpenMPRuntime->clear();
1250 PGOReader->getSummary(
false).getMD(VMContext),
1251 llvm::ProfileSummary::PSK_Instr);
1252 if (PGOStats.hasDiagnostics())
1258 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1259 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1261 EmitStaticExternCAliases();
1266 if (CoverageMapping)
1267 CoverageMapping->emit();
1268 if (CodeGenOpts.SanitizeCfiCrossDso) {
1272 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1274 emitAtAvailableLinkGuard();
1275 if (Context.getTargetInfo().getTriple().isWasm())
1282 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1283 llvm::CodeObjectVersionKind::COV_None) {
1284 getModule().addModuleFlag(llvm::Module::Error,
1285 "amdhsa_code_object_version",
1286 getTarget().getTargetOpts().CodeObjectVersion);
1291 auto *MDStr = llvm::MDString::get(
1296 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1306 llvm::Module::Error,
"amdgpu.xnack",
1307 llvm::ConstantInt::get(
1315 llvm::Module::Error,
"amdgpu.sramecc",
1316 llvm::ConstantInt::get(
1326 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1328 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1330 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1334 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1338 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1340 auto *GV =
new llvm::GlobalVariable(
1341 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1342 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1349 if (LangOpts.HIP && !LangOpts.IncrementalExtensions) {
1352 auto *GV =
new llvm::GlobalVariable(
1354 llvm::Constant::getNullValue(
Int8Ty),
1363 if (CodeGenOpts.Autolink &&
1364 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1365 EmitModuleLinkOptions();
1380 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1381 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1382 for (
auto *MD : ELFDependentLibraries)
1383 NMD->addOperand(MD);
1386 if (CodeGenOpts.DwarfVersion) {
1387 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1388 CodeGenOpts.DwarfVersion);
1391 if (CodeGenOpts.Dwarf64)
1392 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1394 if (Context.getLangOpts().SemanticInterposition)
1396 getModule().setSemanticInterposition(
true);
1398 if (CodeGenOpts.EmitCodeView) {
1400 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1402 if (CodeGenOpts.CodeViewGHash) {
1403 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1405 if (CodeGenOpts.ControlFlowGuard) {
1408 llvm::Module::Warning,
"cfguard",
1409 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1410 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1413 llvm::Module::Warning,
"cfguard",
1414 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1416 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1417 llvm::ControlFlowGuardMechanism::Automatic) {
1420 llvm::Module::Warning,
"cfguard-mechanism",
1421 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1423 if (CodeGenOpts.EHContGuard) {
1425 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1427 if (Context.getLangOpts().Kernel) {
1429 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1431 if (CodeGenOpts.HotPatch) {
1434 getModule().addModuleFlag(llvm::Module::Min,
"ms-hotpatch", 1);
1436 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1441 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1443 llvm::Metadata *Ops[2] = {
1444 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1445 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1446 llvm::Type::getInt32Ty(VMContext), 1))};
1448 getModule().addModuleFlag(llvm::Module::Require,
1449 "StrictVTablePointersRequirement",
1450 llvm::MDNode::get(VMContext, Ops));
1456 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1457 llvm::DEBUG_METADATA_VERSION);
1462 uint64_t WCharWidth =
1463 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1464 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1465 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size",
1466 static_cast<uint32_t
>(WCharWidth));
1470 llvm::FloatABI::ABIType FloatABI =
1471 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
1472 .Cases({
"soft",
"softfp"}, llvm::FloatABI::Soft)
1473 .Case(
"hard", llvm::FloatABI::Hard)
1474 .Default(llvm::FloatABI::Default);
1475 if (FloatABI != llvm::FloatABI::Default &&
1476 FloatABI !=
getTriple().getDefaultFloatABI()) {
1478 llvm::Module::Error,
"float-abi",
1480 llvm::FloatABI::getABITypeName(FloatABI)));
1485 llvm::ThreadModel ThreadModel =
1487 ? llvm::ThreadModel::Single
1488 : llvm::ThreadModel::POSIX;
1489 if (ThreadModel !=
getTriple().getDefaultThreadModel())
1490 getModule().setThreadModel(ThreadModel);
1492 if (
getTypes().isLongDoubleReferenced()) {
1495 std::optional<llvm::LongDoubleFormat> Format;
1496 if (flt == &llvm::APFloat::IEEEquad())
1497 Format = llvm::LongDoubleFormat::IEEEquad;
1498 else if (flt == &llvm::APFloat::IEEEdouble())
1499 Format = llvm::LongDoubleFormat::IEEEdouble;
1500 else if (flt == &llvm::APFloat::PPCDoubleDouble())
1501 Format = llvm::LongDoubleFormat::PPCDoubleDouble;
1502 else if (flt == &llvm::APFloat::x87DoubleExtended())
1503 Format = llvm::LongDoubleFormat::X87DoubleExtended;
1504 else if (flt == &llvm::APFloat::IEEEsingle())
1505 Format = llvm::LongDoubleFormat::IEEEsingle;
1508 getModule().setLongDoubleFormat(*Format);
1515 llvm::ExceptionHandling ExceptionModel =
1517 if (ExceptionModel != llvm::ExceptionHandling::Default) {
1519 llvm::Module::Error,
"exception-model",
1521 llvm::getExceptionModelName(ExceptionModel)));
1524 if (CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::Default)
1525 getModule().setDebuggerTuning(CodeGenOpts.getDebuggerTuning());
1528 getModule().addModuleFlag(llvm::Module::Warning,
1529 "zos_product_major_version",
1531 getModule().addModuleFlag(llvm::Module::Warning,
1532 "zos_product_minor_version",
1534 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1535 uint32_t(CLANG_VERSION_PATCHLEVEL));
1537 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1538 llvm::MDString::get(VMContext, ProductId));
1543 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1544 llvm::MDString::get(VMContext, lang_str));
1546 time_t TT = PreprocessorOpts.SourceDateEpoch
1547 ? *PreprocessorOpts.SourceDateEpoch
1548 : std::time(
nullptr);
1549 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1550 static_cast<uint64_t
>(TT));
1553 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1554 llvm::MDString::get(VMContext,
"ascii"));
1557 llvm::Triple
T = Context.getTargetInfo().getTriple();
1562 if (StringRef ABIStr = Target.getABI();
1563 !ABIStr.empty() && (
T.isARM() ||
T.isThumb() ||
T.isRISCV() ||
1564 T.isPPC() ||
T.isLoongArch() ||
T.isWasm())) {
1565 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1566 llvm::MDString::get(VMContext, ABIStr));
1569 if (
T.isARM() ||
T.isThumb()) {
1571 uint32_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1572 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1576 llvm::LLVMContext &Ctx = TheModule.getContext();
1581 const std::vector<std::string> &Features =
1584 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1585 if (!errorToBool(ParseResult.takeError()))
1587 llvm::Module::AppendUnique,
"riscv-isa",
1589 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1592 if (CodeGenOpts.SanitizeCfiCrossDso) {
1594 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1597 if (CodeGenOpts.WholeProgramVTables) {
1601 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1602 CodeGenOpts.VirtualFunctionElimination);
1605 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1606 getModule().addModuleFlag(llvm::Module::Override,
1607 "CFI Canonical Jump Tables",
1608 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1611 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1612 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1616 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1618 llvm::Module::Append,
"Unique Source File Identifier",
1620 TheModule.getContext(),
1621 llvm::MDString::get(TheModule.getContext(),
1622 CodeGenOpts.UniqueSourceFileIdentifier)));
1625 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1626 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1629 if (CodeGenOpts.PatchableFunctionEntryOffset)
1630 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1631 CodeGenOpts.PatchableFunctionEntryOffset);
1632 if (CodeGenOpts.SanitizeKcfiArity)
1633 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1636 llvm::Module::Override,
"kcfi-hash",
1637 llvm::MDString::get(
1639 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1642 if (CodeGenOpts.CFProtectionReturn &&
1643 Target.checkCFProtectionReturnSupported(
getDiags())) {
1645 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1649 if (CodeGenOpts.CFProtectionBranch &&
1650 Target.checkCFProtectionBranchSupported(
getDiags())) {
1652 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1655 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1656 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1658 Scheme = Target.getDefaultCFBranchLabelScheme();
1660 llvm::Module::Error,
"cf-branch-label-scheme",
1666 if (CodeGenOpts.FunctionReturnThunks)
1667 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1669 if (CodeGenOpts.IndirectBranchCSPrefix)
1670 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1672 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1680 if (LangOpts.BranchTargetEnforcement)
1681 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1683 if (LangOpts.BranchProtectionPAuthLR)
1684 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1686 if (LangOpts.GuardedControlStack)
1687 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1688 if (LangOpts.hasSignReturnAddress())
1689 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1690 if (LangOpts.isSignReturnAddressScopeAll())
1691 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1693 if (!LangOpts.isSignReturnAddressWithAKey())
1694 getModule().addModuleFlag(llvm::Module::Min,
1695 "sign-return-address-with-bkey", 2);
1697 if (
T.isAArch64()) {
1709 if (LangOpts.PointerAuthReturns)
1710 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-returns", 1);
1711 if (LangOpts.PointerAuthAuthTraps)
1712 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-auth-traps", 1);
1713 if (LangOpts.PointerAuthIndirectGotos)
1714 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-indirect-gotos", 1);
1715 if (LangOpts.AArch64JumpTableHardening)
1716 getModule().addModuleFlag(llvm::Module::Max,
1717 "aarch64-jump-table-hardening", 1);
1725 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got",
1726 LangOpts.PointerAuthELFGOT);
1728 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-init-fini",
1729 LangOpts.PointerAuthCalls &&
1730 LangOpts.PointerAuthInitFini);
1732 llvm::Module::Error,
"ptrauth-init-fini-address-discrimination",
1733 LangOpts.PointerAuthCalls && LangOpts.PointerAuthInitFini &&
1734 LangOpts.PointerAuthInitFiniAddressDiscrimination);
1737 if (LangOpts.hasSignReturnAddressHardening()) {
1740 llvm::Module::Error,
"sign-return-address-harden",
1746 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-sign-personality",
1747 LangOpts.PointerAuthCalls);
1750 using namespace llvm::ELF;
1751 assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST < 32);
1752 uint32_t PAuthABIVersion =
1753 (LangOpts.PointerAuthIntrinsics
1754 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1755 (LangOpts.PointerAuthCalls
1756 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1757 (LangOpts.PointerAuthReturns
1758 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1759 (LangOpts.PointerAuthAuthTraps
1760 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1761 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1762 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1763 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1764 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1765 (LangOpts.PointerAuthInitFini
1766 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1767 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1768 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1769 (LangOpts.PointerAuthELFGOT
1770 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1771 (LangOpts.PointerAuthIndirectGotos
1772 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1773 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1774 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1775 (LangOpts.PointerAuthFunctionTypeDiscrimination
1776 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1777 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1778 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1779 "Update when new enum items are defined");
1784 getModule().addModuleFlag(llvm::Module::Error,
1785 "aarch64-elf-pauthabi-platform",
1786 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1788 llvm::Module::Error,
"aarch64-elf-pauthabi-version", PAuthABIVersion);
1791 if ((
T.isARM() ||
T.isThumb()) &&
getTriple().isTargetAEABI() &&
1793 uint32_t TagVal = 0;
1794 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1796 llvm::DenormalMode::getPositiveZero()) {
1797 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1799 llvm::DenormalMode::getIEEE()) {
1800 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1801 DenormalTagBehavior = llvm::Module::Override;
1803 llvm::DenormalMode::getPreserveSign()) {
1804 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1806 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1811 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1812 llvm::ARMBuildAttrs::Allowed);
1815 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1817 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1818 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1822 if (CodeGenOpts.StackClashProtector)
1824 llvm::Module::Override,
"probe-stack",
1825 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1827 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1828 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1829 CodeGenOpts.StackProbeSize);
1831 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1832 llvm::LLVMContext &Ctx = TheModule.getContext();
1834 llvm::Module::Error,
"MemProfProfileFilename",
1835 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1838 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1842 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1843 CodeGenOpts.FP32DenormalMode.Output !=
1844 llvm::DenormalMode::IEEE);
1847 if (LangOpts.EHAsynch)
1848 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1851 if (CodeGenOpts.ImportCallOptimization)
1852 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1862 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
1863 if (UnwindMode == llvm::WinX64EHUnwindMode::Default) {
1864 if (
T.isOSWindows() &&
T.isX86_64() &&
1865 Context.getTargetInfo().hasFeature(
"egpr"))
1866 UnwindMode = llvm::WinX64EHUnwindMode::V3;
1868 UnwindMode = llvm::WinX64EHUnwindMode::V1;
1870 if (UnwindMode != llvm::WinX64EHUnwindMode::V1)
1871 getModule().addModuleFlag(llvm::Module::Warning,
"winx64-eh-unwind",
1872 static_cast<unsigned>(UnwindMode));
1876 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1878 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1882 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1883 EmitOpenCLMetadata();
1890 auto Version = LangOpts.getOpenCLCompatibleVersion();
1891 llvm::Metadata *SPIRVerElts[] = {
1892 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1894 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1895 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1896 llvm::NamedMDNode *SPIRVerMD =
1897 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1898 llvm::LLVMContext &Ctx = TheModule.getContext();
1899 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1907 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1908 assert(PLevel < 3 &&
"Invalid PIC Level");
1909 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1910 if (Context.getLangOpts().PIE)
1911 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1915 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1916 .Case(
"tiny", llvm::CodeModel::Tiny)
1917 .Case(
"small", llvm::CodeModel::Small)
1918 .Case(
"kernel", llvm::CodeModel::Kernel)
1919 .Case(
"medium", llvm::CodeModel::Medium)
1920 .Case(
"large", llvm::CodeModel::Large)
1923 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1926 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1927 Context.getTargetInfo().getTriple().getArch() ==
1928 llvm::Triple::x86_64) {
1934 if (CodeGenOpts.NoPLT)
1937 CodeGenOpts.DirectAccessExternalData !=
1938 getModule().getDirectAccessExternalData()) {
1939 getModule().setDirectAccessExternalData(
1940 CodeGenOpts.DirectAccessExternalData);
1942 if (CodeGenOpts.UnwindTables)
1943 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1945 switch (CodeGenOpts.getFramePointer()) {
1950 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1953 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1956 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1959 getModule().setFramePointer(llvm::FramePointerKind::All);
1963 SimplifyPersonality();
1976 EmitVersionIdentMetadata();
1979 EmitCommandLineMetadata();
1987 getModule().setStackProtectorGuardSymbol(
1990 getModule().setStackProtectorGuardOffset(
1993 getModule().setStackProtectorGuardValueWidth(
1996 if (
getModule().getStackProtectorGuard() !=
"global") {
1997 Diags.Report(diag::err_opt_not_valid_without_opt)
1998 <<
"-mstack-protector-guard-record"
1999 <<
"-mstack-protector-guard=global";
2001 getModule().setStackProtectorGuardRecord(
true);
2006 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
2008 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
2010 if (
getContext().getTargetInfo().getMaxTLSAlign())
2011 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
2012 getContext().getTargetInfo().getMaxTLSAlign());
2030 if (!MustTailCallUndefinedGlobals.empty()) {
2032 for (
auto &I : MustTailCallUndefinedGlobals) {
2033 if (!I.first->isDefined())
2034 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
2038 if (!Entry || Entry->isWeakForLinker() ||
2039 Entry->isDeclarationForLinker())
2040 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
2044 for (
auto &I : MustTailCallUndefinedGlobals) {
2053 if (Entry->isDeclarationForLinker()) {
2056 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
2058 CalleeIsLocal = Entry->isDSOLocal();
2062 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
2075 llvm::MDBuilder MDB(TheModule.getContext());
2076 uint64_t Size = Context.getTypeSizeInChars(Context.IntTy).getQuantity();
2077 llvm::MDNode *StructNode =
2078 CodeGenOpts.NewStructPathTBAA
2079 ? MDB.createTBAATypeNode(TBAA->getChar(), Size,
2080 MDB.createString(
"__libc_errno"),
2081 {{0, Size, IntegerNode}})
2082 : MDB.createTBAAStructTypeNode(
"__libc_errno",
2083 {{IntegerNode, 0}});
2086 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
2087 ErrnoTBAAMD->addOperand(StructTagNode);
2092void CodeGenModule::EmitOpenCLMetadata() {
2097 unsigned CLVersion =
2100 auto EmitVersion = [
this](StringRef MDName,
int Version) {
2101 llvm::Metadata *OCLVerElts[] = {
2102 llvm::ConstantAsMetadata::get(
2103 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
2104 llvm::ConstantAsMetadata::get(
2105 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
2106 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
2107 llvm::LLVMContext &Ctx = TheModule.getContext();
2108 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
2111 EmitVersion(
"opencl.ocl.version", CLVersion);
2112 if (LangOpts.OpenCLCPlusPlus) {
2114 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
2118void CodeGenModule::EmitBackendOptionsMetadata(
2119 const CodeGenOptions &CodeGenOpts) {
2121 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
2122 CodeGenOpts.SmallDataLimit);
2126 if (LangOpts.AllocTokenMode) {
2127 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
2128 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
2129 llvm::MDString::get(VMContext, S));
2131 if (LangOpts.AllocTokenMax)
2133 llvm::Module::Error,
"alloc-token-max",
2134 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
2135 *LangOpts.AllocTokenMax));
2136 if (CodeGenOpts.SanitizeAllocTokenFastABI)
2137 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
2138 if (CodeGenOpts.SanitizeAllocTokenExtended)
2139 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
2155 return TBAA->getTypeInfo(QTy);
2174 return TBAA->getAccessInfo(AccessType);
2181 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
2187 return TBAA->getTBAAStructInfo(QTy);
2193 return TBAA->getBaseTypeInfo(QTy);
2199 return TBAA->getAccessTagInfo(Info);
2206 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
2214 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
2222 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
2228 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
2233 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
2245 std::string Msg =
Type;
2247 diag::err_codegen_unsupported)
2253 diag::err_codegen_unsupported)
2260 std::string Msg =
Type;
2262 diag::err_codegen_unsupported)
2267 llvm::function_ref<
void()> Fn) {
2268 StackHandler.runWithSufficientStackSpace(Loc, Fn);
2278 if (GV->hasLocalLinkage()) {
2279 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2292 if (Context.getLangOpts().OpenMP &&
2293 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
2294 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
2295 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
2296 OMPDeclareTargetDeclAttr::DT_NoHost &&
2298 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2305 if (Context.getLangOpts().CUDAIsDevice &&
2307 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
2308 bool NeedsProtected =
false;
2312 else if (
const auto *VD = dyn_cast<VarDecl>(D))
2313 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
2314 VD->hasAttr<CUDAConstantAttr>() ||
2315 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
2316 VD->getType()->isCUDADeviceBuiltinTextureType();
2317 if (NeedsProtected) {
2318 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2324 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2328 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
2332 if (GV->hasDLLExportStorageClass()) {
2335 diag::err_hidden_visibility_dllexport);
2338 diag::err_non_default_visibility_dllimport);
2344 !GV->isDeclarationForLinker())
2349 llvm::GlobalValue *GV) {
2350 if (GV->hasLocalLinkage())
2353 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
2357 if (GV->hasDLLImportStorageClass())
2360 const llvm::Triple &TT = CGM.
getTriple();
2362 if (TT.isOSCygMing()) {
2380 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2388 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2392 if (!TT.isOSBinFormatELF())
2398 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2406 return !(CGM.
getLangOpts().SemanticInterposition ||
2411 if (!GV->isDeclarationForLinker())
2417 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2424 if (CGOpts.DirectAccessExternalData) {
2430 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2431 if (!Var->isThreadLocal())
2456 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2458 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2468 if (D->
hasAttr<DLLImportAttr>())
2469 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2470 else if ((D->
hasAttr<DLLExportAttr>() ||
2472 !GV->isDeclarationForLinker())
2473 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2493 GV->setPartition(CodeGenOpts.SymbolPartition);
2497 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2498 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2499 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2500 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2501 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2504llvm::GlobalVariable::ThreadLocalMode
2506 switch (CodeGenOpts.getDefaultTLSModel()) {
2508 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2510 return llvm::GlobalVariable::LocalDynamicTLSModel;
2512 return llvm::GlobalVariable::InitialExecTLSModel;
2514 return llvm::GlobalVariable::LocalExecTLSModel;
2516 llvm_unreachable(
"Invalid TLS model!");
2520 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2522 llvm::GlobalValue::ThreadLocalMode TLM;
2526 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2530 GV->setThreadLocalMode(TLM);
2536 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2540 const CPUSpecificAttr *
Attr,
2557 !D->
hasAttr<AsmLabelAttr>() &&
2563 bool OmitMultiVersionMangling =
false,
2564 bool IgnoreAsmLabel =
false) {
2566 llvm::raw_svector_ostream Out(Buffer);
2570 bool ShouldMangle = !IgnoreAsmLabel
2574 if (!IgnoreAsmLabel)
2580 assert(II &&
"Attempt to mangle unnamed decl.");
2581 const auto *FD = dyn_cast<FunctionDecl>(ND);
2586 Out <<
"__regcall4__" << II->
getName();
2588 Out <<
"__regcall3__" << II->
getName();
2589 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2591 Out <<
"__device_stub__" << II->
getName();
2593 DeviceKernelAttr::isOpenCLSpelling(
2594 FD->getAttr<DeviceKernelAttr>()) &&
2596 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2612 "Hash computed when not explicitly requested");
2616 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2617 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2618 switch (FD->getMultiVersionKind()) {
2622 FD->getAttr<CPUSpecificAttr>(),
2626 auto *
Attr = FD->getAttr<TargetAttr>();
2627 assert(
Attr &&
"Expected TargetAttr to be present "
2628 "for attribute mangling");
2634 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2635 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2636 "for attribute mangling");
2642 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2643 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2644 "for attribute mangling");
2651 llvm_unreachable(
"None multiversion type isn't valid here");
2661 return std::string(Out.str());
2664void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2665 const FunctionDecl *FD,
2666 StringRef &CurName) {
2673 std::string NonTargetName =
2681 "Other GD should now be a multiversioned function");
2691 if (OtherName != NonTargetName) {
2694 const auto ExistingRecord = Manglings.find(NonTargetName);
2695 if (ExistingRecord != std::end(Manglings))
2696 Manglings.remove(&(*ExistingRecord));
2697 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2702 CurName = OtherNameRef;
2704 Entry->setName(OtherName);
2714 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2728 auto FoundName = MangledDeclNames.find(CanonicalGD);
2729 if (FoundName != MangledDeclNames.end())
2730 return FoundName->second;
2767 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2768 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2773 std::string MangledName =
2785 llvm::raw_svector_ostream Out(Buffer);
2788 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2789 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2791 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2796 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2797 return Result.first->first();
2801 auto it = MangledDeclNames.begin();
2802 while (it != MangledDeclNames.end()) {
2803 if (it->second == Name)
2818 llvm::Constant *AssociatedData) {
2820 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2826 bool IsDtorAttrFunc) {
2827 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2829 DtorsUsingAtExit[Priority].push_back(Dtor);
2834 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2837void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2838 if (Fns.empty())
return;
2841 llvm::PointerType *PtrTy = llvm::PointerType::get(
2842 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2845 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2849 auto Ctors = Builder.beginArray(CtorStructTy);
2850 for (
const auto &I : Fns) {
2851 auto Ctor = Ctors.beginStruct(CtorStructTy);
2852 Ctor.addInt(
Int32Ty, I.Priority);
2853 Ctor.add(I.Initializer);
2854 if (I.AssociatedData)
2855 Ctor.add(I.AssociatedData);
2857 Ctor.addNullPointer(PtrTy);
2858 Ctor.finishAndAddTo(Ctors);
2861 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2863 llvm::GlobalValue::AppendingLinkage);
2867 List->setAlignment(std::nullopt);
2872llvm::GlobalValue::LinkageTypes
2878 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2885 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2886 if (!MDS)
return nullptr;
2888 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2896 if (!UD->
hasAttr<TransparentUnionAttr>())
2898 if (!UD->
fields().empty())
2899 return UD->
fields().begin()->getType();
2908 bool GeneralizePointers) {
2921 bool GeneralizePointers) {
2924 for (
auto &Param : FnType->param_types())
2925 GeneralizedParams.push_back(
2929 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2930 GeneralizedParams, FnType->getExtProtoInfo());
2935 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2937 llvm_unreachable(
"Encountered unknown FunctionType");
2945 FnType->getReturnType(), FnType->getParamTypes(),
2946 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2948 std::string OutName;
2949 llvm::raw_string_ostream Out(OutName);
2957 Out <<
".normalized";
2959 Out <<
".generalized";
2961 return llvm::ConstantInt::get(
2967 llvm::Function *F,
bool IsThunk) {
2969 llvm::AttributeList PAL;
2972 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2976 Loc = D->getLocation();
2978 Error(Loc,
"__vectorcall calling convention is not currently supported");
2980 F->setAttributes(PAL);
2981 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2985 std::string ReadOnlyQual(
"__read_only");
2986 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2987 if (ReadOnlyPos != std::string::npos)
2989 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2991 std::string WriteOnlyQual(
"__write_only");
2992 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2993 if (WriteOnlyPos != std::string::npos)
2994 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2996 std::string ReadWriteQual(
"__read_write");
2997 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2998 if (ReadWritePos != std::string::npos)
2999 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
3032 assert(((FD && CGF) || (!FD && !CGF)) &&
3033 "Incorrect use - FD and CGF should either be both null or not!");
3059 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
3062 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
3067 std::string typeQuals;
3071 const Decl *PDecl = parm;
3073 PDecl = TD->getDecl();
3074 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
3075 if (A && A->isWriteOnly())
3076 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
3077 else if (A && A->isReadWrite())
3078 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
3080 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
3082 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
3084 auto getTypeSpelling = [&](
QualType Ty) {
3085 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
3087 if (Ty.isCanonical()) {
3088 StringRef typeNameRef = typeName;
3090 if (typeNameRef.consume_front(
"unsigned "))
3091 return std::string(
"u") + typeNameRef.str();
3092 if (typeNameRef.consume_front(
"signed "))
3093 return typeNameRef.str();
3103 addressQuals.push_back(
3104 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
3108 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
3109 std::string baseTypeName =
3111 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
3112 argBaseTypeNames.push_back(
3113 llvm::MDString::get(VMContext, baseTypeName));
3117 typeQuals =
"restrict";
3120 typeQuals += typeQuals.empty() ?
"const" :
" const";
3122 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
3124 uint32_t AddrSpc = 0;
3129 addressQuals.push_back(
3130 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
3134 std::string typeName = getTypeSpelling(ty);
3146 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
3147 argBaseTypeNames.push_back(
3148 llvm::MDString::get(VMContext, baseTypeName));
3153 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
3157 Fn->setMetadata(
"kernel_arg_addr_space",
3158 llvm::MDNode::get(VMContext, addressQuals));
3159 Fn->setMetadata(
"kernel_arg_access_qual",
3160 llvm::MDNode::get(VMContext, accessQuals));
3161 Fn->setMetadata(
"kernel_arg_type",
3162 llvm::MDNode::get(VMContext, argTypeNames));
3163 Fn->setMetadata(
"kernel_arg_base_type",
3164 llvm::MDNode::get(VMContext, argBaseTypeNames));
3165 Fn->setMetadata(
"kernel_arg_type_qual",
3166 llvm::MDNode::get(VMContext, argTypeQuals));
3170 Fn->setMetadata(
"kernel_arg_name",
3171 llvm::MDNode::get(VMContext, argNames));
3187SmallVector<const CXXRecordDecl *, 0>
3189 llvm::SetVector<const CXXRecordDecl *> MostBases;
3194 MostBases.insert(RD);
3196 CollectMostBases(B.getType()->getAsCXXRecordDecl());
3198 CollectMostBases(RD);
3199 return MostBases.takeVector();
3203 llvm::Function *F) {
3204 llvm::AttrBuilder B(F->getContext());
3206 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
3207 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
3209 if (CodeGenOpts.StackClashProtector)
3210 B.addAttribute(
"probe-stack",
"inline-asm");
3212 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
3213 B.addAttribute(
"stack-probe-size",
3214 std::to_string(CodeGenOpts.StackProbeSize));
3217 B.addAttribute(llvm::Attribute::NoUnwind);
3219 if (std::optional<llvm::Attribute::AttrKind>
Attr =
3221 B.addAttribute(*
Attr);
3226 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
3227 B.addAttribute(llvm::Attribute::AlwaysInline);
3231 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
3233 B.addAttribute(llvm::Attribute::NoInline);
3241 if (D->
hasAttr<ArmLocallyStreamingAttr>())
3242 B.addAttribute(
"aarch64_pstate_sm_body");
3245 if (
Attr->isNewZA())
3246 B.addAttribute(
"aarch64_new_za");
3247 if (
Attr->isNewZT0())
3248 B.addAttribute(
"aarch64_new_zt0");
3253 bool ShouldAddOptNone =
3254 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
3256 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
3257 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
3260 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
3261 !D->
hasAttr<NoInlineAttr>()) {
3262 B.addAttribute(llvm::Attribute::AlwaysInline);
3263 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
3264 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3266 B.addAttribute(llvm::Attribute::OptimizeNone);
3269 B.addAttribute(llvm::Attribute::NoInline);
3274 B.addAttribute(llvm::Attribute::Naked);
3277 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
3278 F->removeFnAttr(llvm::Attribute::MinSize);
3279 }
else if (D->
hasAttr<NakedAttr>()) {
3281 B.addAttribute(llvm::Attribute::Naked);
3282 B.addAttribute(llvm::Attribute::NoInline);
3283 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
3284 B.addAttribute(llvm::Attribute::NoDuplicate);
3285 }
else if (D->
hasAttr<NoInlineAttr>() &&
3286 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3288 B.addAttribute(llvm::Attribute::NoInline);
3289 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
3290 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
3292 B.addAttribute(llvm::Attribute::AlwaysInline);
3296 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
3297 B.addAttribute(llvm::Attribute::NoInline);
3301 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3304 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
3305 return Redecl->isInlineSpecified();
3307 if (any_of(FD->
redecls(), CheckRedeclForInline))
3312 return any_of(Pattern->
redecls(), CheckRedeclForInline);
3314 if (CheckForInline(FD)) {
3315 B.addAttribute(llvm::Attribute::InlineHint);
3316 }
else if (CodeGenOpts.getInlining() ==
3319 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3320 B.addAttribute(llvm::Attribute::NoInline);
3327 if (!D->
hasAttr<OptimizeNoneAttr>()) {
3329 if (!ShouldAddOptNone)
3330 B.addAttribute(llvm::Attribute::OptimizeForSize);
3331 B.addAttribute(llvm::Attribute::Cold);
3334 B.addAttribute(llvm::Attribute::Hot);
3335 if (D->
hasAttr<MinSizeAttr>())
3336 B.addAttribute(llvm::Attribute::MinSize);
3341 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3342 B.addAttribute(llvm::Attribute::NoOutline);
3347 if (CodeGenOpts.ModuleLocalHints) {
3348 const auto *FD = dyn_cast<FunctionDecl>(D);
3356 B.addAttribute(llvm::Attribute::LikelyModuleLocal);
3361 llvm::MaybeAlign ExplicitAlignment;
3362 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3363 ExplicitAlignment = llvm::Align(alignment);
3364 else if (LangOpts.FunctionAlignment)
3365 ExplicitAlignment = llvm::Align::fromLog2(LangOpts.FunctionAlignment);
3367 if (ExplicitAlignment) {
3368 F->setAlignment(ExplicitAlignment);
3369 F->setPreferredAlignment(ExplicitAlignment);
3370 }
else if (LangOpts.PreferredFunctionAlignment) {
3371 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3380 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3385 if (CodeGenOpts.SanitizeCfiCrossDso &&
3386 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3387 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3395 if (CodeGenOpts.CallGraphSection) {
3396 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3403 auto *MD = dyn_cast<CXXMethodDecl>(D);
3406 llvm::Metadata *Id =
3408 MD->getType(), std::nullopt,
Base));
3409 F->addTypeMetadata(0, Id);
3416 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3417 if (FD->
hasAttr<SYCLExternalAttr>())
3418 addSYCLModuleIdAttr(F);
3422void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3424 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3432 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FD))
3434 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FD))
3448 Linkage != llvm::GlobalValue::AvailableExternallyLinkage;
3453 if (isa_and_nonnull<NamedDecl>(D))
3456 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3458 if (D && D->
hasAttr<UsedAttr>())
3461 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3463 ((CodeGenOpts.KeepPersistentStorageVariables &&
3464 (VD->getStorageDuration() ==
SD_Static ||
3465 VD->getStorageDuration() ==
SD_Thread)) ||
3466 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3467 VD->getType().isConstQualified())))
3470 if (CodeGenOpts.KeepInlineFunctions)
3471 if (
const auto *FD = dyn_cast_if_present<FunctionDecl>(D))
3477static std::vector<std::string>
3479 llvm::StringMap<bool> &FeatureMap) {
3480 llvm::StringMap<bool> DefaultFeatureMap;
3484 std::vector<std::string> Delta;
3485 for (
const auto &[K,
V] : FeatureMap) {
3486 auto DefaultIt = DefaultFeatureMap.find(K);
3487 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3488 Delta.push_back((
V ?
"+" :
"-") + K.str());
3494bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3495 llvm::AttrBuilder &Attrs,
3496 bool SetTargetFeatures) {
3502 std::vector<std::string> Features;
3503 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3506 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3507 assert((!TD || !TV) &&
"both target_version and target specified");
3510 bool AddedAttr =
false;
3511 if (TD || TV || SD || TC) {
3512 llvm::StringMap<bool> FeatureMap;
3519 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3522 if (!FeatureStr.empty()) {
3523 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3524 if (!ParsedAttr.
CPU.empty() &&
3526 TargetCPU = ParsedAttr.
CPU;
3529 if (!ParsedAttr.
Tune.empty() &&
3531 TuneCPU = ParsedAttr.
Tune;
3547 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3548 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3549 Entry.getKey().str());
3555 llvm::StringMap<bool> FeatureMap;
3574 if (!TargetCPU.empty()) {
3575 Attrs.addAttribute(
"target-cpu", TargetCPU);
3578 if (!TuneCPU.empty()) {
3579 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3582 if (!Features.empty() && SetTargetFeatures) {
3583 llvm::erase_if(Features, [&](
const std::string& F) {
3586 if (!Features.empty()) {
3587 llvm::sort(Features);
3588 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3594 llvm::SmallVector<StringRef, 8> Feats;
3595 bool IsDefault =
false;
3597 IsDefault = TV->isDefaultVersion();
3598 TV->getFeatures(Feats);
3604 Attrs.addAttribute(
"fmv-features");
3606 }
else if (!Feats.empty()) {
3608 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3609 std::string FMVFeatures;
3610 for (StringRef F : OrderedFeats)
3611 FMVFeatures.append(
"," + F.str());
3612 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3619void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3620 llvm::GlobalObject *GO) {
3625 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3628 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3629 GV->addAttribute(
"bss-section", SA->getName());
3630 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3631 GV->addAttribute(
"data-section", SA->getName());
3632 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3633 GV->addAttribute(
"rodata-section", SA->getName());
3634 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3635 GV->addAttribute(
"relro-section", SA->getName());
3638 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3641 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3642 if (!D->
getAttr<SectionAttr>())
3643 F->setSection(SA->getName());
3645 llvm::AttrBuilder Attrs(F->getContext());
3646 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3650 llvm::AttributeMask RemoveAttrs;
3651 RemoveAttrs.addAttribute(
"target-cpu");
3652 RemoveAttrs.addAttribute(
"target-features");
3653 RemoveAttrs.addAttribute(
"fmv-features");
3654 RemoveAttrs.addAttribute(
"tune-cpu");
3655 F->removeFnAttrs(RemoveAttrs);
3656 F->addFnAttrs(Attrs);
3660 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3661 GO->setSection(CSA->getName());
3662 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3663 GO->setSection(SA->getName());
3676 F->setLinkage(llvm::Function::InternalLinkage);
3678 setNonAliasAttributes(GD, F);
3689 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3693 llvm::Function *F) {
3696 if (!F->hasLocalLinkage() ||
3697 F->getFunction().hasAddressTaken(
nullptr,
true,
3701 bool HasBody = FD->
hasBody(Def);
3702 if (!HasBody || !Def)
3719 ParamTypes.push_back(P->getType());
3727 llvm::LLVMContext::MD_callgraph,
3734 llvm::Function *F) {
3736 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3747 F->addTypeMetadata(0, MD);
3754 if (CodeGenOpts.SanitizeCfiCrossDso)
3756 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3760 llvm::CallBase *CB) {
3762 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3766 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
getLLVMContext(), {TypeIdMD});
3767 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3768 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3772 llvm::LLVMContext &Ctx = F->getContext();
3773 llvm::MDBuilder MDB(Ctx);
3774 llvm::StringRef Salt;
3777 if (
const auto &Info = FP->getExtraAttributeInfo())
3778 Salt = Info.CFISalt;
3780 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3789 return llvm::all_of(Name, [](
const char &
C) {
3790 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3796 for (
auto &F : M.functions()) {
3798 bool AddressTaken = F.hasAddressTaken();
3799 if (!AddressTaken && F.hasLocalLinkage())
3800 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3805 if (!AddressTaken || !F.isDeclaration())
3808 const llvm::ConstantInt *
Type;
3809 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3810 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3814 StringRef Name = F.getName();
3818 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3819 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3820 Twine(
Type->getSExtValue()) +
" */\n")
3822 M.appendModuleInlineAsm(
Asm);
3826void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3827 bool IsIncompleteFunction,
3830 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3838 if (!IsIncompleteFunction)
3845 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3847 assert(!F->arg_empty() &&
3848 F->arg_begin()->getType()
3849 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3850 "unexpected this return");
3851 F->addParamAttr(0, llvm::Attribute::Returned);
3861 if (!IsIncompleteFunction && F->isDeclaration())
3864 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3865 F->setSection(CSA->getName());
3866 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3867 F->setSection(SA->getName());
3869 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3871 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3872 else if (EA->isWarning())
3873 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3878 const FunctionDecl *FDBody;
3879 bool HasBody = FD->
hasBody(FDBody);
3881 assert(HasBody &&
"Inline builtin declarations should always have an "
3883 if (shouldEmitFunction(FDBody))
3884 F->addFnAttr(llvm::Attribute::NoBuiltin);
3890 F->addFnAttr(llvm::Attribute::NoBuiltin);
3894 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3895 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3896 if (MD->isVirtual())
3897 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3903 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3904 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3907 if (CodeGenOpts.CallGraphSection)
3910 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3916 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3917 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3919 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3923 llvm::LLVMContext &Ctx = F->getContext();
3924 llvm::MDBuilder MDB(Ctx);
3928 int CalleeIdx = *CB->encoding_begin();
3929 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3930 F->addMetadata(llvm::LLVMContext::MD_callback,
3931 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3932 CalleeIdx, PayloadIndices,
3939 "Only globals with definition can force usage.");
3940 LLVMUsed.emplace_back(GV);
3944 assert(!GV->isDeclaration() &&
3945 "Only globals with definition can force usage.");
3946 LLVMCompilerUsed.emplace_back(GV);
3951 "Only globals with definition can force usage.");
3953 LLVMCompilerUsed.emplace_back(GV);
3955 LLVMUsed.emplace_back(GV);
3959 std::vector<llvm::WeakTrackingVH> &List) {
3969 UsedArray.reserve(List.size());
3970 for (
const llvm::WeakTrackingVH &VH : List) {
3971 if (llvm::Value *
V = VH)
3972 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3976 if (UsedArray.empty())
3978 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3980 auto *GV =
new llvm::GlobalVariable(
3981 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3982 llvm::ConstantArray::get(ATy, UsedArray), Name);
3984 GV->setSection(
"llvm.metadata");
3987void CodeGenModule::emitLLVMUsed() {
3988 emitUsed(*
this,
"llvm.used", LLVMUsed);
3989 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3994 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
4003 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
4009 ELFDependentLibraries.push_back(
4010 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
4017 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
4024void CodeGenModule::ProcessPragmaCommentCopyright(StringRef Comment,
4025 bool isFromASTFile) {
4027 "pragma comment copyright is supported only when targeting AIX");
4040 assert(!LoadTimeCommentGlobal &&
4041 "Only one copyright pragma allowed per translation unit.");
4046 uint64_t Hash = xxh3_64bits(Comment);
4047 std::string GlobalName =
4048 (
"__loadtime_comment_str_" + Twine::utohexstr(Hash)).str();
4051 llvm::Constant *StrInit =
4052 llvm::ConstantDataArray::getString(
C, Comment,
true);
4055 auto *GV =
new llvm::GlobalVariable(
getModule(), StrInit->getType(),
4057 llvm::GlobalValue::WeakODRLinkage,
4058 StrInit, GlobalName);
4060 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4061 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4062 GV->setAlignment(llvm::Align(1));
4068 GV->setSection(
"__loadtime_comment");
4071 GV->setMetadata(
"loadtime_comment", llvm::MDNode::get(
C, {}));
4074 llvm::appendToCompilerUsed(
getModule(), {GV});
4076 LoadTimeCommentGlobal = GV;
4085 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
4091 if (Visited.insert(Import).second)
4108 if (LL.IsFramework) {
4109 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
4110 llvm::MDString::get(Context, LL.Library)};
4112 Metadata.push_back(llvm::MDNode::get(Context, Args));
4118 llvm::Metadata *Args[2] = {
4119 llvm::MDString::get(Context,
"lib"),
4120 llvm::MDString::get(Context, LL.Library),
4122 Metadata.push_back(llvm::MDNode::get(Context, Args));
4126 auto *OptString = llvm::MDString::get(Context, Opt);
4127 Metadata.push_back(llvm::MDNode::get(Context, OptString));
4132void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
4134 "We should only emit module initializers for named modules.");
4142 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
4159 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
4165void CodeGenModule::EmitModuleLinkOptions() {
4169 llvm::SetVector<clang::Module *> LinkModules;
4170 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4171 SmallVector<clang::Module *, 16> Stack;
4174 for (
Module *M : ImportedModules) {
4177 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
4180 if (Visited.insert(M).second)
4186 while (!Stack.empty()) {
4189 bool AnyChildren =
false;
4198 if (Visited.insert(SM).second) {
4199 Stack.push_back(SM);
4207 LinkModules.insert(Mod);
4214 SmallVector<llvm::MDNode *, 16> MetadataArgs;
4216 for (
Module *M : LinkModules)
4217 if (Visited.insert(M).second)
4219 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
4220 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
4223 if (!LinkerOptionsMetadata.empty()) {
4224 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
4225 for (
auto *MD : LinkerOptionsMetadata)
4226 NMD->addOperand(MD);
4230void CodeGenModule::EmitDeferred() {
4239 if (!DeferredVTables.empty()) {
4240 EmitDeferredVTables();
4245 assert(DeferredVTables.empty());
4252 llvm::append_range(DeferredDeclsToEmit,
4256 if (DeferredDeclsToEmit.empty())
4261 std::vector<GlobalDecl> CurDeclsToEmit;
4262 CurDeclsToEmit.swap(DeferredDeclsToEmit);
4264 for (GlobalDecl &D : CurDeclsToEmit) {
4270 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
4274 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
4295 if (GV && !GV->isDeclaration()) {
4296 GlobalDecl ExistingGD;
4319 if (!GV->isDeclaration())
4323 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
4327 EmitGlobalDefinition(D, GV);
4332 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
4334 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
4339void CodeGenModule::EmitVTablesOpportunistically() {
4345 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
4346 &&
"Only emit opportunistic vtables with optimizations");
4348 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
4350 "This queue should only contain external vtables");
4351 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
4352 VTables.GenerateClassData(RD);
4354 OpportunisticVTables.clear();
4358 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
4363 DeferredAnnotations.clear();
4365 if (Annotations.empty())
4369 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
4370 Annotations[0]->
getType(), Annotations.size()), Annotations);
4371 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
4372 llvm::GlobalValue::AppendingLinkage,
4373 Array,
"llvm.global.annotations");
4378 llvm::Constant *&AStr = AnnotationStrings[Str];
4383 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
4384 auto *gv =
new llvm::GlobalVariable(
4385 getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s,
4386 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
4389 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4407 return llvm::ConstantInt::get(
Int32Ty, LineNo);
4415 llvm::FoldingSetNodeID ID;
4416 for (
Expr *E : Exprs) {
4419 llvm::Constant *&Lookup = AnnotationArgs[ID.computeHash()];
4424 LLVMArgs.reserve(Exprs.size());
4426 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
4428 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
4431 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
4432 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
4433 llvm::GlobalValue::PrivateLinkage,
Struct,
4436 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4443 const AnnotateAttr *AA,
4451 llvm::Constant *GVInGlobalsAS = GV;
4452 if (GV->getAddressSpace() !=
4454 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
4456 llvm::PointerType::get(
4457 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
4461 llvm::Constant *Fields[] = {
4462 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
4464 return llvm::ConstantStruct::getAnon(Fields);
4468 llvm::GlobalValue *GV) {
4469 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4479 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4482 auto &SM = Context.getSourceManager();
4483 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
4484 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4489 return NoSanitizeL.containsLocation(Kind, Loc);
4492 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4496 llvm::GlobalVariable *GV,
4498 StringRef Category)
const {
4500 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4502 auto &SM = Context.getSourceManager();
4503 if (NoSanitizeL.containsMainFile(
4504 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
4507 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4514 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4515 Ty = AT->getElementType();
4520 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4528 StringRef Category)
const {
4531 auto Attr = ImbueAttr::NONE;
4533 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4534 if (
Attr == ImbueAttr::NONE)
4535 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4537 case ImbueAttr::NONE:
4539 case ImbueAttr::ALWAYS:
4540 Fn->addFnAttr(
"function-instrument",
"xray-always");
4542 case ImbueAttr::ALWAYS_ARG1:
4543 Fn->addFnAttr(
"function-instrument",
"xray-always");
4544 Fn->addFnAttr(
"xray-log-args",
"1");
4546 case ImbueAttr::NEVER:
4547 Fn->addFnAttr(
"function-instrument",
"xray-never");
4560 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4570 auto &SM = Context.getSourceManager();
4571 if (
auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
4585 if (NumGroups > 1) {
4586 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4595 if (LangOpts.EmitAllDecls)
4598 const auto *VD = dyn_cast<VarDecl>(
Global);
4600 ((CodeGenOpts.KeepPersistentStorageVariables &&
4601 (VD->getStorageDuration() ==
SD_Static ||
4602 VD->getStorageDuration() ==
SD_Thread)) ||
4603 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4604 VD->getType().isConstQualified())))
4607 if (CodeGenOpts.KeepInlineFunctions)
4608 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global))
4629 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4630 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4631 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4632 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4636 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4646 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4653 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4654 if (Context.getInlineVariableDefinitionKind(VD) ==
4659 if (CXX20ModuleInits && VD->getOwningModule() &&
4660 !VD->getOwningModule()->isModuleMapModule()) {
4669 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4672 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4685 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4689 llvm::Constant *
Init;
4692 if (!
V.isAbsent()) {
4703 llvm::Constant *Fields[4] = {
4707 llvm::ConstantDataArray::getRaw(
4708 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4710 Init = llvm::ConstantStruct::getAnon(Fields);
4713 auto *GV =
new llvm::GlobalVariable(
4715 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4717 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4720 if (!
V.isAbsent()) {
4733 llvm::GlobalVariable **Entry =
nullptr;
4734 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4739 llvm::Constant *
Init;
4743 assert(!
V.isAbsent());
4747 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4749 llvm::GlobalValue::PrivateLinkage,
Init,
4751 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4766 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4770 llvm::Constant *
Init =
Emitter.emitForInitializer(
4778 llvm::GlobalValue::LinkageTypes
Linkage =
4780 ? llvm::GlobalValue::LinkOnceODRLinkage
4781 : llvm::GlobalValue::InternalLinkage;
4782 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4786 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4793 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4794 assert(AA &&
"No alias?");
4804 llvm::Constant *Aliasee;
4806 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4814 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4815 WeakRefReferences.insert(F);
4823 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4826 const auto *AA =
Global->getAttr<AliasAttr>();
4834 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4835 if (LangOpts.OpenMPIsTargetDevice)
4836 return !AliaseeDecl ||
4837 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4840 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4841 const bool AliaseeHasDeviceAttr =
4842 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4844 if (LangOpts.CUDAIsDevice)
4845 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4856 if (
Global->hasAttr<WeakRefAttr>())
4861 if (
Global->hasAttr<AliasAttr>()) {
4864 return EmitAliasDefinition(GD);
4868 if (
Global->hasAttr<IFuncAttr>())
4869 return emitIFuncDefinition(GD);
4872 if (
Global->hasAttr<CPUDispatchAttr>())
4873 return emitCPUDispatchDefinition(GD);
4879 if (LangOpts.OpenMP) {
4881 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4883 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4884 if (MustBeEmitted(
Global))
4888 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4889 if (MustBeEmitted(
Global))
4896 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4897 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4903 if (FD->
hasAttr<AnnotateAttr>()) {
4906 DeferredAnnotations[MangledName.str()] = FD;
4921 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4927 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4929 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4930 if (LangOpts.OpenMP) {
4932 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4933 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4937 if (VD->hasExternalStorage() &&
4938 Res != OMPDeclareTargetDeclAttr::MT_Link)
4941 bool UnifiedMemoryEnabled =
4943 if (*Res == OMPDeclareTargetDeclAttr::MT_Local ||
4944 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4945 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4946 !UnifiedMemoryEnabled)) {
4949 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4950 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4951 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4952 UnifiedMemoryEnabled)) &&
4953 "Link clause or to clause with unified memory expected.");
4963 if (LangOpts.HLSL) {
4964 if (VD->getStorageClass() ==
SC_Extern) {
4973 if (Context.getInlineVariableDefinitionKind(VD) ==
4983 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4985 EmitGlobalDefinition(GD);
4986 addEmittedDeferredDecl(GD);
4994 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4995 CXXGlobalInits.push_back(
nullptr);
5001 addDeferredDeclToEmit(GD);
5002 }
else if (MustBeEmitted(
Global)) {
5004 assert(!MayBeEmittedEagerly(
Global));
5005 addDeferredDeclToEmit(GD);
5010 DeferredDecls[MangledName] = GD;
5016 if (
const auto *RT =
5017 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
5018 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5019 RD = RD->getDefinitionOrSelf();
5020 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
5029struct DLLImportFunctionVisitor
5030 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
5031 bool SafeToInline =
true;
5033 bool shouldVisitImplicitCode()
const {
return true; }
5035 bool VisitVarDecl(VarDecl *VD) {
5038 SafeToInline =
false;
5039 return SafeToInline;
5046 return SafeToInline;
5049 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
5051 SafeToInline = D->
hasAttr<DLLImportAttr>();
5052 return SafeToInline;
5055 bool VisitDeclRefExpr(DeclRefExpr *E) {
5058 SafeToInline = VD->
hasAttr<DLLImportAttr>();
5059 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
5060 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
5061 return SafeToInline;
5064 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
5066 return SafeToInline;
5069 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
5073 SafeToInline =
true;
5075 SafeToInline = M->
hasAttr<DLLImportAttr>();
5077 return SafeToInline;
5080 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
5082 return SafeToInline;
5085 bool VisitCXXNewExpr(CXXNewExpr *E) {
5087 return SafeToInline;
5092bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
5099 if (F->isInlineBuiltinDeclaration())
5102 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
5107 if (
const Module *M = F->getOwningModule();
5108 M && M->getTopLevelModule()->isNamedModule() &&
5109 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
5119 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
5124 if (F->hasAttr<NoInlineAttr>())
5127 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
5129 DLLImportFunctionVisitor Visitor;
5130 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
5131 if (!Visitor.SafeToInline)
5134 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
5141 for (
const CXXBaseSpecifier &B :
Dtor->getParent()->bases())
5155bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
5156 return CodeGenOpts.OptimizationLevel > 0;
5159void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
5160 llvm::GlobalValue *GV) {
5164 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
5165 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
5167 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
5168 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
5169 if (TC->isFirstOfVersion(I))
5172 EmitGlobalFunctionDefinition(GD, GV);
5178 AddDeferredMultiVersionResolverToEmit(GD);
5180 GetOrCreateMultiVersionResolver(GD);
5184void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
5187 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
5188 Context.getSourceManager(),
5189 "Generating code for declaration");
5191 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5194 if (!shouldEmitFunction(GD))
5197 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
5199 llvm::raw_string_ostream
OS(Name);
5205 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
5209 ABI->emitCXXStructor(GD);
5211 EmitMultiVersionFunctionDefinition(GD, GV);
5213 EmitGlobalFunctionDefinition(GD, GV);
5222 return EmitMultiVersionFunctionDefinition(GD, GV);
5223 return EmitGlobalFunctionDefinition(GD, GV);
5226 if (
const auto *VD = dyn_cast<VarDecl>(D))
5227 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
5229 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
5233 llvm::Function *NewFn);
5249static llvm::GlobalValue::LinkageTypes
5253 return llvm::GlobalValue::InternalLinkage;
5254 return llvm::GlobalValue::WeakODRLinkage;
5257void CodeGenModule::emitMultiVersionFunctions() {
5258 std::vector<GlobalDecl> MVFuncsToEmit;
5259 MultiVersionFuncs.swap(MVFuncsToEmit);
5260 for (GlobalDecl GD : MVFuncsToEmit) {
5262 assert(FD &&
"Expected a FunctionDecl");
5264 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
5265 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
5269 if (
Decl->isDefined()) {
5270 EmitGlobalFunctionDefinition(CurGD,
nullptr);
5278 assert(
Func &&
"This should have just been created");
5286 bool ShouldEmitResolver = !
getTriple().isAArch64();
5287 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5288 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
5291 FD, [&](
const FunctionDecl *CurFD) {
5292 llvm::SmallVector<StringRef, 8> Feats;
5295 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
5297 TA->getX86AddedFeatures(Feats);
5298 llvm::Function *
Func = createFunction(CurFD);
5299 DeclMap.insert({
Func, CurFD});
5300 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
5301 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
5302 if (TVA->isDefaultVersion() && IsDefined)
5303 ShouldEmitResolver =
true;
5304 llvm::Function *
Func = createFunction(CurFD);
5305 DeclMap.insert({
Func, CurFD});
5307 TVA->getFeatures(Feats, Delim);
5308 Options.emplace_back(
Func, Feats);
5309 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
5310 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
5311 if (!TC->isFirstOfVersion(I))
5313 if (TC->isDefaultVersion(I) && IsDefined)
5314 ShouldEmitResolver =
true;
5315 llvm::Function *
Func = createFunction(CurFD, I);
5316 DeclMap.insert({
Func, CurFD});
5319 TC->getX86Feature(Feats, I);
5320 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
5323 TC->getFeatures(Feats, I, Delim);
5324 Options.emplace_back(
Func, Feats);
5328 llvm_unreachable(
"unexpected MultiVersionKind");
5331 if (!ShouldEmitResolver)
5334 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
5335 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
5336 ResolverConstant = IFunc->getResolver();
5341 *
this, GD, FD,
true);
5348 auto *Alias = llvm::GlobalAlias::create(
5350 MangledName +
".ifunc", IFunc, &
getModule());
5359 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
5360 const CodeGenFunction::FMVResolverOption &RHS) {
5366 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
5367 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
5368 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
5369 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
5370 return LHS.isSubsetOf(RHS);
5372 Diags.Report(DeclMap[I->Function]->getLocation(),
5373 diag::warn_unreachable_version)
5374 << I->Function->getName();
5375 assert(I->Function->user_empty() &&
"unexpected users");
5376 I->Function->eraseFromParent();
5377 I->Function =
nullptr;
5381 CodeGenFunction CGF(*
this);
5382 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5384 setMultiVersionResolverAttributes(ResolverFunc, GD);
5386 ResolverFunc->setComdat(
5387 getModule().getOrInsertComdat(ResolverFunc->getName()));
5393 if (!MVFuncsToEmit.empty())
5398 if (!MultiVersionFuncs.empty())
5399 emitMultiVersionFunctions();
5409 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5411 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5412 llvm::GlobalVariable::ExternalWeakLinkage,
5414 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5419void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5420 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5422 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5424 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5425 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5426 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5427 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5429 DS->takeName(OldDS);
5430 OldDS->replaceAllUsesWith(DS);
5431 OldDS->eraseFromParent();
5437 llvm::Constant *
New) {
5440 Old->replaceAllUsesWith(
New);
5441 Old->eraseFromParent();
5444void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5446 assert(FD &&
"Not a FunctionDecl?");
5448 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5449 assert(DD &&
"Not a cpu_dispatch Function?");
5455 UpdateMultiVersionNames(GD, FD, ResolverName);
5457 llvm::Type *ResolverType;
5458 GlobalDecl ResolverGD;
5460 ResolverType = llvm::FunctionType::get(
5466 ResolverType = DeclTy;
5471 ResolverName, ResolverType, ResolverGD,
false));
5474 ResolverFunc->setComdat(
5475 getModule().getOrInsertComdat(ResolverFunc->getName()));
5477 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5480 for (
const IdentifierInfo *II : DD->cpus()) {
5488 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5491 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5497 Func = GetOrCreateLLVMFunction(
5498 MangledName, DeclTy, ExistingDecl,
5504 llvm::SmallVector<StringRef, 32> Features;
5505 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5506 llvm::transform(Features, Features.begin(),
5507 [](StringRef Str) { return Str.substr(1); });
5508 llvm::erase_if(Features, [&Target](StringRef Feat) {
5509 return !Target.validateCpuSupports(Feat);
5515 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5516 const CodeGenFunction::FMVResolverOption &RHS) {
5517 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5518 llvm::X86::getCpuSupportsMask(RHS.
Features);
5525 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5526 (Options.end() - 2)->Features),
5527 [](
auto X) { return X == 0; })) {
5528 StringRef LHSName = (Options.end() - 2)->Function->getName();
5529 StringRef RHSName = (Options.end() - 1)->Function->getName();
5530 if (LHSName.compare(RHSName) < 0)
5531 Options.erase(Options.end() - 2);
5533 Options.erase(Options.end() - 1);
5536 CodeGenFunction CGF(*
this);
5537 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5538 setMultiVersionResolverAttributes(ResolverFunc, GD);
5543 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5548 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5554 std::string AliasName =
5558 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5566void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5568 assert(FD &&
"Not a FunctionDecl?");
5571 std::string MangledName =
5573 if (!DeferredResolversToEmit.insert(MangledName).second)
5576 MultiVersionFuncs.push_back(GD);
5582llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5584 assert(FD &&
"Not a FunctionDecl?");
5586 std::string MangledName =
5591 std::string ResolverName = MangledName;
5595 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5599 ResolverName +=
".ifunc";
5606 ResolverName +=
".resolver";
5609 bool ShouldReturnIFunc =
5628 AddDeferredMultiVersionResolverToEmit(GD);
5632 if (ShouldReturnIFunc) {
5634 llvm::Type *ResolverType = llvm::FunctionType::get(
5636 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5637 MangledName +
".resolver", ResolverType, GlobalDecl{},
5645 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5647 GIF->setName(ResolverName);
5654 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5655 ResolverName, DeclTy, GlobalDecl{},
false);
5657 "Resolver should be created for the first time");
5662void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5664 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5677 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5688bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5689 const llvm::GlobalValue *GV)
const {
5690 auto SC = GV->getDLLStorageClass();
5691 if (SC == llvm::GlobalValue::DefaultStorageClass)
5694 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5695 !MRD->
hasAttr<DLLImportAttr>()) ||
5696 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5697 !MRD->
hasAttr<DLLExportAttr>())) &&
5708llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5709 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5710 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5714 std::string NameWithoutMultiVersionMangling;
5715 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5717 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5718 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5719 !DontDefer && !IsForDefinition) {
5722 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5724 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5727 GDDef = GlobalDecl(FDDef);
5735 UpdateMultiVersionNames(GD, FD, MangledName);
5736 if (!IsForDefinition) {
5742 AddDeferredMultiVersionResolverToEmit(GD);
5744 *
this, GD, FD,
true);
5753 *
this, GD, FD,
true);
5755 return GetOrCreateMultiVersionResolver(GD);
5760 if (!NameWithoutMultiVersionMangling.empty())
5761 MangledName = NameWithoutMultiVersionMangling;
5766 if (WeakRefReferences.erase(Entry)) {
5767 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5768 if (FD && !FD->
hasAttr<WeakAttr>())
5769 Entry->setLinkage(llvm::Function::ExternalLinkage);
5773 if (D && shouldDropDLLAttribute(D, Entry)) {
5774 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5780 if (IsForDefinition && !Entry->isDeclaration()) {
5787 DiagnosedConflictingDefinitions.insert(GD).second) {
5791 diag::note_previous_definition);
5796 (Entry->getValueType() == Ty)) {
5803 if (!IsForDefinition)
5810 bool IsIncompleteFunction =
false;
5812 llvm::FunctionType *FTy;
5816 FTy = llvm::FunctionType::get(
VoidTy,
false);
5817 IsIncompleteFunction =
true;
5821 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5822 Entry ? StringRef() : MangledName, &
getModule());
5826 if (D && D->
hasAttr<AnnotateAttr>())
5844 if (!Entry->use_empty()) {
5846 Entry->removeDeadConstantUsers();
5852 assert(F->getName() == MangledName &&
"name was uniqued!");
5854 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5855 if (ExtraAttrs.hasFnAttrs()) {
5856 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5864 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5867 addDeferredDeclToEmit(GD);
5872 auto DDI = DeferredDecls.find(MangledName);
5873 if (DDI != DeferredDecls.end()) {
5877 addDeferredDeclToEmit(DDI->second);
5878 DeferredDecls.erase(DDI);
5906 if (!IsIncompleteFunction) {
5907 assert(F->getFunctionType() == Ty);
5925 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5935 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5938 DD->getParent()->getNumVBases() == 0)
5943 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5944 false, llvm::AttributeList(),
5947 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5951 if (IsForDefinition)
5959 llvm::GlobalValue *F =
5962 return llvm::NoCFIValue::get(F);
5972 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5975 if (!
C.getLangOpts().CPlusPlus)
5980 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5981 ?
C.Idents.get(
"terminate")
5982 :
C.Idents.get(Name);
5984 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5988 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5989 for (
const auto *
Result : LSD->lookup(&NS))
5990 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5995 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
6004 llvm::Function *F, StringRef Name) {
6013 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
6014 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6015 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
6022 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
6023 if (AssumeConvergent) {
6025 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
6028 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
6033 llvm::Constant *
C = GetOrCreateLLVMFunction(
6035 false,
false, ExtraAttrs);
6037 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
6053 llvm::AttributeList ExtraAttrs,
bool Local,
6054 bool AssumeConvergent) {
6055 if (AssumeConvergent) {
6057 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
6061 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
6065 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
6074 markRegisterParameterAttributes(F);
6100 if (WeakRefReferences.erase(Entry)) {
6101 if (D && !D->
hasAttr<WeakAttr>())
6102 Entry->setLinkage(llvm::Function::ExternalLinkage);
6106 if (D && shouldDropDLLAttribute(D, Entry))
6107 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
6109 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
6112 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
6117 if (IsForDefinition && !Entry->isDeclaration()) {
6125 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
6127 DiagnosedConflictingDefinitions.insert(D).second) {
6131 diag::note_previous_definition);
6136 if (Entry->getType()->getAddressSpace() != TargetAS &&
6138 return llvm::ConstantExpr::getAddrSpaceCast(
6139 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
6143 if (!IsForDefinition)
6149 auto *GV =
new llvm::GlobalVariable(
6150 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
6151 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
6152 getContext().getTargetAddressSpace(DAddrSpace));
6157 GV->takeName(Entry);
6159 if (!Entry->use_empty()) {
6160 Entry->replaceAllUsesWith(GV);
6163 Entry->eraseFromParent();
6169 auto DDI = DeferredDecls.find(MangledName);
6170 if (DDI != DeferredDecls.end()) {
6173 addDeferredDeclToEmit(DDI->second);
6174 DeferredDecls.erase(DDI);
6179 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
6186 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
6192 CXXThreadLocals.push_back(D);
6200 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
6201 EmitGlobalVarDefinition(D);
6206 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
6207 GV->setSection(SA->getName());
6211 if (
getTriple().getArch() == llvm::Triple::xcore &&
6215 GV->setSection(
".cp.rodata");
6218 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
6219 GV->setCodeModel(CMA->getModel());
6224 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
6228 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
6229 bool HasMutableFields =
Record &&
Record->hasMutableFields();
6230 if (!HasMutableFields) {
6237 auto *InitType =
Init->getType();
6238 if (GV->getValueType() != InitType) {
6243 GV->setName(StringRef());
6248 ->stripPointerCasts());
6251 GV->eraseFromParent();
6254 GV->setInitializer(
Init);
6255 GV->setConstant(
true);
6256 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
6276 SanitizerMD->reportGlobal(GV, *D);
6281 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
6295 false, IsForDefinition);
6316 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
6317 llvm::Align Alignment) {
6318 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
6319 llvm::GlobalVariable *OldGV =
nullptr;
6323 if (GV->getValueType() == Ty)
6328 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
6333 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
6338 GV->takeName(OldGV);
6340 if (!OldGV->use_empty()) {
6341 OldGV->replaceAllUsesWith(GV);
6344 OldGV->eraseFromParent();
6348 !GV->hasAvailableExternallyLinkage())
6349 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6351 GV->setAlignment(Alignment);
6388 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
6396 if (GV && !GV->isDeclaration())
6401 if (!MustBeEmitted(D) && !GV) {
6402 DeferredDecls[MangledName] = D;
6407 EmitGlobalVarDefinition(D);
6412 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6414 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6429 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6433 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6436 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6438 if (!Fn->getSubprogram())
6444 return Context.toCharUnitsFromBits(
6449 if (LangOpts.OpenCL) {
6460 if (LangOpts.SYCLIsDevice &&
6464 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6469 if (D->
hasAttr<CUDAConstantAttr>())
6471 if (D->
hasAttr<CUDASharedAttr>())
6473 if (D->
hasAttr<CUDADeviceAttr>())
6481 if (LangOpts.OpenMP) {
6483 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6501static llvm::Constant *
6503 llvm::GlobalVariable *GV) {
6504 llvm::Constant *Cast = GV;
6509 GV, llvm::PointerType::get(
6516template<
typename SomeDecl>
6518 llvm::GlobalValue *GV) {
6533 const SomeDecl *
First = D->getFirstDecl();
6534 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6540 std::pair<StaticExternCMap::iterator, bool> R =
6541 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6546 R.first->second =
nullptr;
6554 llvm::GlobalObject &GO) {
6557 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6565void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6582 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6583 OpenMPRuntime->emitTargetGlobalVariable(D))
6586 llvm::TrackingVH<llvm::Constant>
Init;
6587 bool NeedsGlobalCtor =
false;
6591 bool IsDefinitionAvailableExternally =
6593 bool NeedsGlobalDtor =
6594 !IsDefinitionAvailableExternally &&
6601 if (IsDefinitionAvailableExternally &&
6612 std::optional<ConstantEmitter> emitter;
6617 bool IsCUDASharedVar =
6622 bool IsCUDAShadowVar =
6624 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6625 D->
hasAttr<CUDASharedAttr>());
6626 bool IsCUDADeviceShadowVar =
6631 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6632 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6636 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6639 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6640 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6641 }
else if (!InitExpr) {
6654 initializedGlobalDecl = GlobalDecl(D);
6655 emitter.emplace(*
this);
6656 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6664 if (!IsDefinitionAvailableExternally)
6665 NeedsGlobalCtor =
true;
6669 NeedsGlobalCtor =
false;
6681 DelayedCXXInitPosition.erase(D);
6688 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6693 llvm::Type* InitType =
Init->getType();
6694 llvm::Constant *Entry =
6698 Entry = Entry->stripPointerCasts();
6701 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6712 if (!GV || GV->getValueType() != InitType ||
6713 GV->getType()->getAddressSpace() !=
6717 Entry->setName(StringRef());
6722 ->stripPointerCasts());
6725 llvm::Constant *NewPtrForOldDecl =
6726 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6728 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6736 if (D->
hasAttr<AnnotateAttr>())
6749 if (LangOpts.CUDA) {
6750 if (LangOpts.CUDAIsDevice) {
6753 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6756 GV->setExternallyInitialized(
true);
6763 if (LangOpts.HLSL &&
6768 GV->setExternallyInitialized(
true);
6770 GV->setInitializer(
Init);
6777 emitter->finalize(GV);
6780 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6781 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6785 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6786 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6788 GV->setConstant(
true);
6793 if (std::optional<CharUnits> AlignValFromAllocate =
6795 AlignVal = *AlignValFromAllocate;
6813 Linkage == llvm::GlobalValue::ExternalLinkage &&
6814 Context.getTargetInfo().getTriple().isOSDarwin() &&
6816 Linkage = llvm::GlobalValue::InternalLinkage;
6821 if (LangOpts.HLSL &&
6823 Linkage = llvm::GlobalValue::ExternalLinkage;
6826 if (D->
hasAttr<DLLImportAttr>())
6827 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6828 else if (D->
hasAttr<DLLExportAttr>())
6829 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6831 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6833 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6835 GV->setConstant(
false);
6840 if (!GV->getInitializer()->isNullValue())
6841 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6844 setNonAliasAttributes(D, GV);
6846 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6848 CXXThreadLocals.push_back(D);
6855 if (NeedsGlobalCtor || NeedsGlobalDtor)
6856 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6858 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6863 DI->EmitGlobalVariable(GV, D);
6866llvm::GlobalValue::LinkageTypes
6870 return llvm::Function::InternalLinkage;
6873 return llvm::GlobalVariable::WeakAnyLinkage;
6877 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6882 return llvm::GlobalValue::AvailableExternallyLinkage;
6896 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6897 : llvm::Function::InternalLinkage;
6911 return llvm::Function::ExternalLinkage;
6914 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6915 : llvm::Function::InternalLinkage;
6916 return llvm::Function::WeakODRLinkage;
6923 CodeGenOpts.NoCommon))
6924 return llvm::GlobalVariable::CommonLinkage;
6930 if (D->
hasAttr<SelectAnyAttr>())
6931 return llvm::GlobalVariable::WeakODRLinkage;
6935 return llvm::GlobalVariable::ExternalLinkage;
6938llvm::GlobalValue::LinkageTypes
6947 llvm::Function *newFn) {
6949 if (old->use_empty())
6952 llvm::Type *newRetTy = newFn->getReturnType();
6957 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6959 llvm::User *user = ui->getUser();
6963 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6964 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6970 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6973 if (!callSite->isCallee(&*ui))
6978 if (callSite->getType() != newRetTy && !callSite->use_empty())
6983 llvm::AttributeList oldAttrs = callSite->getAttributes();
6986 unsigned newNumArgs = newFn->arg_size();
6987 if (callSite->arg_size() < newNumArgs)
6993 bool dontTransform =
false;
6994 for (llvm::Argument &A : newFn->args()) {
6995 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6996 dontTransform =
true;
7001 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
7009 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
7013 callSite->getOperandBundlesAsDefs(newBundles);
7015 llvm::CallBase *newCall;
7017 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
7018 callSite->getIterator());
7021 newCall = llvm::InvokeInst::Create(
7022 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
7023 newArgs, newBundles,
"", callSite->getIterator());
7027 if (!newCall->getType()->isVoidTy())
7028 newCall->takeName(callSite);
7029 newCall->setAttributes(
7030 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
7031 oldAttrs.getRetAttrs(), newArgAttrs));
7032 newCall->setCallingConv(callSite->getCallingConv());
7035 if (!callSite->use_empty())
7036 callSite->replaceAllUsesWith(newCall);
7039 if (callSite->getDebugLoc())
7040 newCall->setDebugLoc(callSite->getDebugLoc());
7042 callSitesToBeRemovedFromParent.push_back(callSite);
7045 for (
auto *callSite : callSitesToBeRemovedFromParent) {
7046 callSite->eraseFromParent();
7060 llvm::Function *NewFn) {
7070 (LangOpts.CUDA && !
getContext().shouldEmitCUDADecl(VD)))
7082void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
7083 llvm::GlobalValue *GV) {
7091 if (!GV || (GV->getValueType() != Ty))
7097 if (!GV->isDeclaration())
7107 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
7108 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
7120 setNonAliasAttributes(GD, Fn);
7122 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
7123 (CodeGenOpts.OptimizationLevel == 0) &&
7126 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
7128 !D->
hasAttr<NoInlineAttr>() &&
7129 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
7130 !D->
hasAttr<OptimizeNoneAttr>() &&
7131 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
7132 !ShouldAddOptNone) {
7133 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
7143 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
7144 if (UnwindMode != llvm::WinX64EHUnwindMode::Default &&
7145 UnwindMode != llvm::WinX64EHUnwindMode::V3 &&
7146 Fn->needsUnwindTableEntry()) {
7147 bool HasEGPR =
false;
7148 if (Fn->hasFnAttribute(
"target-features")) {
7150 Fn->getFnAttribute(
"target-features").getValueAsString();
7152 Feats.split(Tokens,
',', -1,
false);
7153 for (StringRef
Tok : Tokens) {
7156 else if (
Tok ==
"-egpr")
7160 HasEGPR = Context.getTargetInfo().hasFeature(
"egpr");
7163 unsigned DiagID = Diags.getCustomDiagID(
7165 "EGPR target feature requires unwind version 3");
7171 auto GetPriority = [
this](
const auto *Attr) ->
int {
7172 Expr *E = Attr->getPriority();
7176 return Attr->DefaultPriority;
7179 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
7181 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
7187void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
7189 const AliasAttr *AA = D->
getAttr<AliasAttr>();
7190 assert(AA &&
"Not an alias?");
7194 if (AA->getAliasee() == MangledName) {
7195 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7202 if (Entry && !Entry->isDeclaration())
7205 Aliases.push_back(GD);
7211 llvm::Constant *Aliasee;
7212 llvm::GlobalValue::LinkageTypes
LT;
7214 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
7220 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
7227 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
7229 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
7232 if (GA->getAliasee() == Entry) {
7233 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7237 assert(Entry->isDeclaration());
7246 GA->takeName(Entry);
7248 Entry->replaceAllUsesWith(GA);
7249 Entry->eraseFromParent();
7251 GA->setName(MangledName);
7259 GA->setLinkage(llvm::Function::WeakAnyLinkage);
7262 if (
const auto *VD = dyn_cast<VarDecl>(D))
7263 if (VD->getTLSKind())
7274void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
7276 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
7277 assert(IFA &&
"Not an ifunc?");
7281 if (IFA->getResolver() == MangledName) {
7282 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7288 if (Entry && !Entry->isDeclaration()) {
7291 DiagnosedConflictingDefinitions.insert(GD).second) {
7292 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
7295 diag::note_previous_definition);
7300 Aliases.push_back(GD);
7306 llvm::Constant *Resolver =
7307 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
7311 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
7312 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
7314 if (GIF->getResolver() == Entry) {
7315 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7318 assert(Entry->isDeclaration());
7327 GIF->takeName(Entry);
7329 Entry->replaceAllUsesWith(GIF);
7330 Entry->eraseFromParent();
7332 GIF->setName(MangledName);
7338 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7339 (llvm::Intrinsic::ID)IID, Tys);
7342static llvm::StringMapEntry<llvm::GlobalVariable *> &
7345 bool &IsUTF16,
unsigned &StringLength) {
7346 StringRef String = Literal->getString();
7347 unsigned NumBytes = String.size();
7350 if (!Literal->containsNonAsciiOrNull()) {
7351 StringLength = NumBytes;
7352 return *Map.insert(std::make_pair(String,
nullptr)).first;
7359 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7360 llvm::UTF16 *ToPtr = &ToBuf[0];
7362 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7363 ToPtr + NumBytes, llvm::strictConversion);
7366 StringLength = ToPtr - &ToBuf[0];
7370 return *Map.insert(std::make_pair(
7371 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7372 (StringLength + 1) * 2),
7378 unsigned StringLength = 0;
7379 bool isUTF16 =
false;
7380 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7385 if (
auto *
C = Entry.second)
7390 const llvm::Triple &Triple =
getTriple();
7393 const bool IsSwiftABI =
7394 static_cast<unsigned>(CFRuntime) >=
7399 if (!CFConstantStringClassRef) {
7400 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7402 Ty = llvm::ArrayType::get(Ty, 0);
7404 switch (CFRuntime) {
7408 CFConstantStringClassName =
7409 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7410 :
"$s10Foundation19_NSCFConstantStringCN";
7414 CFConstantStringClassName =
7415 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7416 :
"$S10Foundation19_NSCFConstantStringCN";
7420 CFConstantStringClassName =
7421 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7422 :
"__T010Foundation19_NSCFConstantStringCN";
7429 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7430 llvm::GlobalValue *GV =
nullptr;
7432 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7439 if ((VD = dyn_cast<VarDecl>(
Result)))
7442 if (Triple.isOSBinFormatELF()) {
7444 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7446 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7447 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7448 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7450 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7458 CFConstantStringClassRef =
7459 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7462 QualType CFTy = Context.getCFConstantStringType();
7467 auto Fields = Builder.beginStruct(STy);
7476 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7477 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7479 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7483 llvm::Constant *
C =
nullptr;
7486 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7487 Entry.first().size() / 2);
7488 C = llvm::ConstantDataArray::get(VMContext, Arr);
7490 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7496 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7497 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7498 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7501 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7502 : Context.getTypeAlignInChars(Context.CharTy);
7508 if (Triple.isOSBinFormatMachO())
7509 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7510 :
"__TEXT,__cstring,cstring_literals");
7513 else if (Triple.isOSBinFormatELF())
7514 GV->setSection(
".rodata");
7520 llvm::IntegerType *LengthTy =
7530 Fields.addInt(LengthTy, StringLength);
7538 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7540 llvm::GlobalVariable::PrivateLinkage);
7541 GV->addAttribute(
"objc_arc_inert");
7542 switch (Triple.getObjectFormat()) {
7543 case llvm::Triple::UnknownObjectFormat:
7544 llvm_unreachable(
"unknown file format");
7545 case llvm::Triple::DXContainer:
7546 case llvm::Triple::GOFF:
7547 case llvm::Triple::SPIRV:
7548 case llvm::Triple::XCOFF:
7549 llvm_unreachable(
"unimplemented");
7550 case llvm::Triple::COFF:
7551 case llvm::Triple::ELF:
7552 case llvm::Triple::Wasm:
7553 GV->setSection(
"cfstring");
7555 case llvm::Triple::MachO:
7556 GV->setSection(
"__DATA,__cfstring");
7565 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7569 if (ObjCFastEnumerationStateType.isNull()) {
7570 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7574 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7575 Context.getPointerType(Context.UnsignedLongTy),
7576 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7579 for (
size_t i = 0; i < 4; ++i) {
7584 FieldTypes[i],
nullptr,
7593 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7596 return ObjCFastEnumerationStateType;
7610 assert(CAT &&
"String literal not of constant array type!");
7612 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7616 llvm::Type *ElemTy = AType->getElementType();
7617 unsigned NumElements = AType->getNumElements();
7620 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7622 Elements.reserve(NumElements);
7624 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7626 Elements.resize(NumElements);
7627 return llvm::ConstantDataArray::get(VMContext, Elements);
7630 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7632 Elements.reserve(NumElements);
7634 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7636 Elements.resize(NumElements);
7637 return llvm::ConstantDataArray::get(VMContext, Elements);
7640static llvm::GlobalVariable *
7649 auto *GV =
new llvm::GlobalVariable(
7650 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7651 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7653 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7654 if (GV->isWeakForLinker()) {
7655 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7656 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7672 llvm::GlobalVariable **Entry =
nullptr;
7673 if (!LangOpts.WritableStrings) {
7674 Entry = &ConstantStringMap[
C];
7675 if (
auto GV = *Entry) {
7676 if (Alignment.
getAsAlign() > GV->getAlign().valueOrOne())
7679 GV->getValueType(), Alignment);
7684 StringRef GlobalVariableName;
7685 llvm::GlobalValue::LinkageTypes LT;
7690 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7691 !LangOpts.WritableStrings) {
7692 llvm::raw_svector_ostream Out(MangledNameBuffer);
7694 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7695 GlobalVariableName = MangledNameBuffer;
7697 LT = llvm::GlobalValue::PrivateLinkage;
7698 GlobalVariableName = Name;
7710 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7713 GV->getValueType(), Alignment);
7730 StringRef GlobalName) {
7731 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7736 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7739 llvm::GlobalVariable **Entry =
nullptr;
7740 if (!LangOpts.WritableStrings) {
7741 Entry = &ConstantStringMap[
C];
7742 if (
auto GV = *Entry) {
7743 if (Alignment.
getAsAlign() > GV->getAlign().valueOrOne())
7746 GV->getValueType(), Alignment);
7752 GlobalName, Alignment);
7757 GV->getValueType(), Alignment);
7775 MaterializedType = E->
getType();
7779 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7780 if (!InsertResult.second) {
7783 if (!InsertResult.first->second) {
7788 InsertResult.first->second =
new llvm::GlobalVariable(
7789 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7793 llvm::cast<llvm::GlobalVariable>(
7794 InsertResult.first->second->stripPointerCasts())
7803 llvm::raw_svector_ostream Out(Name);
7825 std::optional<ConstantEmitter> emitter;
7826 llvm::Constant *InitialValue =
nullptr;
7831 emitter.emplace(*
this);
7832 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7837 Type = InitialValue->getType();
7846 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7848 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7852 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7856 Linkage = llvm::GlobalVariable::InternalLinkage;
7860 auto *GV =
new llvm::GlobalVariable(
7862 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7863 if (emitter) emitter->finalize(GV);
7865 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7867 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7869 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7873 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7874 if (VD->getTLSKind())
7876 llvm::Constant *CV = GV;
7879 GV, llvm::PointerType::get(
7885 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7887 Entry->replaceAllUsesWith(CV);
7888 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7897void CodeGenModule::EmitObjCPropertyImplementations(
const
7910 if (!Getter || Getter->isSynthesizedAccessorStub())
7913 auto *Setter = PID->getSetterMethodDecl();
7914 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7925 if (ivar->getType().isDestructedType())
7946void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7959 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7974 getContext().getObjCIdType(),
nullptr, D,
true,
7980 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7985void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7992 EmitDeclContext(LSD);
7995void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7997 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8000 std::unique_ptr<CodeGenFunction> &CurCGF =
8001 GlobalTopLevelStmtBlockInFlight.first;
8005 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
8013 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
8014 FunctionArgList Args;
8016 const CGFunctionInfo &FnInfo =
8019 llvm::Function *
Fn = llvm::Function::Create(
8020 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
8022 CurCGF.reset(
new CodeGenFunction(*
this));
8023 GlobalTopLevelStmtBlockInFlight.second = D;
8024 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
8026 CXXGlobalInits.push_back(Fn);
8029 CurCGF->EmitStmt(D->
getStmt());
8032void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
8033 for (
auto *I : DC->
decls()) {
8039 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
8040 for (
auto *M : OID->methods())
8059 case Decl::CXXConversion:
8060 case Decl::CXXMethod:
8061 case Decl::Function:
8068 case Decl::CXXDeductionGuide:
8073 case Decl::Decomposition:
8074 case Decl::VarTemplateSpecialization:
8076 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
8077 for (
auto *B : DD->flat_bindings())
8078 if (
auto *HD = B->getHoldingVar())
8085 case Decl::IndirectField:
8089 case Decl::Namespace:
8092 case Decl::ClassTemplateSpecialization: {
8095 if (Spec->getSpecializationKind() ==
8097 Spec->hasDefinition())
8098 DI->completeTemplateDefinition(*Spec);
8100 case Decl::CXXRecord: {
8104 DI->EmitAndRetainType(
8108 DI->completeUnusedClass(*CRD);
8111 for (
auto *I : CRD->
decls())
8117 case Decl::UsingShadow:
8118 case Decl::ClassTemplate:
8119 case Decl::VarTemplate:
8121 case Decl::VarTemplatePartialSpecialization:
8122 case Decl::FunctionTemplate:
8123 case Decl::TypeAliasTemplate:
8132 case Decl::UsingEnum:
8136 case Decl::NamespaceAlias:
8140 case Decl::UsingDirective:
8144 case Decl::CXXConstructor:
8147 case Decl::CXXDestructor:
8151 case Decl::StaticAssert:
8152 case Decl::ExplicitInstantiation:
8159 case Decl::ObjCInterface:
8160 case Decl::ObjCCategory:
8163 case Decl::ObjCProtocol: {
8165 if (Proto->isThisDeclarationADefinition())
8166 ObjCRuntime->GenerateProtocol(Proto);
8170 case Decl::ObjCCategoryImpl:
8176 case Decl::ObjCImplementation: {
8178 EmitObjCPropertyImplementations(OMD);
8179 EmitObjCIvarInitializations(OMD);
8180 ObjCRuntime->GenerateClass(OMD);
8184 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
8185 OMD->getClassInterface()), OMD->getLocation());
8188 case Decl::ObjCMethod: {
8195 case Decl::ObjCCompatibleAlias:
8199 case Decl::PragmaComment: {
8201 switch (PCD->getCommentKind()) {
8203 llvm_unreachable(
"unexpected pragma comment kind");
8211 ProcessPragmaCommentCopyright(PCD->getArg(), PCD->isFromASTFile());
8221 case Decl::PragmaDetectMismatch: {
8227 case Decl::LinkageSpec:
8231 case Decl::FileScopeAsm: {
8233 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8236 if (LangOpts.OpenMPIsTargetDevice)
8239 if (LangOpts.SYCLIsDevice)
8244 llvm::Module::GlobalAsmProperties Props;
8245 Props.TargetFeatures = llvm::join(TargetOpts.
Features,
",");
8246 Props.TargetCPU = TargetOpts.
CPU;
8248 llvm::Module::GlobalAsmFragment(AD->getAsmString(), Props));
8252 case Decl::TopLevelStmt:
8256 case Decl::Import: {
8260 if (!ImportedModules.insert(Import->getImportedModule()))
8264 if (!Import->getImportedOwningModule()) {
8266 DI->EmitImportDecl(*Import);
8272 if (CXX20ModuleInits && Import->getImportedModule() &&
8273 Import->getImportedModule()->isNamedModule())
8282 Visited.insert(Import->getImportedModule());
8283 Stack.push_back(Import->getImportedModule());
8285 while (!Stack.empty()) {
8287 if (!EmittedModuleInitializers.insert(Mod).second)
8290 for (
auto *D : Context.getModuleInitializers(Mod))
8297 if (Submodule->IsExplicit)
8300 if (Visited.insert(Submodule).second)
8301 Stack.push_back(Submodule);
8311 case Decl::OMPThreadPrivate:
8315 case Decl::OMPAllocate:
8319 case Decl::OMPDeclareReduction:
8323 case Decl::OMPDeclareMapper:
8327 case Decl::OMPRequires:
8332 case Decl::TypeAlias:
8334 DI->EmitAndRetainType(
getContext().getTypedefType(
8342 DI->EmitAndRetainType(
8349 DI->EmitAndRetainType(
8353 case Decl::HLSLRootSignature:
8356 case Decl::HLSLBuffer:
8360 case Decl::OpenACCDeclare:
8363 case Decl::OpenACCRoutine:
8378 if (!CodeGenOpts.CoverageMapping)
8381 case Decl::CXXConversion:
8382 case Decl::CXXMethod:
8383 case Decl::Function:
8384 case Decl::ObjCMethod:
8385 case Decl::CXXConstructor:
8386 case Decl::CXXDestructor: {
8395 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8405 if (!CodeGenOpts.CoverageMapping)
8407 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8408 if (Fn->isTemplateInstantiation())
8411 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8419 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8422 const Decl *D = Entry.first;
8424 case Decl::CXXConversion:
8425 case Decl::CXXMethod:
8426 case Decl::Function:
8427 case Decl::ObjCMethod: {
8434 case Decl::CXXConstructor: {
8441 case Decl::CXXDestructor: {
8458 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8459 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8460 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8461 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8462 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8471 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8472 return llvm::ConstantInt::get(i64, PtrInt);
8476 llvm::NamedMDNode *&GlobalMetadata,
8478 llvm::GlobalValue *
Addr) {
8479 if (!GlobalMetadata)
8481 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8484 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8487 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8490bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8491 llvm::GlobalValue *CppFunc) {
8493 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8496 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8499 if (Elem == CppFunc)
8505 for (llvm::User *User : Elem->users()) {
8509 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8510 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8513 for (llvm::User *CEUser : ConstExpr->users()) {
8514 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8515 IFuncs.push_back(IFunc);
8520 CEs.push_back(ConstExpr);
8521 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8522 IFuncs.push_back(IFunc);
8534 for (llvm::GlobalIFunc *IFunc : IFuncs)
8535 IFunc->setResolver(
nullptr);
8536 for (llvm::ConstantExpr *ConstExpr : CEs)
8537 ConstExpr->destroyConstant();
8541 Elem->eraseFromParent();
8543 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8548 llvm::FunctionType::get(IFunc->getType(),
false);
8549 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8550 CppFunc->getName(), ResolverTy, {},
false);
8551 IFunc->setResolver(Resolver);
8561void CodeGenModule::EmitStaticExternCAliases() {
8564 for (
auto &I : StaticExternCValues) {
8565 const IdentifierInfo *Name = I.first;
8566 llvm::GlobalValue *Val = I.second;
8574 llvm::GlobalValue *ExistingElem =
8579 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8586 auto Res = Manglings.find(MangledName);
8587 if (Res == Manglings.end())
8589 Result = Res->getValue();
8600void CodeGenModule::EmitDeclMetadata() {
8601 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8603 for (
auto &I : MangledDeclNames) {
8604 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8614void CodeGenFunction::EmitDeclMetadata() {
8615 if (LocalDeclMap.empty())
return;
8620 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8622 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8624 for (
auto &I : LocalDeclMap) {
8625 const Decl *D = I.first;
8626 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8627 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8629 Alloca->setMetadata(
8630 DeclPtrKind, llvm::MDNode::get(
8631 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8632 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8639void CodeGenModule::EmitVersionIdentMetadata() {
8640 llvm::NamedMDNode *IdentMetadata =
8641 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8643 llvm::LLVMContext &Ctx = TheModule.getContext();
8645 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8646 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8649void CodeGenModule::EmitCommandLineMetadata() {
8650 llvm::NamedMDNode *CommandLineMetadata =
8651 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8653 llvm::LLVMContext &Ctx = TheModule.getContext();
8655 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8656 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8659void CodeGenModule::EmitCoverageFile() {
8660 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8664 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8665 llvm::LLVMContext &Ctx = TheModule.getContext();
8666 auto *CoverageDataFile =
8668 auto *CoverageNotesFile =
8670 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8671 llvm::MDNode *CU = CUNode->getOperand(i);
8672 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8673 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8686 LangOpts.ObjCRuntime.isGNUFamily())
8687 return ObjCRuntime->GetEHType(Ty);
8694 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8696 for (
auto RefExpr : D->
varlist()) {
8699 VD->getAnyInitializer() &&
8700 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8706 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8707 CXXGlobalInits.push_back(InitFunction);
8711llvm::Metadata *CodeGenModule::CreateMetadataIdentifierImpl(
8712 QualType T, MetadataTypeMap &Map, StringRef Suffix,
bool ForceString) {
8715 FnType->getReturnType(), FnType->getParamTypes(),
8716 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8718 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
8723 std::string OutName;
8724 llvm::raw_string_ostream Out(OutName);
8729 Out <<
".normalized";
8752 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
8757 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8761 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8762 ".generalized",
false);
8775 if (Context.isPromotableIntegerType(Ty))
8776 return Context.getPromotedIntegerType(Ty);
8778 if (BT->getKind() == BuiltinType::Float ||
8779 BT->getKind() == BuiltinType::Half)
8780 return Context.DoubleTy;
8788 PromotedParamTypes.reserve(ParamTypes.size());
8792 return Context.getFunctionType(FNPT->
getReturnType(), PromotedParamTypes,
8800 return CreateMetadataIdentifierImpl(
T, CallGraphMetadataIdMap,
"",
8808 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8809 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8810 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8811 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8812 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8813 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8814 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8815 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8823 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8825 if (CodeGenOpts.SanitizeCfiCrossDso)
8827 VTable->addTypeMetadata(Offset.getQuantity(),
8828 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8831 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8832 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8838 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8848 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8863 bool forPointeeType) {
8874 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8881 bool AlignForArray =
T->isArrayType();
8887 if (
T->isIncompleteType()) {
8904 if (
T.getQualifiers().hasUnaligned()) {
8906 }
else if (forPointeeType && !AlignForArray &&
8907 (RD =
T->getAsCXXRecordDecl())) {
8918 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8931 if (NumAutoVarInit >= StopAfter) {
8934 if (!NumAutoVarInit) {
8948 const Decl *D)
const {
8952 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8954 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8960 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8964 llvm::MD5::MD5Result
Result;
8965 for (
const auto &Arg : PreprocessorOpts.Macros)
8966 Hash.update(Arg.first);
8970 llvm::sys::fs::UniqueID ID;
8974 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8979 << PLoc.
getFilename() << Status.getError().message();
8981 ID = Status->getUniqueID();
8983 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8984 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8991 assert(DeferredDeclsToEmit.empty() &&
8992 "Should have emitted all decls deferred to emit.");
8993 assert(NewBuilder->DeferredDecls.empty() &&
8994 "Newly created module should not have deferred decls");
8995 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8996 assert(EmittedDeferredDecls.empty() &&
8997 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8999 assert(NewBuilder->DeferredVTables.empty() &&
9000 "Newly created module should not have deferred vtables");
9001 NewBuilder->DeferredVTables = std::move(DeferredVTables);
9003 assert(NewBuilder->EmittedVTables.empty() &&
9004 "Newly created module should not have defined vtables");
9005 NewBuilder->EmittedVTables = std::move(EmittedVTables);
9007 assert(NewBuilder->MangledDeclNames.empty() &&
9008 "Newly created module should not have mangled decl names");
9009 assert(NewBuilder->Manglings.empty() &&
9010 "Newly created module should not have manglings");
9011 NewBuilder->Manglings = std::move(Manglings);
9013 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
9015 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
9019 std::string OutName;
9020 llvm::raw_string_ostream Out(OutName);
9028 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
9034 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
9037 return RequireVectorDeletingDtor.count(RD);
9041 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
9043 RequireVectorDeletingDtor.insert(RD);
9057 if (Entry && !Entry->isDeclaration()) {
9062 auto *NewFn = llvm::Function::Create(
9064 llvm::Function::ExternalLinkage, VDName, &
getModule());
9065 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
9067 NewFn->takeName(VDEntry);
9068 VDEntry->replaceAllUsesWith(NewFn);
9069 VDEntry->eraseFromParent();
9070 Entry->replaceAllUsesWith(NewFn);
9071 Entry->eraseFromParent();
9076 addDeferredDeclToEmit(VectorDtorGD);
9080 llvm::GlobalAlias *GlobalDeleteAlias,
9084 PendingMSVCGlobalDeletes.insert({GlobalDeleteAlias, OperatorDeleteFD});
9106 "__global_delete wrapper is only used with the Microsoft ABI");
9108 llvm::LLVMContext &LLVMCtx = M.getContext();
9112 llvm::FunctionType *FnTy = GlobDeleteFn->getFunctionType();
9122 StringRef GlobDeleteMangledName = GlobDeleteFn->getName();
9123 StringRef Signature;
9124 const char *WrapperBase;
9125 if (GlobDeleteMangledName.starts_with(
"??3@")) {
9126 Signature = GlobDeleteMangledName.substr(4);
9127 WrapperBase =
"?__global_delete@@";
9128 }
else if (GlobDeleteMangledName.starts_with(
"??_V@")) {
9129 Signature = GlobDeleteMangledName.substr(5);
9130 WrapperBase =
"?__global_array_delete@@";
9132 llvm_unreachable(
"unexpected global operator delete mangling");
9135 std::string GlobalDeleteName = (WrapperBase + Signature).str();
9136 std::string EmptyGlobalDeleteName =
9137 (
"?__empty_global_delete@@" + Signature).str();
9141 if (llvm::GlobalValue *Existing = M.getNamedValue(GlobalDeleteName))
9150 llvm::Function *EmptyFn = M.getFunction(EmptyGlobalDeleteName);
9152 EmptyFn = llvm::Function::Create(
9153 FnTy, llvm::GlobalValue::LinkOnceODRLinkage, EmptyGlobalDeleteName, &M);
9154 EmptyFn->setComdat(M.getOrInsertComdat(EmptyGlobalDeleteName));
9155 EmptyFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
9162 auto *BB = llvm::BasicBlock::Create(LLVMCtx,
"", EmptyFn);
9163 llvm::Function *TrapFn =
9164 llvm::Intrinsic::getOrInsertDeclaration(&M, llvm::Intrinsic::trap);
9165 auto *TrapCall = llvm::CallInst::Create(TrapFn, {},
"", BB);
9166 TrapCall->setDoesNotReturn();
9167 TrapCall->setDoesNotThrow();
9168 new llvm::UnreachableInst(LLVMCtx, BB);
9182 auto *GlobalDeleteAlias = llvm::GlobalAlias::create(
9183 FnTy, GlobDeleteFn->getAddressSpace(), llvm::GlobalValue::WeakAnyLinkage,
9184 GlobalDeleteName, EmptyFn, &M);
9191 return GlobalDeleteAlias;
9203 if (!HasDirectGlobalDelete)
9206 for (
const auto &Entry : PendingMSVCGlobalDeletes) {
9207 llvm::GlobalAlias *Alias = Entry.first;
9215 llvm::Function::Create(FnTy, llvm::GlobalValue::LinkOnceODRLinkage,
9216 Alias->getAddressSpace(),
"", &
getModule());
9222 for (
auto &Arg : GlobDelFn->args())
9223 Args.push_back(&Arg);
9224 llvm::CallInst::Create(FnTy, RealDeleteFn, Args,
"", BB);
9229 Alias->replaceAllUsesWith(GlobDelFn);
9230 GlobDelFn->takeName(Alias);
9231 Alias->eraseFromParent();
9233 GlobDelFn->setComdat(
getModule().getOrInsertComdat(GlobDelFn->getName()));
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 shouldSkipAliasEmission(const CIRGenModule &cgm, const ValueDecl *global)
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static std::vector< std::string > getFeatureDeltaFromDefault(const CIRGenModule &cgm, llvm::StringRef targetCPU, llvm::StringMap< bool > &featureMap)
Get the feature delta from the default feature map for the given target CPU.
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static void emitUsed(CIRGenModule &cgm, StringRef name, std::vector< cir::CIRGlobalValueInterface > &list)
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static void initializeCommonABICompatInfo(llvm::abi::ABICompatInfo &CompatInfo, const LangOptions::ClangABI Compat)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static bool shouldKeepInlineFunction(llvm::GlobalValue::LinkageTypes Linkage, const FunctionDecl *FD)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static const char PFPDeactivationSymbolPrefix[]
static GlobalDecl getGlobalDeclForLinkage(const FunctionDecl *FD)
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 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 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 void initializeX86ABICompatInfo(llvm::abi::X86ABICompatInfo &CompatInfo, const llvm::Triple &T, const LangOptions::ClangABI Compat)
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.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::Preprocessor interface.
Maps Clang QualType instances to corresponding LLVM ABI type representations.
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.
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.
DiagnosticsEngine & getDiagnostics() const
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.
This class is used for builtin types like 'int'.
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
Represents a C++ destructor within a class.
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
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
const CXXDestructorDecl * getDestructor() const
This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits One()
Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
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.
static llvm::ExceptionHandling toExceptionHandling(ExceptionHandlingKind Kind)
Translate a clang ExceptionHandlingKind into the corresponding LLVM ExceptionHandling model.
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.
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 EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl)
Emit information about global variable alias.
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
std::optional< llvm::Attribute::AttrKind > StackProtectorAttribute(const Decl *D) const
llvm::GlobalValue * getPFPDeactivationSymbol(const FieldDecl *FD)
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()
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
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.
llvm::Metadata * CreateMetadataIdentifierForCallGraphType(QualType T)
Create a metadata identifier for the Call Graph Section.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool classNeedsVectorDestructor(const CXXRecordDecl *RD)
Check that class need vector deleting destructor body.
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.
llvm::Constant * getOrCreateMSVCGlobalDeleteWrapper(const FunctionDecl *GlobOD)
Get or create the MSVC-compatible __global_delete wrapper for the given global operator delete,...
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 callgraph metadata if the function is a potential indirect call target to support c...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach callee_type metadata to the given call.
bool tryEmitCUDADeviceInvalidFunctionBody(GlobalDecl GD, llvm::Function *Fn)
Emit a trap stub body for functions in ASTContext::CUDADeviceInvalidFuncs.
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
QualType GetCallGraphPromotedType(QualType Ty) const
Applies C default argument promotions to a parameter type for Call Graph Section type reconstruction.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
void requireVectorDestructorDefinition(const CXXRecordDecl *RD)
Record that new[] was called for the class, transform vector deleting destructor definition in a form...
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.
std::string getPFPFieldName(const FieldDecl *FD)
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
void addPendingGlobalDelete(llvm::GlobalAlias *GlobalDeleteAlias, const FunctionDecl *OperatorDeleteFD)
Record a pending __global_delete variant that may need a forwarding body.
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...
const llvm::abi::TargetInfo & getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB)
Lazily build and return the LLVMABI library's TargetInfo for the current target.
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)
void noteDirectGlobalDelete()
Note that global operator delete is directly used in this TU.
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.
QualType ReconstructCallGraphPrototype(const FunctionNoProtoType *FNPT, ArrayRef< QualType > ParamTypes) const
Reconstructs a FunctionProtoType for an unprototyped function type (FunctionNoProtoType) using the gi...
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...
std::string getMangledNameIgnoringAsmLabel(GlobalDecl GD, const NamedDecl *ND)
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 emitGlobalDeleteForwardingBodies()
Emit __global_delete forwarding bodies for any pending variants, if this TU directly uses global oper...
void addReplacement(StringRef Name, llvm::Constant *C)
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...
bool shouldUseLLVMABILowering(unsigned CallingConv) const
True when -fexperimental-abi-lowering is in effect AND the active target has an LLVMABI implementatio...
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.
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 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 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).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
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
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
bool isImmediateFunction() const
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
ArrayRef< ParmVarDecl * > parameters() const
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:
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
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.
bool isImplicitHDExplicitInstantiation() const
True if both host and device are implicit attributes and this is (or is a member of) an explicit temp...
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
QualType getReturnType() 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.
@ 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.
@ Single
Single Threaded Environment.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
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.
ClangABI
Clang versions with different platform ABI conformance.
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 isTriviallyRecursive(const FunctionDecl *FD)
Return true if FD's body contains a direct call back to the symbol it links as, through an asm label ...
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
void mangleNameIgnoringAsmLabel(GlobalDecl GD, raw_ostream &)
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
bool shouldMangleDeclNameIgnoringAsmLabel(const NamedDecl *D)
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.
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.
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.
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
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.
@ 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.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
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.
RecordDecl * getDefinitionOrSelf() const
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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
DiagnosticsEngine & getDiagnostics() const
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
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
Return the code unit at the given position.
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const char * getSignReturnAddressHardeningStr() const
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.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
const llvm::fltSemantics & getLongDoubleFormat() const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual StringRef getABI() const
Get the ABI currently in use.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
Options for controlling the target.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
AMDGPUFeatureState AMDGPUSramEccState
AMDGPU sramecc setting from -msramecc/-mno-sramecc.
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.
AMDGPUFeatureState AMDGPUXnackState
AMDGPU xnack setting from -mxnack/-mno-xnack.
@ Enabled
Feature explicitly enabled.
@ Any
Feature state not specified and should generate most compatible code.
@ 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.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isAMDGPUNamedBarrierTypeOrWrapper() const
Check if the type is the AMDGPU named barrier type/a RecordType of a named barrier wrapper,...
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.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
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.
@ TLS_None
Not a TLS variable.
@ 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.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
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.
LangAS getGlobalConstantAddressSpace(const LangOptions &LangOpts, const TargetInfo &Target)
Determines whether the language options require us to model unwind exceptions.
bool isVarDeclStrongDefinition(const ASTContext &Ctx, const VarDecl *D, bool NoCommon)
Check whether D is a strong definition, and thus must not be given common linkage.
bool hasUnwindExceptions(const LangOptions &LangOpts)
bool shouldBeInCOMDAT(const ASTContext &Ctx, const Decl &D)
Check whether D should be emitted into a COMDAT group.
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 > createXtensaTargetCodeGenInfo(CodeGenModule &CGM)
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)
std::unique_ptr< TargetCodeGenInfo > createSystemZ_ZOS_TargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, 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,...
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
Top level wrappers for InstallAPI frontend operations.
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.
@ Result
The result type of a method or function.
const FunctionProtoType * T
StringRef languageToString(Language L)
@ Dtor_VectorDeleting
Vector deleting dtor.
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
@ Dtor_Deleting
Deleting 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::PointerType * VoidPtrTy
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
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
llvm::PointerType * ProgramPtrTy
Pointer in program address space.
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.
Describes how types, statements, expressions, and declarations should be printed.