52#include "llvm/ABI/IRTypeMapper.h"
53#include "llvm/ABI/TargetInfo.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/ADT/StringSwitch.h"
57#include "llvm/Analysis/TargetLibraryInfo.h"
58#include "llvm/BinaryFormat/ELF.h"
59#include "llvm/IR/AttributeMask.h"
60#include "llvm/IR/CallingConv.h"
61#include "llvm/IR/DataLayout.h"
62#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/ProfileSummary.h"
66#include "llvm/ProfileData/InstrProfReader.h"
67#include "llvm/ProfileData/SampleProf.h"
68#include "llvm/Support/ARMBuildAttributes.h"
69#include "llvm/Support/CRC.h"
70#include "llvm/Support/CodeGen.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/ConvertUTF.h"
73#include "llvm/Support/ErrorHandling.h"
74#include "llvm/Support/TimeProfiler.h"
75#include "llvm/TargetParser/AArch64TargetParser.h"
76#include "llvm/TargetParser/RISCVISAInfo.h"
77#include "llvm/TargetParser/Triple.h"
78#include "llvm/TargetParser/X86TargetParser.h"
79#include "llvm/Transforms/Instrumentation/KCFI.h"
80#include "llvm/Transforms/Utils/BuildLibCalls.h"
81#include "llvm/Transforms/Utils/KCFIHash.h"
82#include "llvm/Transforms/Utils/ModuleUtils.h"
90 "limited-coverage-experimental", llvm::cl::Hidden,
91 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
98 case TargetCXXABI::AppleARM64:
99 case TargetCXXABI::Fuchsia:
100 case TargetCXXABI::GenericAArch64:
101 case TargetCXXABI::GenericARM:
102 case TargetCXXABI::iOS:
103 case TargetCXXABI::WatchOS:
104 case TargetCXXABI::GenericMIPS:
105 case TargetCXXABI::GenericItanium:
106 case TargetCXXABI::WebAssembly:
107 case TargetCXXABI::XL:
109 case TargetCXXABI::Microsoft:
113 llvm_unreachable(
"invalid C++ ABI kind");
116static std::unique_ptr<TargetCodeGenInfo>
119 const llvm::Triple &Triple =
Target.getTriple();
122 switch (Triple.getArch()) {
126 case llvm::Triple::m68k:
128 case llvm::Triple::mips:
129 case llvm::Triple::mipsel:
130 if (Triple.getOS() == llvm::Triple::Win32)
134 case llvm::Triple::mips64:
135 case llvm::Triple::mips64el:
138 case llvm::Triple::avr: {
142 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
143 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
147 case llvm::Triple::aarch64:
148 case llvm::Triple::aarch64_32:
149 case llvm::Triple::aarch64_be: {
151 if (
Target.getABI() ==
"darwinpcs")
152 Kind = AArch64ABIKind::DarwinPCS;
153 else if (Triple.isOSWindows())
155 else if (
Target.getABI() ==
"aapcs-soft")
156 Kind = AArch64ABIKind::AAPCSSoft;
161 case llvm::Triple::wasm32:
162 case llvm::Triple::wasm64: {
164 if (
Target.getABI() ==
"experimental-mv")
165 Kind = WebAssemblyABIKind::ExperimentalMV;
169 case llvm::Triple::arm:
170 case llvm::Triple::armeb:
171 case llvm::Triple::thumb:
172 case llvm::Triple::thumbeb: {
173 if (Triple.getOS() == llvm::Triple::Win32)
177 StringRef ABIStr =
Target.getABI();
178 if (ABIStr ==
"apcs-gnu")
179 Kind = ARMABIKind::APCS;
180 else if (ABIStr ==
"aapcs16")
181 Kind = ARMABIKind::AAPCS16_VFP;
182 else if (CodeGenOpts.
FloatABI ==
"hard" ||
183 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
184 Kind = ARMABIKind::AAPCS_VFP;
189 case llvm::Triple::ppc: {
190 if (Triple.isOSAIX())
197 case llvm::Triple::ppcle: {
202 case llvm::Triple::ppc64:
203 if (Triple.isOSAIX())
206 if (Triple.isOSBinFormatELF()) {
208 if (
Target.getABI() ==
"elfv2")
209 Kind = PPC64_SVR4_ABIKind::ELFv2;
210 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
215 case llvm::Triple::ppc64le: {
216 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
218 if (
Target.getABI() ==
"elfv1")
219 Kind = PPC64_SVR4_ABIKind::ELFv1;
220 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
225 case llvm::Triple::nvptx:
226 case llvm::Triple::nvptx64:
229 case llvm::Triple::msp430:
232 case llvm::Triple::riscv32:
233 case llvm::Triple::riscv64:
234 case llvm::Triple::riscv32be:
235 case llvm::Triple::riscv64be: {
236 StringRef ABIStr =
Target.getABI();
238 unsigned ABIFLen = 0;
239 if (ABIStr.ends_with(
"f"))
241 else if (ABIStr.ends_with(
"d"))
243 bool EABI = ABIStr.ends_with(
"e");
247 case llvm::Triple::systemz: {
248 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
249 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
250 if (Triple.getOS() == llvm::Triple::ZOS)
255 case llvm::Triple::tce:
256 case llvm::Triple::tcele:
257 case llvm::Triple::tcele64:
260 case llvm::Triple::x86: {
261 bool IsDarwinVectorABI = Triple.isOSDarwin();
262 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
264 if (Triple.getOS() == llvm::Triple::Win32) {
266 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
267 CodeGenOpts.NumRegisterParameters);
270 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
271 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
274 case llvm::Triple::x86_64: {
275 StringRef ABI =
Target.getABI();
276 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
277 : ABI ==
"avx" ? X86AVXABILevel::AVX
278 : X86AVXABILevel::None);
280 switch (Triple.getOS()) {
281 case llvm::Triple::UEFI:
282 case llvm::Triple::Win32:
288 case llvm::Triple::hexagon:
290 case llvm::Triple::lanai:
292 case llvm::Triple::r600:
294 case llvm::Triple::amdgpu:
296 case llvm::Triple::sparc:
298 case llvm::Triple::sparcv9:
300 case llvm::Triple::xcore:
302 case llvm::Triple::arc:
304 case llvm::Triple::spir:
305 case llvm::Triple::spir64:
307 case llvm::Triple::spirv32:
308 case llvm::Triple::spirv64:
309 case llvm::Triple::spirv:
311 case llvm::Triple::dxil:
313 case llvm::Triple::ve:
315 case llvm::Triple::csky: {
316 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
318 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
323 case llvm::Triple::bpfeb:
324 case llvm::Triple::bpfel:
326 case llvm::Triple::loongarch32:
327 case llvm::Triple::loongarch64: {
328 StringRef ABIStr =
Target.getABI();
329 unsigned ABIFRLen = 0;
330 if (ABIStr.ends_with(
"f"))
332 else if (ABIStr.ends_with(
"d"))
341 if (!TheTargetCodeGenInfo)
343 return *TheTargetCodeGenInfo;
347 if (!CodeGenOpts.ExperimentalABILowering)
354 if (
T.getArch() == llvm::Triple::x86_64 && !
T.isOSWindows() && !
T.isUEFI() &&
355 !
T.isOSDarwin() && !
T.isOSCygMing()) {
357 case llvm::CallingConv::Win64:
358 case llvm::CallingConv::X86_RegCall:
359 case llvm::CallingConv::X86_FastCall:
360 case llvm::CallingConv::X86_VectorCall:
361 case llvm::CallingConv::X86_StdCall:
362 case llvm::CallingConv::X86_ThisCall:
366 case llvm::CallingConv::Intel_OCL_BI:
367 case llvm::CallingConv::PreserveMost:
368 case llvm::CallingConv::PreserveAll:
369 case llvm::CallingConv::PreserveNone:
378const llvm::abi::TargetInfo &
380 if (TheLLVMABITargetInfo)
381 return *TheLLVMABITargetInfo;
385 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
386 return *TheLLVMABITargetInfo;
389 if (
T.getArch() == llvm::Triple::x86_64) {
391 llvm::abi::X86AVXABILevel AVXLevel =
392 ABI ==
"avx512" ? llvm::abi::X86AVXABILevel::AVX512
393 : ABI ==
"avx" ? llvm::abi::X86AVXABILevel::AVX
394 : llvm::abi::X86AVXABILevel::None;
396 llvm::abi::ABICompatInfo CompatInfo;
398 CompatInfo.ClassifyIntegerMMXAsSSE =
399 Compat > LangOptions::ClangABI::Ver3_8 && !
T.isOSDarwin() &&
400 !
T.isPS() && !
T.isOSFreeBSD();
401 CompatInfo.HonorsRevision98 = !
T.isOSDarwin();
402 CompatInfo.PassInt128VectorsInMem = Compat > LangOptions::ClangABI::Ver9 &&
403 (
T.isOSLinux() ||
T.isOSNetBSD());
405 CompatInfo.ReturnCXXRecordGreaterThan128InMem =
406 Compat > LangOptions::ClangABI::Ver20 && !
T.isPS();
407 CompatInfo.Clang11Compat =
408 Compat <= LangOptions::ClangABI::Ver11 ||
T.isPS();
412 TheLLVMABITargetInfo = llvm::abi::createX86_64TargetInfo(
413 TB, AVXLevel, Has64BitPointers, CompatInfo);
414 return *TheLLVMABITargetInfo;
417 llvm_unreachable(
"LLVMABI lowering requested for an unsupported target");
421 llvm::LLVMContext &Context,
425 if (Opts.AlignDouble || Opts.OpenCL)
428 llvm::Triple Triple =
Target.getTriple();
429 llvm::DataLayout DL(
Target.getDataLayoutString());
430 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
431 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
432 llvm::Align ClangAlign(Alignment / 8);
433 if (DLAlign != ClangAlign) {
434 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
435 <<
" mapping to " << *Ty <<
" has data layout alignment "
436 << DLAlign.value() <<
" while clang specifies "
437 << ClangAlign.value() <<
"\n";
442 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
444 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
446 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
448 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
451 if (Triple.getArch() != llvm::Triple::m68k)
452 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
455 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
456 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
457 Triple.getArch() != llvm::Triple::ve)
458 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
460 if (
Target.hasFloat16Type())
461 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
463 if (
Target.hasBFloat16Type())
464 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
465 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
467 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
470 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
472 if (
Target.hasFloat128Type())
473 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
474 if (
Target.hasIbm128Type())
475 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
477 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
479 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
480 llvm::errs() <<
"Datalayout for target " << Triple.str()
481 <<
" sets element-aligned vectors to '"
482 <<
Target.vectorsAreElementAligned()
483 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
497 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
498 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
500 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
504 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
505 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
506 M.getContext(), M.getDataLayout());
510 llvm::LLVMContext &LLVMContext = M.getContext();
511 VoidTy = llvm::Type::getVoidTy(LLVMContext);
512 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
513 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
514 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
515 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
516 HalfTy = llvm::Type::getHalfTy(LLVMContext);
517 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
518 FloatTy = llvm::Type::getFloatTy(LLVMContext);
519 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
525 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
527 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
529 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
530 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
531 IntPtrTy = llvm::IntegerType::get(LLVMContext,
532 C.getTargetInfo().getMaxPointerWidth());
533 Int8PtrTy = llvm::PointerType::get(LLVMContext,
535 const llvm::DataLayout &DL = M.getDataLayout();
537 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
539 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
541 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
557 createOpenCLRuntime();
559 createOpenMPRuntime();
566 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
567 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
573 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
574 CodeGenOpts.CoverageNotesFile.size() ||
575 CodeGenOpts.CoverageDataFile.size())
583 Block.GlobalUniqueCount = 0;
585 if (
C.getLangOpts().ObjC)
588 if (CodeGenOpts.hasProfileClangUse()) {
589 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
590 CodeGenOpts.ProfileInstrumentUsePath, *FS,
591 CodeGenOpts.ProfileRemappingFile);
592 if (
auto E = ReaderOrErr.takeError()) {
593 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
594 Diags.Report(diag::err_reading_profile)
595 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
599 PGOReader = std::move(ReaderOrErr.get());
604 if (CodeGenOpts.CoverageMapping)
608 if (CodeGenOpts.UniqueInternalLinkageNames &&
609 !
getModule().getSourceFileName().empty()) {
613 Context.getTargetInfo());
614 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
618 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
619 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
620 CodeGenOpts.NumRegisterParameters);
629 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
630 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
632 this->MSHotPatchFunctions.push_back(std::string{*I});
634 auto &DE = Context.getDiagnostics();
635 DE.Report(diag::err_open_hotpatch_file_failed)
637 << BufOrErr.getError().message();
642 this->MSHotPatchFunctions.push_back(FuncName);
644 llvm::sort(this->MSHotPatchFunctions);
647 if (!Context.getAuxTargetInfo())
653void CodeGenModule::createObjCRuntime() {
670 llvm_unreachable(
"bad runtime kind");
673void CodeGenModule::createOpenCLRuntime() {
677void CodeGenModule::createOpenMPRuntime() {
678 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
679 Diags.Report(diag::err_omp_host_ir_file_not_found)
680 << LangOpts.OMPHostIRFile;
685 case llvm::Triple::nvptx:
686 case llvm::Triple::nvptx64:
687 case llvm::Triple::amdgpu:
688 case llvm::Triple::spirv64:
691 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
692 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
695 if (LangOpts.OpenMPSimd)
696 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
698 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
703void CodeGenModule::createCUDARuntime() {
707void CodeGenModule::createHLSLRuntime() {
708 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
712 Replacements[Name] =
C;
715void CodeGenModule::applyReplacements() {
716 for (
auto &I : Replacements) {
717 StringRef MangledName = I.first;
718 llvm::Constant *Replacement = I.second;
723 auto *NewF = dyn_cast<llvm::Function>(Replacement);
725 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
726 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
729 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
730 CE->getOpcode() == llvm::Instruction::GetElementPtr);
731 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
736 OldF->replaceAllUsesWith(Replacement);
738 NewF->removeFromParent();
739 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
742 OldF->eraseFromParent();
747 GlobalValReplacements.push_back(std::make_pair(GV,
C));
750void CodeGenModule::applyGlobalValReplacements() {
751 for (
auto &I : GlobalValReplacements) {
752 llvm::GlobalValue *GV = I.first;
753 llvm::Constant *
C = I.second;
755 GV->replaceAllUsesWith(
C);
756 GV->eraseFromParent();
763 const llvm::Constant *
C;
764 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
765 C = GA->getAliasee();
766 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
767 C = GI->getResolver();
771 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
775 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
784 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
785 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
789 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
793 if (GV->hasCommonLinkage()) {
794 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
795 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
796 Diags.
Report(Location, diag::err_alias_to_common);
801 if (GV->isDeclaration()) {
802 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
803 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
804 << IsIFunc << IsIFunc;
807 for (
const auto &[
Decl, Name] : MangledDeclNames) {
808 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
810 if (II && II->
getName() == GV->getName()) {
811 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
815 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
825 const auto *F = dyn_cast<llvm::Function>(GV);
827 Diags.
Report(Location, diag::err_alias_to_undefined)
828 << IsIFunc << IsIFunc;
832 llvm::FunctionType *FTy = F->getFunctionType();
833 if (!FTy->getReturnType()->isPointerTy()) {
834 Diags.
Report(Location, diag::err_ifunc_resolver_return);
848 if (GVar->hasAttribute(
"toc-data")) {
849 auto GVId = GVar->getName();
852 Diags.
Report(Location, diag::warn_toc_unsupported_type)
853 << GVId <<
"the variable has an alias";
855 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
856 llvm::AttributeSet NewAttributes =
857 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
858 GVar->setAttributes(NewAttributes);
862void CodeGenModule::checkAliases() {
867 DiagnosticsEngine &Diags =
getDiags();
868 for (
const GlobalDecl &GD : Aliases) {
870 SourceLocation Location;
872 bool IsIFunc = D->hasAttr<IFuncAttr>();
873 if (
const Attr *A = D->getDefiningAttr()) {
874 Location = A->getLocation();
875 Range = A->getRange();
877 llvm_unreachable(
"Not an alias or ifunc?");
881 const llvm::GlobalValue *GV =
nullptr;
883 MangledDeclNames, Range)) {
889 GlobalDecl AliaseeGD;
892 Diags.Report(Location, diag::err_alias_to_undefined)
893 << IsIFunc << IsIFunc;
902 if (AliasIsFuncDecl != AliaseeIsFunc) {
903 Diags.Report(Location, diag::err_alias_between_function_and_variable)
906 diag::note_aliasee_declaration);
913 if (AliasIsFuncDecl && AliaseeIsFunc) {
914 QualType AliasTy = D->getType();
916 auto shouldReportTypeMismatch = [&]() {
917 const auto *AliasFTy =
919 const auto *AliaseeFTy =
921 assert(AliasFTy && AliaseeFTy);
922 if (!Context.typesAreCompatible(AliasFTy->getReturnType(),
925 const auto *AliasFPTy = dyn_cast<FunctionProtoType>(AliasFTy);
926 const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(AliaseeFTy);
928 if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) ||
929 (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy))
932 if (!AliasFPTy || !AliaseeFPTy)
936 if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() ||
937 AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic())
939 for (
unsigned i = 0; i < AliasFPTy->getNumParams(); ++i)
940 if (!Context.typesAreCompatible(AliasFPTy->getParamType(i),
941 AliaseeFPTy->getParamType(i)))
945 if (shouldReportTypeMismatch()) {
946 Diags.Report(Location, diag::warn_alias_type_mismatch)
947 << AliasTy << AliaseeTy;
949 diag::note_aliasee_declaration);
955 if (
const llvm::GlobalVariable *GVar =
956 dyn_cast<const llvm::GlobalVariable>(GV))
960 llvm::Constant *Aliasee =
964 llvm::GlobalValue *AliaseeGV;
965 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
970 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
971 StringRef AliasSection = SA->getName();
972 if (AliasSection != AliaseeGV->getSection())
973 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
974 << AliasSection << IsIFunc << IsIFunc;
982 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
983 if (GA->isInterposable()) {
984 Diags.Report(Location, diag::warn_alias_to_weak_alias)
985 << GV->getName() << GA->getName() << IsIFunc;
986 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
987 GA->getAliasee(), Alias->getType());
999 llvm::Attribute::DisableSanitizerInstrumentation);
1004 for (
const GlobalDecl &GD : Aliases) {
1007 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
1008 Alias->eraseFromParent();
1013 DeferredDeclsToEmit.clear();
1014 EmittedDeferredDecls.clear();
1015 DeferredAnnotations.clear();
1017 OpenMPRuntime->clear();
1021 StringRef MainFile) {
1024 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
1025 if (MainFile.empty())
1026 MainFile =
"<stdin>";
1027 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
1030 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
1033 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
1037static std::optional<llvm::GlobalValue::VisibilityTypes>
1042 return std::nullopt;
1044 return llvm::GlobalValue::DefaultVisibility;
1046 return llvm::GlobalValue::HiddenVisibility;
1048 return llvm::GlobalValue::ProtectedVisibility;
1050 llvm_unreachable(
"unknown option value!");
1055 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
1064 GV.setDSOLocal(
false);
1065 GV.setVisibility(*
V);
1070 if (!LO.VisibilityFromDLLStorageClass)
1073 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
1076 std::optional<llvm::GlobalValue::VisibilityTypes>
1077 NoDLLStorageClassVisibility =
1080 std::optional<llvm::GlobalValue::VisibilityTypes>
1081 ExternDeclDLLImportVisibility =
1084 std::optional<llvm::GlobalValue::VisibilityTypes>
1085 ExternDeclNoDLLStorageClassVisibility =
1088 for (llvm::GlobalValue &GV : M.global_values()) {
1089 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
1092 if (GV.isDeclarationForLinker())
1094 llvm::GlobalValue::DLLImportStorageClass
1095 ? ExternDeclDLLImportVisibility
1096 : ExternDeclNoDLLStorageClassVisibility);
1099 llvm::GlobalValue::DLLExportStorageClass
1100 ? DLLExportVisibility
1101 : NoDLLStorageClassVisibility);
1103 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1108 const llvm::Triple &Triple,
1112 return LangOpts.getStackProtector() == Mode;
1115std::optional<llvm::Attribute::AttrKind>
1117 if (D && D->
hasAttr<NoStackProtectorAttr>())
1119 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1121 return llvm::Attribute::StackProtectStrong;
1123 return llvm::Attribute::StackProtect;
1125 return llvm::Attribute::StackProtectStrong;
1127 return llvm::Attribute::StackProtectReq;
1128 return std::nullopt;
1134 EmitModuleInitializers(Primary);
1136 DeferredDecls.insert_range(EmittedDeferredDecls);
1137 EmittedDeferredDecls.clear();
1138 EmitVTablesOpportunistically();
1139 applyGlobalValReplacements();
1140 applyReplacements();
1141 emitMultiVersionFunctions();
1142 emitPFPFieldsWithEvaluatedOffset();
1145 if (Context.getLangOpts().IncrementalExtensions &&
1146 GlobalTopLevelStmtBlockInFlight.first) {
1148 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1149 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1155 EmitCXXModuleInitFunc(Primary);
1157 EmitCXXGlobalInitFunc();
1158 EmitCXXGlobalCleanUpFunc();
1159 registerGlobalDtorsWithAtExit();
1160 EmitCXXThreadLocalInitFunc();
1162 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1164 if (Context.getLangOpts().CUDA && CUDARuntime) {
1165 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1168 if (OpenMPRuntime) {
1169 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1170 OpenMPRuntime->clear();
1174 PGOReader->getSummary(
false).getMD(VMContext),
1175 llvm::ProfileSummary::PSK_Instr);
1176 if (PGOStats.hasDiagnostics())
1182 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1183 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1185 EmitStaticExternCAliases();
1190 if (CoverageMapping)
1191 CoverageMapping->emit();
1192 if (CodeGenOpts.SanitizeCfiCrossDso) {
1196 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1198 emitAtAvailableLinkGuard();
1199 if (Context.getTargetInfo().getTriple().isWasm())
1206 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1207 llvm::CodeObjectVersionKind::COV_None) {
1208 getModule().addModuleFlag(llvm::Module::Error,
1209 "amdhsa_code_object_version",
1210 getTarget().getTargetOpts().CodeObjectVersion);
1215 auto *MDStr = llvm::MDString::get(
1220 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1230 llvm::Module::Error,
"amdgpu.xnack",
1231 llvm::ConstantInt::get(
1239 llvm::Module::Error,
"amdgpu.sramecc",
1240 llvm::ConstantInt::get(
1250 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1252 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1254 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1258 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1262 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1264 auto *GV =
new llvm::GlobalVariable(
1265 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1266 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1272 auto *GV =
new llvm::GlobalVariable(
1274 llvm::Constant::getNullValue(
Int8Ty),
1283 if (CodeGenOpts.Autolink &&
1284 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1285 EmitModuleLinkOptions();
1300 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1301 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1302 for (
auto *MD : ELFDependentLibraries)
1303 NMD->addOperand(MD);
1306 if (CodeGenOpts.DwarfVersion) {
1307 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1308 CodeGenOpts.DwarfVersion);
1311 if (CodeGenOpts.Dwarf64)
1312 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1314 if (Context.getLangOpts().SemanticInterposition)
1316 getModule().setSemanticInterposition(
true);
1318 if (CodeGenOpts.EmitCodeView) {
1320 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1322 if (CodeGenOpts.CodeViewGHash) {
1323 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1325 if (CodeGenOpts.ControlFlowGuard) {
1328 llvm::Module::Warning,
"cfguard",
1329 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1330 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1333 llvm::Module::Warning,
"cfguard",
1334 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1336 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1337 llvm::ControlFlowGuardMechanism::Automatic) {
1340 llvm::Module::Warning,
"cfguard-mechanism",
1341 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1343 if (CodeGenOpts.EHContGuard) {
1345 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1347 if (Context.getLangOpts().Kernel) {
1349 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1351 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1356 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1358 llvm::Metadata *Ops[2] = {
1359 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1360 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1361 llvm::Type::getInt32Ty(VMContext), 1))};
1363 getModule().addModuleFlag(llvm::Module::Require,
1364 "StrictVTablePointersRequirement",
1365 llvm::MDNode::get(VMContext, Ops));
1371 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1372 llvm::DEBUG_METADATA_VERSION);
1377 uint64_t WCharWidth =
1378 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1379 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1380 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size",
1381 static_cast<uint32_t
>(WCharWidth));
1384 getModule().addModuleFlag(llvm::Module::Warning,
1385 "zos_product_major_version",
1387 getModule().addModuleFlag(llvm::Module::Warning,
1388 "zos_product_minor_version",
1390 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1391 uint32_t(CLANG_VERSION_PATCHLEVEL));
1393 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1394 llvm::MDString::get(VMContext, ProductId));
1399 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1400 llvm::MDString::get(VMContext, lang_str));
1402 time_t TT = PreprocessorOpts.SourceDateEpoch
1403 ? *PreprocessorOpts.SourceDateEpoch
1404 : std::time(
nullptr);
1405 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1406 static_cast<uint64_t
>(TT));
1409 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1410 llvm::MDString::get(VMContext,
"ascii"));
1413 llvm::Triple
T = Context.getTargetInfo().getTriple();
1414 if (
T.isARM() ||
T.isThumb()) {
1416 uint32_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1417 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1421 StringRef ABIStr = Target.getABI();
1422 llvm::LLVMContext &Ctx = TheModule.getContext();
1423 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1424 llvm::MDString::get(Ctx, ABIStr));
1429 const std::vector<std::string> &Features =
1432 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1433 if (!errorToBool(ParseResult.takeError()))
1435 llvm::Module::AppendUnique,
"riscv-isa",
1437 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1440 if (CodeGenOpts.SanitizeCfiCrossDso) {
1442 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1445 if (CodeGenOpts.WholeProgramVTables) {
1449 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1450 CodeGenOpts.VirtualFunctionElimination);
1453 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1454 getModule().addModuleFlag(llvm::Module::Override,
1455 "CFI Canonical Jump Tables",
1456 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1459 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1460 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1464 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1466 llvm::Module::Append,
"Unique Source File Identifier",
1468 TheModule.getContext(),
1469 llvm::MDString::get(TheModule.getContext(),
1470 CodeGenOpts.UniqueSourceFileIdentifier)));
1473 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1474 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1477 if (CodeGenOpts.PatchableFunctionEntryOffset)
1478 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1479 CodeGenOpts.PatchableFunctionEntryOffset);
1480 if (CodeGenOpts.SanitizeKcfiArity)
1481 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1484 llvm::Module::Override,
"kcfi-hash",
1485 llvm::MDString::get(
1487 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1490 if (CodeGenOpts.CFProtectionReturn &&
1491 Target.checkCFProtectionReturnSupported(
getDiags())) {
1493 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1497 if (CodeGenOpts.CFProtectionBranch &&
1498 Target.checkCFProtectionBranchSupported(
getDiags())) {
1500 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1503 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1504 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1506 Scheme = Target.getDefaultCFBranchLabelScheme();
1508 llvm::Module::Error,
"cf-branch-label-scheme",
1514 if (CodeGenOpts.FunctionReturnThunks)
1515 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1517 if (CodeGenOpts.IndirectBranchCSPrefix)
1518 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1520 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1528 if (LangOpts.BranchTargetEnforcement)
1529 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1531 if (LangOpts.BranchProtectionPAuthLR)
1532 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1534 if (LangOpts.GuardedControlStack)
1535 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1536 if (LangOpts.hasSignReturnAddress())
1537 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1538 if (LangOpts.isSignReturnAddressScopeAll())
1539 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1541 if (!LangOpts.isSignReturnAddressWithAKey())
1542 getModule().addModuleFlag(llvm::Module::Min,
1543 "sign-return-address-with-bkey", 2);
1545 if (
T.isAArch64()) {
1547 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got",
1548 LangOpts.PointerAuthELFGOT);
1550 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-init-fini",
1551 LangOpts.PointerAuthCalls &&
1552 LangOpts.PointerAuthInitFini);
1554 llvm::Module::Error,
"ptrauth-init-fini-address-discrimination",
1555 LangOpts.PointerAuthCalls && LangOpts.PointerAuthInitFini &&
1556 LangOpts.PointerAuthInitFiniAddressDiscrimination);
1560 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-sign-personality",
1561 LangOpts.PointerAuthCalls);
1564 using namespace llvm::ELF;
1565 assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST < 32);
1566 uint32_t PAuthABIVersion =
1567 (LangOpts.PointerAuthIntrinsics
1568 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1569 (LangOpts.PointerAuthCalls
1570 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1571 (LangOpts.PointerAuthReturns
1572 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1573 (LangOpts.PointerAuthAuthTraps
1574 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1575 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1576 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1577 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1578 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1579 (LangOpts.PointerAuthInitFini
1580 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1581 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1582 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1583 (LangOpts.PointerAuthELFGOT
1584 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1585 (LangOpts.PointerAuthIndirectGotos
1586 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1587 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1588 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1589 (LangOpts.PointerAuthFunctionTypeDiscrimination
1590 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1591 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1592 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1593 "Update when new enum items are defined");
1598 getModule().addModuleFlag(llvm::Module::Error,
1599 "aarch64-elf-pauthabi-platform",
1600 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1602 llvm::Module::Error,
"aarch64-elf-pauthabi-version", PAuthABIVersion);
1605 if ((
T.isARM() ||
T.isThumb()) &&
getTriple().isTargetAEABI() &&
1607 uint32_t TagVal = 0;
1608 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1610 llvm::DenormalMode::getPositiveZero()) {
1611 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1613 llvm::DenormalMode::getIEEE()) {
1614 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1615 DenormalTagBehavior = llvm::Module::Override;
1617 llvm::DenormalMode::getPreserveSign()) {
1618 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1620 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1625 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1626 llvm::ARMBuildAttrs::Allowed);
1629 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1631 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1632 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1636 if (CodeGenOpts.StackClashProtector)
1638 llvm::Module::Override,
"probe-stack",
1639 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1641 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1642 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1643 CodeGenOpts.StackProbeSize);
1645 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1646 llvm::LLVMContext &Ctx = TheModule.getContext();
1648 llvm::Module::Error,
"MemProfProfileFilename",
1649 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1652 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1656 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1657 CodeGenOpts.FP32DenormalMode.Output !=
1658 llvm::DenormalMode::IEEE);
1661 if (LangOpts.EHAsynch)
1662 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1665 if (CodeGenOpts.ImportCallOptimization)
1666 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1676 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
1677 if (UnwindMode == llvm::WinX64EHUnwindMode::Default) {
1678 if (
T.isOSWindows() &&
T.isX86_64() &&
1679 Context.getTargetInfo().hasFeature(
"egpr"))
1680 UnwindMode = llvm::WinX64EHUnwindMode::V3;
1682 UnwindMode = llvm::WinX64EHUnwindMode::V1;
1684 if (UnwindMode != llvm::WinX64EHUnwindMode::V1)
1685 getModule().addModuleFlag(llvm::Module::Warning,
"winx64-eh-unwind",
1686 static_cast<unsigned>(UnwindMode));
1690 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1692 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1696 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1697 EmitOpenCLMetadata();
1704 auto Version = LangOpts.getOpenCLCompatibleVersion();
1705 llvm::Metadata *SPIRVerElts[] = {
1706 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1708 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1709 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1710 llvm::NamedMDNode *SPIRVerMD =
1711 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1712 llvm::LLVMContext &Ctx = TheModule.getContext();
1713 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1721 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1722 assert(PLevel < 3 &&
"Invalid PIC Level");
1723 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1724 if (Context.getLangOpts().PIE)
1725 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1729 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1730 .Case(
"tiny", llvm::CodeModel::Tiny)
1731 .Case(
"small", llvm::CodeModel::Small)
1732 .Case(
"kernel", llvm::CodeModel::Kernel)
1733 .Case(
"medium", llvm::CodeModel::Medium)
1734 .Case(
"large", llvm::CodeModel::Large)
1737 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1740 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1741 Context.getTargetInfo().getTriple().getArch() ==
1742 llvm::Triple::x86_64) {
1748 if (CodeGenOpts.NoPLT)
1751 CodeGenOpts.DirectAccessExternalData !=
1752 getModule().getDirectAccessExternalData()) {
1753 getModule().setDirectAccessExternalData(
1754 CodeGenOpts.DirectAccessExternalData);
1756 if (CodeGenOpts.UnwindTables)
1757 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1759 switch (CodeGenOpts.getFramePointer()) {
1764 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1767 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1770 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1773 getModule().setFramePointer(llvm::FramePointerKind::All);
1777 SimplifyPersonality();
1790 EmitVersionIdentMetadata();
1793 EmitCommandLineMetadata();
1801 getModule().setStackProtectorGuardSymbol(
1804 getModule().setStackProtectorGuardOffset(
1807 getModule().setStackProtectorGuardValueWidth(
1810 if (
getModule().getStackProtectorGuard() !=
"global") {
1811 Diags.Report(diag::err_opt_not_valid_without_opt)
1812 <<
"-mstack-protector-guard-record"
1813 <<
"-mstack-protector-guard=global";
1815 getModule().setStackProtectorGuardRecord(
true);
1820 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1822 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1824 if (
getContext().getTargetInfo().getMaxTLSAlign())
1825 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1826 getContext().getTargetInfo().getMaxTLSAlign());
1844 if (!MustTailCallUndefinedGlobals.empty()) {
1846 for (
auto &I : MustTailCallUndefinedGlobals) {
1847 if (!I.first->isDefined())
1848 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1852 if (!Entry || Entry->isWeakForLinker() ||
1853 Entry->isDeclarationForLinker())
1854 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1858 for (
auto &I : MustTailCallUndefinedGlobals) {
1867 if (Entry->isDeclarationForLinker()) {
1870 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1872 CalleeIsLocal = Entry->isDSOLocal();
1876 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1889 llvm::MDBuilder MDB(TheModule.getContext());
1890 uint64_t Size = Context.getTypeSizeInChars(Context.IntTy).getQuantity();
1891 llvm::MDNode *StructNode =
1892 CodeGenOpts.NewStructPathTBAA
1893 ? MDB.createTBAATypeNode(TBAA->getChar(), Size,
1894 MDB.createString(
"__libc_errno"),
1895 {{0, Size, IntegerNode}})
1896 : MDB.createTBAAStructTypeNode(
"__libc_errno",
1897 {{IntegerNode, 0}});
1900 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1901 ErrnoTBAAMD->addOperand(StructTagNode);
1906void CodeGenModule::EmitOpenCLMetadata() {
1912 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1913 llvm::Metadata *OCLVerElts[] = {
1914 llvm::ConstantAsMetadata::get(
1915 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1916 llvm::ConstantAsMetadata::get(
1917 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1918 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1919 llvm::LLVMContext &Ctx = TheModule.getContext();
1920 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1923 EmitVersion(
"opencl.ocl.version", CLVersion);
1924 if (LangOpts.OpenCLCPlusPlus) {
1926 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1930void CodeGenModule::EmitBackendOptionsMetadata(
1931 const CodeGenOptions &CodeGenOpts) {
1933 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1934 CodeGenOpts.SmallDataLimit);
1938 if (LangOpts.AllocTokenMode) {
1939 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1940 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
1941 llvm::MDString::get(VMContext, S));
1943 if (LangOpts.AllocTokenMax)
1945 llvm::Module::Error,
"alloc-token-max",
1946 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1947 *LangOpts.AllocTokenMax));
1948 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1949 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
1950 if (CodeGenOpts.SanitizeAllocTokenExtended)
1951 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
1967 return TBAA->getTypeInfo(QTy);
1986 return TBAA->getAccessInfo(AccessType);
1993 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1999 return TBAA->getTBAAStructInfo(QTy);
2005 return TBAA->getBaseTypeInfo(QTy);
2011 return TBAA->getAccessTagInfo(Info);
2018 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
2026 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
2034 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
2040 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
2045 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
2057 std::string Msg =
Type;
2059 diag::err_codegen_unsupported)
2065 diag::err_codegen_unsupported)
2072 std::string Msg =
Type;
2074 diag::err_codegen_unsupported)
2079 llvm::function_ref<
void()> Fn) {
2080 StackHandler.runWithSufficientStackSpace(Loc, Fn);
2090 if (GV->hasLocalLinkage()) {
2091 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2104 if (Context.getLangOpts().OpenMP &&
2105 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
2106 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
2107 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
2108 OMPDeclareTargetDeclAttr::DT_NoHost &&
2110 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2117 if (Context.getLangOpts().CUDAIsDevice &&
2119 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
2120 bool NeedsProtected =
false;
2124 else if (
const auto *VD = dyn_cast<VarDecl>(D))
2125 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
2126 VD->hasAttr<CUDAConstantAttr>() ||
2127 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
2128 VD->getType()->isCUDADeviceBuiltinTextureType();
2129 if (NeedsProtected) {
2130 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2136 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2140 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
2144 if (GV->hasDLLExportStorageClass()) {
2147 diag::err_hidden_visibility_dllexport);
2150 diag::err_non_default_visibility_dllimport);
2156 !GV->isDeclarationForLinker())
2161 llvm::GlobalValue *GV) {
2162 if (GV->hasLocalLinkage())
2165 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
2169 if (GV->hasDLLImportStorageClass())
2172 const llvm::Triple &TT = CGM.
getTriple();
2174 if (TT.isOSCygMing()) {
2192 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2200 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2204 if (!TT.isOSBinFormatELF())
2210 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2218 return !(CGM.
getLangOpts().SemanticInterposition ||
2223 if (!GV->isDeclarationForLinker())
2229 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2236 if (CGOpts.DirectAccessExternalData) {
2242 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2243 if (!Var->isThreadLocal())
2268 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2270 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2280 if (D->
hasAttr<DLLImportAttr>())
2281 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2282 else if ((D->
hasAttr<DLLExportAttr>() ||
2284 !GV->isDeclarationForLinker())
2285 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2305 GV->setPartition(CodeGenOpts.SymbolPartition);
2309 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2310 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2311 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2312 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2313 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2316llvm::GlobalVariable::ThreadLocalMode
2318 switch (CodeGenOpts.getDefaultTLSModel()) {
2320 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2322 return llvm::GlobalVariable::LocalDynamicTLSModel;
2324 return llvm::GlobalVariable::InitialExecTLSModel;
2326 return llvm::GlobalVariable::LocalExecTLSModel;
2328 llvm_unreachable(
"Invalid TLS model!");
2332 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2334 llvm::GlobalValue::ThreadLocalMode TLM;
2338 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2342 GV->setThreadLocalMode(TLM);
2348 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2352 const CPUSpecificAttr *
Attr,
2369 !D->
hasAttr<AsmLabelAttr>() &&
2375 bool OmitMultiVersionMangling =
false) {
2377 llvm::raw_svector_ostream Out(Buffer);
2386 assert(II &&
"Attempt to mangle unnamed decl.");
2387 const auto *FD = dyn_cast<FunctionDecl>(ND);
2392 Out <<
"__regcall4__" << II->
getName();
2394 Out <<
"__regcall3__" << II->
getName();
2395 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2397 Out <<
"__device_stub__" << II->
getName();
2399 DeviceKernelAttr::isOpenCLSpelling(
2400 FD->getAttr<DeviceKernelAttr>()) &&
2402 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2418 "Hash computed when not explicitly requested");
2422 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2423 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2424 switch (FD->getMultiVersionKind()) {
2428 FD->getAttr<CPUSpecificAttr>(),
2432 auto *
Attr = FD->getAttr<TargetAttr>();
2433 assert(
Attr &&
"Expected TargetAttr to be present "
2434 "for attribute mangling");
2440 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2441 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2442 "for attribute mangling");
2448 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2449 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2450 "for attribute mangling");
2457 llvm_unreachable(
"None multiversion type isn't valid here");
2467 return std::string(Out.str());
2470void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2471 const FunctionDecl *FD,
2472 StringRef &CurName) {
2479 std::string NonTargetName =
2487 "Other GD should now be a multiversioned function");
2497 if (OtherName != NonTargetName) {
2500 const auto ExistingRecord = Manglings.find(NonTargetName);
2501 if (ExistingRecord != std::end(Manglings))
2502 Manglings.remove(&(*ExistingRecord));
2503 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2508 CurName = OtherNameRef;
2510 Entry->setName(OtherName);
2520 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2534 auto FoundName = MangledDeclNames.find(CanonicalGD);
2535 if (FoundName != MangledDeclNames.end())
2536 return FoundName->second;
2573 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2574 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2583 llvm::raw_svector_ostream Out(Buffer);
2586 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2587 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2589 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2594 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2595 return Result.first->first();
2599 auto it = MangledDeclNames.begin();
2600 while (it != MangledDeclNames.end()) {
2601 if (it->second == Name)
2616 llvm::Constant *AssociatedData) {
2618 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2624 bool IsDtorAttrFunc) {
2625 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2627 DtorsUsingAtExit[Priority].push_back(Dtor);
2632 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2635void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2636 if (Fns.empty())
return;
2639 llvm::PointerType *PtrTy = llvm::PointerType::get(
2640 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2643 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2647 auto Ctors = Builder.beginArray(CtorStructTy);
2648 for (
const auto &I : Fns) {
2649 auto Ctor = Ctors.beginStruct(CtorStructTy);
2650 Ctor.addInt(
Int32Ty, I.Priority);
2651 Ctor.add(I.Initializer);
2652 if (I.AssociatedData)
2653 Ctor.add(I.AssociatedData);
2655 Ctor.addNullPointer(PtrTy);
2656 Ctor.finishAndAddTo(Ctors);
2659 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2661 llvm::GlobalValue::AppendingLinkage);
2665 List->setAlignment(std::nullopt);
2670llvm::GlobalValue::LinkageTypes
2676 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2683 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2684 if (!MDS)
return nullptr;
2686 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2694 if (!UD->
hasAttr<TransparentUnionAttr>())
2696 if (!UD->
fields().empty())
2697 return UD->
fields().begin()->getType();
2706 bool GeneralizePointers) {
2719 bool GeneralizePointers) {
2722 for (
auto &Param : FnType->param_types())
2723 GeneralizedParams.push_back(
2727 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2728 GeneralizedParams, FnType->getExtProtoInfo());
2733 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2735 llvm_unreachable(
"Encountered unknown FunctionType");
2743 FnType->getReturnType(), FnType->getParamTypes(),
2744 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2746 std::string OutName;
2747 llvm::raw_string_ostream Out(OutName);
2755 Out <<
".normalized";
2757 Out <<
".generalized";
2759 return llvm::ConstantInt::get(
2765 llvm::Function *F,
bool IsThunk) {
2767 llvm::AttributeList PAL;
2770 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2774 Loc = D->getLocation();
2776 Error(Loc,
"__vectorcall calling convention is not currently supported");
2778 F->setAttributes(PAL);
2779 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2783 std::string ReadOnlyQual(
"__read_only");
2784 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2785 if (ReadOnlyPos != std::string::npos)
2787 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2789 std::string WriteOnlyQual(
"__write_only");
2790 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2791 if (WriteOnlyPos != std::string::npos)
2792 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2794 std::string ReadWriteQual(
"__read_write");
2795 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2796 if (ReadWritePos != std::string::npos)
2797 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2830 assert(((FD && CGF) || (!FD && !CGF)) &&
2831 "Incorrect use - FD and CGF should either be both null or not!");
2857 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2860 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2865 std::string typeQuals;
2869 const Decl *PDecl = parm;
2871 PDecl = TD->getDecl();
2872 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2873 if (A && A->isWriteOnly())
2874 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2875 else if (A && A->isReadWrite())
2876 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2878 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2880 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2882 auto getTypeSpelling = [&](
QualType Ty) {
2883 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2885 if (Ty.isCanonical()) {
2886 StringRef typeNameRef = typeName;
2888 if (typeNameRef.consume_front(
"unsigned "))
2889 return std::string(
"u") + typeNameRef.str();
2890 if (typeNameRef.consume_front(
"signed "))
2891 return typeNameRef.str();
2901 addressQuals.push_back(
2902 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2906 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2907 std::string baseTypeName =
2909 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2910 argBaseTypeNames.push_back(
2911 llvm::MDString::get(VMContext, baseTypeName));
2915 typeQuals =
"restrict";
2918 typeQuals += typeQuals.empty() ?
"const" :
" const";
2920 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2922 uint32_t AddrSpc = 0;
2927 addressQuals.push_back(
2928 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2932 std::string typeName = getTypeSpelling(ty);
2944 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2945 argBaseTypeNames.push_back(
2946 llvm::MDString::get(VMContext, baseTypeName));
2951 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2955 Fn->setMetadata(
"kernel_arg_addr_space",
2956 llvm::MDNode::get(VMContext, addressQuals));
2957 Fn->setMetadata(
"kernel_arg_access_qual",
2958 llvm::MDNode::get(VMContext, accessQuals));
2959 Fn->setMetadata(
"kernel_arg_type",
2960 llvm::MDNode::get(VMContext, argTypeNames));
2961 Fn->setMetadata(
"kernel_arg_base_type",
2962 llvm::MDNode::get(VMContext, argBaseTypeNames));
2963 Fn->setMetadata(
"kernel_arg_type_qual",
2964 llvm::MDNode::get(VMContext, argTypeQuals));
2968 Fn->setMetadata(
"kernel_arg_name",
2969 llvm::MDNode::get(VMContext, argNames));
2979 if (!LangOpts.Exceptions)
return false;
2982 if (LangOpts.CXXExceptions)
return true;
2985 if (LangOpts.ObjCExceptions) {
3005SmallVector<const CXXRecordDecl *, 0>
3007 llvm::SetVector<const CXXRecordDecl *> MostBases;
3012 MostBases.insert(RD);
3014 CollectMostBases(B.getType()->getAsCXXRecordDecl());
3016 CollectMostBases(RD);
3017 return MostBases.takeVector();
3021 llvm::Function *F) {
3022 llvm::AttrBuilder B(F->getContext());
3024 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
3025 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
3027 if (CodeGenOpts.StackClashProtector)
3028 B.addAttribute(
"probe-stack",
"inline-asm");
3030 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
3031 B.addAttribute(
"stack-probe-size",
3032 std::to_string(CodeGenOpts.StackProbeSize));
3035 B.addAttribute(llvm::Attribute::NoUnwind);
3037 if (std::optional<llvm::Attribute::AttrKind>
Attr =
3039 B.addAttribute(*
Attr);
3044 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
3045 B.addAttribute(llvm::Attribute::AlwaysInline);
3049 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
3051 B.addAttribute(llvm::Attribute::NoInline);
3059 if (D->
hasAttr<ArmLocallyStreamingAttr>())
3060 B.addAttribute(
"aarch64_pstate_sm_body");
3063 if (
Attr->isNewZA())
3064 B.addAttribute(
"aarch64_new_za");
3065 if (
Attr->isNewZT0())
3066 B.addAttribute(
"aarch64_new_zt0");
3071 bool ShouldAddOptNone =
3072 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
3074 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
3075 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
3078 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
3079 !D->
hasAttr<NoInlineAttr>()) {
3080 B.addAttribute(llvm::Attribute::AlwaysInline);
3081 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
3082 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3084 B.addAttribute(llvm::Attribute::OptimizeNone);
3087 B.addAttribute(llvm::Attribute::NoInline);
3092 B.addAttribute(llvm::Attribute::Naked);
3095 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
3096 F->removeFnAttr(llvm::Attribute::MinSize);
3097 }
else if (D->
hasAttr<NakedAttr>()) {
3099 B.addAttribute(llvm::Attribute::Naked);
3100 B.addAttribute(llvm::Attribute::NoInline);
3101 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
3102 B.addAttribute(llvm::Attribute::NoDuplicate);
3103 }
else if (D->
hasAttr<NoInlineAttr>() &&
3104 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3106 B.addAttribute(llvm::Attribute::NoInline);
3107 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
3108 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
3110 B.addAttribute(llvm::Attribute::AlwaysInline);
3114 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
3115 B.addAttribute(llvm::Attribute::NoInline);
3119 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3122 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
3123 return Redecl->isInlineSpecified();
3125 if (any_of(FD->
redecls(), CheckRedeclForInline))
3130 return any_of(Pattern->
redecls(), CheckRedeclForInline);
3132 if (CheckForInline(FD)) {
3133 B.addAttribute(llvm::Attribute::InlineHint);
3134 }
else if (CodeGenOpts.getInlining() ==
3137 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3138 B.addAttribute(llvm::Attribute::NoInline);
3145 if (!D->
hasAttr<OptimizeNoneAttr>()) {
3147 if (!ShouldAddOptNone)
3148 B.addAttribute(llvm::Attribute::OptimizeForSize);
3149 B.addAttribute(llvm::Attribute::Cold);
3152 B.addAttribute(llvm::Attribute::Hot);
3153 if (D->
hasAttr<MinSizeAttr>())
3154 B.addAttribute(llvm::Attribute::MinSize);
3159 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3160 B.addAttribute(llvm::Attribute::NoOutline);
3164 llvm::MaybeAlign ExplicitAlignment;
3165 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3166 ExplicitAlignment = llvm::Align(alignment);
3167 else if (LangOpts.FunctionAlignment)
3168 ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment);
3170 if (ExplicitAlignment) {
3171 F->setAlignment(ExplicitAlignment);
3172 F->setPreferredAlignment(ExplicitAlignment);
3173 }
else if (LangOpts.PreferredFunctionAlignment) {
3174 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3183 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3188 if (CodeGenOpts.SanitizeCfiCrossDso &&
3189 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3190 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3198 if (CodeGenOpts.CallGraphSection) {
3199 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3206 auto *MD = dyn_cast<CXXMethodDecl>(D);
3209 llvm::Metadata *Id =
3211 MD->getType(), std::nullopt,
Base));
3212 F->addTypeMetadata(0, Id);
3219 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3220 if (FD->
hasAttr<SYCLExternalAttr>())
3221 addSYCLModuleIdAttr(F);
3225void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3227 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3232 if (isa_and_nonnull<NamedDecl>(D))
3235 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3237 if (D && D->
hasAttr<UsedAttr>())
3240 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3242 ((CodeGenOpts.KeepPersistentStorageVariables &&
3243 (VD->getStorageDuration() ==
SD_Static ||
3244 VD->getStorageDuration() ==
SD_Thread)) ||
3245 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3246 VD->getType().isConstQualified())))
3251static std::vector<std::string>
3253 llvm::StringMap<bool> &FeatureMap) {
3254 llvm::StringMap<bool> DefaultFeatureMap;
3258 std::vector<std::string> Delta;
3259 for (
const auto &[K,
V] : FeatureMap) {
3260 auto DefaultIt = DefaultFeatureMap.find(K);
3261 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3262 Delta.push_back((
V ?
"+" :
"-") + K.str());
3268bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3269 llvm::AttrBuilder &Attrs,
3270 bool SetTargetFeatures) {
3276 std::vector<std::string> Features;
3277 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3280 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3281 assert((!TD || !TV) &&
"both target_version and target specified");
3284 bool AddedAttr =
false;
3285 if (TD || TV || SD || TC) {
3286 llvm::StringMap<bool> FeatureMap;
3293 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3296 if (!FeatureStr.empty()) {
3297 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3298 if (!ParsedAttr.
CPU.empty() &&
3300 TargetCPU = ParsedAttr.
CPU;
3303 if (!ParsedAttr.
Tune.empty() &&
3305 TuneCPU = ParsedAttr.
Tune;
3321 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3322 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3323 Entry.getKey().str());
3329 llvm::StringMap<bool> FeatureMap;
3343 if (!TargetCPU.empty()) {
3344 Attrs.addAttribute(
"target-cpu", TargetCPU);
3347 if (!TuneCPU.empty()) {
3348 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3351 if (!Features.empty() && SetTargetFeatures) {
3352 llvm::erase_if(Features, [&](
const std::string& F) {
3355 llvm::sort(Features);
3356 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3361 llvm::SmallVector<StringRef, 8> Feats;
3362 bool IsDefault =
false;
3364 IsDefault = TV->isDefaultVersion();
3365 TV->getFeatures(Feats);
3371 Attrs.addAttribute(
"fmv-features");
3373 }
else if (!Feats.empty()) {
3375 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3376 std::string FMVFeatures;
3377 for (StringRef F : OrderedFeats)
3378 FMVFeatures.append(
"," + F.str());
3379 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3386void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3387 llvm::GlobalObject *GO) {
3392 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3395 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3396 GV->addAttribute(
"bss-section", SA->getName());
3397 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3398 GV->addAttribute(
"data-section", SA->getName());
3399 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3400 GV->addAttribute(
"rodata-section", SA->getName());
3401 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3402 GV->addAttribute(
"relro-section", SA->getName());
3405 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3408 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3409 if (!D->
getAttr<SectionAttr>())
3410 F->setSection(SA->getName());
3412 llvm::AttrBuilder Attrs(F->getContext());
3413 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3417 llvm::AttributeMask RemoveAttrs;
3418 RemoveAttrs.addAttribute(
"target-cpu");
3419 RemoveAttrs.addAttribute(
"target-features");
3420 RemoveAttrs.addAttribute(
"fmv-features");
3421 RemoveAttrs.addAttribute(
"tune-cpu");
3422 F->removeFnAttrs(RemoveAttrs);
3423 F->addFnAttrs(Attrs);
3427 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3428 GO->setSection(CSA->getName());
3429 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3430 GO->setSection(SA->getName());
3443 F->setLinkage(llvm::Function::InternalLinkage);
3445 setNonAliasAttributes(GD, F);
3456 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3460 llvm::Function *F) {
3463 if (!F->hasLocalLinkage() ||
3464 F->getFunction().hasAddressTaken(
nullptr,
true,
3468 llvm::LLVMContext::MD_callgraph,
3469 *llvm::MDTuple::get(
3476 llvm::Function *F) {
3478 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3489 F->addTypeMetadata(0, MD);
3496 if (CodeGenOpts.SanitizeCfiCrossDso)
3498 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3502 llvm::CallBase *CB) {
3504 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3508 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
getLLVMContext(), {TypeIdMD});
3509 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3510 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3514 llvm::LLVMContext &Ctx = F->getContext();
3515 llvm::MDBuilder MDB(Ctx);
3516 llvm::StringRef Salt;
3519 if (
const auto &Info = FP->getExtraAttributeInfo())
3520 Salt = Info.CFISalt;
3522 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3531 return llvm::all_of(Name, [](
const char &
C) {
3532 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3538 for (
auto &F : M.functions()) {
3540 bool AddressTaken = F.hasAddressTaken();
3541 if (!AddressTaken && F.hasLocalLinkage())
3542 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3547 if (!AddressTaken || !F.isDeclaration())
3550 const llvm::ConstantInt *
Type;
3551 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3552 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3556 StringRef Name = F.getName();
3560 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3561 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3562 Twine(
Type->getSExtValue()) +
" */\n")
3564 M.appendModuleInlineAsm(
Asm);
3568void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3569 bool IsIncompleteFunction,
3572 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3580 if (!IsIncompleteFunction)
3587 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3589 assert(!F->arg_empty() &&
3590 F->arg_begin()->getType()
3591 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3592 "unexpected this return");
3593 F->addParamAttr(0, llvm::Attribute::Returned);
3603 if (!IsIncompleteFunction && F->isDeclaration())
3606 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3607 F->setSection(CSA->getName());
3608 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3609 F->setSection(SA->getName());
3611 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3613 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3614 else if (EA->isWarning())
3615 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3620 const FunctionDecl *FDBody;
3621 bool HasBody = FD->
hasBody(FDBody);
3623 assert(HasBody &&
"Inline builtin declarations should always have an "
3625 if (shouldEmitFunction(FDBody))
3626 F->addFnAttr(llvm::Attribute::NoBuiltin);
3632 F->addFnAttr(llvm::Attribute::NoBuiltin);
3636 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3637 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3638 if (MD->isVirtual())
3639 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3645 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3646 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3649 if (CodeGenOpts.CallGraphSection)
3652 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3658 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3659 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3661 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3665 llvm::LLVMContext &Ctx = F->getContext();
3666 llvm::MDBuilder MDB(Ctx);
3670 int CalleeIdx = *CB->encoding_begin();
3671 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3672 F->addMetadata(llvm::LLVMContext::MD_callback,
3673 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3674 CalleeIdx, PayloadIndices,
3681 "Only globals with definition can force usage.");
3682 LLVMUsed.emplace_back(GV);
3686 assert(!GV->isDeclaration() &&
3687 "Only globals with definition can force usage.");
3688 LLVMCompilerUsed.emplace_back(GV);
3693 "Only globals with definition can force usage.");
3695 LLVMCompilerUsed.emplace_back(GV);
3697 LLVMUsed.emplace_back(GV);
3701 std::vector<llvm::WeakTrackingVH> &List) {
3711 UsedArray.reserve(List.size());
3712 for (
const llvm::WeakTrackingVH &VH : List) {
3713 if (llvm::Value *
V = VH)
3714 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3718 if (UsedArray.empty())
3720 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3722 auto *GV =
new llvm::GlobalVariable(
3723 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3724 llvm::ConstantArray::get(ATy, UsedArray), Name);
3726 GV->setSection(
"llvm.metadata");
3729void CodeGenModule::emitLLVMUsed() {
3730 emitUsed(*
this,
"llvm.used", LLVMUsed);
3731 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3736 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3745 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3751 ELFDependentLibraries.push_back(
3752 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3759 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3766void CodeGenModule::ProcessPragmaCommentCopyright(StringRef Comment,
3767 bool isFromASTFile) {
3769 "pragma comment copyright is supported only when targeting AIX");
3782 assert(!LoadTimeCommentGlobal &&
3783 "Only one copyright pragma allowed per translation unit.");
3788 uint64_t Hash = xxh3_64bits(Comment);
3789 std::string GlobalName =
3790 (
"__loadtime_comment_str_" + Twine::utohexstr(Hash)).str();
3793 llvm::Constant *StrInit =
3794 llvm::ConstantDataArray::getString(
C, Comment,
true);
3797 auto *GV =
new llvm::GlobalVariable(
getModule(), StrInit->getType(),
3799 llvm::GlobalValue::WeakODRLinkage,
3800 StrInit, GlobalName);
3802 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3803 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3804 GV->setAlignment(llvm::Align(1));
3810 GV->setSection(
"__loadtime_comment");
3813 GV->setMetadata(
"loadtime_comment", llvm::MDNode::get(
C, {}));
3816 llvm::appendToCompilerUsed(
getModule(), {GV});
3818 LoadTimeCommentGlobal = GV;
3827 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3833 if (Visited.insert(Import).second)
3850 if (LL.IsFramework) {
3851 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3852 llvm::MDString::get(Context, LL.Library)};
3854 Metadata.push_back(llvm::MDNode::get(Context, Args));
3860 llvm::Metadata *Args[2] = {
3861 llvm::MDString::get(Context,
"lib"),
3862 llvm::MDString::get(Context, LL.Library),
3864 Metadata.push_back(llvm::MDNode::get(Context, Args));
3868 auto *OptString = llvm::MDString::get(Context, Opt);
3869 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3874void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3876 "We should only emit module initializers for named modules.");
3884 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3901 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3907void CodeGenModule::EmitModuleLinkOptions() {
3911 llvm::SetVector<clang::Module *> LinkModules;
3912 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3913 SmallVector<clang::Module *, 16> Stack;
3916 for (
Module *M : ImportedModules) {
3919 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3922 if (Visited.insert(M).second)
3928 while (!Stack.empty()) {
3931 bool AnyChildren =
false;
3940 if (Visited.insert(
SM).second) {
3941 Stack.push_back(
SM);
3949 LinkModules.insert(Mod);
3956 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3958 for (
Module *M : LinkModules)
3959 if (Visited.insert(M).second)
3961 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3962 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3965 if (!LinkerOptionsMetadata.empty()) {
3966 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3967 for (
auto *MD : LinkerOptionsMetadata)
3968 NMD->addOperand(MD);
3972void CodeGenModule::EmitDeferred() {
3981 if (!DeferredVTables.empty()) {
3982 EmitDeferredVTables();
3987 assert(DeferredVTables.empty());
3994 llvm::append_range(DeferredDeclsToEmit,
3998 if (DeferredDeclsToEmit.empty())
4003 std::vector<GlobalDecl> CurDeclsToEmit;
4004 CurDeclsToEmit.swap(DeferredDeclsToEmit);
4006 for (GlobalDecl &D : CurDeclsToEmit) {
4012 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
4016 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
4032 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
4050 if (!GV->isDeclaration())
4054 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
4058 EmitGlobalDefinition(D, GV);
4063 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
4065 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
4070void CodeGenModule::EmitVTablesOpportunistically() {
4076 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
4077 &&
"Only emit opportunistic vtables with optimizations");
4079 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
4081 "This queue should only contain external vtables");
4082 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
4083 VTables.GenerateClassData(RD);
4085 OpportunisticVTables.clear();
4089 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
4094 DeferredAnnotations.clear();
4096 if (Annotations.empty())
4100 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
4101 Annotations[0]->
getType(), Annotations.size()), Annotations);
4102 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
4103 llvm::GlobalValue::AppendingLinkage,
4104 Array,
"llvm.global.annotations");
4109 llvm::Constant *&AStr = AnnotationStrings[Str];
4114 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
4115 auto *gv =
new llvm::GlobalVariable(
4116 getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s,
4117 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
4120 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4137 SM.getExpansionLineNumber(L);
4138 return llvm::ConstantInt::get(
Int32Ty, LineNo);
4146 llvm::FoldingSetNodeID ID;
4147 for (
Expr *E : Exprs) {
4150 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
4155 LLVMArgs.reserve(Exprs.size());
4157 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
4159 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
4162 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
4163 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
4164 llvm::GlobalValue::PrivateLinkage,
Struct,
4167 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4174 const AnnotateAttr *AA,
4182 llvm::Constant *GVInGlobalsAS = GV;
4183 if (GV->getAddressSpace() !=
4185 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
4187 llvm::PointerType::get(
4188 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
4192 llvm::Constant *Fields[] = {
4193 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
4195 return llvm::ConstantStruct::getAnon(Fields);
4199 llvm::GlobalValue *GV) {
4200 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4210 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4213 auto &
SM = Context.getSourceManager();
4215 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4220 return NoSanitizeL.containsLocation(Kind, Loc);
4223 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4227 llvm::GlobalVariable *GV,
4229 StringRef Category)
const {
4231 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4233 auto &
SM = Context.getSourceManager();
4234 if (NoSanitizeL.containsMainFile(
4235 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
4238 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4245 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4246 Ty = AT->getElementType();
4251 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4259 StringRef Category)
const {
4262 auto Attr = ImbueAttr::NONE;
4264 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4265 if (
Attr == ImbueAttr::NONE)
4266 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4268 case ImbueAttr::NONE:
4270 case ImbueAttr::ALWAYS:
4271 Fn->addFnAttr(
"function-instrument",
"xray-always");
4273 case ImbueAttr::ALWAYS_ARG1:
4274 Fn->addFnAttr(
"function-instrument",
"xray-always");
4275 Fn->addFnAttr(
"xray-log-args",
"1");
4277 case ImbueAttr::NEVER:
4278 Fn->addFnAttr(
"function-instrument",
"xray-never");
4291 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4301 auto &
SM = Context.getSourceManager();
4302 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
4316 if (NumGroups > 1) {
4317 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4326 if (LangOpts.EmitAllDecls)
4329 const auto *VD = dyn_cast<VarDecl>(
Global);
4331 ((CodeGenOpts.KeepPersistentStorageVariables &&
4332 (VD->getStorageDuration() ==
SD_Static ||
4333 VD->getStorageDuration() ==
SD_Thread)) ||
4334 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4335 VD->getType().isConstQualified())))
4348 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4349 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4350 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4351 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4355 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4365 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4372 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4373 if (Context.getInlineVariableDefinitionKind(VD) ==
4378 if (CXX20ModuleInits && VD->getOwningModule() &&
4379 !VD->getOwningModule()->isModuleMapModule()) {
4388 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4391 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4404 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4408 llvm::Constant *
Init;
4411 if (!
V.isAbsent()) {
4422 llvm::Constant *Fields[4] = {
4426 llvm::ConstantDataArray::getRaw(
4427 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4429 Init = llvm::ConstantStruct::getAnon(Fields);
4432 auto *GV =
new llvm::GlobalVariable(
4434 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4436 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4439 if (!
V.isAbsent()) {
4452 llvm::GlobalVariable **Entry =
nullptr;
4453 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4458 llvm::Constant *
Init;
4462 assert(!
V.isAbsent());
4466 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4468 llvm::GlobalValue::PrivateLinkage,
Init,
4470 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4485 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4489 llvm::Constant *
Init =
Emitter.emitForInitializer(
4497 llvm::GlobalValue::LinkageTypes
Linkage =
4499 ? llvm::GlobalValue::LinkOnceODRLinkage
4500 : llvm::GlobalValue::InternalLinkage;
4501 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4505 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4512 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4513 assert(AA &&
"No alias?");
4523 llvm::Constant *Aliasee;
4525 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4533 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4534 WeakRefReferences.insert(F);
4542 if (
auto *A = D->
getAttr<AttrT>())
4543 return A->isImplicit();
4550 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4553 const auto *AA =
Global->getAttr<AliasAttr>();
4561 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4562 if (LangOpts.OpenMPIsTargetDevice)
4563 return !AliaseeDecl ||
4564 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4567 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4568 const bool AliaseeHasDeviceAttr =
4569 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4571 if (LangOpts.CUDAIsDevice)
4572 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4579bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4580 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4585 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4586 Global->hasAttr<CUDAConstantAttr>() ||
4587 Global->hasAttr<CUDASharedAttr>() ||
4588 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4589 Global->getType()->isCUDADeviceBuiltinTextureType();
4596 if (
Global->hasAttr<WeakRefAttr>())
4601 if (
Global->hasAttr<AliasAttr>()) {
4604 return EmitAliasDefinition(GD);
4608 if (
Global->hasAttr<IFuncAttr>())
4609 return emitIFuncDefinition(GD);
4612 if (
Global->hasAttr<CPUDispatchAttr>())
4613 return emitCPUDispatchDefinition(GD);
4618 if (LangOpts.CUDA) {
4620 "Expected Variable or Function");
4621 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4622 if (!shouldEmitCUDAGlobalVar(VD))
4624 }
else if (LangOpts.CUDAIsDevice) {
4625 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4626 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4627 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4631 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4632 !
Global->hasAttr<CUDAGlobalAttr>() &&
4634 !
Global->hasAttr<CUDAHostAttr>()))
4637 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4638 Global->hasAttr<CUDADeviceAttr>())
4642 if (LangOpts.OpenMP) {
4644 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4646 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4647 if (MustBeEmitted(
Global))
4651 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4652 if (MustBeEmitted(
Global))
4659 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4660 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4666 if (FD->
hasAttr<AnnotateAttr>()) {
4669 DeferredAnnotations[MangledName] = FD;
4684 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4690 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4692 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4693 if (LangOpts.OpenMP) {
4695 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4696 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4700 if (VD->hasExternalStorage() &&
4701 Res != OMPDeclareTargetDeclAttr::MT_Link)
4704 bool UnifiedMemoryEnabled =
4706 if (*Res == OMPDeclareTargetDeclAttr::MT_Local ||
4707 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4708 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4709 !UnifiedMemoryEnabled)) {
4712 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4713 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4714 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4715 UnifiedMemoryEnabled)) &&
4716 "Link clause or to clause with unified memory expected.");
4726 if (LangOpts.HLSL) {
4727 if (VD->getStorageClass() ==
SC_Extern) {
4736 if (Context.getInlineVariableDefinitionKind(VD) ==
4746 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4748 EmitGlobalDefinition(GD);
4749 addEmittedDeferredDecl(GD);
4757 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4758 CXXGlobalInits.push_back(
nullptr);
4764 addDeferredDeclToEmit(GD);
4765 }
else if (MustBeEmitted(
Global)) {
4767 assert(!MayBeEmittedEagerly(
Global));
4768 addDeferredDeclToEmit(GD);
4773 DeferredDecls[MangledName] = GD;
4779 if (
const auto *RT =
4780 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4781 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4782 RD = RD->getDefinitionOrSelf();
4783 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4792struct DLLImportFunctionVisitor
4793 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4794 bool SafeToInline =
true;
4796 bool shouldVisitImplicitCode()
const {
return true; }
4798 bool VisitVarDecl(VarDecl *VD) {
4801 SafeToInline =
false;
4802 return SafeToInline;
4809 return SafeToInline;
4812 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4814 SafeToInline = D->
hasAttr<DLLImportAttr>();
4815 return SafeToInline;
4818 bool VisitDeclRefExpr(DeclRefExpr *E) {
4821 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4822 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4823 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4824 return SafeToInline;
4827 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4829 return SafeToInline;
4832 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4836 SafeToInline =
true;
4838 SafeToInline = M->
hasAttr<DLLImportAttr>();
4840 return SafeToInline;
4843 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4845 return SafeToInline;
4848 bool VisitCXXNewExpr(CXXNewExpr *E) {
4850 return SafeToInline;
4855bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4862 if (F->isInlineBuiltinDeclaration())
4865 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4870 if (
const Module *M = F->getOwningModule();
4871 M && M->getTopLevelModule()->isNamedModule() &&
4872 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4882 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4887 if (F->hasAttr<NoInlineAttr>())
4890 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4892 DLLImportFunctionVisitor Visitor;
4893 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4894 if (!Visitor.SafeToInline)
4897 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4904 for (
const CXXBaseSpecifier &B :
Dtor->getParent()->bases())
4918bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4919 return CodeGenOpts.OptimizationLevel > 0;
4922void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4923 llvm::GlobalValue *GV) {
4927 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4928 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4930 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4931 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4932 if (TC->isFirstOfVersion(I))
4935 EmitGlobalFunctionDefinition(GD, GV);
4941 AddDeferredMultiVersionResolverToEmit(GD);
4943 GetOrCreateMultiVersionResolver(GD);
4947void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4950 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4951 Context.getSourceManager(),
4952 "Generating code for declaration");
4954 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4957 if (!shouldEmitFunction(GD))
4960 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4962 llvm::raw_string_ostream
OS(Name);
4968 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4972 ABI->emitCXXStructor(GD);
4974 EmitMultiVersionFunctionDefinition(GD, GV);
4976 EmitGlobalFunctionDefinition(GD, GV);
4985 return EmitMultiVersionFunctionDefinition(GD, GV);
4986 return EmitGlobalFunctionDefinition(GD, GV);
4989 if (
const auto *VD = dyn_cast<VarDecl>(D))
4990 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4992 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4996 llvm::Function *NewFn);
5012static llvm::GlobalValue::LinkageTypes
5016 return llvm::GlobalValue::InternalLinkage;
5017 return llvm::GlobalValue::WeakODRLinkage;
5020void CodeGenModule::emitMultiVersionFunctions() {
5021 std::vector<GlobalDecl> MVFuncsToEmit;
5022 MultiVersionFuncs.swap(MVFuncsToEmit);
5023 for (GlobalDecl GD : MVFuncsToEmit) {
5025 assert(FD &&
"Expected a FunctionDecl");
5027 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
5028 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
5032 if (
Decl->isDefined()) {
5033 EmitGlobalFunctionDefinition(CurGD,
nullptr);
5041 assert(
Func &&
"This should have just been created");
5049 bool ShouldEmitResolver = !
getTriple().isAArch64();
5050 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5051 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
5054 FD, [&](
const FunctionDecl *CurFD) {
5055 llvm::SmallVector<StringRef, 8> Feats;
5058 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
5060 TA->getX86AddedFeatures(Feats);
5061 llvm::Function *
Func = createFunction(CurFD);
5062 DeclMap.insert({
Func, CurFD});
5063 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
5064 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
5065 if (TVA->isDefaultVersion() && IsDefined)
5066 ShouldEmitResolver =
true;
5067 llvm::Function *
Func = createFunction(CurFD);
5068 DeclMap.insert({
Func, CurFD});
5070 TVA->getFeatures(Feats, Delim);
5071 Options.emplace_back(
Func, Feats);
5072 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
5073 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
5074 if (!TC->isFirstOfVersion(I))
5076 if (TC->isDefaultVersion(I) && IsDefined)
5077 ShouldEmitResolver =
true;
5078 llvm::Function *
Func = createFunction(CurFD, I);
5079 DeclMap.insert({
Func, CurFD});
5082 TC->getX86Feature(Feats, I);
5083 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
5086 TC->getFeatures(Feats, I, Delim);
5087 Options.emplace_back(
Func, Feats);
5091 llvm_unreachable(
"unexpected MultiVersionKind");
5094 if (!ShouldEmitResolver)
5097 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
5098 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
5099 ResolverConstant = IFunc->getResolver();
5104 *
this, GD, FD,
true);
5111 auto *Alias = llvm::GlobalAlias::create(
5113 MangledName +
".ifunc", IFunc, &
getModule());
5122 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
5123 const CodeGenFunction::FMVResolverOption &RHS) {
5129 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
5130 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
5131 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
5132 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
5133 return LHS.isSubsetOf(RHS);
5135 Diags.Report(DeclMap[I->Function]->getLocation(),
5136 diag::warn_unreachable_version)
5137 << I->Function->getName();
5138 assert(I->Function->user_empty() &&
"unexpected users");
5139 I->Function->eraseFromParent();
5140 I->Function =
nullptr;
5144 CodeGenFunction CGF(*
this);
5145 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5147 setMultiVersionResolverAttributes(ResolverFunc, GD);
5149 ResolverFunc->setComdat(
5150 getModule().getOrInsertComdat(ResolverFunc->getName()));
5156 if (!MVFuncsToEmit.empty())
5161 if (!MultiVersionFuncs.empty())
5162 emitMultiVersionFunctions();
5172 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5174 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5175 llvm::GlobalVariable::ExternalWeakLinkage,
5177 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5182void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5183 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5185 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5187 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5188 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5189 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5190 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5192 DS->takeName(OldDS);
5193 OldDS->replaceAllUsesWith(DS);
5194 OldDS->eraseFromParent();
5200 llvm::Constant *
New) {
5203 Old->replaceAllUsesWith(
New);
5204 Old->eraseFromParent();
5207void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5209 assert(FD &&
"Not a FunctionDecl?");
5211 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5212 assert(DD &&
"Not a cpu_dispatch Function?");
5218 UpdateMultiVersionNames(GD, FD, ResolverName);
5220 llvm::Type *ResolverType;
5221 GlobalDecl ResolverGD;
5223 ResolverType = llvm::FunctionType::get(
5234 ResolverName, ResolverType, ResolverGD,
false));
5237 ResolverFunc->setComdat(
5238 getModule().getOrInsertComdat(ResolverFunc->getName()));
5240 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5243 for (
const IdentifierInfo *II : DD->cpus()) {
5251 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5254 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5260 Func = GetOrCreateLLVMFunction(
5261 MangledName, DeclTy, ExistingDecl,
5267 llvm::SmallVector<StringRef, 32> Features;
5268 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5269 llvm::transform(Features, Features.begin(),
5270 [](StringRef Str) { return Str.substr(1); });
5271 llvm::erase_if(Features, [&Target](StringRef Feat) {
5272 return !Target.validateCpuSupports(Feat);
5278 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5279 const CodeGenFunction::FMVResolverOption &RHS) {
5280 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5281 llvm::X86::getCpuSupportsMask(RHS.
Features);
5288 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5289 (Options.end() - 2)->Features),
5290 [](
auto X) { return X == 0; })) {
5291 StringRef LHSName = (Options.end() - 2)->Function->getName();
5292 StringRef RHSName = (Options.end() - 1)->Function->getName();
5293 if (LHSName.compare(RHSName) < 0)
5294 Options.erase(Options.end() - 2);
5296 Options.erase(Options.end() - 1);
5299 CodeGenFunction CGF(*
this);
5300 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5301 setMultiVersionResolverAttributes(ResolverFunc, GD);
5306 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5311 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5318 *
this, GD, FD,
true);
5321 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5329void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5331 assert(FD &&
"Not a FunctionDecl?");
5334 std::string MangledName =
5336 if (!DeferredResolversToEmit.insert(MangledName).second)
5339 MultiVersionFuncs.push_back(GD);
5345llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5347 assert(FD &&
"Not a FunctionDecl?");
5349 std::string MangledName =
5354 std::string ResolverName = MangledName;
5358 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5362 ResolverName +=
".ifunc";
5369 ResolverName +=
".resolver";
5372 bool ShouldReturnIFunc =
5391 AddDeferredMultiVersionResolverToEmit(GD);
5395 if (ShouldReturnIFunc) {
5397 llvm::Type *ResolverType = llvm::FunctionType::get(
5399 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5400 MangledName +
".resolver", ResolverType, GlobalDecl{},
5408 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5410 GIF->setName(ResolverName);
5417 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5418 ResolverName, DeclTy, GlobalDecl{},
false);
5420 "Resolver should be created for the first time");
5425void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5427 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5440 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5451bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5452 const llvm::GlobalValue *GV)
const {
5453 auto SC = GV->getDLLStorageClass();
5454 if (SC == llvm::GlobalValue::DefaultStorageClass)
5457 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5458 !MRD->
hasAttr<DLLImportAttr>()) ||
5459 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5460 !MRD->
hasAttr<DLLExportAttr>())) &&
5471llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5472 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5473 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5477 std::string NameWithoutMultiVersionMangling;
5478 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5480 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5481 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5482 !DontDefer && !IsForDefinition) {
5485 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5487 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5490 GDDef = GlobalDecl(FDDef);
5498 UpdateMultiVersionNames(GD, FD, MangledName);
5499 if (!IsForDefinition) {
5505 AddDeferredMultiVersionResolverToEmit(GD);
5507 *
this, GD, FD,
true);
5516 *
this, GD, FD,
true);
5518 return GetOrCreateMultiVersionResolver(GD);
5523 if (!NameWithoutMultiVersionMangling.empty())
5524 MangledName = NameWithoutMultiVersionMangling;
5529 if (WeakRefReferences.erase(Entry)) {
5530 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5531 if (FD && !FD->
hasAttr<WeakAttr>())
5532 Entry->setLinkage(llvm::Function::ExternalLinkage);
5536 if (D && shouldDropDLLAttribute(D, Entry)) {
5537 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5543 if (IsForDefinition && !Entry->isDeclaration()) {
5550 DiagnosedConflictingDefinitions.insert(GD).second) {
5554 diag::note_previous_definition);
5559 (Entry->getValueType() == Ty)) {
5566 if (!IsForDefinition)
5573 bool IsIncompleteFunction =
false;
5575 llvm::FunctionType *FTy;
5579 FTy = llvm::FunctionType::get(
VoidTy,
false);
5580 IsIncompleteFunction =
true;
5584 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5585 Entry ? StringRef() : MangledName, &
getModule());
5589 if (D && D->
hasAttr<AnnotateAttr>())
5607 if (!Entry->use_empty()) {
5609 Entry->removeDeadConstantUsers();
5615 assert(F->getName() == MangledName &&
"name was uniqued!");
5617 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5618 if (ExtraAttrs.hasFnAttrs()) {
5619 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5627 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5630 addDeferredDeclToEmit(GD);
5635 auto DDI = DeferredDecls.find(MangledName);
5636 if (DDI != DeferredDecls.end()) {
5640 addDeferredDeclToEmit(DDI->second);
5641 DeferredDecls.erase(DDI);
5669 if (!IsIncompleteFunction) {
5670 assert(F->getFunctionType() == Ty);
5688 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5698 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5701 DD->getParent()->getNumVBases() == 0)
5706 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5707 false, llvm::AttributeList(),
5710 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5714 if (IsForDefinition)
5722 llvm::GlobalValue *F =
5725 return llvm::NoCFIValue::get(F);
5735 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5738 if (!
C.getLangOpts().CPlusPlus)
5743 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5744 ?
C.Idents.get(
"terminate")
5745 :
C.Idents.get(Name);
5747 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5751 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5752 for (
const auto *
Result : LSD->lookup(&NS))
5753 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5758 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5767 llvm::Function *F, StringRef Name) {
5773 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5776 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5777 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5778 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5785 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5786 if (AssumeConvergent) {
5788 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5791 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5796 llvm::Constant *
C = GetOrCreateLLVMFunction(
5798 false,
false, ExtraAttrs);
5800 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5816 llvm::AttributeList ExtraAttrs,
bool Local,
5817 bool AssumeConvergent) {
5818 if (AssumeConvergent) {
5820 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5824 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5828 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5837 markRegisterParameterAttributes(F);
5863 if (WeakRefReferences.erase(Entry)) {
5864 if (D && !D->
hasAttr<WeakAttr>())
5865 Entry->setLinkage(llvm::Function::ExternalLinkage);
5869 if (D && shouldDropDLLAttribute(D, Entry))
5870 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5872 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5875 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5880 if (IsForDefinition && !Entry->isDeclaration()) {
5888 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5890 DiagnosedConflictingDefinitions.insert(D).second) {
5894 diag::note_previous_definition);
5899 if (Entry->getType()->getAddressSpace() != TargetAS)
5900 return llvm::ConstantExpr::getAddrSpaceCast(
5901 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5905 if (!IsForDefinition)
5911 auto *GV =
new llvm::GlobalVariable(
5912 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5913 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5914 getContext().getTargetAddressSpace(DAddrSpace));
5919 GV->takeName(Entry);
5921 if (!Entry->use_empty()) {
5922 Entry->replaceAllUsesWith(GV);
5925 Entry->eraseFromParent();
5931 auto DDI = DeferredDecls.find(MangledName);
5932 if (DDI != DeferredDecls.end()) {
5935 addDeferredDeclToEmit(DDI->second);
5936 DeferredDecls.erase(DDI);
5941 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5948 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5954 CXXThreadLocals.push_back(D);
5962 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5963 EmitGlobalVarDefinition(D);
5968 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5969 GV->setSection(SA->getName());
5973 if (
getTriple().getArch() == llvm::Triple::xcore &&
5977 GV->setSection(
".cp.rodata");
5980 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5981 GV->setCodeModel(CMA->getModel());
5986 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5990 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5991 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5992 if (!HasMutableFields) {
5999 auto *InitType =
Init->getType();
6000 if (GV->getValueType() != InitType) {
6005 GV->setName(StringRef());
6010 ->stripPointerCasts());
6013 GV->eraseFromParent();
6016 GV->setInitializer(
Init);
6017 GV->setConstant(
true);
6018 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
6038 SanitizerMD->reportGlobal(GV, *D);
6043 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
6044 if (DAddrSpace != ExpectedAS)
6057 false, IsForDefinition);
6078 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
6079 llvm::Align Alignment) {
6080 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
6081 llvm::GlobalVariable *OldGV =
nullptr;
6085 if (GV->getValueType() == Ty)
6090 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
6095 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
6100 GV->takeName(OldGV);
6102 if (!OldGV->use_empty()) {
6103 OldGV->replaceAllUsesWith(GV);
6106 OldGV->eraseFromParent();
6110 !GV->hasAvailableExternallyLinkage())
6111 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6113 GV->setAlignment(Alignment);
6150 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
6158 if (GV && !GV->isDeclaration())
6163 if (!MustBeEmitted(D) && !GV) {
6164 DeferredDecls[MangledName] = D;
6169 EmitGlobalVarDefinition(D);
6174 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6176 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6191 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6195 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6198 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6200 if (!Fn->getSubprogram())
6206 return Context.toCharUnitsFromBits(
6211 if (LangOpts.OpenCL) {
6222 if (LangOpts.SYCLIsDevice &&
6226 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6228 if (D->
hasAttr<CUDAConstantAttr>())
6230 if (D->
hasAttr<CUDASharedAttr>())
6232 if (D->
hasAttr<CUDADeviceAttr>())
6240 if (LangOpts.OpenMP) {
6242 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6250 if (LangOpts.OpenCL)
6252 if (LangOpts.SYCLIsDevice)
6254 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
6262 if (
auto AS =
getTarget().getConstantAddressSpace())
6275static llvm::Constant *
6277 llvm::GlobalVariable *GV) {
6278 llvm::Constant *Cast = GV;
6283 GV, llvm::PointerType::get(
6290template<
typename SomeDecl>
6292 llvm::GlobalValue *GV) {
6307 const SomeDecl *
First = D->getFirstDecl();
6308 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6314 std::pair<StaticExternCMap::iterator, bool> R =
6315 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6320 R.first->second =
nullptr;
6327 if (D.
hasAttr<SelectAnyAttr>())
6331 if (
auto *VD = dyn_cast<VarDecl>(&D))
6345 llvm_unreachable(
"No such linkage");
6353 llvm::GlobalObject &GO) {
6356 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6364void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6379 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6380 OpenMPRuntime->emitTargetGlobalVariable(D))
6383 llvm::TrackingVH<llvm::Constant>
Init;
6384 bool NeedsGlobalCtor =
false;
6388 bool IsDefinitionAvailableExternally =
6390 bool NeedsGlobalDtor =
6391 !IsDefinitionAvailableExternally &&
6398 if (IsDefinitionAvailableExternally &&
6409 std::optional<ConstantEmitter> emitter;
6414 bool IsCUDASharedVar =
6419 bool IsCUDAShadowVar =
6421 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6422 D->
hasAttr<CUDASharedAttr>());
6423 bool IsCUDADeviceShadowVar =
6428 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6429 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6433 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6436 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6437 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6438 }
else if (!InitExpr) {
6451 initializedGlobalDecl = GlobalDecl(D);
6452 emitter.emplace(*
this);
6453 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6461 if (!IsDefinitionAvailableExternally)
6462 NeedsGlobalCtor =
true;
6466 NeedsGlobalCtor =
false;
6478 DelayedCXXInitPosition.erase(D);
6485 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6490 llvm::Type* InitType =
Init->getType();
6491 llvm::Constant *Entry =
6495 Entry = Entry->stripPointerCasts();
6498 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6509 if (!GV || GV->getValueType() != InitType ||
6510 GV->getType()->getAddressSpace() !=
6514 Entry->setName(StringRef());
6519 ->stripPointerCasts());
6522 llvm::Constant *NewPtrForOldDecl =
6523 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6525 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6533 if (D->
hasAttr<AnnotateAttr>())
6546 if (LangOpts.CUDA) {
6547 if (LangOpts.CUDAIsDevice) {
6550 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6553 GV->setExternallyInitialized(
true);
6560 if (LangOpts.HLSL &&
6565 GV->setExternallyInitialized(
true);
6567 GV->setInitializer(
Init);
6574 emitter->finalize(GV);
6577 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6578 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6582 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6583 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6585 GV->setConstant(
true);
6590 if (std::optional<CharUnits> AlignValFromAllocate =
6592 AlignVal = *AlignValFromAllocate;
6610 Linkage == llvm::GlobalValue::ExternalLinkage &&
6611 Context.getTargetInfo().getTriple().isOSDarwin() &&
6613 Linkage = llvm::GlobalValue::InternalLinkage;
6618 if (LangOpts.HLSL &&
6620 Linkage = llvm::GlobalValue::ExternalLinkage;
6623 if (D->
hasAttr<DLLImportAttr>())
6624 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6625 else if (D->
hasAttr<DLLExportAttr>())
6626 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6628 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6630 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6632 GV->setConstant(
false);
6637 if (!GV->getInitializer()->isNullValue())
6638 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6641 setNonAliasAttributes(D, GV);
6643 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6645 CXXThreadLocals.push_back(D);
6652 if (NeedsGlobalCtor || NeedsGlobalDtor)
6653 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6655 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6660 DI->EmitGlobalVariable(GV, D);
6668 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6679 if (D->
hasAttr<SectionAttr>())
6685 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6686 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6687 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6688 D->
hasAttr<PragmaClangRodataSectionAttr>())
6696 if (D->
hasAttr<WeakImportAttr>())
6705 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6706 if (D->
hasAttr<AlignedAttr>())
6709 if (Context.isAlignmentRequired(VarType))
6713 for (
const FieldDecl *FD : RD->fields()) {
6714 if (FD->isBitField())
6716 if (FD->
hasAttr<AlignedAttr>())
6718 if (Context.isAlignmentRequired(FD->
getType()))
6730 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6731 Context.getTypeAlignIfKnown(D->
getType()) >
6738llvm::GlobalValue::LinkageTypes
6742 return llvm::Function::InternalLinkage;
6745 return llvm::GlobalVariable::WeakAnyLinkage;
6749 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6754 return llvm::GlobalValue::AvailableExternallyLinkage;
6768 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6769 : llvm::Function::InternalLinkage;
6783 return llvm::Function::ExternalLinkage;
6786 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6787 : llvm::Function::InternalLinkage;
6788 return llvm::Function::WeakODRLinkage;
6795 CodeGenOpts.NoCommon))
6796 return llvm::GlobalVariable::CommonLinkage;
6802 if (D->
hasAttr<SelectAnyAttr>())
6803 return llvm::GlobalVariable::WeakODRLinkage;
6807 return llvm::GlobalVariable::ExternalLinkage;
6810llvm::GlobalValue::LinkageTypes
6819 llvm::Function *newFn) {
6821 if (old->use_empty())
6824 llvm::Type *newRetTy = newFn->getReturnType();
6829 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6831 llvm::User *user = ui->getUser();
6835 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6836 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6842 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6845 if (!callSite->isCallee(&*ui))
6850 if (callSite->getType() != newRetTy && !callSite->use_empty())
6855 llvm::AttributeList oldAttrs = callSite->getAttributes();
6858 unsigned newNumArgs = newFn->arg_size();
6859 if (callSite->arg_size() < newNumArgs)
6865 bool dontTransform =
false;
6866 for (llvm::Argument &A : newFn->args()) {
6867 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6868 dontTransform =
true;
6873 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6881 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6885 callSite->getOperandBundlesAsDefs(newBundles);
6887 llvm::CallBase *newCall;
6889 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6890 callSite->getIterator());
6893 newCall = llvm::InvokeInst::Create(
6894 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6895 newArgs, newBundles,
"", callSite->getIterator());
6899 if (!newCall->getType()->isVoidTy())
6900 newCall->takeName(callSite);
6901 newCall->setAttributes(
6902 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6903 oldAttrs.getRetAttrs(), newArgAttrs));
6904 newCall->setCallingConv(callSite->getCallingConv());
6907 if (!callSite->use_empty())
6908 callSite->replaceAllUsesWith(newCall);
6911 if (callSite->getDebugLoc())
6912 newCall->setDebugLoc(callSite->getDebugLoc());
6914 callSitesToBeRemovedFromParent.push_back(callSite);
6917 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6918 callSite->eraseFromParent();
6932 llvm::Function *NewFn) {
6942 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6954void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6955 llvm::GlobalValue *GV) {
6963 if (!GV || (GV->getValueType() != Ty))
6969 if (!GV->isDeclaration())
6979 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
6980 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
6992 setNonAliasAttributes(GD, Fn);
6994 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6995 (CodeGenOpts.OptimizationLevel == 0) &&
6998 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
7000 !D->
hasAttr<NoInlineAttr>() &&
7001 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
7002 !D->
hasAttr<OptimizeNoneAttr>() &&
7003 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
7004 !ShouldAddOptNone) {
7005 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
7015 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
7016 if (UnwindMode != llvm::WinX64EHUnwindMode::Default &&
7017 UnwindMode != llvm::WinX64EHUnwindMode::V3 &&
7018 Fn->needsUnwindTableEntry()) {
7019 bool HasEGPR =
false;
7020 if (Fn->hasFnAttribute(
"target-features")) {
7022 Fn->getFnAttribute(
"target-features").getValueAsString();
7024 Feats.split(Tokens,
',', -1,
false);
7025 for (StringRef
Tok : Tokens) {
7028 else if (
Tok ==
"-egpr")
7032 HasEGPR = Context.getTargetInfo().hasFeature(
"egpr");
7035 unsigned DiagID = Diags.getCustomDiagID(
7037 "EGPR target feature requires unwind version 3");
7043 auto GetPriority = [
this](
const auto *Attr) ->
int {
7044 Expr *E = Attr->getPriority();
7048 return Attr->DefaultPriority;
7051 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
7053 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
7059void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
7061 const AliasAttr *AA = D->
getAttr<AliasAttr>();
7062 assert(AA &&
"Not an alias?");
7066 if (AA->getAliasee() == MangledName) {
7067 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7074 if (Entry && !Entry->isDeclaration())
7077 Aliases.push_back(GD);
7083 llvm::Constant *Aliasee;
7084 llvm::GlobalValue::LinkageTypes
LT;
7086 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
7092 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
7099 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
7101 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
7104 if (GA->getAliasee() == Entry) {
7105 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7109 assert(Entry->isDeclaration());
7118 GA->takeName(Entry);
7120 Entry->replaceAllUsesWith(GA);
7121 Entry->eraseFromParent();
7123 GA->setName(MangledName);
7131 GA->setLinkage(llvm::Function::WeakAnyLinkage);
7134 if (
const auto *VD = dyn_cast<VarDecl>(D))
7135 if (VD->getTLSKind())
7146void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
7148 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
7149 assert(IFA &&
"Not an ifunc?");
7153 if (IFA->getResolver() == MangledName) {
7154 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7160 if (Entry && !Entry->isDeclaration()) {
7163 DiagnosedConflictingDefinitions.insert(GD).second) {
7164 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
7167 diag::note_previous_definition);
7172 Aliases.push_back(GD);
7178 llvm::Constant *Resolver =
7179 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
7183 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
7184 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
7186 if (GIF->getResolver() == Entry) {
7187 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7190 assert(Entry->isDeclaration());
7199 GIF->takeName(Entry);
7201 Entry->replaceAllUsesWith(GIF);
7202 Entry->eraseFromParent();
7204 GIF->setName(MangledName);
7210 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7211 (llvm::Intrinsic::ID)IID, Tys);
7214static llvm::StringMapEntry<llvm::GlobalVariable *> &
7217 bool &IsUTF16,
unsigned &StringLength) {
7218 StringRef String = Literal->getString();
7219 unsigned NumBytes = String.size();
7222 if (!Literal->containsNonAsciiOrNull()) {
7223 StringLength = NumBytes;
7224 return *Map.insert(std::make_pair(String,
nullptr)).first;
7231 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7232 llvm::UTF16 *ToPtr = &ToBuf[0];
7234 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7235 ToPtr + NumBytes, llvm::strictConversion);
7238 StringLength = ToPtr - &ToBuf[0];
7242 return *Map.insert(std::make_pair(
7243 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7244 (StringLength + 1) * 2),
7250 unsigned StringLength = 0;
7251 bool isUTF16 =
false;
7252 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7257 if (
auto *
C = Entry.second)
7262 const llvm::Triple &Triple =
getTriple();
7265 const bool IsSwiftABI =
7266 static_cast<unsigned>(CFRuntime) >=
7271 if (!CFConstantStringClassRef) {
7272 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7274 Ty = llvm::ArrayType::get(Ty, 0);
7276 switch (CFRuntime) {
7280 CFConstantStringClassName =
7281 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7282 :
"$s10Foundation19_NSCFConstantStringCN";
7286 CFConstantStringClassName =
7287 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7288 :
"$S10Foundation19_NSCFConstantStringCN";
7292 CFConstantStringClassName =
7293 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7294 :
"__T010Foundation19_NSCFConstantStringCN";
7301 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7302 llvm::GlobalValue *GV =
nullptr;
7304 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7311 if ((VD = dyn_cast<VarDecl>(
Result)))
7314 if (Triple.isOSBinFormatELF()) {
7316 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7318 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7319 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7320 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7322 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7330 CFConstantStringClassRef =
7331 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7334 QualType CFTy = Context.getCFConstantStringType();
7339 auto Fields = Builder.beginStruct(STy);
7348 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7349 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7351 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7355 llvm::Constant *
C =
nullptr;
7358 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7359 Entry.first().size() / 2);
7360 C = llvm::ConstantDataArray::get(VMContext, Arr);
7362 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7368 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7369 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7370 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7373 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7374 : Context.getTypeAlignInChars(Context.CharTy);
7380 if (Triple.isOSBinFormatMachO())
7381 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7382 :
"__TEXT,__cstring,cstring_literals");
7385 else if (Triple.isOSBinFormatELF())
7386 GV->setSection(
".rodata");
7392 llvm::IntegerType *LengthTy =
7402 Fields.addInt(LengthTy, StringLength);
7410 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7412 llvm::GlobalVariable::PrivateLinkage);
7413 GV->addAttribute(
"objc_arc_inert");
7414 switch (Triple.getObjectFormat()) {
7415 case llvm::Triple::UnknownObjectFormat:
7416 llvm_unreachable(
"unknown file format");
7417 case llvm::Triple::DXContainer:
7418 case llvm::Triple::GOFF:
7419 case llvm::Triple::SPIRV:
7420 case llvm::Triple::XCOFF:
7421 llvm_unreachable(
"unimplemented");
7422 case llvm::Triple::COFF:
7423 case llvm::Triple::ELF:
7424 case llvm::Triple::Wasm:
7425 GV->setSection(
"cfstring");
7427 case llvm::Triple::MachO:
7428 GV->setSection(
"__DATA,__cfstring");
7437 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7441 if (ObjCFastEnumerationStateType.isNull()) {
7442 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7446 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7447 Context.getPointerType(Context.UnsignedLongTy),
7448 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7451 for (
size_t i = 0; i < 4; ++i) {
7456 FieldTypes[i],
nullptr,
7465 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7468 return ObjCFastEnumerationStateType;
7482 assert(CAT &&
"String literal not of constant array type!");
7484 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7488 llvm::Type *ElemTy = AType->getElementType();
7489 unsigned NumElements = AType->getNumElements();
7492 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7494 Elements.reserve(NumElements);
7496 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7498 Elements.resize(NumElements);
7499 return llvm::ConstantDataArray::get(VMContext, Elements);
7502 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7504 Elements.reserve(NumElements);
7506 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7508 Elements.resize(NumElements);
7509 return llvm::ConstantDataArray::get(VMContext, Elements);
7512static llvm::GlobalVariable *
7521 auto *GV =
new llvm::GlobalVariable(
7522 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7523 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7525 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7526 if (GV->isWeakForLinker()) {
7527 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7528 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7544 llvm::GlobalVariable **Entry =
nullptr;
7545 if (!LangOpts.WritableStrings) {
7546 Entry = &ConstantStringMap[
C];
7547 if (
auto GV = *Entry) {
7548 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7551 GV->getValueType(), Alignment);
7556 StringRef GlobalVariableName;
7557 llvm::GlobalValue::LinkageTypes LT;
7562 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7563 !LangOpts.WritableStrings) {
7564 llvm::raw_svector_ostream Out(MangledNameBuffer);
7566 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7567 GlobalVariableName = MangledNameBuffer;
7569 LT = llvm::GlobalValue::PrivateLinkage;
7570 GlobalVariableName = Name;
7582 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7585 GV->getValueType(), Alignment);
7602 StringRef GlobalName) {
7603 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7608 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7611 llvm::GlobalVariable **Entry =
nullptr;
7612 if (!LangOpts.WritableStrings) {
7613 Entry = &ConstantStringMap[
C];
7614 if (
auto GV = *Entry) {
7615 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7618 GV->getValueType(), Alignment);
7624 GlobalName, Alignment);
7629 GV->getValueType(), Alignment);
7647 MaterializedType = E->
getType();
7651 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7652 if (!InsertResult.second) {
7655 if (!InsertResult.first->second) {
7660 InsertResult.first->second =
new llvm::GlobalVariable(
7661 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7665 llvm::cast<llvm::GlobalVariable>(
7666 InsertResult.first->second->stripPointerCasts())
7675 llvm::raw_svector_ostream Out(Name);
7697 std::optional<ConstantEmitter> emitter;
7698 llvm::Constant *InitialValue =
nullptr;
7703 emitter.emplace(*
this);
7704 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7709 Type = InitialValue->getType();
7718 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7720 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7724 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7728 Linkage = llvm::GlobalVariable::InternalLinkage;
7732 auto *GV =
new llvm::GlobalVariable(
7734 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7735 if (emitter) emitter->finalize(GV);
7737 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7739 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7741 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7745 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7746 if (VD->getTLSKind())
7748 llvm::Constant *CV = GV;
7751 GV, llvm::PointerType::get(
7757 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7759 Entry->replaceAllUsesWith(CV);
7760 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7769void CodeGenModule::EmitObjCPropertyImplementations(
const
7782 if (!Getter || Getter->isSynthesizedAccessorStub())
7785 auto *Setter = PID->getSetterMethodDecl();
7786 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7797 if (ivar->getType().isDestructedType())
7818void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7831 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7846 getContext().getObjCIdType(),
nullptr, D,
true,
7852 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7857void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7864 EmitDeclContext(LSD);
7867void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7869 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7872 std::unique_ptr<CodeGenFunction> &CurCGF =
7873 GlobalTopLevelStmtBlockInFlight.first;
7877 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7885 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7886 FunctionArgList Args;
7888 const CGFunctionInfo &FnInfo =
7891 llvm::Function *
Fn = llvm::Function::Create(
7892 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7894 CurCGF.reset(
new CodeGenFunction(*
this));
7895 GlobalTopLevelStmtBlockInFlight.second = D;
7896 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7898 CXXGlobalInits.push_back(Fn);
7901 CurCGF->EmitStmt(D->
getStmt());
7904void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7905 for (
auto *I : DC->
decls()) {
7911 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7912 for (
auto *M : OID->methods())
7931 case Decl::CXXConversion:
7932 case Decl::CXXMethod:
7933 case Decl::Function:
7940 case Decl::CXXDeductionGuide:
7945 case Decl::Decomposition:
7946 case Decl::VarTemplateSpecialization:
7948 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7949 for (
auto *B : DD->flat_bindings())
7950 if (
auto *HD = B->getHoldingVar())
7957 case Decl::IndirectField:
7961 case Decl::Namespace:
7964 case Decl::ClassTemplateSpecialization: {
7967 if (Spec->getSpecializationKind() ==
7969 Spec->hasDefinition())
7970 DI->completeTemplateDefinition(*Spec);
7972 case Decl::CXXRecord: {
7976 DI->EmitAndRetainType(
7980 DI->completeUnusedClass(*CRD);
7983 for (
auto *I : CRD->
decls())
7989 case Decl::UsingShadow:
7990 case Decl::ClassTemplate:
7991 case Decl::VarTemplate:
7993 case Decl::VarTemplatePartialSpecialization:
7994 case Decl::FunctionTemplate:
7995 case Decl::TypeAliasTemplate:
8004 case Decl::UsingEnum:
8008 case Decl::NamespaceAlias:
8012 case Decl::UsingDirective:
8016 case Decl::CXXConstructor:
8019 case Decl::CXXDestructor:
8023 case Decl::StaticAssert:
8024 case Decl::ExplicitInstantiation:
8031 case Decl::ObjCInterface:
8032 case Decl::ObjCCategory:
8035 case Decl::ObjCProtocol: {
8037 if (Proto->isThisDeclarationADefinition())
8038 ObjCRuntime->GenerateProtocol(Proto);
8042 case Decl::ObjCCategoryImpl:
8048 case Decl::ObjCImplementation: {
8050 EmitObjCPropertyImplementations(OMD);
8051 EmitObjCIvarInitializations(OMD);
8052 ObjCRuntime->GenerateClass(OMD);
8056 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
8057 OMD->getClassInterface()), OMD->getLocation());
8060 case Decl::ObjCMethod: {
8067 case Decl::ObjCCompatibleAlias:
8071 case Decl::PragmaComment: {
8073 switch (PCD->getCommentKind()) {
8075 llvm_unreachable(
"unexpected pragma comment kind");
8083 ProcessPragmaCommentCopyright(PCD->getArg(), PCD->isFromASTFile());
8093 case Decl::PragmaDetectMismatch: {
8099 case Decl::LinkageSpec:
8103 case Decl::FileScopeAsm: {
8105 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8108 if (LangOpts.OpenMPIsTargetDevice)
8111 if (LangOpts.SYCLIsDevice)
8116 llvm::Module::GlobalAsmProperties Props;
8117 Props.TargetFeatures = llvm::join(TargetOpts.
Features,
",");
8118 Props.TargetCPU = TargetOpts.
CPU;
8120 llvm::Module::GlobalAsmFragment(AD->getAsmString(), Props));
8124 case Decl::TopLevelStmt:
8128 case Decl::Import: {
8132 if (!ImportedModules.insert(Import->getImportedModule()))
8136 if (!Import->getImportedOwningModule()) {
8138 DI->EmitImportDecl(*Import);
8144 if (CXX20ModuleInits && Import->getImportedModule() &&
8145 Import->getImportedModule()->isNamedModule())
8154 Visited.insert(Import->getImportedModule());
8155 Stack.push_back(Import->getImportedModule());
8157 while (!Stack.empty()) {
8159 if (!EmittedModuleInitializers.insert(Mod).second)
8162 for (
auto *D : Context.getModuleInitializers(Mod))
8169 if (Submodule->IsExplicit)
8172 if (Visited.insert(Submodule).second)
8173 Stack.push_back(Submodule);
8183 case Decl::OMPThreadPrivate:
8187 case Decl::OMPAllocate:
8191 case Decl::OMPDeclareReduction:
8195 case Decl::OMPDeclareMapper:
8199 case Decl::OMPRequires:
8204 case Decl::TypeAlias:
8206 DI->EmitAndRetainType(
getContext().getTypedefType(
8214 DI->EmitAndRetainType(
8221 DI->EmitAndRetainType(
8225 case Decl::HLSLRootSignature:
8228 case Decl::HLSLBuffer:
8232 case Decl::OpenACCDeclare:
8235 case Decl::OpenACCRoutine:
8250 if (!CodeGenOpts.CoverageMapping)
8253 case Decl::CXXConversion:
8254 case Decl::CXXMethod:
8255 case Decl::Function:
8256 case Decl::ObjCMethod:
8257 case Decl::CXXConstructor:
8258 case Decl::CXXDestructor: {
8267 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8277 if (!CodeGenOpts.CoverageMapping)
8279 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8280 if (Fn->isTemplateInstantiation())
8283 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8291 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8294 const Decl *D = Entry.first;
8296 case Decl::CXXConversion:
8297 case Decl::CXXMethod:
8298 case Decl::Function:
8299 case Decl::ObjCMethod: {
8306 case Decl::CXXConstructor: {
8313 case Decl::CXXDestructor: {
8330 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8331 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8332 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8333 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8334 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8343 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8344 return llvm::ConstantInt::get(i64, PtrInt);
8348 llvm::NamedMDNode *&GlobalMetadata,
8350 llvm::GlobalValue *
Addr) {
8351 if (!GlobalMetadata)
8353 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8356 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8359 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8362bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8363 llvm::GlobalValue *CppFunc) {
8365 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8368 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8371 if (Elem == CppFunc)
8377 for (llvm::User *User : Elem->users()) {
8381 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8382 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8385 for (llvm::User *CEUser : ConstExpr->users()) {
8386 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8387 IFuncs.push_back(IFunc);
8392 CEs.push_back(ConstExpr);
8393 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8394 IFuncs.push_back(IFunc);
8406 for (llvm::GlobalIFunc *IFunc : IFuncs)
8407 IFunc->setResolver(
nullptr);
8408 for (llvm::ConstantExpr *ConstExpr : CEs)
8409 ConstExpr->destroyConstant();
8413 Elem->eraseFromParent();
8415 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8420 llvm::FunctionType::get(IFunc->getType(),
false);
8421 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8422 CppFunc->getName(), ResolverTy, {},
false);
8423 IFunc->setResolver(Resolver);
8433void CodeGenModule::EmitStaticExternCAliases() {
8436 for (
auto &I : StaticExternCValues) {
8437 const IdentifierInfo *Name = I.first;
8438 llvm::GlobalValue *Val = I.second;
8446 llvm::GlobalValue *ExistingElem =
8451 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8458 auto Res = Manglings.find(MangledName);
8459 if (Res == Manglings.end())
8461 Result = Res->getValue();
8472void CodeGenModule::EmitDeclMetadata() {
8473 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8475 for (
auto &I : MangledDeclNames) {
8476 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8486void CodeGenFunction::EmitDeclMetadata() {
8487 if (LocalDeclMap.empty())
return;
8492 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8494 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8496 for (
auto &I : LocalDeclMap) {
8497 const Decl *D = I.first;
8498 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8499 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8501 Alloca->setMetadata(
8502 DeclPtrKind, llvm::MDNode::get(
8503 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8504 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8511void CodeGenModule::EmitVersionIdentMetadata() {
8512 llvm::NamedMDNode *IdentMetadata =
8513 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8515 llvm::LLVMContext &Ctx = TheModule.getContext();
8517 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8518 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8521void CodeGenModule::EmitCommandLineMetadata() {
8522 llvm::NamedMDNode *CommandLineMetadata =
8523 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8525 llvm::LLVMContext &Ctx = TheModule.getContext();
8527 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8528 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8531void CodeGenModule::EmitCoverageFile() {
8532 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8536 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8537 llvm::LLVMContext &Ctx = TheModule.getContext();
8538 auto *CoverageDataFile =
8540 auto *CoverageNotesFile =
8542 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8543 llvm::MDNode *CU = CUNode->getOperand(i);
8544 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8545 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8558 LangOpts.ObjCRuntime.isGNUFamily())
8559 return ObjCRuntime->GetEHType(Ty);
8566 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8568 for (
auto RefExpr : D->
varlist()) {
8571 VD->getAnyInitializer() &&
8572 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8578 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8579 CXXGlobalInits.push_back(InitFunction);
8583llvm::Metadata *CodeGenModule::CreateMetadataIdentifierImpl(
8584 QualType T, MetadataTypeMap &Map, StringRef Suffix,
bool ForceString) {
8587 FnType->getReturnType(), FnType->getParamTypes(),
8588 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8590 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
8595 std::string OutName;
8596 llvm::raw_string_ostream Out(OutName);
8601 Out <<
".normalized";
8624 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
8629 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8633 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8634 ".generalized",
false);
8639 return CreateMetadataIdentifierImpl(
T, CallGraphMetadataIdMap,
"",
8647 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8648 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8649 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8650 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8651 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8652 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8653 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8654 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8662 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8664 if (CodeGenOpts.SanitizeCfiCrossDso)
8666 VTable->addTypeMetadata(Offset.getQuantity(),
8667 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8670 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8671 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8677 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8687 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8702 bool forPointeeType) {
8713 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8720 bool AlignForArray =
T->isArrayType();
8726 if (
T->isIncompleteType()) {
8743 if (
T.getQualifiers().hasUnaligned()) {
8745 }
else if (forPointeeType && !AlignForArray &&
8746 (RD =
T->getAsCXXRecordDecl())) {
8757 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8770 if (NumAutoVarInit >= StopAfter) {
8773 if (!NumAutoVarInit) {
8787 const Decl *D)
const {
8791 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8793 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8799 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8803 llvm::MD5::MD5Result
Result;
8804 for (
const auto &Arg : PreprocessorOpts.Macros)
8805 Hash.update(Arg.first);
8809 llvm::sys::fs::UniqueID ID;
8813 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8817 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8818 << PLoc.
getFilename() << Status.getError().message();
8820 ID = Status->getUniqueID();
8822 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8823 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8830 assert(DeferredDeclsToEmit.empty() &&
8831 "Should have emitted all decls deferred to emit.");
8832 assert(NewBuilder->DeferredDecls.empty() &&
8833 "Newly created module should not have deferred decls");
8834 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8835 assert(EmittedDeferredDecls.empty() &&
8836 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8838 assert(NewBuilder->DeferredVTables.empty() &&
8839 "Newly created module should not have deferred vtables");
8840 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8842 assert(NewBuilder->EmittedVTables.empty() &&
8843 "Newly created module should not have defined vtables");
8844 NewBuilder->EmittedVTables = std::move(EmittedVTables);
8846 assert(NewBuilder->MangledDeclNames.empty() &&
8847 "Newly created module should not have mangled decl names");
8848 assert(NewBuilder->Manglings.empty() &&
8849 "Newly created module should not have manglings");
8850 NewBuilder->Manglings = std::move(Manglings);
8852 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8854 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8858 std::string OutName;
8859 llvm::raw_string_ostream Out(OutName);
8867 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8873 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
8876 return RequireVectorDeletingDtor.count(RD);
8880 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8882 RequireVectorDeletingDtor.insert(RD);
8896 if (Entry && !Entry->isDeclaration()) {
8901 auto *NewFn = llvm::Function::Create(
8903 llvm::Function::ExternalLinkage, VDName, &
getModule());
8904 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
8906 NewFn->takeName(VDEntry);
8907 VDEntry->replaceAllUsesWith(NewFn);
8908 VDEntry->eraseFromParent();
8909 Entry->replaceAllUsesWith(NewFn);
8910 Entry->eraseFromParent();
8915 addDeferredDeclToEmit(VectorDtorGD);
8919 llvm::GlobalAlias *GlobalDeleteAlias,
8923 PendingMSVCGlobalDeletes.insert({GlobalDeleteAlias, OperatorDeleteFD});
8945 "__global_delete wrapper is only used with the Microsoft ABI");
8947 llvm::LLVMContext &LLVMCtx = M.getContext();
8951 llvm::FunctionType *FnTy = GlobDeleteFn->getFunctionType();
8961 StringRef GlobDeleteMangledName = GlobDeleteFn->getName();
8962 StringRef Signature;
8963 const char *WrapperBase;
8964 if (GlobDeleteMangledName.starts_with(
"??3@")) {
8965 Signature = GlobDeleteMangledName.substr(4);
8966 WrapperBase =
"?__global_delete@@";
8967 }
else if (GlobDeleteMangledName.starts_with(
"??_V@")) {
8968 Signature = GlobDeleteMangledName.substr(5);
8969 WrapperBase =
"?__global_array_delete@@";
8971 llvm_unreachable(
"unexpected global operator delete mangling");
8974 std::string GlobalDeleteName = (WrapperBase + Signature).str();
8975 std::string EmptyGlobalDeleteName =
8976 (
"?__empty_global_delete@@" + Signature).str();
8980 if (llvm::GlobalValue *Existing = M.getNamedValue(GlobalDeleteName))
8989 llvm::Function *EmptyFn = M.getFunction(EmptyGlobalDeleteName);
8991 EmptyFn = llvm::Function::Create(
8992 FnTy, llvm::GlobalValue::LinkOnceODRLinkage, EmptyGlobalDeleteName, &M);
8993 EmptyFn->setComdat(M.getOrInsertComdat(EmptyGlobalDeleteName));
8994 EmptyFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
9001 auto *BB = llvm::BasicBlock::Create(LLVMCtx,
"", EmptyFn);
9002 llvm::Function *TrapFn =
9003 llvm::Intrinsic::getOrInsertDeclaration(&M, llvm::Intrinsic::trap);
9004 auto *TrapCall = llvm::CallInst::Create(TrapFn, {},
"", BB);
9005 TrapCall->setDoesNotReturn();
9006 TrapCall->setDoesNotThrow();
9007 new llvm::UnreachableInst(LLVMCtx, BB);
9013 appendToUsed(M, {EmptyFn});
9021 auto *GlobalDeleteAlias = llvm::GlobalAlias::create(
9022 FnTy, GlobDeleteFn->getAddressSpace(), llvm::GlobalValue::WeakAnyLinkage,
9023 GlobalDeleteName, EmptyFn, &M);
9030 return GlobalDeleteAlias;
9042 if (!HasDirectGlobalDelete)
9045 for (
const auto &Entry : PendingMSVCGlobalDeletes) {
9046 llvm::GlobalAlias *Alias = Entry.first;
9054 llvm::Function::Create(FnTy, llvm::GlobalValue::LinkOnceODRLinkage,
9055 Alias->getAddressSpace(),
"", &
getModule());
9061 for (
auto &Arg : GlobDelFn->args())
9062 Args.push_back(&Arg);
9063 llvm::CallInst::Create(FnTy, RealDeleteFn, Args,
"", BB);
9068 Alias->replaceAllUsesWith(GlobDelFn);
9069 GlobDelFn->takeName(Alias);
9070 Alias->eraseFromParent();
9072 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 shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static bool hasUnwindExceptions(const LangOptions &langOpts)
Determines whether the language options require us to model unwind exceptions.
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static bool hasImplicitAttr(const ValueDecl *decl)
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 bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
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 bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static const char PFPDeactivationSymbolPrefix[]
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 bool shouldSkipAliasEmission(const CodeGenModule &CGM, const ValueDecl *Global)
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.
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
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
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
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.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void 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 isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
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 isImmediateFunction() const
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
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.
@ 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
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
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.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
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.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
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.
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.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
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.
@ 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.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
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)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
const FunctionProtoType * T
StringRef languageToString(Language L)
@ Dtor_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...
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
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.