52#include "llvm/ABI/IRTypeMapper.h"
53#include "llvm/ABI/TargetInfo.h"
54#include "llvm/ADT/APFloat.h"
55#include "llvm/ADT/STLExtras.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/ADT/StringSwitch.h"
58#include "llvm/Analysis/TargetLibraryInfo.h"
59#include "llvm/BinaryFormat/ELF.h"
60#include "llvm/IR/AttributeMask.h"
61#include "llvm/IR/CallingConv.h"
62#include "llvm/IR/DataLayout.h"
63#include "llvm/IR/Intrinsics.h"
64#include "llvm/IR/LLVMContext.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/ProfileSummary.h"
67#include "llvm/ProfileData/InstrProfReader.h"
68#include "llvm/ProfileData/SampleProf.h"
69#include "llvm/Support/ARMBuildAttributes.h"
70#include "llvm/Support/CRC.h"
71#include "llvm/Support/CodeGen.h"
72#include "llvm/Support/CommandLine.h"
73#include "llvm/Support/ConvertUTF.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/TimeProfiler.h"
76#include "llvm/TargetParser/AArch64TargetParser.h"
77#include "llvm/TargetParser/RISCVISAInfo.h"
78#include "llvm/TargetParser/Triple.h"
79#include "llvm/TargetParser/X86TargetParser.h"
80#include "llvm/Transforms/Instrumentation/KCFI.h"
81#include "llvm/Transforms/Utils/BuildLibCalls.h"
82#include "llvm/Transforms/Utils/KCFIHash.h"
83#include "llvm/Transforms/Utils/ModuleUtils.h"
91 "limited-coverage-experimental", llvm::cl::Hidden,
92 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
99 case TargetCXXABI::AppleARM64:
100 case TargetCXXABI::Fuchsia:
101 case TargetCXXABI::GenericAArch64:
102 case TargetCXXABI::GenericARM:
103 case TargetCXXABI::iOS:
104 case TargetCXXABI::WatchOS:
105 case TargetCXXABI::GenericMIPS:
106 case TargetCXXABI::GenericItanium:
107 case TargetCXXABI::WebAssembly:
108 case TargetCXXABI::XL:
110 case TargetCXXABI::Microsoft:
114 llvm_unreachable(
"invalid C++ ABI kind");
117static std::unique_ptr<TargetCodeGenInfo>
120 const llvm::Triple &Triple =
Target.getTriple();
123 switch (Triple.getArch()) {
127 case llvm::Triple::m68k:
129 case llvm::Triple::mips:
130 case llvm::Triple::mipsel:
131 if (Triple.getOS() == llvm::Triple::Win32)
135 case llvm::Triple::mips64:
136 case llvm::Triple::mips64el:
139 case llvm::Triple::avr: {
143 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
144 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
148 case llvm::Triple::aarch64:
149 case llvm::Triple::aarch64_32:
150 case llvm::Triple::aarch64_be: {
152 if (
Target.getABI() ==
"darwinpcs")
153 Kind = AArch64ABIKind::DarwinPCS;
154 else if (Triple.isOSWindows())
156 else if (
Target.getABI() ==
"aapcs-soft")
157 Kind = AArch64ABIKind::AAPCSSoft;
162 case llvm::Triple::wasm32:
163 case llvm::Triple::wasm64: {
165 if (
Target.getABI() ==
"experimental-mv")
166 Kind = WebAssemblyABIKind::ExperimentalMV;
170 case llvm::Triple::arm:
171 case llvm::Triple::armeb:
172 case llvm::Triple::thumb:
173 case llvm::Triple::thumbeb: {
174 if (Triple.getOS() == llvm::Triple::Win32)
178 StringRef ABIStr =
Target.getABI();
179 if (ABIStr ==
"apcs-gnu")
180 Kind = ARMABIKind::APCS;
181 else if (ABIStr ==
"aapcs16")
182 Kind = ARMABIKind::AAPCS16_VFP;
183 else if (CodeGenOpts.
FloatABI ==
"hard" ||
184 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
185 Kind = ARMABIKind::AAPCS_VFP;
190 case llvm::Triple::ppc: {
191 if (Triple.isOSAIX())
198 case llvm::Triple::ppcle: {
203 case llvm::Triple::ppc64:
204 if (Triple.isOSAIX())
207 if (Triple.isOSBinFormatELF()) {
209 if (
Target.getABI() ==
"elfv2")
210 Kind = PPC64_SVR4_ABIKind::ELFv2;
211 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
216 case llvm::Triple::ppc64le: {
217 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
219 if (
Target.getABI() ==
"elfv1")
220 Kind = PPC64_SVR4_ABIKind::ELFv1;
221 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
226 case llvm::Triple::nvptx:
227 case llvm::Triple::nvptx64:
230 case llvm::Triple::msp430:
233 case llvm::Triple::riscv32:
234 case llvm::Triple::riscv64:
235 case llvm::Triple::riscv32be:
236 case llvm::Triple::riscv64be: {
237 StringRef ABIStr =
Target.getABI();
239 unsigned ABIFLen = 0;
240 if (ABIStr.ends_with(
"f"))
242 else if (ABIStr.ends_with(
"d"))
244 bool EABI = ABIStr.ends_with(
"e");
248 case llvm::Triple::systemz: {
249 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
250 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
251 if (Triple.getOS() == llvm::Triple::ZOS)
256 case llvm::Triple::tce:
257 case llvm::Triple::tcele:
258 case llvm::Triple::tcele64:
261 case llvm::Triple::x86: {
262 bool IsDarwinVectorABI = Triple.isOSDarwin();
263 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
265 if (Triple.getOS() == llvm::Triple::Win32) {
267 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
268 CodeGenOpts.NumRegisterParameters);
271 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
272 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
275 case llvm::Triple::x86_64: {
276 StringRef ABI =
Target.getABI();
277 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
278 : ABI ==
"avx" ? X86AVXABILevel::AVX
279 : X86AVXABILevel::None);
281 switch (Triple.getOS()) {
282 case llvm::Triple::UEFI:
283 case llvm::Triple::Win32:
289 case llvm::Triple::hexagon:
291 case llvm::Triple::lanai:
293 case llvm::Triple::r600:
295 case llvm::Triple::amdgpu:
297 case llvm::Triple::sparc:
299 case llvm::Triple::sparcv9:
301 case llvm::Triple::xcore:
303 case llvm::Triple::arc:
305 case llvm::Triple::spir:
306 case llvm::Triple::spir64:
308 case llvm::Triple::spirv32:
309 case llvm::Triple::spirv64:
310 case llvm::Triple::spirv:
312 case llvm::Triple::dxil:
314 case llvm::Triple::ve:
316 case llvm::Triple::csky: {
317 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
319 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
324 case llvm::Triple::bpfeb:
325 case llvm::Triple::bpfel:
327 case llvm::Triple::loongarch32:
328 case llvm::Triple::loongarch64: {
329 StringRef ABIStr =
Target.getABI();
330 unsigned ABIFRLen = 0;
331 if (ABIStr.ends_with(
"f"))
333 else if (ABIStr.ends_with(
"d"))
342 if (!TheTargetCodeGenInfo)
344 return *TheTargetCodeGenInfo;
348 if (!CodeGenOpts.ExperimentalABILowering)
355 if (
T.getArch() == llvm::Triple::aarch64 && !
T.isOSWindows())
358 if (
T.getArch() == llvm::Triple::x86_64 && !
T.isOSWindows() && !
T.isUEFI() &&
359 !
T.isOSDarwin() && !
T.isOSCygMing()) {
361 case llvm::CallingConv::Win64:
362 case llvm::CallingConv::X86_RegCall:
363 case llvm::CallingConv::X86_FastCall:
364 case llvm::CallingConv::X86_VectorCall:
365 case llvm::CallingConv::X86_StdCall:
366 case llvm::CallingConv::X86_ThisCall:
370 case llvm::CallingConv::Intel_OCL_BI:
371 case llvm::CallingConv::PreserveMost:
372 case llvm::CallingConv::PreserveAll:
373 case llvm::CallingConv::PreserveNone:
382const llvm::abi::TargetInfo &
384 if (TheLLVMABITargetInfo)
385 return *TheLLVMABITargetInfo;
389 switch (
T.getArch()) {
391 llvm_unreachable(
"LLVMABI lowering requested for an unsupported target");
393 case llvm::Triple::aarch64: {
395 llvm::abi::AArch64ABIKind Kind = llvm::abi::AArch64ABIKind::AAPCS;
396 if (ABI ==
"darwinpcs")
397 Kind = llvm::abi::AArch64ABIKind::DarwinPCS;
398 else if (
T.isOSWindows())
399 Kind = llvm::abi::AArch64ABIKind::Win64;
400 else if (ABI ==
"aapcs-soft")
401 Kind = llvm::abi::AArch64ABIKind::AAPCSSoft;
402 TheLLVMABITargetInfo = llvm::abi::createAArch64TargetInfo(TB, Kind);
403 return *TheLLVMABITargetInfo;
406 case llvm::Triple::bpfeb:
407 case llvm::Triple::bpfel:
408 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
409 return *TheLLVMABITargetInfo;
411 case llvm::Triple::x86_64: {
413 llvm::abi::X86AVXABILevel AVXLevel =
414 ABI ==
"avx512" ? llvm::abi::X86AVXABILevel::AVX512
415 : ABI ==
"avx" ? llvm::abi::X86AVXABILevel::AVX
416 : llvm::abi::X86AVXABILevel::None;
418 llvm::abi::ABICompatInfo CompatInfo;
420 CompatInfo.ClassifyIntegerMMXAsSSE =
421 Compat > LangOptions::ClangABI::Ver3_8 && !
T.isOSDarwin() &&
422 !
T.isPS() && !
T.isOSFreeBSD();
423 CompatInfo.HonorsRevision98 = !
T.isOSDarwin();
424 CompatInfo.PassInt128VectorsInMem = Compat > LangOptions::ClangABI::Ver9 &&
425 (
T.isOSLinux() ||
T.isOSNetBSD());
427 CompatInfo.ReturnCXXRecordGreaterThan128InMem =
428 Compat > LangOptions::ClangABI::Ver20 && !
T.isPS();
429 CompatInfo.Clang11Compat =
430 Compat <= LangOptions::ClangABI::Ver11 ||
T.isPS();
434 TheLLVMABITargetInfo = llvm::abi::createX86_64TargetInfo(
435 TB, AVXLevel, Has64BitPointers, CompatInfo);
436 return *TheLLVMABITargetInfo;
442 llvm::LLVMContext &Context,
446 if (Opts.AlignDouble || Opts.OpenCL)
449 llvm::Triple Triple =
Target.getTriple();
450 llvm::DataLayout DL(
Target.getDataLayoutString());
451 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
452 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
453 llvm::Align ClangAlign(Alignment / 8);
454 if (DLAlign != ClangAlign) {
455 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
456 <<
" mapping to " << *Ty <<
" has data layout alignment "
457 << DLAlign.value() <<
" while clang specifies "
458 << ClangAlign.value() <<
"\n";
463 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
465 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
467 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
469 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
472 if (Triple.getArch() != llvm::Triple::m68k)
473 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
476 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
477 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
478 Triple.getArch() != llvm::Triple::ve)
479 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
481 if (
Target.hasFloat16Type())
482 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
484 if (
Target.hasBFloat16Type())
485 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
486 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
488 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
491 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
493 if (
Target.hasFloat128Type())
494 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
495 if (
Target.hasIbm128Type())
496 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
498 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
500 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
501 llvm::errs() <<
"Datalayout for target " << Triple.str()
502 <<
" sets element-aligned vectors to '"
503 <<
Target.vectorsAreElementAligned()
504 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
518 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
519 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
521 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
525 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
526 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
527 M.getContext(), M.getDataLayout());
531 llvm::LLVMContext &LLVMContext = M.getContext();
532 VoidTy = llvm::Type::getVoidTy(LLVMContext);
533 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
534 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
535 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
536 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
537 HalfTy = llvm::Type::getHalfTy(LLVMContext);
538 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
539 FloatTy = llvm::Type::getFloatTy(LLVMContext);
540 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
546 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
548 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
550 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
551 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
552 IntPtrTy = llvm::IntegerType::get(LLVMContext,
553 C.getTargetInfo().getMaxPointerWidth());
554 Int8PtrTy = llvm::PointerType::get(LLVMContext,
556 const llvm::DataLayout &DL = M.getDataLayout();
558 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
560 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
562 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
578 createOpenCLRuntime();
580 createOpenMPRuntime();
587 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
588 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
594 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
595 CodeGenOpts.CoverageNotesFile.size() ||
596 CodeGenOpts.CoverageDataFile.size())
604 Block.GlobalUniqueCount = 0;
606 if (
C.getLangOpts().ObjC)
609 if (CodeGenOpts.hasProfileClangUse()) {
610 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
611 CodeGenOpts.ProfileInstrumentUsePath, *FS,
612 CodeGenOpts.ProfileRemappingFile);
613 if (
auto E = ReaderOrErr.takeError()) {
614 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
615 Diags.Report(diag::err_reading_profile)
616 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
620 PGOReader = std::move(ReaderOrErr.get());
625 if (CodeGenOpts.CoverageMapping)
629 if (CodeGenOpts.UniqueInternalLinkageNames &&
630 !
getModule().getSourceFileName().empty()) {
634 Context.getTargetInfo());
635 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
639 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
640 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
641 CodeGenOpts.NumRegisterParameters);
650 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
651 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
653 this->MSHotPatchFunctions.push_back(std::string{*I});
655 auto &DE = Context.getDiagnostics();
656 DE.Report(diag::err_open_hotpatch_file_failed)
658 << BufOrErr.getError().message();
663 this->MSHotPatchFunctions.push_back(FuncName);
665 llvm::sort(this->MSHotPatchFunctions);
668 if (!Context.getAuxTargetInfo())
674void CodeGenModule::createObjCRuntime() {
691 llvm_unreachable(
"bad runtime kind");
694void CodeGenModule::createOpenCLRuntime() {
698void CodeGenModule::createOpenMPRuntime() {
699 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
700 Diags.Report(diag::err_omp_host_ir_file_not_found)
701 << LangOpts.OMPHostIRFile;
706 case llvm::Triple::nvptx:
707 case llvm::Triple::nvptx64:
708 case llvm::Triple::amdgpu:
709 case llvm::Triple::spirv64:
712 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
713 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
716 if (LangOpts.OpenMPSimd)
717 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
719 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
724void CodeGenModule::createCUDARuntime() {
728void CodeGenModule::createHLSLRuntime() {
729 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
733 Replacements[Name] =
C;
736void CodeGenModule::applyReplacements() {
737 for (
auto &I : Replacements) {
738 StringRef MangledName = I.first;
739 llvm::Constant *Replacement = I.second;
744 auto *NewF = dyn_cast<llvm::Function>(Replacement);
746 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
747 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
750 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
751 CE->getOpcode() == llvm::Instruction::GetElementPtr);
752 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
757 OldF->replaceAllUsesWith(Replacement);
759 NewF->removeFromParent();
760 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
763 OldF->eraseFromParent();
768 GlobalValReplacements.push_back(std::make_pair(GV,
C));
771void CodeGenModule::applyGlobalValReplacements() {
772 for (
auto &I : GlobalValReplacements) {
773 llvm::GlobalValue *GV = I.first;
774 llvm::Constant *
C = I.second;
776 GV->replaceAllUsesWith(
C);
777 GV->eraseFromParent();
784 const llvm::Constant *
C;
785 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
786 C = GA->getAliasee();
787 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
788 C = GI->getResolver();
792 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
796 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
805 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
806 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
810 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
814 if (GV->hasCommonLinkage()) {
815 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
816 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
817 Diags.
Report(Location, diag::err_alias_to_common);
822 if (GV->isDeclaration()) {
823 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
824 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
825 << IsIFunc << IsIFunc;
828 for (
const auto &[
Decl, Name] : MangledDeclNames) {
829 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
831 if (II && II->
getName() == GV->getName()) {
832 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
836 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
846 const auto *F = dyn_cast<llvm::Function>(GV);
848 Diags.
Report(Location, diag::err_alias_to_undefined)
849 << IsIFunc << IsIFunc;
853 llvm::FunctionType *FTy = F->getFunctionType();
854 if (!FTy->getReturnType()->isPointerTy()) {
855 Diags.
Report(Location, diag::err_ifunc_resolver_return);
869 if (GVar->hasAttribute(
"toc-data")) {
870 auto GVId = GVar->getName();
873 Diags.
Report(Location, diag::warn_toc_unsupported_type)
874 << GVId <<
"the variable has an alias";
876 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
877 llvm::AttributeSet NewAttributes =
878 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
879 GVar->setAttributes(NewAttributes);
883void CodeGenModule::checkAliases() {
888 DiagnosticsEngine &Diags =
getDiags();
889 for (
const GlobalDecl &GD : Aliases) {
891 SourceLocation Location;
893 bool IsIFunc = D->hasAttr<IFuncAttr>();
894 if (
const Attr *A = D->getDefiningAttr()) {
895 Location = A->getLocation();
896 Range = A->getRange();
898 llvm_unreachable(
"Not an alias or ifunc?");
902 const llvm::GlobalValue *GV =
nullptr;
904 MangledDeclNames, Range)) {
910 GlobalDecl AliaseeGD;
913 Diags.Report(Location, diag::err_alias_to_undefined)
914 << IsIFunc << IsIFunc;
923 if (AliasIsFuncDecl != AliaseeIsFunc) {
924 Diags.Report(Location, diag::err_alias_between_function_and_variable)
927 diag::note_aliasee_declaration);
934 if (AliasIsFuncDecl && AliaseeIsFunc) {
935 QualType AliasTy = D->getType();
937 auto shouldReportTypeMismatch = [&]() {
938 const auto *AliasFTy =
940 const auto *AliaseeFTy =
942 assert(AliasFTy && AliaseeFTy);
943 if (!Context.typesAreCompatible(AliasFTy->getReturnType(),
946 const auto *AliasFPTy = dyn_cast<FunctionProtoType>(AliasFTy);
947 const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(AliaseeFTy);
949 if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) ||
950 (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy))
953 if (!AliasFPTy || !AliaseeFPTy)
957 if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() ||
958 AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic())
960 for (
unsigned i = 0; i < AliasFPTy->getNumParams(); ++i)
961 if (!Context.typesAreCompatible(AliasFPTy->getParamType(i),
962 AliaseeFPTy->getParamType(i)))
966 if (shouldReportTypeMismatch()) {
967 Diags.Report(Location, diag::warn_alias_type_mismatch)
968 << AliasTy << AliaseeTy;
970 diag::note_aliasee_declaration);
976 if (
const llvm::GlobalVariable *GVar =
977 dyn_cast<const llvm::GlobalVariable>(GV))
981 llvm::Constant *Aliasee =
985 llvm::GlobalValue *AliaseeGV;
986 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
991 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
992 StringRef AliasSection = SA->getName();
993 if (AliasSection != AliaseeGV->getSection())
994 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
995 << AliasSection << IsIFunc << IsIFunc;
1003 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
1004 if (GA->isInterposable()) {
1005 Diags.Report(Location, diag::warn_alias_to_weak_alias)
1006 << GV->getName() << GA->getName() << IsIFunc;
1007 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1008 GA->getAliasee(), Alias->getType());
1020 llvm::Attribute::DisableSanitizerInstrumentation);
1025 for (
const GlobalDecl &GD : Aliases) {
1028 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
1029 Alias->eraseFromParent();
1034 DeferredDeclsToEmit.clear();
1035 EmittedDeferredDecls.clear();
1036 DeferredAnnotations.clear();
1038 OpenMPRuntime->clear();
1042 StringRef MainFile) {
1045 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
1046 if (MainFile.empty())
1047 MainFile =
"<stdin>";
1048 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
1051 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
1054 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
1058static std::optional<llvm::GlobalValue::VisibilityTypes>
1063 return std::nullopt;
1065 return llvm::GlobalValue::DefaultVisibility;
1067 return llvm::GlobalValue::HiddenVisibility;
1069 return llvm::GlobalValue::ProtectedVisibility;
1071 llvm_unreachable(
"unknown option value!");
1076 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
1085 GV.setDSOLocal(
false);
1086 GV.setVisibility(*
V);
1091 if (!LO.VisibilityFromDLLStorageClass)
1094 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
1097 std::optional<llvm::GlobalValue::VisibilityTypes>
1098 NoDLLStorageClassVisibility =
1101 std::optional<llvm::GlobalValue::VisibilityTypes>
1102 ExternDeclDLLImportVisibility =
1105 std::optional<llvm::GlobalValue::VisibilityTypes>
1106 ExternDeclNoDLLStorageClassVisibility =
1109 for (llvm::GlobalValue &GV : M.global_values()) {
1110 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
1113 if (GV.isDeclarationForLinker())
1115 llvm::GlobalValue::DLLImportStorageClass
1116 ? ExternDeclDLLImportVisibility
1117 : ExternDeclNoDLLStorageClassVisibility);
1120 llvm::GlobalValue::DLLExportStorageClass
1121 ? DLLExportVisibility
1122 : NoDLLStorageClassVisibility);
1124 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1129 const llvm::Triple &Triple,
1133 return LangOpts.getStackProtector() == Mode;
1136std::optional<llvm::Attribute::AttrKind>
1138 if (D && D->
hasAttr<NoStackProtectorAttr>())
1140 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1142 return llvm::Attribute::StackProtectStrong;
1144 return llvm::Attribute::StackProtect;
1146 return llvm::Attribute::StackProtectStrong;
1148 return llvm::Attribute::StackProtectReq;
1149 return std::nullopt;
1155 EmitModuleInitializers(Primary);
1157 DeferredDecls.insert_range(EmittedDeferredDecls);
1158 EmittedDeferredDecls.clear();
1159 EmitVTablesOpportunistically();
1160 applyGlobalValReplacements();
1161 applyReplacements();
1162 emitMultiVersionFunctions();
1163 emitPFPFieldsWithEvaluatedOffset();
1166 if (Context.getLangOpts().IncrementalExtensions &&
1167 GlobalTopLevelStmtBlockInFlight.first) {
1169 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1170 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1176 EmitCXXModuleInitFunc(Primary);
1178 EmitCXXGlobalInitFunc();
1179 EmitCXXGlobalCleanUpFunc();
1180 registerGlobalDtorsWithAtExit();
1181 EmitCXXThreadLocalInitFunc();
1183 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1185 if (Context.getLangOpts().CUDA && CUDARuntime) {
1186 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1189 if (OpenMPRuntime) {
1190 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1191 OpenMPRuntime->clear();
1195 PGOReader->getSummary(
false).getMD(VMContext),
1196 llvm::ProfileSummary::PSK_Instr);
1197 if (PGOStats.hasDiagnostics())
1203 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1204 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1206 EmitStaticExternCAliases();
1211 if (CoverageMapping)
1212 CoverageMapping->emit();
1213 if (CodeGenOpts.SanitizeCfiCrossDso) {
1217 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1219 emitAtAvailableLinkGuard();
1220 if (Context.getTargetInfo().getTriple().isWasm())
1227 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1228 llvm::CodeObjectVersionKind::COV_None) {
1229 getModule().addModuleFlag(llvm::Module::Error,
1230 "amdhsa_code_object_version",
1231 getTarget().getTargetOpts().CodeObjectVersion);
1236 auto *MDStr = llvm::MDString::get(
1241 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1251 llvm::Module::Error,
"amdgpu.xnack",
1252 llvm::ConstantInt::get(
1260 llvm::Module::Error,
"amdgpu.sramecc",
1261 llvm::ConstantInt::get(
1271 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1273 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1275 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1279 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1283 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1285 auto *GV =
new llvm::GlobalVariable(
1286 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1287 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1293 auto *GV =
new llvm::GlobalVariable(
1295 llvm::Constant::getNullValue(
Int8Ty),
1304 if (CodeGenOpts.Autolink &&
1305 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1306 EmitModuleLinkOptions();
1321 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1322 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1323 for (
auto *MD : ELFDependentLibraries)
1324 NMD->addOperand(MD);
1327 if (CodeGenOpts.DwarfVersion) {
1328 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1329 CodeGenOpts.DwarfVersion);
1332 if (CodeGenOpts.Dwarf64)
1333 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1335 if (Context.getLangOpts().SemanticInterposition)
1337 getModule().setSemanticInterposition(
true);
1339 if (CodeGenOpts.EmitCodeView) {
1341 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1343 if (CodeGenOpts.CodeViewGHash) {
1344 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1346 if (CodeGenOpts.ControlFlowGuard) {
1349 llvm::Module::Warning,
"cfguard",
1350 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1351 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1354 llvm::Module::Warning,
"cfguard",
1355 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1357 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1358 llvm::ControlFlowGuardMechanism::Automatic) {
1361 llvm::Module::Warning,
"cfguard-mechanism",
1362 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1364 if (CodeGenOpts.EHContGuard) {
1366 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1368 if (Context.getLangOpts().Kernel) {
1370 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1372 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1377 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1379 llvm::Metadata *Ops[2] = {
1380 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1381 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1382 llvm::Type::getInt32Ty(VMContext), 1))};
1384 getModule().addModuleFlag(llvm::Module::Require,
1385 "StrictVTablePointersRequirement",
1386 llvm::MDNode::get(VMContext, Ops));
1392 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1393 llvm::DEBUG_METADATA_VERSION);
1398 uint64_t WCharWidth =
1399 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1400 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1401 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size",
1402 static_cast<uint32_t
>(WCharWidth));
1406 llvm::FloatABI::ABIType FloatABI =
1407 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
1408 .Cases({
"soft",
"softfp"}, llvm::FloatABI::Soft)
1409 .Case(
"hard", llvm::FloatABI::Hard)
1410 .Default(llvm::FloatABI::Default);
1411 if (FloatABI != llvm::FloatABI::Default &&
1412 FloatABI !=
getTriple().getDefaultFloatABI()) {
1414 llvm::Module::Error,
"float-abi",
1416 llvm::FloatABI::getABITypeName(FloatABI)));
1419 if (
getTypes().isLongDoubleReferenced()) {
1422 std::optional<llvm::LongDoubleFormat> Format;
1423 if (flt == &llvm::APFloat::IEEEquad())
1424 Format = llvm::LongDoubleFormat::IEEEquad;
1425 else if (flt == &llvm::APFloat::IEEEdouble())
1426 Format = llvm::LongDoubleFormat::IEEEdouble;
1427 else if (flt == &llvm::APFloat::PPCDoubleDouble())
1428 Format = llvm::LongDoubleFormat::PPCDoubleDouble;
1429 else if (flt == &llvm::APFloat::x87DoubleExtended())
1430 Format = llvm::LongDoubleFormat::X87DoubleExtended;
1431 else if (flt == &llvm::APFloat::IEEEsingle())
1432 Format = llvm::LongDoubleFormat::IEEEsingle;
1435 getModule().setLongDoubleFormat(*Format);
1439 getModule().addModuleFlag(llvm::Module::Warning,
1440 "zos_product_major_version",
1442 getModule().addModuleFlag(llvm::Module::Warning,
1443 "zos_product_minor_version",
1445 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1446 uint32_t(CLANG_VERSION_PATCHLEVEL));
1448 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1449 llvm::MDString::get(VMContext, ProductId));
1454 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1455 llvm::MDString::get(VMContext, lang_str));
1457 time_t TT = PreprocessorOpts.SourceDateEpoch
1458 ? *PreprocessorOpts.SourceDateEpoch
1459 : std::time(
nullptr);
1460 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1461 static_cast<uint64_t
>(TT));
1464 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1465 llvm::MDString::get(VMContext,
"ascii"));
1468 llvm::Triple
T = Context.getTargetInfo().getTriple();
1469 if (
T.isARM() ||
T.isThumb()) {
1471 uint32_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1472 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1476 StringRef ABIStr = Target.getABI();
1477 llvm::LLVMContext &Ctx = TheModule.getContext();
1478 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1479 llvm::MDString::get(Ctx, ABIStr));
1484 const std::vector<std::string> &Features =
1487 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1488 if (!errorToBool(ParseResult.takeError()))
1490 llvm::Module::AppendUnique,
"riscv-isa",
1492 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1495 if (CodeGenOpts.SanitizeCfiCrossDso) {
1497 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1500 if (CodeGenOpts.WholeProgramVTables) {
1504 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1505 CodeGenOpts.VirtualFunctionElimination);
1508 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1509 getModule().addModuleFlag(llvm::Module::Override,
1510 "CFI Canonical Jump Tables",
1511 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1514 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1515 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1519 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1521 llvm::Module::Append,
"Unique Source File Identifier",
1523 TheModule.getContext(),
1524 llvm::MDString::get(TheModule.getContext(),
1525 CodeGenOpts.UniqueSourceFileIdentifier)));
1528 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1529 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1532 if (CodeGenOpts.PatchableFunctionEntryOffset)
1533 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1534 CodeGenOpts.PatchableFunctionEntryOffset);
1535 if (CodeGenOpts.SanitizeKcfiArity)
1536 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1539 llvm::Module::Override,
"kcfi-hash",
1540 llvm::MDString::get(
1542 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1545 if (CodeGenOpts.CFProtectionReturn &&
1546 Target.checkCFProtectionReturnSupported(
getDiags())) {
1548 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1552 if (CodeGenOpts.CFProtectionBranch &&
1553 Target.checkCFProtectionBranchSupported(
getDiags())) {
1555 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1558 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1559 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1561 Scheme = Target.getDefaultCFBranchLabelScheme();
1563 llvm::Module::Error,
"cf-branch-label-scheme",
1569 if (CodeGenOpts.FunctionReturnThunks)
1570 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1572 if (CodeGenOpts.IndirectBranchCSPrefix)
1573 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1575 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1583 if (LangOpts.BranchTargetEnforcement)
1584 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1586 if (LangOpts.BranchProtectionPAuthLR)
1587 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1589 if (LangOpts.GuardedControlStack)
1590 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1591 if (LangOpts.hasSignReturnAddress())
1592 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1593 if (LangOpts.isSignReturnAddressScopeAll())
1594 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1596 if (!LangOpts.isSignReturnAddressWithAKey())
1597 getModule().addModuleFlag(llvm::Module::Min,
1598 "sign-return-address-with-bkey", 2);
1600 if (
T.isAArch64()) {
1612 if (LangOpts.PointerAuthReturns)
1613 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-returns", 1);
1614 if (LangOpts.PointerAuthAuthTraps)
1615 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-auth-traps", 1);
1616 if (LangOpts.PointerAuthIndirectGotos)
1617 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-indirect-gotos", 1);
1618 if (LangOpts.AArch64JumpTableHardening)
1619 getModule().addModuleFlag(llvm::Module::Max,
1620 "aarch64-jump-table-hardening", 1);
1628 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got",
1629 LangOpts.PointerAuthELFGOT);
1631 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-init-fini",
1632 LangOpts.PointerAuthCalls &&
1633 LangOpts.PointerAuthInitFini);
1635 llvm::Module::Error,
"ptrauth-init-fini-address-discrimination",
1636 LangOpts.PointerAuthCalls && LangOpts.PointerAuthInitFini &&
1637 LangOpts.PointerAuthInitFiniAddressDiscrimination);
1641 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-sign-personality",
1642 LangOpts.PointerAuthCalls);
1645 using namespace llvm::ELF;
1646 assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST < 32);
1647 uint32_t PAuthABIVersion =
1648 (LangOpts.PointerAuthIntrinsics
1649 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1650 (LangOpts.PointerAuthCalls
1651 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1652 (LangOpts.PointerAuthReturns
1653 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1654 (LangOpts.PointerAuthAuthTraps
1655 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1656 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1657 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1658 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1659 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1660 (LangOpts.PointerAuthInitFini
1661 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1662 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1663 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1664 (LangOpts.PointerAuthELFGOT
1665 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1666 (LangOpts.PointerAuthIndirectGotos
1667 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1668 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1669 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1670 (LangOpts.PointerAuthFunctionTypeDiscrimination
1671 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1672 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1673 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1674 "Update when new enum items are defined");
1679 getModule().addModuleFlag(llvm::Module::Error,
1680 "aarch64-elf-pauthabi-platform",
1681 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1683 llvm::Module::Error,
"aarch64-elf-pauthabi-version", PAuthABIVersion);
1686 if ((
T.isARM() ||
T.isThumb()) &&
getTriple().isTargetAEABI() &&
1688 uint32_t TagVal = 0;
1689 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1691 llvm::DenormalMode::getPositiveZero()) {
1692 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1694 llvm::DenormalMode::getIEEE()) {
1695 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1696 DenormalTagBehavior = llvm::Module::Override;
1698 llvm::DenormalMode::getPreserveSign()) {
1699 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1701 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1706 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1707 llvm::ARMBuildAttrs::Allowed);
1710 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1712 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1713 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1717 if (CodeGenOpts.StackClashProtector)
1719 llvm::Module::Override,
"probe-stack",
1720 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1722 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1723 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1724 CodeGenOpts.StackProbeSize);
1726 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1727 llvm::LLVMContext &Ctx = TheModule.getContext();
1729 llvm::Module::Error,
"MemProfProfileFilename",
1730 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1733 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1737 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1738 CodeGenOpts.FP32DenormalMode.Output !=
1739 llvm::DenormalMode::IEEE);
1742 if (LangOpts.EHAsynch)
1743 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1746 if (CodeGenOpts.ImportCallOptimization)
1747 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1757 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
1758 if (UnwindMode == llvm::WinX64EHUnwindMode::Default) {
1759 if (
T.isOSWindows() &&
T.isX86_64() &&
1760 Context.getTargetInfo().hasFeature(
"egpr"))
1761 UnwindMode = llvm::WinX64EHUnwindMode::V3;
1763 UnwindMode = llvm::WinX64EHUnwindMode::V1;
1765 if (UnwindMode != llvm::WinX64EHUnwindMode::V1)
1766 getModule().addModuleFlag(llvm::Module::Warning,
"winx64-eh-unwind",
1767 static_cast<unsigned>(UnwindMode));
1771 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1773 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1777 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1778 EmitOpenCLMetadata();
1785 auto Version = LangOpts.getOpenCLCompatibleVersion();
1786 llvm::Metadata *SPIRVerElts[] = {
1787 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1789 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1790 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1791 llvm::NamedMDNode *SPIRVerMD =
1792 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1793 llvm::LLVMContext &Ctx = TheModule.getContext();
1794 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1802 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1803 assert(PLevel < 3 &&
"Invalid PIC Level");
1804 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1805 if (Context.getLangOpts().PIE)
1806 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1810 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1811 .Case(
"tiny", llvm::CodeModel::Tiny)
1812 .Case(
"small", llvm::CodeModel::Small)
1813 .Case(
"kernel", llvm::CodeModel::Kernel)
1814 .Case(
"medium", llvm::CodeModel::Medium)
1815 .Case(
"large", llvm::CodeModel::Large)
1818 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1821 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1822 Context.getTargetInfo().getTriple().getArch() ==
1823 llvm::Triple::x86_64) {
1829 if (CodeGenOpts.NoPLT)
1832 CodeGenOpts.DirectAccessExternalData !=
1833 getModule().getDirectAccessExternalData()) {
1834 getModule().setDirectAccessExternalData(
1835 CodeGenOpts.DirectAccessExternalData);
1837 if (CodeGenOpts.UnwindTables)
1838 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1840 switch (CodeGenOpts.getFramePointer()) {
1845 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1848 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1851 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1854 getModule().setFramePointer(llvm::FramePointerKind::All);
1858 SimplifyPersonality();
1871 EmitVersionIdentMetadata();
1874 EmitCommandLineMetadata();
1882 getModule().setStackProtectorGuardSymbol(
1885 getModule().setStackProtectorGuardOffset(
1888 getModule().setStackProtectorGuardValueWidth(
1891 if (
getModule().getStackProtectorGuard() !=
"global") {
1892 Diags.Report(diag::err_opt_not_valid_without_opt)
1893 <<
"-mstack-protector-guard-record"
1894 <<
"-mstack-protector-guard=global";
1896 getModule().setStackProtectorGuardRecord(
true);
1901 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1903 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1905 if (
getContext().getTargetInfo().getMaxTLSAlign())
1906 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1907 getContext().getTargetInfo().getMaxTLSAlign());
1925 if (!MustTailCallUndefinedGlobals.empty()) {
1927 for (
auto &I : MustTailCallUndefinedGlobals) {
1928 if (!I.first->isDefined())
1929 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1933 if (!Entry || Entry->isWeakForLinker() ||
1934 Entry->isDeclarationForLinker())
1935 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1939 for (
auto &I : MustTailCallUndefinedGlobals) {
1948 if (Entry->isDeclarationForLinker()) {
1951 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1953 CalleeIsLocal = Entry->isDSOLocal();
1957 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1970 llvm::MDBuilder MDB(TheModule.getContext());
1971 uint64_t Size = Context.getTypeSizeInChars(Context.IntTy).getQuantity();
1972 llvm::MDNode *StructNode =
1973 CodeGenOpts.NewStructPathTBAA
1974 ? MDB.createTBAATypeNode(TBAA->getChar(), Size,
1975 MDB.createString(
"__libc_errno"),
1976 {{0, Size, IntegerNode}})
1977 : MDB.createTBAAStructTypeNode(
"__libc_errno",
1978 {{IntegerNode, 0}});
1981 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1982 ErrnoTBAAMD->addOperand(StructTagNode);
1987void CodeGenModule::EmitOpenCLMetadata() {
1993 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1994 llvm::Metadata *OCLVerElts[] = {
1995 llvm::ConstantAsMetadata::get(
1996 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1997 llvm::ConstantAsMetadata::get(
1998 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1999 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
2000 llvm::LLVMContext &Ctx = TheModule.getContext();
2001 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
2004 EmitVersion(
"opencl.ocl.version", CLVersion);
2005 if (LangOpts.OpenCLCPlusPlus) {
2007 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
2011void CodeGenModule::EmitBackendOptionsMetadata(
2012 const CodeGenOptions &CodeGenOpts) {
2014 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
2015 CodeGenOpts.SmallDataLimit);
2019 if (LangOpts.AllocTokenMode) {
2020 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
2021 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
2022 llvm::MDString::get(VMContext, S));
2024 if (LangOpts.AllocTokenMax)
2026 llvm::Module::Error,
"alloc-token-max",
2027 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
2028 *LangOpts.AllocTokenMax));
2029 if (CodeGenOpts.SanitizeAllocTokenFastABI)
2030 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
2031 if (CodeGenOpts.SanitizeAllocTokenExtended)
2032 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
2048 return TBAA->getTypeInfo(QTy);
2067 return TBAA->getAccessInfo(AccessType);
2074 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
2080 return TBAA->getTBAAStructInfo(QTy);
2086 return TBAA->getBaseTypeInfo(QTy);
2092 return TBAA->getAccessTagInfo(Info);
2099 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
2107 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
2115 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
2121 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
2126 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
2138 std::string Msg =
Type;
2140 diag::err_codegen_unsupported)
2146 diag::err_codegen_unsupported)
2153 std::string Msg =
Type;
2155 diag::err_codegen_unsupported)
2160 llvm::function_ref<
void()> Fn) {
2161 StackHandler.runWithSufficientStackSpace(Loc, Fn);
2171 if (GV->hasLocalLinkage()) {
2172 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2185 if (Context.getLangOpts().OpenMP &&
2186 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
2187 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
2188 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
2189 OMPDeclareTargetDeclAttr::DT_NoHost &&
2191 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2198 if (Context.getLangOpts().CUDAIsDevice &&
2200 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
2201 bool NeedsProtected =
false;
2205 else if (
const auto *VD = dyn_cast<VarDecl>(D))
2206 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
2207 VD->hasAttr<CUDAConstantAttr>() ||
2208 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
2209 VD->getType()->isCUDADeviceBuiltinTextureType();
2210 if (NeedsProtected) {
2211 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2217 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2221 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
2225 if (GV->hasDLLExportStorageClass()) {
2228 diag::err_hidden_visibility_dllexport);
2231 diag::err_non_default_visibility_dllimport);
2237 !GV->isDeclarationForLinker())
2242 llvm::GlobalValue *GV) {
2243 if (GV->hasLocalLinkage())
2246 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
2250 if (GV->hasDLLImportStorageClass())
2253 const llvm::Triple &TT = CGM.
getTriple();
2255 if (TT.isOSCygMing()) {
2273 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2281 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2285 if (!TT.isOSBinFormatELF())
2291 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2299 return !(CGM.
getLangOpts().SemanticInterposition ||
2304 if (!GV->isDeclarationForLinker())
2310 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2317 if (CGOpts.DirectAccessExternalData) {
2323 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2324 if (!Var->isThreadLocal())
2349 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2351 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2361 if (D->
hasAttr<DLLImportAttr>())
2362 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2363 else if ((D->
hasAttr<DLLExportAttr>() ||
2365 !GV->isDeclarationForLinker())
2366 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2386 GV->setPartition(CodeGenOpts.SymbolPartition);
2390 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2391 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2392 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2393 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2394 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2397llvm::GlobalVariable::ThreadLocalMode
2399 switch (CodeGenOpts.getDefaultTLSModel()) {
2401 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2403 return llvm::GlobalVariable::LocalDynamicTLSModel;
2405 return llvm::GlobalVariable::InitialExecTLSModel;
2407 return llvm::GlobalVariable::LocalExecTLSModel;
2409 llvm_unreachable(
"Invalid TLS model!");
2413 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2415 llvm::GlobalValue::ThreadLocalMode TLM;
2419 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2423 GV->setThreadLocalMode(TLM);
2429 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2433 const CPUSpecificAttr *
Attr,
2450 !D->
hasAttr<AsmLabelAttr>() &&
2456 bool OmitMultiVersionMangling =
false) {
2458 llvm::raw_svector_ostream Out(Buffer);
2467 assert(II &&
"Attempt to mangle unnamed decl.");
2468 const auto *FD = dyn_cast<FunctionDecl>(ND);
2473 Out <<
"__regcall4__" << II->
getName();
2475 Out <<
"__regcall3__" << II->
getName();
2476 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2478 Out <<
"__device_stub__" << II->
getName();
2480 DeviceKernelAttr::isOpenCLSpelling(
2481 FD->getAttr<DeviceKernelAttr>()) &&
2483 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2499 "Hash computed when not explicitly requested");
2503 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2504 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2505 switch (FD->getMultiVersionKind()) {
2509 FD->getAttr<CPUSpecificAttr>(),
2513 auto *
Attr = FD->getAttr<TargetAttr>();
2514 assert(
Attr &&
"Expected TargetAttr to be present "
2515 "for attribute mangling");
2521 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2522 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2523 "for attribute mangling");
2529 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2530 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2531 "for attribute mangling");
2538 llvm_unreachable(
"None multiversion type isn't valid here");
2548 return std::string(Out.str());
2551void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2552 const FunctionDecl *FD,
2553 StringRef &CurName) {
2560 std::string NonTargetName =
2568 "Other GD should now be a multiversioned function");
2578 if (OtherName != NonTargetName) {
2581 const auto ExistingRecord = Manglings.find(NonTargetName);
2582 if (ExistingRecord != std::end(Manglings))
2583 Manglings.remove(&(*ExistingRecord));
2584 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2589 CurName = OtherNameRef;
2591 Entry->setName(OtherName);
2601 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2615 auto FoundName = MangledDeclNames.find(CanonicalGD);
2616 if (FoundName != MangledDeclNames.end())
2617 return FoundName->second;
2654 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2655 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2664 llvm::raw_svector_ostream Out(Buffer);
2667 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2668 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2670 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2675 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2676 return Result.first->first();
2680 auto it = MangledDeclNames.begin();
2681 while (it != MangledDeclNames.end()) {
2682 if (it->second == Name)
2697 llvm::Constant *AssociatedData) {
2699 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2705 bool IsDtorAttrFunc) {
2706 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2708 DtorsUsingAtExit[Priority].push_back(Dtor);
2713 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2716void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2717 if (Fns.empty())
return;
2720 llvm::PointerType *PtrTy = llvm::PointerType::get(
2721 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2724 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2728 auto Ctors = Builder.beginArray(CtorStructTy);
2729 for (
const auto &I : Fns) {
2730 auto Ctor = Ctors.beginStruct(CtorStructTy);
2731 Ctor.addInt(
Int32Ty, I.Priority);
2732 Ctor.add(I.Initializer);
2733 if (I.AssociatedData)
2734 Ctor.add(I.AssociatedData);
2736 Ctor.addNullPointer(PtrTy);
2737 Ctor.finishAndAddTo(Ctors);
2740 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2742 llvm::GlobalValue::AppendingLinkage);
2746 List->setAlignment(std::nullopt);
2751llvm::GlobalValue::LinkageTypes
2757 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2764 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2765 if (!MDS)
return nullptr;
2767 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2775 if (!UD->
hasAttr<TransparentUnionAttr>())
2777 if (!UD->
fields().empty())
2778 return UD->
fields().begin()->getType();
2787 bool GeneralizePointers) {
2800 bool GeneralizePointers) {
2803 for (
auto &Param : FnType->param_types())
2804 GeneralizedParams.push_back(
2808 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2809 GeneralizedParams, FnType->getExtProtoInfo());
2814 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2816 llvm_unreachable(
"Encountered unknown FunctionType");
2824 FnType->getReturnType(), FnType->getParamTypes(),
2825 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2827 std::string OutName;
2828 llvm::raw_string_ostream Out(OutName);
2836 Out <<
".normalized";
2838 Out <<
".generalized";
2840 return llvm::ConstantInt::get(
2846 llvm::Function *F,
bool IsThunk) {
2848 llvm::AttributeList PAL;
2851 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2855 Loc = D->getLocation();
2857 Error(Loc,
"__vectorcall calling convention is not currently supported");
2859 F->setAttributes(PAL);
2860 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2864 std::string ReadOnlyQual(
"__read_only");
2865 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2866 if (ReadOnlyPos != std::string::npos)
2868 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2870 std::string WriteOnlyQual(
"__write_only");
2871 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2872 if (WriteOnlyPos != std::string::npos)
2873 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2875 std::string ReadWriteQual(
"__read_write");
2876 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2877 if (ReadWritePos != std::string::npos)
2878 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2911 assert(((FD && CGF) || (!FD && !CGF)) &&
2912 "Incorrect use - FD and CGF should either be both null or not!");
2938 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2941 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2946 std::string typeQuals;
2950 const Decl *PDecl = parm;
2952 PDecl = TD->getDecl();
2953 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2954 if (A && A->isWriteOnly())
2955 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2956 else if (A && A->isReadWrite())
2957 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2959 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2961 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2963 auto getTypeSpelling = [&](
QualType Ty) {
2964 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2966 if (Ty.isCanonical()) {
2967 StringRef typeNameRef = typeName;
2969 if (typeNameRef.consume_front(
"unsigned "))
2970 return std::string(
"u") + typeNameRef.str();
2971 if (typeNameRef.consume_front(
"signed "))
2972 return typeNameRef.str();
2982 addressQuals.push_back(
2983 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2987 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2988 std::string baseTypeName =
2990 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2991 argBaseTypeNames.push_back(
2992 llvm::MDString::get(VMContext, baseTypeName));
2996 typeQuals =
"restrict";
2999 typeQuals += typeQuals.empty() ?
"const" :
" const";
3001 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
3003 uint32_t AddrSpc = 0;
3008 addressQuals.push_back(
3009 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
3013 std::string typeName = getTypeSpelling(ty);
3025 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
3026 argBaseTypeNames.push_back(
3027 llvm::MDString::get(VMContext, baseTypeName));
3032 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
3036 Fn->setMetadata(
"kernel_arg_addr_space",
3037 llvm::MDNode::get(VMContext, addressQuals));
3038 Fn->setMetadata(
"kernel_arg_access_qual",
3039 llvm::MDNode::get(VMContext, accessQuals));
3040 Fn->setMetadata(
"kernel_arg_type",
3041 llvm::MDNode::get(VMContext, argTypeNames));
3042 Fn->setMetadata(
"kernel_arg_base_type",
3043 llvm::MDNode::get(VMContext, argBaseTypeNames));
3044 Fn->setMetadata(
"kernel_arg_type_qual",
3045 llvm::MDNode::get(VMContext, argTypeQuals));
3049 Fn->setMetadata(
"kernel_arg_name",
3050 llvm::MDNode::get(VMContext, argNames));
3060 if (!LangOpts.Exceptions)
return false;
3063 if (LangOpts.CXXExceptions)
return true;
3066 if (LangOpts.ObjCExceptions) {
3086SmallVector<const CXXRecordDecl *, 0>
3088 llvm::SetVector<const CXXRecordDecl *> MostBases;
3093 MostBases.insert(RD);
3095 CollectMostBases(B.getType()->getAsCXXRecordDecl());
3097 CollectMostBases(RD);
3098 return MostBases.takeVector();
3102 llvm::Function *F) {
3103 llvm::AttrBuilder B(F->getContext());
3105 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
3106 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
3108 if (CodeGenOpts.StackClashProtector)
3109 B.addAttribute(
"probe-stack",
"inline-asm");
3111 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
3112 B.addAttribute(
"stack-probe-size",
3113 std::to_string(CodeGenOpts.StackProbeSize));
3116 B.addAttribute(llvm::Attribute::NoUnwind);
3118 if (std::optional<llvm::Attribute::AttrKind>
Attr =
3120 B.addAttribute(*
Attr);
3125 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
3126 B.addAttribute(llvm::Attribute::AlwaysInline);
3130 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
3132 B.addAttribute(llvm::Attribute::NoInline);
3140 if (D->
hasAttr<ArmLocallyStreamingAttr>())
3141 B.addAttribute(
"aarch64_pstate_sm_body");
3144 if (
Attr->isNewZA())
3145 B.addAttribute(
"aarch64_new_za");
3146 if (
Attr->isNewZT0())
3147 B.addAttribute(
"aarch64_new_zt0");
3152 bool ShouldAddOptNone =
3153 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
3155 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
3156 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
3159 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
3160 !D->
hasAttr<NoInlineAttr>()) {
3161 B.addAttribute(llvm::Attribute::AlwaysInline);
3162 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
3163 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3165 B.addAttribute(llvm::Attribute::OptimizeNone);
3168 B.addAttribute(llvm::Attribute::NoInline);
3173 B.addAttribute(llvm::Attribute::Naked);
3176 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
3177 F->removeFnAttr(llvm::Attribute::MinSize);
3178 }
else if (D->
hasAttr<NakedAttr>()) {
3180 B.addAttribute(llvm::Attribute::Naked);
3181 B.addAttribute(llvm::Attribute::NoInline);
3182 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
3183 B.addAttribute(llvm::Attribute::NoDuplicate);
3184 }
else if (D->
hasAttr<NoInlineAttr>() &&
3185 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3187 B.addAttribute(llvm::Attribute::NoInline);
3188 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
3189 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
3191 B.addAttribute(llvm::Attribute::AlwaysInline);
3195 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
3196 B.addAttribute(llvm::Attribute::NoInline);
3200 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3203 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
3204 return Redecl->isInlineSpecified();
3206 if (any_of(FD->
redecls(), CheckRedeclForInline))
3211 return any_of(Pattern->
redecls(), CheckRedeclForInline);
3213 if (CheckForInline(FD)) {
3214 B.addAttribute(llvm::Attribute::InlineHint);
3215 }
else if (CodeGenOpts.getInlining() ==
3218 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3219 B.addAttribute(llvm::Attribute::NoInline);
3226 if (!D->
hasAttr<OptimizeNoneAttr>()) {
3228 if (!ShouldAddOptNone)
3229 B.addAttribute(llvm::Attribute::OptimizeForSize);
3230 B.addAttribute(llvm::Attribute::Cold);
3233 B.addAttribute(llvm::Attribute::Hot);
3234 if (D->
hasAttr<MinSizeAttr>())
3235 B.addAttribute(llvm::Attribute::MinSize);
3240 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3241 B.addAttribute(llvm::Attribute::NoOutline);
3245 llvm::MaybeAlign ExplicitAlignment;
3246 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3247 ExplicitAlignment = llvm::Align(alignment);
3248 else if (LangOpts.FunctionAlignment)
3249 ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment);
3251 if (ExplicitAlignment) {
3252 F->setAlignment(ExplicitAlignment);
3253 F->setPreferredAlignment(ExplicitAlignment);
3254 }
else if (LangOpts.PreferredFunctionAlignment) {
3255 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3264 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3269 if (CodeGenOpts.SanitizeCfiCrossDso &&
3270 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3271 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3279 if (CodeGenOpts.CallGraphSection) {
3280 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3287 auto *MD = dyn_cast<CXXMethodDecl>(D);
3290 llvm::Metadata *Id =
3292 MD->getType(), std::nullopt,
Base));
3293 F->addTypeMetadata(0, Id);
3300 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3301 if (FD->
hasAttr<SYCLExternalAttr>())
3302 addSYCLModuleIdAttr(F);
3306void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3308 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3313 if (isa_and_nonnull<NamedDecl>(D))
3316 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3318 if (D && D->
hasAttr<UsedAttr>())
3321 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3323 ((CodeGenOpts.KeepPersistentStorageVariables &&
3324 (VD->getStorageDuration() ==
SD_Static ||
3325 VD->getStorageDuration() ==
SD_Thread)) ||
3326 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3327 VD->getType().isConstQualified())))
3332static std::vector<std::string>
3334 llvm::StringMap<bool> &FeatureMap) {
3335 llvm::StringMap<bool> DefaultFeatureMap;
3339 std::vector<std::string> Delta;
3340 for (
const auto &[K,
V] : FeatureMap) {
3341 auto DefaultIt = DefaultFeatureMap.find(K);
3342 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3343 Delta.push_back((
V ?
"+" :
"-") + K.str());
3349bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3350 llvm::AttrBuilder &Attrs,
3351 bool SetTargetFeatures) {
3357 std::vector<std::string> Features;
3358 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3361 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3362 assert((!TD || !TV) &&
"both target_version and target specified");
3365 bool AddedAttr =
false;
3366 if (TD || TV || SD || TC) {
3367 llvm::StringMap<bool> FeatureMap;
3374 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3377 if (!FeatureStr.empty()) {
3378 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3379 if (!ParsedAttr.
CPU.empty() &&
3381 TargetCPU = ParsedAttr.
CPU;
3384 if (!ParsedAttr.
Tune.empty() &&
3386 TuneCPU = ParsedAttr.
Tune;
3402 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3403 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3404 Entry.getKey().str());
3410 llvm::StringMap<bool> FeatureMap;
3424 if (!TargetCPU.empty()) {
3425 Attrs.addAttribute(
"target-cpu", TargetCPU);
3428 if (!TuneCPU.empty()) {
3429 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3432 if (!Features.empty() && SetTargetFeatures) {
3433 llvm::erase_if(Features, [&](
const std::string& F) {
3436 llvm::sort(Features);
3437 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3442 llvm::SmallVector<StringRef, 8> Feats;
3443 bool IsDefault =
false;
3445 IsDefault = TV->isDefaultVersion();
3446 TV->getFeatures(Feats);
3452 Attrs.addAttribute(
"fmv-features");
3454 }
else if (!Feats.empty()) {
3456 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3457 std::string FMVFeatures;
3458 for (StringRef F : OrderedFeats)
3459 FMVFeatures.append(
"," + F.str());
3460 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3467void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3468 llvm::GlobalObject *GO) {
3473 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3476 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3477 GV->addAttribute(
"bss-section", SA->getName());
3478 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3479 GV->addAttribute(
"data-section", SA->getName());
3480 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3481 GV->addAttribute(
"rodata-section", SA->getName());
3482 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3483 GV->addAttribute(
"relro-section", SA->getName());
3486 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3489 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3490 if (!D->
getAttr<SectionAttr>())
3491 F->setSection(SA->getName());
3493 llvm::AttrBuilder Attrs(F->getContext());
3494 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3498 llvm::AttributeMask RemoveAttrs;
3499 RemoveAttrs.addAttribute(
"target-cpu");
3500 RemoveAttrs.addAttribute(
"target-features");
3501 RemoveAttrs.addAttribute(
"fmv-features");
3502 RemoveAttrs.addAttribute(
"tune-cpu");
3503 F->removeFnAttrs(RemoveAttrs);
3504 F->addFnAttrs(Attrs);
3508 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3509 GO->setSection(CSA->getName());
3510 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3511 GO->setSection(SA->getName());
3524 F->setLinkage(llvm::Function::InternalLinkage);
3526 setNonAliasAttributes(GD, F);
3537 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3541 llvm::Function *F) {
3544 if (!F->hasLocalLinkage() ||
3545 F->getFunction().hasAddressTaken(
nullptr,
true,
3549 llvm::LLVMContext::MD_callgraph,
3550 *llvm::MDTuple::get(
3557 llvm::Function *F) {
3559 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3570 F->addTypeMetadata(0, MD);
3577 if (CodeGenOpts.SanitizeCfiCrossDso)
3579 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3583 llvm::CallBase *CB) {
3585 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3589 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
getLLVMContext(), {TypeIdMD});
3590 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3591 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3595 llvm::LLVMContext &Ctx = F->getContext();
3596 llvm::MDBuilder MDB(Ctx);
3597 llvm::StringRef Salt;
3600 if (
const auto &Info = FP->getExtraAttributeInfo())
3601 Salt = Info.CFISalt;
3603 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3612 return llvm::all_of(Name, [](
const char &
C) {
3613 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3619 for (
auto &F : M.functions()) {
3621 bool AddressTaken = F.hasAddressTaken();
3622 if (!AddressTaken && F.hasLocalLinkage())
3623 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3628 if (!AddressTaken || !F.isDeclaration())
3631 const llvm::ConstantInt *
Type;
3632 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3633 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3637 StringRef Name = F.getName();
3641 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3642 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3643 Twine(
Type->getSExtValue()) +
" */\n")
3645 M.appendModuleInlineAsm(
Asm);
3649void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3650 bool IsIncompleteFunction,
3653 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3661 if (!IsIncompleteFunction)
3668 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3670 assert(!F->arg_empty() &&
3671 F->arg_begin()->getType()
3672 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3673 "unexpected this return");
3674 F->addParamAttr(0, llvm::Attribute::Returned);
3684 if (!IsIncompleteFunction && F->isDeclaration())
3687 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3688 F->setSection(CSA->getName());
3689 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3690 F->setSection(SA->getName());
3692 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3694 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3695 else if (EA->isWarning())
3696 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3701 const FunctionDecl *FDBody;
3702 bool HasBody = FD->
hasBody(FDBody);
3704 assert(HasBody &&
"Inline builtin declarations should always have an "
3706 if (shouldEmitFunction(FDBody))
3707 F->addFnAttr(llvm::Attribute::NoBuiltin);
3713 F->addFnAttr(llvm::Attribute::NoBuiltin);
3717 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3718 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3719 if (MD->isVirtual())
3720 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3726 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3727 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3730 if (CodeGenOpts.CallGraphSection)
3733 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3739 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3740 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3742 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3746 llvm::LLVMContext &Ctx = F->getContext();
3747 llvm::MDBuilder MDB(Ctx);
3751 int CalleeIdx = *CB->encoding_begin();
3752 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3753 F->addMetadata(llvm::LLVMContext::MD_callback,
3754 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3755 CalleeIdx, PayloadIndices,
3762 "Only globals with definition can force usage.");
3763 LLVMUsed.emplace_back(GV);
3767 assert(!GV->isDeclaration() &&
3768 "Only globals with definition can force usage.");
3769 LLVMCompilerUsed.emplace_back(GV);
3774 "Only globals with definition can force usage.");
3776 LLVMCompilerUsed.emplace_back(GV);
3778 LLVMUsed.emplace_back(GV);
3782 std::vector<llvm::WeakTrackingVH> &List) {
3792 UsedArray.reserve(List.size());
3793 for (
const llvm::WeakTrackingVH &VH : List) {
3794 if (llvm::Value *
V = VH)
3795 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3799 if (UsedArray.empty())
3801 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3803 auto *GV =
new llvm::GlobalVariable(
3804 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3805 llvm::ConstantArray::get(ATy, UsedArray), Name);
3807 GV->setSection(
"llvm.metadata");
3810void CodeGenModule::emitLLVMUsed() {
3811 emitUsed(*
this,
"llvm.used", LLVMUsed);
3812 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3817 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3826 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3832 ELFDependentLibraries.push_back(
3833 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3840 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3847void CodeGenModule::ProcessPragmaCommentCopyright(StringRef Comment,
3848 bool isFromASTFile) {
3850 "pragma comment copyright is supported only when targeting AIX");
3863 assert(!LoadTimeCommentGlobal &&
3864 "Only one copyright pragma allowed per translation unit.");
3869 uint64_t Hash = xxh3_64bits(Comment);
3870 std::string GlobalName =
3871 (
"__loadtime_comment_str_" + Twine::utohexstr(Hash)).str();
3874 llvm::Constant *StrInit =
3875 llvm::ConstantDataArray::getString(
C, Comment,
true);
3878 auto *GV =
new llvm::GlobalVariable(
getModule(), StrInit->getType(),
3880 llvm::GlobalValue::WeakODRLinkage,
3881 StrInit, GlobalName);
3883 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3884 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3885 GV->setAlignment(llvm::Align(1));
3891 GV->setSection(
"__loadtime_comment");
3894 GV->setMetadata(
"loadtime_comment", llvm::MDNode::get(
C, {}));
3897 llvm::appendToCompilerUsed(
getModule(), {GV});
3899 LoadTimeCommentGlobal = GV;
3908 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3914 if (Visited.insert(Import).second)
3931 if (LL.IsFramework) {
3932 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3933 llvm::MDString::get(Context, LL.Library)};
3935 Metadata.push_back(llvm::MDNode::get(Context, Args));
3941 llvm::Metadata *Args[2] = {
3942 llvm::MDString::get(Context,
"lib"),
3943 llvm::MDString::get(Context, LL.Library),
3945 Metadata.push_back(llvm::MDNode::get(Context, Args));
3949 auto *OptString = llvm::MDString::get(Context, Opt);
3950 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3955void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3957 "We should only emit module initializers for named modules.");
3965 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3982 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3988void CodeGenModule::EmitModuleLinkOptions() {
3992 llvm::SetVector<clang::Module *> LinkModules;
3993 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3994 SmallVector<clang::Module *, 16> Stack;
3997 for (
Module *M : ImportedModules) {
4000 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
4003 if (Visited.insert(M).second)
4009 while (!Stack.empty()) {
4012 bool AnyChildren =
false;
4021 if (Visited.insert(SM).second) {
4022 Stack.push_back(SM);
4030 LinkModules.insert(Mod);
4037 SmallVector<llvm::MDNode *, 16> MetadataArgs;
4039 for (
Module *M : LinkModules)
4040 if (Visited.insert(M).second)
4042 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
4043 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
4046 if (!LinkerOptionsMetadata.empty()) {
4047 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
4048 for (
auto *MD : LinkerOptionsMetadata)
4049 NMD->addOperand(MD);
4053void CodeGenModule::EmitDeferred() {
4062 if (!DeferredVTables.empty()) {
4063 EmitDeferredVTables();
4068 assert(DeferredVTables.empty());
4075 llvm::append_range(DeferredDeclsToEmit,
4079 if (DeferredDeclsToEmit.empty())
4084 std::vector<GlobalDecl> CurDeclsToEmit;
4085 CurDeclsToEmit.swap(DeferredDeclsToEmit);
4087 for (GlobalDecl &D : CurDeclsToEmit) {
4093 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
4097 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
4113 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
4131 if (!GV->isDeclaration())
4135 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
4139 EmitGlobalDefinition(D, GV);
4144 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
4146 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
4151void CodeGenModule::EmitVTablesOpportunistically() {
4157 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
4158 &&
"Only emit opportunistic vtables with optimizations");
4160 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
4162 "This queue should only contain external vtables");
4163 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
4164 VTables.GenerateClassData(RD);
4166 OpportunisticVTables.clear();
4170 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
4175 DeferredAnnotations.clear();
4177 if (Annotations.empty())
4181 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
4182 Annotations[0]->
getType(), Annotations.size()), Annotations);
4183 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
4184 llvm::GlobalValue::AppendingLinkage,
4185 Array,
"llvm.global.annotations");
4190 llvm::Constant *&AStr = AnnotationStrings[Str];
4195 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
4196 auto *gv =
new llvm::GlobalVariable(
4197 getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s,
4198 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
4201 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4219 return llvm::ConstantInt::get(
Int32Ty, LineNo);
4227 llvm::FoldingSetNodeID ID;
4228 for (
Expr *E : Exprs) {
4231 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
4236 LLVMArgs.reserve(Exprs.size());
4238 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
4240 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
4243 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
4244 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
4245 llvm::GlobalValue::PrivateLinkage,
Struct,
4248 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4255 const AnnotateAttr *AA,
4263 llvm::Constant *GVInGlobalsAS = GV;
4264 if (GV->getAddressSpace() !=
4266 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
4268 llvm::PointerType::get(
4269 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
4273 llvm::Constant *Fields[] = {
4274 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
4276 return llvm::ConstantStruct::getAnon(Fields);
4280 llvm::GlobalValue *GV) {
4281 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4291 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4294 auto &SM = Context.getSourceManager();
4295 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
4296 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4301 return NoSanitizeL.containsLocation(Kind, Loc);
4304 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4308 llvm::GlobalVariable *GV,
4310 StringRef Category)
const {
4312 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4314 auto &SM = Context.getSourceManager();
4315 if (NoSanitizeL.containsMainFile(
4316 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
4319 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4326 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4327 Ty = AT->getElementType();
4332 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4340 StringRef Category)
const {
4343 auto Attr = ImbueAttr::NONE;
4345 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4346 if (
Attr == ImbueAttr::NONE)
4347 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4349 case ImbueAttr::NONE:
4351 case ImbueAttr::ALWAYS:
4352 Fn->addFnAttr(
"function-instrument",
"xray-always");
4354 case ImbueAttr::ALWAYS_ARG1:
4355 Fn->addFnAttr(
"function-instrument",
"xray-always");
4356 Fn->addFnAttr(
"xray-log-args",
"1");
4358 case ImbueAttr::NEVER:
4359 Fn->addFnAttr(
"function-instrument",
"xray-never");
4372 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4382 auto &SM = Context.getSourceManager();
4383 if (
auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
4397 if (NumGroups > 1) {
4398 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4407 if (LangOpts.EmitAllDecls)
4410 const auto *VD = dyn_cast<VarDecl>(
Global);
4412 ((CodeGenOpts.KeepPersistentStorageVariables &&
4413 (VD->getStorageDuration() ==
SD_Static ||
4414 VD->getStorageDuration() ==
SD_Thread)) ||
4415 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4416 VD->getType().isConstQualified())))
4429 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4430 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4431 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4432 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4436 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4446 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4453 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4454 if (Context.getInlineVariableDefinitionKind(VD) ==
4459 if (CXX20ModuleInits && VD->getOwningModule() &&
4460 !VD->getOwningModule()->isModuleMapModule()) {
4469 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4472 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4485 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4489 llvm::Constant *
Init;
4492 if (!
V.isAbsent()) {
4503 llvm::Constant *Fields[4] = {
4507 llvm::ConstantDataArray::getRaw(
4508 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4510 Init = llvm::ConstantStruct::getAnon(Fields);
4513 auto *GV =
new llvm::GlobalVariable(
4515 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4517 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4520 if (!
V.isAbsent()) {
4533 llvm::GlobalVariable **Entry =
nullptr;
4534 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4539 llvm::Constant *
Init;
4543 assert(!
V.isAbsent());
4547 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4549 llvm::GlobalValue::PrivateLinkage,
Init,
4551 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4566 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4570 llvm::Constant *
Init =
Emitter.emitForInitializer(
4578 llvm::GlobalValue::LinkageTypes
Linkage =
4580 ? llvm::GlobalValue::LinkOnceODRLinkage
4581 : llvm::GlobalValue::InternalLinkage;
4582 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4586 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4593 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4594 assert(AA &&
"No alias?");
4604 llvm::Constant *Aliasee;
4606 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4614 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4615 WeakRefReferences.insert(F);
4623 if (
auto *A = D->
getAttr<AttrT>())
4624 return A->isImplicit();
4631 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4634 const auto *AA =
Global->getAttr<AliasAttr>();
4642 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4643 if (LangOpts.OpenMPIsTargetDevice)
4644 return !AliaseeDecl ||
4645 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4648 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4649 const bool AliaseeHasDeviceAttr =
4650 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4652 if (LangOpts.CUDAIsDevice)
4653 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4660bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4661 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4666 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4667 Global->hasAttr<CUDAConstantAttr>() ||
4668 Global->hasAttr<CUDASharedAttr>() ||
4669 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4670 Global->getType()->isCUDADeviceBuiltinTextureType();
4677 if (
Global->hasAttr<WeakRefAttr>())
4682 if (
Global->hasAttr<AliasAttr>()) {
4685 return EmitAliasDefinition(GD);
4689 if (
Global->hasAttr<IFuncAttr>())
4690 return emitIFuncDefinition(GD);
4693 if (
Global->hasAttr<CPUDispatchAttr>())
4694 return emitCPUDispatchDefinition(GD);
4699 if (LangOpts.CUDA) {
4701 "Expected Variable or Function");
4702 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4703 if (!shouldEmitCUDAGlobalVar(VD))
4705 }
else if (LangOpts.CUDAIsDevice) {
4706 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4707 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4708 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4712 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4713 !
Global->hasAttr<CUDAGlobalAttr>() &&
4715 !
Global->hasAttr<CUDAHostAttr>()))
4718 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4719 Global->hasAttr<CUDADeviceAttr>())
4723 if (LangOpts.OpenMP) {
4725 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4727 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4728 if (MustBeEmitted(
Global))
4732 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4733 if (MustBeEmitted(
Global))
4740 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4741 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4747 if (FD->
hasAttr<AnnotateAttr>()) {
4750 DeferredAnnotations[MangledName] = FD;
4765 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4771 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4773 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4774 if (LangOpts.OpenMP) {
4776 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4777 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4781 if (VD->hasExternalStorage() &&
4782 Res != OMPDeclareTargetDeclAttr::MT_Link)
4785 bool UnifiedMemoryEnabled =
4787 if (*Res == OMPDeclareTargetDeclAttr::MT_Local ||
4788 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4789 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4790 !UnifiedMemoryEnabled)) {
4793 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4794 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4795 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4796 UnifiedMemoryEnabled)) &&
4797 "Link clause or to clause with unified memory expected.");
4807 if (LangOpts.HLSL) {
4808 if (VD->getStorageClass() ==
SC_Extern) {
4817 if (Context.getInlineVariableDefinitionKind(VD) ==
4827 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4829 EmitGlobalDefinition(GD);
4830 addEmittedDeferredDecl(GD);
4838 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4839 CXXGlobalInits.push_back(
nullptr);
4845 addDeferredDeclToEmit(GD);
4846 }
else if (MustBeEmitted(
Global)) {
4848 assert(!MayBeEmittedEagerly(
Global));
4849 addDeferredDeclToEmit(GD);
4854 DeferredDecls[MangledName] = GD;
4860 if (
const auto *RT =
4861 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4862 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4863 RD = RD->getDefinitionOrSelf();
4864 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4873struct DLLImportFunctionVisitor
4874 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4875 bool SafeToInline =
true;
4877 bool shouldVisitImplicitCode()
const {
return true; }
4879 bool VisitVarDecl(VarDecl *VD) {
4882 SafeToInline =
false;
4883 return SafeToInline;
4890 return SafeToInline;
4893 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4895 SafeToInline = D->
hasAttr<DLLImportAttr>();
4896 return SafeToInline;
4899 bool VisitDeclRefExpr(DeclRefExpr *E) {
4902 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4903 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4904 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4905 return SafeToInline;
4908 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4910 return SafeToInline;
4913 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4917 SafeToInline =
true;
4919 SafeToInline = M->
hasAttr<DLLImportAttr>();
4921 return SafeToInline;
4924 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4926 return SafeToInline;
4929 bool VisitCXXNewExpr(CXXNewExpr *E) {
4931 return SafeToInline;
4936bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4943 if (F->isInlineBuiltinDeclaration())
4946 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4951 if (
const Module *M = F->getOwningModule();
4952 M && M->getTopLevelModule()->isNamedModule() &&
4953 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4963 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4968 if (F->hasAttr<NoInlineAttr>())
4971 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4973 DLLImportFunctionVisitor Visitor;
4974 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4975 if (!Visitor.SafeToInline)
4978 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4985 for (
const CXXBaseSpecifier &B :
Dtor->getParent()->bases())
4999bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
5000 return CodeGenOpts.OptimizationLevel > 0;
5003void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
5004 llvm::GlobalValue *GV) {
5008 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
5009 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
5011 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
5012 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
5013 if (TC->isFirstOfVersion(I))
5016 EmitGlobalFunctionDefinition(GD, GV);
5022 AddDeferredMultiVersionResolverToEmit(GD);
5024 GetOrCreateMultiVersionResolver(GD);
5028void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
5031 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
5032 Context.getSourceManager(),
5033 "Generating code for declaration");
5035 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5038 if (!shouldEmitFunction(GD))
5041 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
5043 llvm::raw_string_ostream
OS(Name);
5049 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
5053 ABI->emitCXXStructor(GD);
5055 EmitMultiVersionFunctionDefinition(GD, GV);
5057 EmitGlobalFunctionDefinition(GD, GV);
5066 return EmitMultiVersionFunctionDefinition(GD, GV);
5067 return EmitGlobalFunctionDefinition(GD, GV);
5070 if (
const auto *VD = dyn_cast<VarDecl>(D))
5071 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
5073 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
5077 llvm::Function *NewFn);
5093static llvm::GlobalValue::LinkageTypes
5097 return llvm::GlobalValue::InternalLinkage;
5098 return llvm::GlobalValue::WeakODRLinkage;
5101void CodeGenModule::emitMultiVersionFunctions() {
5102 std::vector<GlobalDecl> MVFuncsToEmit;
5103 MultiVersionFuncs.swap(MVFuncsToEmit);
5104 for (GlobalDecl GD : MVFuncsToEmit) {
5106 assert(FD &&
"Expected a FunctionDecl");
5108 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
5109 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
5113 if (
Decl->isDefined()) {
5114 EmitGlobalFunctionDefinition(CurGD,
nullptr);
5122 assert(
Func &&
"This should have just been created");
5130 bool ShouldEmitResolver = !
getTriple().isAArch64();
5131 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5132 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
5135 FD, [&](
const FunctionDecl *CurFD) {
5136 llvm::SmallVector<StringRef, 8> Feats;
5139 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
5141 TA->getX86AddedFeatures(Feats);
5142 llvm::Function *
Func = createFunction(CurFD);
5143 DeclMap.insert({
Func, CurFD});
5144 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
5145 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
5146 if (TVA->isDefaultVersion() && IsDefined)
5147 ShouldEmitResolver =
true;
5148 llvm::Function *
Func = createFunction(CurFD);
5149 DeclMap.insert({
Func, CurFD});
5151 TVA->getFeatures(Feats, Delim);
5152 Options.emplace_back(
Func, Feats);
5153 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
5154 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
5155 if (!TC->isFirstOfVersion(I))
5157 if (TC->isDefaultVersion(I) && IsDefined)
5158 ShouldEmitResolver =
true;
5159 llvm::Function *
Func = createFunction(CurFD, I);
5160 DeclMap.insert({
Func, CurFD});
5163 TC->getX86Feature(Feats, I);
5164 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
5167 TC->getFeatures(Feats, I, Delim);
5168 Options.emplace_back(
Func, Feats);
5172 llvm_unreachable(
"unexpected MultiVersionKind");
5175 if (!ShouldEmitResolver)
5178 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
5179 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
5180 ResolverConstant = IFunc->getResolver();
5185 *
this, GD, FD,
true);
5192 auto *Alias = llvm::GlobalAlias::create(
5194 MangledName +
".ifunc", IFunc, &
getModule());
5203 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
5204 const CodeGenFunction::FMVResolverOption &RHS) {
5210 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
5211 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
5212 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
5213 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
5214 return LHS.isSubsetOf(RHS);
5216 Diags.Report(DeclMap[I->Function]->getLocation(),
5217 diag::warn_unreachable_version)
5218 << I->Function->getName();
5219 assert(I->Function->user_empty() &&
"unexpected users");
5220 I->Function->eraseFromParent();
5221 I->Function =
nullptr;
5225 CodeGenFunction CGF(*
this);
5226 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5228 setMultiVersionResolverAttributes(ResolverFunc, GD);
5230 ResolverFunc->setComdat(
5231 getModule().getOrInsertComdat(ResolverFunc->getName()));
5237 if (!MVFuncsToEmit.empty())
5242 if (!MultiVersionFuncs.empty())
5243 emitMultiVersionFunctions();
5253 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5255 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5256 llvm::GlobalVariable::ExternalWeakLinkage,
5258 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5263void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5264 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5266 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5268 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5269 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5270 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5271 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5273 DS->takeName(OldDS);
5274 OldDS->replaceAllUsesWith(DS);
5275 OldDS->eraseFromParent();
5281 llvm::Constant *
New) {
5284 Old->replaceAllUsesWith(
New);
5285 Old->eraseFromParent();
5288void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5290 assert(FD &&
"Not a FunctionDecl?");
5292 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5293 assert(DD &&
"Not a cpu_dispatch Function?");
5299 UpdateMultiVersionNames(GD, FD, ResolverName);
5301 llvm::Type *ResolverType;
5302 GlobalDecl ResolverGD;
5304 ResolverType = llvm::FunctionType::get(
5310 ResolverType = DeclTy;
5315 ResolverName, ResolverType, ResolverGD,
false));
5318 ResolverFunc->setComdat(
5319 getModule().getOrInsertComdat(ResolverFunc->getName()));
5321 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5324 for (
const IdentifierInfo *II : DD->cpus()) {
5332 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5335 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5341 Func = GetOrCreateLLVMFunction(
5342 MangledName, DeclTy, ExistingDecl,
5348 llvm::SmallVector<StringRef, 32> Features;
5349 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5350 llvm::transform(Features, Features.begin(),
5351 [](StringRef Str) { return Str.substr(1); });
5352 llvm::erase_if(Features, [&Target](StringRef Feat) {
5353 return !Target.validateCpuSupports(Feat);
5359 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5360 const CodeGenFunction::FMVResolverOption &RHS) {
5361 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5362 llvm::X86::getCpuSupportsMask(RHS.
Features);
5369 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5370 (Options.end() - 2)->Features),
5371 [](
auto X) { return X == 0; })) {
5372 StringRef LHSName = (Options.end() - 2)->Function->getName();
5373 StringRef RHSName = (Options.end() - 1)->Function->getName();
5374 if (LHSName.compare(RHSName) < 0)
5375 Options.erase(Options.end() - 2);
5377 Options.erase(Options.end() - 1);
5380 CodeGenFunction CGF(*
this);
5381 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5382 setMultiVersionResolverAttributes(ResolverFunc, GD);
5387 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5392 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5399 *
this, GD, FD,
true);
5402 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5410void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5412 assert(FD &&
"Not a FunctionDecl?");
5415 std::string MangledName =
5417 if (!DeferredResolversToEmit.insert(MangledName).second)
5420 MultiVersionFuncs.push_back(GD);
5426llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5428 assert(FD &&
"Not a FunctionDecl?");
5430 std::string MangledName =
5435 std::string ResolverName = MangledName;
5439 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5443 ResolverName +=
".ifunc";
5450 ResolverName +=
".resolver";
5453 bool ShouldReturnIFunc =
5472 AddDeferredMultiVersionResolverToEmit(GD);
5476 if (ShouldReturnIFunc) {
5478 llvm::Type *ResolverType = llvm::FunctionType::get(
5480 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5481 MangledName +
".resolver", ResolverType, GlobalDecl{},
5489 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5491 GIF->setName(ResolverName);
5498 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5499 ResolverName, DeclTy, GlobalDecl{},
false);
5501 "Resolver should be created for the first time");
5506void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5508 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5521 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5532bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5533 const llvm::GlobalValue *GV)
const {
5534 auto SC = GV->getDLLStorageClass();
5535 if (SC == llvm::GlobalValue::DefaultStorageClass)
5538 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5539 !MRD->
hasAttr<DLLImportAttr>()) ||
5540 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5541 !MRD->
hasAttr<DLLExportAttr>())) &&
5552llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5553 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5554 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5558 std::string NameWithoutMultiVersionMangling;
5559 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5561 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5562 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5563 !DontDefer && !IsForDefinition) {
5566 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5568 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5571 GDDef = GlobalDecl(FDDef);
5579 UpdateMultiVersionNames(GD, FD, MangledName);
5580 if (!IsForDefinition) {
5586 AddDeferredMultiVersionResolverToEmit(GD);
5588 *
this, GD, FD,
true);
5597 *
this, GD, FD,
true);
5599 return GetOrCreateMultiVersionResolver(GD);
5604 if (!NameWithoutMultiVersionMangling.empty())
5605 MangledName = NameWithoutMultiVersionMangling;
5610 if (WeakRefReferences.erase(Entry)) {
5611 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5612 if (FD && !FD->
hasAttr<WeakAttr>())
5613 Entry->setLinkage(llvm::Function::ExternalLinkage);
5617 if (D && shouldDropDLLAttribute(D, Entry)) {
5618 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5624 if (IsForDefinition && !Entry->isDeclaration()) {
5631 DiagnosedConflictingDefinitions.insert(GD).second) {
5635 diag::note_previous_definition);
5640 (Entry->getValueType() == Ty)) {
5647 if (!IsForDefinition)
5654 bool IsIncompleteFunction =
false;
5656 llvm::FunctionType *FTy;
5660 FTy = llvm::FunctionType::get(
VoidTy,
false);
5661 IsIncompleteFunction =
true;
5665 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5666 Entry ? StringRef() : MangledName, &
getModule());
5670 if (D && D->
hasAttr<AnnotateAttr>())
5688 if (!Entry->use_empty()) {
5690 Entry->removeDeadConstantUsers();
5696 assert(F->getName() == MangledName &&
"name was uniqued!");
5698 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5699 if (ExtraAttrs.hasFnAttrs()) {
5700 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5708 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5711 addDeferredDeclToEmit(GD);
5716 auto DDI = DeferredDecls.find(MangledName);
5717 if (DDI != DeferredDecls.end()) {
5721 addDeferredDeclToEmit(DDI->second);
5722 DeferredDecls.erase(DDI);
5750 if (!IsIncompleteFunction) {
5751 assert(F->getFunctionType() == Ty);
5769 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5779 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5782 DD->getParent()->getNumVBases() == 0)
5787 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5788 false, llvm::AttributeList(),
5791 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5795 if (IsForDefinition)
5803 llvm::GlobalValue *F =
5806 return llvm::NoCFIValue::get(F);
5816 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5819 if (!
C.getLangOpts().CPlusPlus)
5824 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5825 ?
C.Idents.get(
"terminate")
5826 :
C.Idents.get(Name);
5828 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5832 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5833 for (
const auto *
Result : LSD->lookup(&NS))
5834 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5839 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5848 llvm::Function *F, StringRef Name) {
5854 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5857 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5858 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5859 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5866 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5867 if (AssumeConvergent) {
5869 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5872 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5877 llvm::Constant *
C = GetOrCreateLLVMFunction(
5879 false,
false, ExtraAttrs);
5881 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5897 llvm::AttributeList ExtraAttrs,
bool Local,
5898 bool AssumeConvergent) {
5899 if (AssumeConvergent) {
5901 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5905 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5909 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5918 markRegisterParameterAttributes(F);
5944 if (WeakRefReferences.erase(Entry)) {
5945 if (D && !D->
hasAttr<WeakAttr>())
5946 Entry->setLinkage(llvm::Function::ExternalLinkage);
5950 if (D && shouldDropDLLAttribute(D, Entry))
5951 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5953 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5956 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5961 if (IsForDefinition && !Entry->isDeclaration()) {
5969 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5971 DiagnosedConflictingDefinitions.insert(D).second) {
5975 diag::note_previous_definition);
5980 if (Entry->getType()->getAddressSpace() != TargetAS)
5981 return llvm::ConstantExpr::getAddrSpaceCast(
5982 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5986 if (!IsForDefinition)
5992 auto *GV =
new llvm::GlobalVariable(
5993 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5994 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5995 getContext().getTargetAddressSpace(DAddrSpace));
6000 GV->takeName(Entry);
6002 if (!Entry->use_empty()) {
6003 Entry->replaceAllUsesWith(GV);
6006 Entry->eraseFromParent();
6012 auto DDI = DeferredDecls.find(MangledName);
6013 if (DDI != DeferredDecls.end()) {
6016 addDeferredDeclToEmit(DDI->second);
6017 DeferredDecls.erase(DDI);
6022 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
6029 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
6035 CXXThreadLocals.push_back(D);
6043 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
6044 EmitGlobalVarDefinition(D);
6049 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
6050 GV->setSection(SA->getName());
6054 if (
getTriple().getArch() == llvm::Triple::xcore &&
6058 GV->setSection(
".cp.rodata");
6061 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
6062 GV->setCodeModel(CMA->getModel());
6067 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
6071 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
6072 bool HasMutableFields =
Record &&
Record->hasMutableFields();
6073 if (!HasMutableFields) {
6080 auto *InitType =
Init->getType();
6081 if (GV->getValueType() != InitType) {
6086 GV->setName(StringRef());
6091 ->stripPointerCasts());
6094 GV->eraseFromParent();
6097 GV->setInitializer(
Init);
6098 GV->setConstant(
true);
6099 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
6119 SanitizerMD->reportGlobal(GV, *D);
6124 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
6125 if (DAddrSpace != ExpectedAS)
6138 false, IsForDefinition);
6159 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
6160 llvm::Align Alignment) {
6161 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
6162 llvm::GlobalVariable *OldGV =
nullptr;
6166 if (GV->getValueType() == Ty)
6171 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
6176 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
6181 GV->takeName(OldGV);
6183 if (!OldGV->use_empty()) {
6184 OldGV->replaceAllUsesWith(GV);
6187 OldGV->eraseFromParent();
6191 !GV->hasAvailableExternallyLinkage())
6192 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6194 GV->setAlignment(Alignment);
6231 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
6239 if (GV && !GV->isDeclaration())
6244 if (!MustBeEmitted(D) && !GV) {
6245 DeferredDecls[MangledName] = D;
6250 EmitGlobalVarDefinition(D);
6255 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6257 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6272 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6276 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6279 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6281 if (!Fn->getSubprogram())
6287 return Context.toCharUnitsFromBits(
6292 if (LangOpts.OpenCL) {
6303 if (LangOpts.SYCLIsDevice &&
6307 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6312 if (D->
hasAttr<CUDAConstantAttr>())
6314 if (D->
hasAttr<CUDASharedAttr>())
6316 if (D->
hasAttr<CUDADeviceAttr>())
6324 if (LangOpts.OpenMP) {
6326 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6334 if (LangOpts.OpenCL)
6336 if (LangOpts.SYCLIsDevice)
6338 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
6346 if (
auto AS =
getTarget().getConstantAddressSpace())
6359static llvm::Constant *
6361 llvm::GlobalVariable *GV) {
6362 llvm::Constant *Cast = GV;
6367 GV, llvm::PointerType::get(
6374template<
typename SomeDecl>
6376 llvm::GlobalValue *GV) {
6391 const SomeDecl *
First = D->getFirstDecl();
6392 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6398 std::pair<StaticExternCMap::iterator, bool> R =
6399 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6404 R.first->second =
nullptr;
6411 if (D.
hasAttr<SelectAnyAttr>())
6415 if (
auto *VD = dyn_cast<VarDecl>(&D))
6429 llvm_unreachable(
"No such linkage");
6437 llvm::GlobalObject &GO) {
6440 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6448void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6463 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6464 OpenMPRuntime->emitTargetGlobalVariable(D))
6467 llvm::TrackingVH<llvm::Constant>
Init;
6468 bool NeedsGlobalCtor =
false;
6472 bool IsDefinitionAvailableExternally =
6474 bool NeedsGlobalDtor =
6475 !IsDefinitionAvailableExternally &&
6482 if (IsDefinitionAvailableExternally &&
6493 std::optional<ConstantEmitter> emitter;
6498 bool IsCUDASharedVar =
6503 bool IsCUDAShadowVar =
6505 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6506 D->
hasAttr<CUDASharedAttr>());
6507 bool IsCUDADeviceShadowVar =
6512 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6513 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6517 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6520 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6521 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6522 }
else if (!InitExpr) {
6535 initializedGlobalDecl = GlobalDecl(D);
6536 emitter.emplace(*
this);
6537 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6545 if (!IsDefinitionAvailableExternally)
6546 NeedsGlobalCtor =
true;
6550 NeedsGlobalCtor =
false;
6562 DelayedCXXInitPosition.erase(D);
6569 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6574 llvm::Type* InitType =
Init->getType();
6575 llvm::Constant *Entry =
6579 Entry = Entry->stripPointerCasts();
6582 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6593 if (!GV || GV->getValueType() != InitType ||
6594 GV->getType()->getAddressSpace() !=
6598 Entry->setName(StringRef());
6603 ->stripPointerCasts());
6606 llvm::Constant *NewPtrForOldDecl =
6607 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6609 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6617 if (D->
hasAttr<AnnotateAttr>())
6630 if (LangOpts.CUDA) {
6631 if (LangOpts.CUDAIsDevice) {
6634 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6637 GV->setExternallyInitialized(
true);
6644 if (LangOpts.HLSL &&
6649 GV->setExternallyInitialized(
true);
6651 GV->setInitializer(
Init);
6658 emitter->finalize(GV);
6661 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6662 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6666 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6667 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6669 GV->setConstant(
true);
6674 if (std::optional<CharUnits> AlignValFromAllocate =
6676 AlignVal = *AlignValFromAllocate;
6694 Linkage == llvm::GlobalValue::ExternalLinkage &&
6695 Context.getTargetInfo().getTriple().isOSDarwin() &&
6697 Linkage = llvm::GlobalValue::InternalLinkage;
6702 if (LangOpts.HLSL &&
6704 Linkage = llvm::GlobalValue::ExternalLinkage;
6707 if (D->
hasAttr<DLLImportAttr>())
6708 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6709 else if (D->
hasAttr<DLLExportAttr>())
6710 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6712 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6714 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6716 GV->setConstant(
false);
6721 if (!GV->getInitializer()->isNullValue())
6722 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6725 setNonAliasAttributes(D, GV);
6727 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6729 CXXThreadLocals.push_back(D);
6736 if (NeedsGlobalCtor || NeedsGlobalDtor)
6737 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6739 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6744 DI->EmitGlobalVariable(GV, D);
6752 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6763 if (D->
hasAttr<SectionAttr>())
6769 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6770 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6771 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6772 D->
hasAttr<PragmaClangRodataSectionAttr>())
6780 if (D->
hasAttr<WeakImportAttr>())
6789 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6790 if (D->
hasAttr<AlignedAttr>())
6793 if (Context.isAlignmentRequired(VarType))
6797 for (
const FieldDecl *FD : RD->fields()) {
6798 if (FD->isBitField())
6800 if (FD->
hasAttr<AlignedAttr>())
6802 if (Context.isAlignmentRequired(FD->
getType()))
6814 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6815 Context.getTypeAlignIfKnown(D->
getType()) >
6822llvm::GlobalValue::LinkageTypes
6826 return llvm::Function::InternalLinkage;
6829 return llvm::GlobalVariable::WeakAnyLinkage;
6833 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6838 return llvm::GlobalValue::AvailableExternallyLinkage;
6852 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6853 : llvm::Function::InternalLinkage;
6867 return llvm::Function::ExternalLinkage;
6870 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6871 : llvm::Function::InternalLinkage;
6872 return llvm::Function::WeakODRLinkage;
6879 CodeGenOpts.NoCommon))
6880 return llvm::GlobalVariable::CommonLinkage;
6886 if (D->
hasAttr<SelectAnyAttr>())
6887 return llvm::GlobalVariable::WeakODRLinkage;
6891 return llvm::GlobalVariable::ExternalLinkage;
6894llvm::GlobalValue::LinkageTypes
6903 llvm::Function *newFn) {
6905 if (old->use_empty())
6908 llvm::Type *newRetTy = newFn->getReturnType();
6913 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6915 llvm::User *user = ui->getUser();
6919 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6920 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6926 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6929 if (!callSite->isCallee(&*ui))
6934 if (callSite->getType() != newRetTy && !callSite->use_empty())
6939 llvm::AttributeList oldAttrs = callSite->getAttributes();
6942 unsigned newNumArgs = newFn->arg_size();
6943 if (callSite->arg_size() < newNumArgs)
6949 bool dontTransform =
false;
6950 for (llvm::Argument &A : newFn->args()) {
6951 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6952 dontTransform =
true;
6957 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6965 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6969 callSite->getOperandBundlesAsDefs(newBundles);
6971 llvm::CallBase *newCall;
6973 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6974 callSite->getIterator());
6977 newCall = llvm::InvokeInst::Create(
6978 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6979 newArgs, newBundles,
"", callSite->getIterator());
6983 if (!newCall->getType()->isVoidTy())
6984 newCall->takeName(callSite);
6985 newCall->setAttributes(
6986 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6987 oldAttrs.getRetAttrs(), newArgAttrs));
6988 newCall->setCallingConv(callSite->getCallingConv());
6991 if (!callSite->use_empty())
6992 callSite->replaceAllUsesWith(newCall);
6995 if (callSite->getDebugLoc())
6996 newCall->setDebugLoc(callSite->getDebugLoc());
6998 callSitesToBeRemovedFromParent.push_back(callSite);
7001 for (
auto *callSite : callSitesToBeRemovedFromParent) {
7002 callSite->eraseFromParent();
7016 llvm::Function *NewFn) {
7026 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
7038void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
7039 llvm::GlobalValue *GV) {
7047 if (!GV || (GV->getValueType() != Ty))
7053 if (!GV->isDeclaration())
7063 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
7064 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
7076 setNonAliasAttributes(GD, Fn);
7078 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
7079 (CodeGenOpts.OptimizationLevel == 0) &&
7082 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
7084 !D->
hasAttr<NoInlineAttr>() &&
7085 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
7086 !D->
hasAttr<OptimizeNoneAttr>() &&
7087 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
7088 !ShouldAddOptNone) {
7089 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
7099 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
7100 if (UnwindMode != llvm::WinX64EHUnwindMode::Default &&
7101 UnwindMode != llvm::WinX64EHUnwindMode::V3 &&
7102 Fn->needsUnwindTableEntry()) {
7103 bool HasEGPR =
false;
7104 if (Fn->hasFnAttribute(
"target-features")) {
7106 Fn->getFnAttribute(
"target-features").getValueAsString();
7108 Feats.split(Tokens,
',', -1,
false);
7109 for (StringRef
Tok : Tokens) {
7112 else if (
Tok ==
"-egpr")
7116 HasEGPR = Context.getTargetInfo().hasFeature(
"egpr");
7119 unsigned DiagID = Diags.getCustomDiagID(
7121 "EGPR target feature requires unwind version 3");
7127 auto GetPriority = [
this](
const auto *Attr) ->
int {
7128 Expr *E = Attr->getPriority();
7132 return Attr->DefaultPriority;
7135 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
7137 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
7143void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
7145 const AliasAttr *AA = D->
getAttr<AliasAttr>();
7146 assert(AA &&
"Not an alias?");
7150 if (AA->getAliasee() == MangledName) {
7151 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7158 if (Entry && !Entry->isDeclaration())
7161 Aliases.push_back(GD);
7167 llvm::Constant *Aliasee;
7168 llvm::GlobalValue::LinkageTypes
LT;
7170 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
7176 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
7183 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
7185 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
7188 if (GA->getAliasee() == Entry) {
7189 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7193 assert(Entry->isDeclaration());
7202 GA->takeName(Entry);
7204 Entry->replaceAllUsesWith(GA);
7205 Entry->eraseFromParent();
7207 GA->setName(MangledName);
7215 GA->setLinkage(llvm::Function::WeakAnyLinkage);
7218 if (
const auto *VD = dyn_cast<VarDecl>(D))
7219 if (VD->getTLSKind())
7230void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
7232 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
7233 assert(IFA &&
"Not an ifunc?");
7237 if (IFA->getResolver() == MangledName) {
7238 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7244 if (Entry && !Entry->isDeclaration()) {
7247 DiagnosedConflictingDefinitions.insert(GD).second) {
7248 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
7251 diag::note_previous_definition);
7256 Aliases.push_back(GD);
7262 llvm::Constant *Resolver =
7263 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
7267 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
7268 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
7270 if (GIF->getResolver() == Entry) {
7271 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7274 assert(Entry->isDeclaration());
7283 GIF->takeName(Entry);
7285 Entry->replaceAllUsesWith(GIF);
7286 Entry->eraseFromParent();
7288 GIF->setName(MangledName);
7294 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7295 (llvm::Intrinsic::ID)IID, Tys);
7298static llvm::StringMapEntry<llvm::GlobalVariable *> &
7301 bool &IsUTF16,
unsigned &StringLength) {
7302 StringRef String = Literal->getString();
7303 unsigned NumBytes = String.size();
7306 if (!Literal->containsNonAsciiOrNull()) {
7307 StringLength = NumBytes;
7308 return *Map.insert(std::make_pair(String,
nullptr)).first;
7315 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7316 llvm::UTF16 *ToPtr = &ToBuf[0];
7318 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7319 ToPtr + NumBytes, llvm::strictConversion);
7322 StringLength = ToPtr - &ToBuf[0];
7326 return *Map.insert(std::make_pair(
7327 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7328 (StringLength + 1) * 2),
7334 unsigned StringLength = 0;
7335 bool isUTF16 =
false;
7336 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7341 if (
auto *
C = Entry.second)
7346 const llvm::Triple &Triple =
getTriple();
7349 const bool IsSwiftABI =
7350 static_cast<unsigned>(CFRuntime) >=
7355 if (!CFConstantStringClassRef) {
7356 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7358 Ty = llvm::ArrayType::get(Ty, 0);
7360 switch (CFRuntime) {
7364 CFConstantStringClassName =
7365 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7366 :
"$s10Foundation19_NSCFConstantStringCN";
7370 CFConstantStringClassName =
7371 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7372 :
"$S10Foundation19_NSCFConstantStringCN";
7376 CFConstantStringClassName =
7377 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7378 :
"__T010Foundation19_NSCFConstantStringCN";
7385 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7386 llvm::GlobalValue *GV =
nullptr;
7388 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7395 if ((VD = dyn_cast<VarDecl>(
Result)))
7398 if (Triple.isOSBinFormatELF()) {
7400 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7402 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7403 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7404 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7406 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7414 CFConstantStringClassRef =
7415 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7418 QualType CFTy = Context.getCFConstantStringType();
7423 auto Fields = Builder.beginStruct(STy);
7432 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7433 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7435 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7439 llvm::Constant *
C =
nullptr;
7442 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7443 Entry.first().size() / 2);
7444 C = llvm::ConstantDataArray::get(VMContext, Arr);
7446 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7452 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7453 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7454 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7457 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7458 : Context.getTypeAlignInChars(Context.CharTy);
7464 if (Triple.isOSBinFormatMachO())
7465 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7466 :
"__TEXT,__cstring,cstring_literals");
7469 else if (Triple.isOSBinFormatELF())
7470 GV->setSection(
".rodata");
7476 llvm::IntegerType *LengthTy =
7486 Fields.addInt(LengthTy, StringLength);
7494 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7496 llvm::GlobalVariable::PrivateLinkage);
7497 GV->addAttribute(
"objc_arc_inert");
7498 switch (Triple.getObjectFormat()) {
7499 case llvm::Triple::UnknownObjectFormat:
7500 llvm_unreachable(
"unknown file format");
7501 case llvm::Triple::DXContainer:
7502 case llvm::Triple::GOFF:
7503 case llvm::Triple::SPIRV:
7504 case llvm::Triple::XCOFF:
7505 llvm_unreachable(
"unimplemented");
7506 case llvm::Triple::COFF:
7507 case llvm::Triple::ELF:
7508 case llvm::Triple::Wasm:
7509 GV->setSection(
"cfstring");
7511 case llvm::Triple::MachO:
7512 GV->setSection(
"__DATA,__cfstring");
7521 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7525 if (ObjCFastEnumerationStateType.isNull()) {
7526 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7530 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7531 Context.getPointerType(Context.UnsignedLongTy),
7532 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7535 for (
size_t i = 0; i < 4; ++i) {
7540 FieldTypes[i],
nullptr,
7549 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7552 return ObjCFastEnumerationStateType;
7566 assert(CAT &&
"String literal not of constant array type!");
7568 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7572 llvm::Type *ElemTy = AType->getElementType();
7573 unsigned NumElements = AType->getNumElements();
7576 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7578 Elements.reserve(NumElements);
7580 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7582 Elements.resize(NumElements);
7583 return llvm::ConstantDataArray::get(VMContext, Elements);
7586 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7588 Elements.reserve(NumElements);
7590 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7592 Elements.resize(NumElements);
7593 return llvm::ConstantDataArray::get(VMContext, Elements);
7596static llvm::GlobalVariable *
7605 auto *GV =
new llvm::GlobalVariable(
7606 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7607 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7609 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7610 if (GV->isWeakForLinker()) {
7611 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7612 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7628 llvm::GlobalVariable **Entry =
nullptr;
7629 if (!LangOpts.WritableStrings) {
7630 Entry = &ConstantStringMap[
C];
7631 if (
auto GV = *Entry) {
7632 if (Alignment.
getAsAlign() > GV->getAlign().valueOrOne())
7635 GV->getValueType(), Alignment);
7640 StringRef GlobalVariableName;
7641 llvm::GlobalValue::LinkageTypes LT;
7646 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7647 !LangOpts.WritableStrings) {
7648 llvm::raw_svector_ostream Out(MangledNameBuffer);
7650 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7651 GlobalVariableName = MangledNameBuffer;
7653 LT = llvm::GlobalValue::PrivateLinkage;
7654 GlobalVariableName = Name;
7666 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7669 GV->getValueType(), Alignment);
7686 StringRef GlobalName) {
7687 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7692 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7695 llvm::GlobalVariable **Entry =
nullptr;
7696 if (!LangOpts.WritableStrings) {
7697 Entry = &ConstantStringMap[
C];
7698 if (
auto GV = *Entry) {
7699 if (Alignment.
getAsAlign() > GV->getAlign().valueOrOne())
7702 GV->getValueType(), Alignment);
7708 GlobalName, Alignment);
7713 GV->getValueType(), Alignment);
7731 MaterializedType = E->
getType();
7735 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7736 if (!InsertResult.second) {
7739 if (!InsertResult.first->second) {
7744 InsertResult.first->second =
new llvm::GlobalVariable(
7745 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7749 llvm::cast<llvm::GlobalVariable>(
7750 InsertResult.first->second->stripPointerCasts())
7759 llvm::raw_svector_ostream Out(Name);
7781 std::optional<ConstantEmitter> emitter;
7782 llvm::Constant *InitialValue =
nullptr;
7787 emitter.emplace(*
this);
7788 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7793 Type = InitialValue->getType();
7802 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7804 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7808 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7812 Linkage = llvm::GlobalVariable::InternalLinkage;
7816 auto *GV =
new llvm::GlobalVariable(
7818 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7819 if (emitter) emitter->finalize(GV);
7821 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7823 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7825 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7829 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7830 if (VD->getTLSKind())
7832 llvm::Constant *CV = GV;
7835 GV, llvm::PointerType::get(
7841 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7843 Entry->replaceAllUsesWith(CV);
7844 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7853void CodeGenModule::EmitObjCPropertyImplementations(
const
7866 if (!Getter || Getter->isSynthesizedAccessorStub())
7869 auto *Setter = PID->getSetterMethodDecl();
7870 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7881 if (ivar->getType().isDestructedType())
7902void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7915 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7930 getContext().getObjCIdType(),
nullptr, D,
true,
7936 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7941void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7948 EmitDeclContext(LSD);
7951void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7953 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7956 std::unique_ptr<CodeGenFunction> &CurCGF =
7957 GlobalTopLevelStmtBlockInFlight.first;
7961 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7969 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7970 FunctionArgList Args;
7972 const CGFunctionInfo &FnInfo =
7975 llvm::Function *
Fn = llvm::Function::Create(
7976 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7978 CurCGF.reset(
new CodeGenFunction(*
this));
7979 GlobalTopLevelStmtBlockInFlight.second = D;
7980 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7982 CXXGlobalInits.push_back(Fn);
7985 CurCGF->EmitStmt(D->
getStmt());
7988void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7989 for (
auto *I : DC->
decls()) {
7995 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7996 for (
auto *M : OID->methods())
8015 case Decl::CXXConversion:
8016 case Decl::CXXMethod:
8017 case Decl::Function:
8024 case Decl::CXXDeductionGuide:
8029 case Decl::Decomposition:
8030 case Decl::VarTemplateSpecialization:
8032 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
8033 for (
auto *B : DD->flat_bindings())
8034 if (
auto *HD = B->getHoldingVar())
8041 case Decl::IndirectField:
8045 case Decl::Namespace:
8048 case Decl::ClassTemplateSpecialization: {
8051 if (Spec->getSpecializationKind() ==
8053 Spec->hasDefinition())
8054 DI->completeTemplateDefinition(*Spec);
8056 case Decl::CXXRecord: {
8060 DI->EmitAndRetainType(
8064 DI->completeUnusedClass(*CRD);
8067 for (
auto *I : CRD->
decls())
8073 case Decl::UsingShadow:
8074 case Decl::ClassTemplate:
8075 case Decl::VarTemplate:
8077 case Decl::VarTemplatePartialSpecialization:
8078 case Decl::FunctionTemplate:
8079 case Decl::TypeAliasTemplate:
8088 case Decl::UsingEnum:
8092 case Decl::NamespaceAlias:
8096 case Decl::UsingDirective:
8100 case Decl::CXXConstructor:
8103 case Decl::CXXDestructor:
8107 case Decl::StaticAssert:
8108 case Decl::ExplicitInstantiation:
8115 case Decl::ObjCInterface:
8116 case Decl::ObjCCategory:
8119 case Decl::ObjCProtocol: {
8121 if (Proto->isThisDeclarationADefinition())
8122 ObjCRuntime->GenerateProtocol(Proto);
8126 case Decl::ObjCCategoryImpl:
8132 case Decl::ObjCImplementation: {
8134 EmitObjCPropertyImplementations(OMD);
8135 EmitObjCIvarInitializations(OMD);
8136 ObjCRuntime->GenerateClass(OMD);
8140 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
8141 OMD->getClassInterface()), OMD->getLocation());
8144 case Decl::ObjCMethod: {
8151 case Decl::ObjCCompatibleAlias:
8155 case Decl::PragmaComment: {
8157 switch (PCD->getCommentKind()) {
8159 llvm_unreachable(
"unexpected pragma comment kind");
8167 ProcessPragmaCommentCopyright(PCD->getArg(), PCD->isFromASTFile());
8177 case Decl::PragmaDetectMismatch: {
8183 case Decl::LinkageSpec:
8187 case Decl::FileScopeAsm: {
8189 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8192 if (LangOpts.OpenMPIsTargetDevice)
8195 if (LangOpts.SYCLIsDevice)
8200 llvm::Module::GlobalAsmProperties Props;
8201 Props.TargetFeatures = llvm::join(TargetOpts.
Features,
",");
8202 Props.TargetCPU = TargetOpts.
CPU;
8204 llvm::Module::GlobalAsmFragment(AD->getAsmString(), Props));
8208 case Decl::TopLevelStmt:
8212 case Decl::Import: {
8216 if (!ImportedModules.insert(Import->getImportedModule()))
8220 if (!Import->getImportedOwningModule()) {
8222 DI->EmitImportDecl(*Import);
8228 if (CXX20ModuleInits && Import->getImportedModule() &&
8229 Import->getImportedModule()->isNamedModule())
8238 Visited.insert(Import->getImportedModule());
8239 Stack.push_back(Import->getImportedModule());
8241 while (!Stack.empty()) {
8243 if (!EmittedModuleInitializers.insert(Mod).second)
8246 for (
auto *D : Context.getModuleInitializers(Mod))
8253 if (Submodule->IsExplicit)
8256 if (Visited.insert(Submodule).second)
8257 Stack.push_back(Submodule);
8267 case Decl::OMPThreadPrivate:
8271 case Decl::OMPAllocate:
8275 case Decl::OMPDeclareReduction:
8279 case Decl::OMPDeclareMapper:
8283 case Decl::OMPRequires:
8288 case Decl::TypeAlias:
8290 DI->EmitAndRetainType(
getContext().getTypedefType(
8298 DI->EmitAndRetainType(
8305 DI->EmitAndRetainType(
8309 case Decl::HLSLRootSignature:
8312 case Decl::HLSLBuffer:
8316 case Decl::OpenACCDeclare:
8319 case Decl::OpenACCRoutine:
8334 if (!CodeGenOpts.CoverageMapping)
8337 case Decl::CXXConversion:
8338 case Decl::CXXMethod:
8339 case Decl::Function:
8340 case Decl::ObjCMethod:
8341 case Decl::CXXConstructor:
8342 case Decl::CXXDestructor: {
8351 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8361 if (!CodeGenOpts.CoverageMapping)
8363 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8364 if (Fn->isTemplateInstantiation())
8367 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8375 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8378 const Decl *D = Entry.first;
8380 case Decl::CXXConversion:
8381 case Decl::CXXMethod:
8382 case Decl::Function:
8383 case Decl::ObjCMethod: {
8390 case Decl::CXXConstructor: {
8397 case Decl::CXXDestructor: {
8414 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8415 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8416 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8417 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8418 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8427 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8428 return llvm::ConstantInt::get(i64, PtrInt);
8432 llvm::NamedMDNode *&GlobalMetadata,
8434 llvm::GlobalValue *
Addr) {
8435 if (!GlobalMetadata)
8437 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8440 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8443 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8446bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8447 llvm::GlobalValue *CppFunc) {
8449 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8452 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8455 if (Elem == CppFunc)
8461 for (llvm::User *User : Elem->users()) {
8465 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8466 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8469 for (llvm::User *CEUser : ConstExpr->users()) {
8470 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8471 IFuncs.push_back(IFunc);
8476 CEs.push_back(ConstExpr);
8477 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8478 IFuncs.push_back(IFunc);
8490 for (llvm::GlobalIFunc *IFunc : IFuncs)
8491 IFunc->setResolver(
nullptr);
8492 for (llvm::ConstantExpr *ConstExpr : CEs)
8493 ConstExpr->destroyConstant();
8497 Elem->eraseFromParent();
8499 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8504 llvm::FunctionType::get(IFunc->getType(),
false);
8505 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8506 CppFunc->getName(), ResolverTy, {},
false);
8507 IFunc->setResolver(Resolver);
8517void CodeGenModule::EmitStaticExternCAliases() {
8520 for (
auto &I : StaticExternCValues) {
8521 const IdentifierInfo *Name = I.first;
8522 llvm::GlobalValue *Val = I.second;
8530 llvm::GlobalValue *ExistingElem =
8535 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8542 auto Res = Manglings.find(MangledName);
8543 if (Res == Manglings.end())
8545 Result = Res->getValue();
8556void CodeGenModule::EmitDeclMetadata() {
8557 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8559 for (
auto &I : MangledDeclNames) {
8560 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8570void CodeGenFunction::EmitDeclMetadata() {
8571 if (LocalDeclMap.empty())
return;
8576 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8578 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8580 for (
auto &I : LocalDeclMap) {
8581 const Decl *D = I.first;
8582 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8583 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8585 Alloca->setMetadata(
8586 DeclPtrKind, llvm::MDNode::get(
8587 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8588 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8595void CodeGenModule::EmitVersionIdentMetadata() {
8596 llvm::NamedMDNode *IdentMetadata =
8597 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8599 llvm::LLVMContext &Ctx = TheModule.getContext();
8601 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8602 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8605void CodeGenModule::EmitCommandLineMetadata() {
8606 llvm::NamedMDNode *CommandLineMetadata =
8607 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8609 llvm::LLVMContext &Ctx = TheModule.getContext();
8611 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8612 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8615void CodeGenModule::EmitCoverageFile() {
8616 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8620 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8621 llvm::LLVMContext &Ctx = TheModule.getContext();
8622 auto *CoverageDataFile =
8624 auto *CoverageNotesFile =
8626 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8627 llvm::MDNode *CU = CUNode->getOperand(i);
8628 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8629 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8642 LangOpts.ObjCRuntime.isGNUFamily())
8643 return ObjCRuntime->GetEHType(Ty);
8650 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8652 for (
auto RefExpr : D->
varlist()) {
8655 VD->getAnyInitializer() &&
8656 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8662 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8663 CXXGlobalInits.push_back(InitFunction);
8667llvm::Metadata *CodeGenModule::CreateMetadataIdentifierImpl(
8668 QualType T, MetadataTypeMap &Map, StringRef Suffix,
bool ForceString) {
8671 FnType->getReturnType(), FnType->getParamTypes(),
8672 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8674 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
8679 std::string OutName;
8680 llvm::raw_string_ostream Out(OutName);
8685 Out <<
".normalized";
8708 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
8713 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8717 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8718 ".generalized",
false);
8723 return CreateMetadataIdentifierImpl(
T, CallGraphMetadataIdMap,
"",
8731 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8732 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8733 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8734 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8735 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8736 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8737 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8738 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8746 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8748 if (CodeGenOpts.SanitizeCfiCrossDso)
8750 VTable->addTypeMetadata(Offset.getQuantity(),
8751 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8754 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8755 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8761 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8771 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8786 bool forPointeeType) {
8797 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8804 bool AlignForArray =
T->isArrayType();
8810 if (
T->isIncompleteType()) {
8827 if (
T.getQualifiers().hasUnaligned()) {
8829 }
else if (forPointeeType && !AlignForArray &&
8830 (RD =
T->getAsCXXRecordDecl())) {
8841 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8854 if (NumAutoVarInit >= StopAfter) {
8857 if (!NumAutoVarInit) {
8871 const Decl *D)
const {
8875 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8877 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8883 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8887 llvm::MD5::MD5Result
Result;
8888 for (
const auto &Arg : PreprocessorOpts.Macros)
8889 Hash.update(Arg.first);
8893 llvm::sys::fs::UniqueID ID;
8897 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8902 << PLoc.
getFilename() << Status.getError().message();
8904 ID = Status->getUniqueID();
8906 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8907 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8914 assert(DeferredDeclsToEmit.empty() &&
8915 "Should have emitted all decls deferred to emit.");
8916 assert(NewBuilder->DeferredDecls.empty() &&
8917 "Newly created module should not have deferred decls");
8918 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8919 assert(EmittedDeferredDecls.empty() &&
8920 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8922 assert(NewBuilder->DeferredVTables.empty() &&
8923 "Newly created module should not have deferred vtables");
8924 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8926 assert(NewBuilder->EmittedVTables.empty() &&
8927 "Newly created module should not have defined vtables");
8928 NewBuilder->EmittedVTables = std::move(EmittedVTables);
8930 assert(NewBuilder->MangledDeclNames.empty() &&
8931 "Newly created module should not have mangled decl names");
8932 assert(NewBuilder->Manglings.empty() &&
8933 "Newly created module should not have manglings");
8934 NewBuilder->Manglings = std::move(Manglings);
8936 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8938 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8942 std::string OutName;
8943 llvm::raw_string_ostream Out(OutName);
8951 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8957 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
8960 return RequireVectorDeletingDtor.count(RD);
8964 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8966 RequireVectorDeletingDtor.insert(RD);
8980 if (Entry && !Entry->isDeclaration()) {
8985 auto *NewFn = llvm::Function::Create(
8987 llvm::Function::ExternalLinkage, VDName, &
getModule());
8988 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
8990 NewFn->takeName(VDEntry);
8991 VDEntry->replaceAllUsesWith(NewFn);
8992 VDEntry->eraseFromParent();
8993 Entry->replaceAllUsesWith(NewFn);
8994 Entry->eraseFromParent();
8999 addDeferredDeclToEmit(VectorDtorGD);
9003 llvm::GlobalAlias *GlobalDeleteAlias,
9007 PendingMSVCGlobalDeletes.insert({GlobalDeleteAlias, OperatorDeleteFD});
9029 "__global_delete wrapper is only used with the Microsoft ABI");
9031 llvm::LLVMContext &LLVMCtx = M.getContext();
9035 llvm::FunctionType *FnTy = GlobDeleteFn->getFunctionType();
9045 StringRef GlobDeleteMangledName = GlobDeleteFn->getName();
9046 StringRef Signature;
9047 const char *WrapperBase;
9048 if (GlobDeleteMangledName.starts_with(
"??3@")) {
9049 Signature = GlobDeleteMangledName.substr(4);
9050 WrapperBase =
"?__global_delete@@";
9051 }
else if (GlobDeleteMangledName.starts_with(
"??_V@")) {
9052 Signature = GlobDeleteMangledName.substr(5);
9053 WrapperBase =
"?__global_array_delete@@";
9055 llvm_unreachable(
"unexpected global operator delete mangling");
9058 std::string GlobalDeleteName = (WrapperBase + Signature).str();
9059 std::string EmptyGlobalDeleteName =
9060 (
"?__empty_global_delete@@" + Signature).str();
9064 if (llvm::GlobalValue *Existing = M.getNamedValue(GlobalDeleteName))
9073 llvm::Function *EmptyFn = M.getFunction(EmptyGlobalDeleteName);
9075 EmptyFn = llvm::Function::Create(
9076 FnTy, llvm::GlobalValue::LinkOnceODRLinkage, EmptyGlobalDeleteName, &M);
9077 EmptyFn->setComdat(M.getOrInsertComdat(EmptyGlobalDeleteName));
9078 EmptyFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
9085 auto *BB = llvm::BasicBlock::Create(LLVMCtx,
"", EmptyFn);
9086 llvm::Function *TrapFn =
9087 llvm::Intrinsic::getOrInsertDeclaration(&M, llvm::Intrinsic::trap);
9088 auto *TrapCall = llvm::CallInst::Create(TrapFn, {},
"", BB);
9089 TrapCall->setDoesNotReturn();
9090 TrapCall->setDoesNotThrow();
9091 new llvm::UnreachableInst(LLVMCtx, BB);
9097 appendToUsed(M, {EmptyFn});
9105 auto *GlobalDeleteAlias = llvm::GlobalAlias::create(
9106 FnTy, GlobDeleteFn->getAddressSpace(), llvm::GlobalValue::WeakAnyLinkage,
9107 GlobalDeleteName, EmptyFn, &M);
9114 return GlobalDeleteAlias;
9126 if (!HasDirectGlobalDelete)
9129 for (
const auto &Entry : PendingMSVCGlobalDeletes) {
9130 llvm::GlobalAlias *Alias = Entry.first;
9138 llvm::Function::Create(FnTy, llvm::GlobalValue::LinkOnceODRLinkage,
9139 Alias->getAddressSpace(),
"", &
getModule());
9145 for (
auto &Arg : GlobDelFn->args())
9146 Args.push_back(&Arg);
9147 llvm::CallInst::Create(FnTy, RealDeleteFn, Args,
"", BB);
9152 Alias->replaceAllUsesWith(GlobDelFn);
9153 GlobDelFn->takeName(Alias);
9154 Alias->eraseFromParent();
9156 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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
DiagnosticsEngine & getDiagnostics() const
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
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.
const llvm::fltSemantics & getLongDoubleFormat() const
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 isAMDGPUNamedBarrierTypeOrWrapper() const
Check if the type is the AMDGPU named barrier type/a RecordType of a named barrier wrapper,...
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ 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)
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
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.