1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This coordinates the per-module state used while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenModule.h"
16 #include "CGCUDARuntime.h"
19 #include "CGDebugInfo.h"
20 #include "CGHLSLRuntime.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "CGOpenMPRuntime.h"
24 #include "CGOpenMPRuntimeGPU.h"
25 #include "CodeGenFunction.h"
26 #include "CodeGenPGO.h"
27 #include "ConstantEmitter.h"
28 #include "CoverageMappingGen.h"
29 #include "TargetInfo.h"
30 #include "clang/AST/ASTContext.h"
31 #include "clang/AST/ASTLambda.h"
32 #include "clang/AST/CharUnits.h"
33 #include "clang/AST/Decl.h"
34 #include "clang/AST/DeclCXX.h"
35 #include "clang/AST/DeclObjC.h"
36 #include "clang/AST/DeclTemplate.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/RecursiveASTVisitor.h"
39 #include "clang/AST/StmtVisitor.h"
40 #include "clang/Basic/Builtins.h"
41 #include "clang/Basic/CodeGenOptions.h"
42 #include "clang/Basic/Diagnostic.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "clang/Basic/Version.h"
47 #include "clang/CodeGen/BackendUtil.h"
48 #include "clang/CodeGen/ConstantInitBuilder.h"
49 #include "clang/Frontend/FrontendDiagnostic.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/Analysis/TargetLibraryInfo.h"
54 #include "llvm/BinaryFormat/ELF.h"
55 #include "llvm/IR/AttributeMask.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/ProfileSummary.h"
62 #include "llvm/ProfileData/InstrProfReader.h"
63 #include "llvm/ProfileData/SampleProf.h"
64 #include "llvm/Support/CRC.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/ConvertUTF.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/TimeProfiler.h"
70 #include "llvm/Support/xxhash.h"
71 #include "llvm/TargetParser/RISCVISAInfo.h"
72 #include "llvm/TargetParser/Triple.h"
73 #include "llvm/TargetParser/X86TargetParser.h"
74 #include "llvm/Transforms/Utils/BuildLibCalls.h"
77 using namespace clang
;
78 using namespace CodeGen
;
80 static llvm::cl::opt
<bool> LimitedCoverage(
81 "limited-coverage-experimental", llvm::cl::Hidden
,
82 llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
84 static const char AnnotationSection
[] = "llvm.metadata";
86 static CGCXXABI
*createCXXABI(CodeGenModule
&CGM
) {
87 switch (CGM
.getContext().getCXXABIKind()) {
88 case TargetCXXABI::AppleARM64
:
89 case TargetCXXABI::Fuchsia
:
90 case TargetCXXABI::GenericAArch64
:
91 case TargetCXXABI::GenericARM
:
92 case TargetCXXABI::iOS
:
93 case TargetCXXABI::WatchOS
:
94 case TargetCXXABI::GenericMIPS
:
95 case TargetCXXABI::GenericItanium
:
96 case TargetCXXABI::WebAssembly
:
97 case TargetCXXABI::XL
:
98 return CreateItaniumCXXABI(CGM
);
99 case TargetCXXABI::Microsoft
:
100 return CreateMicrosoftCXXABI(CGM
);
103 llvm_unreachable("invalid C++ ABI kind");
106 static std::unique_ptr
<TargetCodeGenInfo
>
107 createTargetCodeGenInfo(CodeGenModule
&CGM
) {
108 const TargetInfo
&Target
= CGM
.getTarget();
109 const llvm::Triple
&Triple
= Target
.getTriple();
110 const CodeGenOptions
&CodeGenOpts
= CGM
.getCodeGenOpts();
112 switch (Triple
.getArch()) {
114 return createDefaultTargetCodeGenInfo(CGM
);
116 case llvm::Triple::m68k
:
117 return createM68kTargetCodeGenInfo(CGM
);
118 case llvm::Triple::mips
:
119 case llvm::Triple::mipsel
:
120 if (Triple
.getOS() == llvm::Triple::NaCl
)
121 return createPNaClTargetCodeGenInfo(CGM
);
122 return createMIPSTargetCodeGenInfo(CGM
, /*IsOS32=*/true);
124 case llvm::Triple::mips64
:
125 case llvm::Triple::mips64el
:
126 return createMIPSTargetCodeGenInfo(CGM
, /*IsOS32=*/false);
128 case llvm::Triple::avr
: {
129 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
130 // on avrtiny. For passing return value, R18~R25 are used on avr, and
131 // R22~R25 are used on avrtiny.
132 unsigned NPR
= Target
.getABI() == "avrtiny" ? 6 : 18;
133 unsigned NRR
= Target
.getABI() == "avrtiny" ? 4 : 8;
134 return createAVRTargetCodeGenInfo(CGM
, NPR
, NRR
);
137 case llvm::Triple::aarch64
:
138 case llvm::Triple::aarch64_32
:
139 case llvm::Triple::aarch64_be
: {
140 AArch64ABIKind Kind
= AArch64ABIKind::AAPCS
;
141 if (Target
.getABI() == "darwinpcs")
142 Kind
= AArch64ABIKind::DarwinPCS
;
143 else if (Triple
.isOSWindows())
144 return createWindowsAArch64TargetCodeGenInfo(CGM
, AArch64ABIKind::Win64
);
145 else if (Target
.getABI() == "aapcs-soft")
146 Kind
= AArch64ABIKind::AAPCSSoft
;
147 else if (Target
.getABI() == "pauthtest")
148 Kind
= AArch64ABIKind::PAuthTest
;
150 return createAArch64TargetCodeGenInfo(CGM
, Kind
);
153 case llvm::Triple::wasm32
:
154 case llvm::Triple::wasm64
: {
155 WebAssemblyABIKind Kind
= WebAssemblyABIKind::MVP
;
156 if (Target
.getABI() == "experimental-mv")
157 Kind
= WebAssemblyABIKind::ExperimentalMV
;
158 return createWebAssemblyTargetCodeGenInfo(CGM
, Kind
);
161 case llvm::Triple::arm
:
162 case llvm::Triple::armeb
:
163 case llvm::Triple::thumb
:
164 case llvm::Triple::thumbeb
: {
165 if (Triple
.getOS() == llvm::Triple::Win32
)
166 return createWindowsARMTargetCodeGenInfo(CGM
, ARMABIKind::AAPCS_VFP
);
168 ARMABIKind Kind
= ARMABIKind::AAPCS
;
169 StringRef ABIStr
= Target
.getABI();
170 if (ABIStr
== "apcs-gnu")
171 Kind
= ARMABIKind::APCS
;
172 else if (ABIStr
== "aapcs16")
173 Kind
= ARMABIKind::AAPCS16_VFP
;
174 else if (CodeGenOpts
.FloatABI
== "hard" ||
175 (CodeGenOpts
.FloatABI
!= "soft" && Triple
.isHardFloatABI()))
176 Kind
= ARMABIKind::AAPCS_VFP
;
178 return createARMTargetCodeGenInfo(CGM
, Kind
);
181 case llvm::Triple::ppc
: {
182 if (Triple
.isOSAIX())
183 return createAIXTargetCodeGenInfo(CGM
, /*Is64Bit=*/false);
186 CodeGenOpts
.FloatABI
== "soft" || Target
.hasFeature("spe");
187 return createPPC32TargetCodeGenInfo(CGM
, IsSoftFloat
);
189 case llvm::Triple::ppcle
: {
190 bool IsSoftFloat
= CodeGenOpts
.FloatABI
== "soft";
191 return createPPC32TargetCodeGenInfo(CGM
, IsSoftFloat
);
193 case llvm::Triple::ppc64
:
194 if (Triple
.isOSAIX())
195 return createAIXTargetCodeGenInfo(CGM
, /*Is64Bit=*/true);
197 if (Triple
.isOSBinFormatELF()) {
198 PPC64_SVR4_ABIKind Kind
= PPC64_SVR4_ABIKind::ELFv1
;
199 if (Target
.getABI() == "elfv2")
200 Kind
= PPC64_SVR4_ABIKind::ELFv2
;
201 bool IsSoftFloat
= CodeGenOpts
.FloatABI
== "soft";
203 return createPPC64_SVR4_TargetCodeGenInfo(CGM
, Kind
, IsSoftFloat
);
205 return createPPC64TargetCodeGenInfo(CGM
);
206 case llvm::Triple::ppc64le
: {
207 assert(Triple
.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
208 PPC64_SVR4_ABIKind Kind
= PPC64_SVR4_ABIKind::ELFv2
;
209 if (Target
.getABI() == "elfv1")
210 Kind
= PPC64_SVR4_ABIKind::ELFv1
;
211 bool IsSoftFloat
= CodeGenOpts
.FloatABI
== "soft";
213 return createPPC64_SVR4_TargetCodeGenInfo(CGM
, Kind
, IsSoftFloat
);
216 case llvm::Triple::nvptx
:
217 case llvm::Triple::nvptx64
:
218 return createNVPTXTargetCodeGenInfo(CGM
);
220 case llvm::Triple::msp430
:
221 return createMSP430TargetCodeGenInfo(CGM
);
223 case llvm::Triple::riscv32
:
224 case llvm::Triple::riscv64
: {
225 StringRef ABIStr
= Target
.getABI();
226 unsigned XLen
= Target
.getPointerWidth(LangAS::Default
);
227 unsigned ABIFLen
= 0;
228 if (ABIStr
.ends_with("f"))
230 else if (ABIStr
.ends_with("d"))
232 bool EABI
= ABIStr
.ends_with("e");
233 return createRISCVTargetCodeGenInfo(CGM
, XLen
, ABIFLen
, EABI
);
236 case llvm::Triple::systemz
: {
237 bool SoftFloat
= CodeGenOpts
.FloatABI
== "soft";
238 bool HasVector
= !SoftFloat
&& Target
.getABI() == "vector";
239 return createSystemZTargetCodeGenInfo(CGM
, HasVector
, SoftFloat
);
242 case llvm::Triple::tce
:
243 case llvm::Triple::tcele
:
244 return createTCETargetCodeGenInfo(CGM
);
246 case llvm::Triple::x86
: {
247 bool IsDarwinVectorABI
= Triple
.isOSDarwin();
248 bool IsWin32FloatStructABI
= Triple
.isOSWindows() && !Triple
.isOSCygMing();
250 if (Triple
.getOS() == llvm::Triple::Win32
) {
251 return createWinX86_32TargetCodeGenInfo(
252 CGM
, IsDarwinVectorABI
, IsWin32FloatStructABI
,
253 CodeGenOpts
.NumRegisterParameters
);
255 return createX86_32TargetCodeGenInfo(
256 CGM
, IsDarwinVectorABI
, IsWin32FloatStructABI
,
257 CodeGenOpts
.NumRegisterParameters
, CodeGenOpts
.FloatABI
== "soft");
260 case llvm::Triple::x86_64
: {
261 StringRef ABI
= Target
.getABI();
262 X86AVXABILevel AVXLevel
= (ABI
== "avx512" ? X86AVXABILevel::AVX512
263 : ABI
== "avx" ? X86AVXABILevel::AVX
264 : X86AVXABILevel::None
);
266 switch (Triple
.getOS()) {
267 case llvm::Triple::Win32
:
268 return createWinX86_64TargetCodeGenInfo(CGM
, AVXLevel
);
270 return createX86_64TargetCodeGenInfo(CGM
, AVXLevel
);
273 case llvm::Triple::hexagon
:
274 return createHexagonTargetCodeGenInfo(CGM
);
275 case llvm::Triple::lanai
:
276 return createLanaiTargetCodeGenInfo(CGM
);
277 case llvm::Triple::r600
:
278 return createAMDGPUTargetCodeGenInfo(CGM
);
279 case llvm::Triple::amdgcn
:
280 return createAMDGPUTargetCodeGenInfo(CGM
);
281 case llvm::Triple::sparc
:
282 return createSparcV8TargetCodeGenInfo(CGM
);
283 case llvm::Triple::sparcv9
:
284 return createSparcV9TargetCodeGenInfo(CGM
);
285 case llvm::Triple::xcore
:
286 return createXCoreTargetCodeGenInfo(CGM
);
287 case llvm::Triple::arc
:
288 return createARCTargetCodeGenInfo(CGM
);
289 case llvm::Triple::spir
:
290 case llvm::Triple::spir64
:
291 return createCommonSPIRTargetCodeGenInfo(CGM
);
292 case llvm::Triple::spirv32
:
293 case llvm::Triple::spirv64
:
294 case llvm::Triple::spirv
:
295 return createSPIRVTargetCodeGenInfo(CGM
);
296 case llvm::Triple::dxil
:
297 return createDirectXTargetCodeGenInfo(CGM
);
298 case llvm::Triple::ve
:
299 return createVETargetCodeGenInfo(CGM
);
300 case llvm::Triple::csky
: {
301 bool IsSoftFloat
= !Target
.hasFeature("hard-float-abi");
303 Target
.hasFeature("fpuv2_df") || Target
.hasFeature("fpuv3_df");
304 return createCSKYTargetCodeGenInfo(CGM
, IsSoftFloat
? 0
308 case llvm::Triple::bpfeb
:
309 case llvm::Triple::bpfel
:
310 return createBPFTargetCodeGenInfo(CGM
);
311 case llvm::Triple::loongarch32
:
312 case llvm::Triple::loongarch64
: {
313 StringRef ABIStr
= Target
.getABI();
314 unsigned ABIFRLen
= 0;
315 if (ABIStr
.ends_with("f"))
317 else if (ABIStr
.ends_with("d"))
319 return createLoongArchTargetCodeGenInfo(
320 CGM
, Target
.getPointerWidth(LangAS::Default
), ABIFRLen
);
325 const TargetCodeGenInfo
&CodeGenModule::getTargetCodeGenInfo() {
326 if (!TheTargetCodeGenInfo
)
327 TheTargetCodeGenInfo
= createTargetCodeGenInfo(*this);
328 return *TheTargetCodeGenInfo
;
331 CodeGenModule::CodeGenModule(ASTContext
&C
,
332 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
,
333 const HeaderSearchOptions
&HSO
,
334 const PreprocessorOptions
&PPO
,
335 const CodeGenOptions
&CGO
, llvm::Module
&M
,
336 DiagnosticsEngine
&diags
,
337 CoverageSourceInfo
*CoverageInfo
)
338 : Context(C
), LangOpts(C
.getLangOpts()), FS(FS
), HeaderSearchOpts(HSO
),
339 PreprocessorOpts(PPO
), CodeGenOpts(CGO
), TheModule(M
), Diags(diags
),
340 Target(C
.getTargetInfo()), ABI(createCXXABI(*this)),
341 VMContext(M
.getContext()), VTables(*this), StackHandler(diags
),
342 SanitizerMD(new SanitizerMetadata(*this)) {
344 // Initialize the type cache.
345 Types
.reset(new CodeGenTypes(*this));
346 llvm::LLVMContext
&LLVMContext
= M
.getContext();
347 VoidTy
= llvm::Type::getVoidTy(LLVMContext
);
348 Int8Ty
= llvm::Type::getInt8Ty(LLVMContext
);
349 Int16Ty
= llvm::Type::getInt16Ty(LLVMContext
);
350 Int32Ty
= llvm::Type::getInt32Ty(LLVMContext
);
351 Int64Ty
= llvm::Type::getInt64Ty(LLVMContext
);
352 HalfTy
= llvm::Type::getHalfTy(LLVMContext
);
353 BFloatTy
= llvm::Type::getBFloatTy(LLVMContext
);
354 FloatTy
= llvm::Type::getFloatTy(LLVMContext
);
355 DoubleTy
= llvm::Type::getDoubleTy(LLVMContext
);
356 PointerWidthInBits
= C
.getTargetInfo().getPointerWidth(LangAS::Default
);
357 PointerAlignInBytes
=
358 C
.toCharUnitsFromBits(C
.getTargetInfo().getPointerAlign(LangAS::Default
))
361 C
.toCharUnitsFromBits(C
.getTargetInfo().getMaxPointerWidth()).getQuantity();
363 C
.toCharUnitsFromBits(C
.getTargetInfo().getIntAlign()).getQuantity();
365 llvm::IntegerType::get(LLVMContext
, C
.getTargetInfo().getCharWidth());
366 IntTy
= llvm::IntegerType::get(LLVMContext
, C
.getTargetInfo().getIntWidth());
367 IntPtrTy
= llvm::IntegerType::get(LLVMContext
,
368 C
.getTargetInfo().getMaxPointerWidth());
369 Int8PtrTy
= llvm::PointerType::get(LLVMContext
,
370 C
.getTargetAddressSpace(LangAS::Default
));
371 const llvm::DataLayout
&DL
= M
.getDataLayout();
373 llvm::PointerType::get(LLVMContext
, DL
.getAllocaAddrSpace());
375 llvm::PointerType::get(LLVMContext
, DL
.getDefaultGlobalsAddressSpace());
376 ConstGlobalsPtrTy
= llvm::PointerType::get(
377 LLVMContext
, C
.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
378 ASTAllocaAddressSpace
= getTargetCodeGenInfo().getASTAllocaAddressSpace();
380 // Build C++20 Module initializers.
381 // TODO: Add Microsoft here once we know the mangling required for the
384 LangOpts
.CPlusPlusModules
&& getCXXABI().getMangleContext().getKind() ==
385 ItaniumMangleContext::MK_Itanium
;
387 RuntimeCC
= getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
392 createOpenCLRuntime();
394 createOpenMPRuntime();
400 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
401 if (LangOpts
.Sanitize
.has(SanitizerKind::Thread
) ||
402 (!CodeGenOpts
.RelaxedAliasing
&& CodeGenOpts
.OptimizationLevel
> 0))
403 TBAA
.reset(new CodeGenTBAA(Context
, getTypes(), TheModule
, CodeGenOpts
,
406 // If debug info or coverage generation is enabled, create the CGDebugInfo
408 if (CodeGenOpts
.getDebugInfo() != llvm::codegenoptions::NoDebugInfo
||
409 CodeGenOpts
.CoverageNotesFile
.size() ||
410 CodeGenOpts
.CoverageDataFile
.size())
411 DebugInfo
.reset(new CGDebugInfo(*this));
413 Block
.GlobalUniqueCount
= 0;
415 if (C
.getLangOpts().ObjC
)
416 ObjCData
.reset(new ObjCEntrypoints());
418 if (CodeGenOpts
.hasProfileClangUse()) {
419 auto ReaderOrErr
= llvm::IndexedInstrProfReader::create(
420 CodeGenOpts
.ProfileInstrumentUsePath
, *FS
,
421 CodeGenOpts
.ProfileRemappingFile
);
422 // We're checking for profile read errors in CompilerInvocation, so if
423 // there was an error it should've already been caught. If it hasn't been
424 // somehow, trip an assertion.
426 PGOReader
= std::move(ReaderOrErr
.get());
429 // If coverage mapping generation is enabled, create the
430 // CoverageMappingModuleGen object.
431 if (CodeGenOpts
.CoverageMapping
)
432 CoverageMapping
.reset(new CoverageMappingModuleGen(*this, *CoverageInfo
));
434 // Generate the module name hash here if needed.
435 if (CodeGenOpts
.UniqueInternalLinkageNames
&&
436 !getModule().getSourceFileName().empty()) {
437 std::string Path
= getModule().getSourceFileName();
438 // Check if a path substitution is needed from the MacroPrefixMap.
439 for (const auto &Entry
: LangOpts
.MacroPrefixMap
)
440 if (Path
.rfind(Entry
.first
, 0) != std::string::npos
) {
441 Path
= Entry
.second
+ Path
.substr(Entry
.first
.size());
444 ModuleNameHash
= llvm::getUniqueInternalLinkagePostfix(Path
);
447 // Record mregparm value now so it is visible through all of codegen.
448 if (Context
.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
)
449 getModule().addModuleFlag(llvm::Module::Error
, "NumRegisterParameters",
450 CodeGenOpts
.NumRegisterParameters
);
453 CodeGenModule::~CodeGenModule() {}
455 void CodeGenModule::createObjCRuntime() {
456 // This is just isGNUFamily(), but we want to force implementors of
457 // new ABIs to decide how best to do this.
458 switch (LangOpts
.ObjCRuntime
.getKind()) {
459 case ObjCRuntime::GNUstep
:
460 case ObjCRuntime::GCC
:
461 case ObjCRuntime::ObjFW
:
462 ObjCRuntime
.reset(CreateGNUObjCRuntime(*this));
465 case ObjCRuntime::FragileMacOSX
:
466 case ObjCRuntime::MacOSX
:
467 case ObjCRuntime::iOS
:
468 case ObjCRuntime::WatchOS
:
469 ObjCRuntime
.reset(CreateMacObjCRuntime(*this));
472 llvm_unreachable("bad runtime kind");
475 void CodeGenModule::createOpenCLRuntime() {
476 OpenCLRuntime
.reset(new CGOpenCLRuntime(*this));
479 void CodeGenModule::createOpenMPRuntime() {
480 // Select a specialized code generation class based on the target, if any.
481 // If it does not exist use the default implementation.
482 switch (getTriple().getArch()) {
483 case llvm::Triple::nvptx
:
484 case llvm::Triple::nvptx64
:
485 case llvm::Triple::amdgcn
:
486 assert(getLangOpts().OpenMPIsTargetDevice
&&
487 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
488 OpenMPRuntime
.reset(new CGOpenMPRuntimeGPU(*this));
491 if (LangOpts
.OpenMPSimd
)
492 OpenMPRuntime
.reset(new CGOpenMPSIMDRuntime(*this));
494 OpenMPRuntime
.reset(new CGOpenMPRuntime(*this));
499 void CodeGenModule::createCUDARuntime() {
500 CUDARuntime
.reset(CreateNVCUDARuntime(*this));
503 void CodeGenModule::createHLSLRuntime() {
504 HLSLRuntime
.reset(new CGHLSLRuntime(*this));
507 void CodeGenModule::addReplacement(StringRef Name
, llvm::Constant
*C
) {
508 Replacements
[Name
] = C
;
511 void CodeGenModule::applyReplacements() {
512 for (auto &I
: Replacements
) {
513 StringRef MangledName
= I
.first
;
514 llvm::Constant
*Replacement
= I
.second
;
515 llvm::GlobalValue
*Entry
= GetGlobalValue(MangledName
);
518 auto *OldF
= cast
<llvm::Function
>(Entry
);
519 auto *NewF
= dyn_cast
<llvm::Function
>(Replacement
);
521 if (auto *Alias
= dyn_cast
<llvm::GlobalAlias
>(Replacement
)) {
522 NewF
= dyn_cast
<llvm::Function
>(Alias
->getAliasee());
524 auto *CE
= cast
<llvm::ConstantExpr
>(Replacement
);
525 assert(CE
->getOpcode() == llvm::Instruction::BitCast
||
526 CE
->getOpcode() == llvm::Instruction::GetElementPtr
);
527 NewF
= dyn_cast
<llvm::Function
>(CE
->getOperand(0));
531 // Replace old with new, but keep the old order.
532 OldF
->replaceAllUsesWith(Replacement
);
534 NewF
->removeFromParent();
535 OldF
->getParent()->getFunctionList().insertAfter(OldF
->getIterator(),
538 OldF
->eraseFromParent();
542 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue
*GV
, llvm::Constant
*C
) {
543 GlobalValReplacements
.push_back(std::make_pair(GV
, C
));
546 void CodeGenModule::applyGlobalValReplacements() {
547 for (auto &I
: GlobalValReplacements
) {
548 llvm::GlobalValue
*GV
= I
.first
;
549 llvm::Constant
*C
= I
.second
;
551 GV
->replaceAllUsesWith(C
);
552 GV
->eraseFromParent();
556 // This is only used in aliases that we created and we know they have a
558 static const llvm::GlobalValue
*getAliasedGlobal(const llvm::GlobalValue
*GV
) {
559 const llvm::Constant
*C
;
560 if (auto *GA
= dyn_cast
<llvm::GlobalAlias
>(GV
))
561 C
= GA
->getAliasee();
562 else if (auto *GI
= dyn_cast
<llvm::GlobalIFunc
>(GV
))
563 C
= GI
->getResolver();
567 const auto *AliaseeGV
= dyn_cast
<llvm::GlobalValue
>(C
->stripPointerCasts());
571 const llvm::GlobalValue
*FinalGV
= AliaseeGV
->getAliaseeObject();
578 static bool checkAliasedGlobal(
579 const ASTContext
&Context
, DiagnosticsEngine
&Diags
, SourceLocation Location
,
580 bool IsIFunc
, const llvm::GlobalValue
*Alias
, const llvm::GlobalValue
*&GV
,
581 const llvm::MapVector
<GlobalDecl
, StringRef
> &MangledDeclNames
,
582 SourceRange AliasRange
) {
583 GV
= getAliasedGlobal(Alias
);
585 Diags
.Report(Location
, diag::err_cyclic_alias
) << IsIFunc
;
589 if (GV
->hasCommonLinkage()) {
590 const llvm::Triple
&Triple
= Context
.getTargetInfo().getTriple();
591 if (Triple
.getObjectFormat() == llvm::Triple::XCOFF
) {
592 Diags
.Report(Location
, diag::err_alias_to_common
);
597 if (GV
->isDeclaration()) {
598 Diags
.Report(Location
, diag::err_alias_to_undefined
) << IsIFunc
<< IsIFunc
;
599 Diags
.Report(Location
, diag::note_alias_requires_mangled_name
)
600 << IsIFunc
<< IsIFunc
;
601 // Provide a note if the given function is not found and exists as a
603 for (const auto &[Decl
, Name
] : MangledDeclNames
) {
604 if (const auto *ND
= dyn_cast
<NamedDecl
>(Decl
.getDecl())) {
605 if (ND
->getName() == GV
->getName()) {
606 Diags
.Report(Location
, diag::note_alias_mangled_name_alternative
)
608 << FixItHint::CreateReplacement(
610 (Twine(IsIFunc
? "ifunc" : "alias") + "(\"" + Name
+ "\")")
619 // Check resolver function type.
620 const auto *F
= dyn_cast
<llvm::Function
>(GV
);
622 Diags
.Report(Location
, diag::err_alias_to_undefined
)
623 << IsIFunc
<< IsIFunc
;
627 llvm::FunctionType
*FTy
= F
->getFunctionType();
628 if (!FTy
->getReturnType()->isPointerTy()) {
629 Diags
.Report(Location
, diag::err_ifunc_resolver_return
);
637 // Emit a warning if toc-data attribute is requested for global variables that
638 // have aliases and remove the toc-data attribute.
639 static void checkAliasForTocData(llvm::GlobalVariable
*GVar
,
640 const CodeGenOptions
&CodeGenOpts
,
641 DiagnosticsEngine
&Diags
,
642 SourceLocation Location
) {
643 if (GVar
->hasAttribute("toc-data")) {
644 auto GVId
= GVar
->getName();
645 // Is this a global variable specified by the user as local?
646 if ((llvm::binary_search(CodeGenOpts
.TocDataVarsUserSpecified
, GVId
))) {
647 Diags
.Report(Location
, diag::warn_toc_unsupported_type
)
648 << GVId
<< "the variable has an alias";
650 llvm::AttributeSet CurrAttributes
= GVar
->getAttributes();
651 llvm::AttributeSet NewAttributes
=
652 CurrAttributes
.removeAttribute(GVar
->getContext(), "toc-data");
653 GVar
->setAttributes(NewAttributes
);
657 void CodeGenModule::checkAliases() {
658 // Check if the constructed aliases are well formed. It is really unfortunate
659 // that we have to do this in CodeGen, but we only construct mangled names
660 // and aliases during codegen.
662 DiagnosticsEngine
&Diags
= getDiags();
663 for (const GlobalDecl
&GD
: Aliases
) {
664 const auto *D
= cast
<ValueDecl
>(GD
.getDecl());
665 SourceLocation Location
;
667 bool IsIFunc
= D
->hasAttr
<IFuncAttr
>();
668 if (const Attr
*A
= D
->getDefiningAttr()) {
669 Location
= A
->getLocation();
670 Range
= A
->getRange();
672 llvm_unreachable("Not an alias or ifunc?");
674 StringRef MangledName
= getMangledName(GD
);
675 llvm::GlobalValue
*Alias
= GetGlobalValue(MangledName
);
676 const llvm::GlobalValue
*GV
= nullptr;
677 if (!checkAliasedGlobal(getContext(), Diags
, Location
, IsIFunc
, Alias
, GV
,
678 MangledDeclNames
, Range
)) {
683 if (getContext().getTargetInfo().getTriple().isOSAIX())
684 if (const llvm::GlobalVariable
*GVar
=
685 dyn_cast
<const llvm::GlobalVariable
>(GV
))
686 checkAliasForTocData(const_cast<llvm::GlobalVariable
*>(GVar
),
687 getCodeGenOpts(), Diags
, Location
);
689 llvm::Constant
*Aliasee
=
690 IsIFunc
? cast
<llvm::GlobalIFunc
>(Alias
)->getResolver()
691 : cast
<llvm::GlobalAlias
>(Alias
)->getAliasee();
693 llvm::GlobalValue
*AliaseeGV
;
694 if (auto CE
= dyn_cast
<llvm::ConstantExpr
>(Aliasee
))
695 AliaseeGV
= cast
<llvm::GlobalValue
>(CE
->getOperand(0));
697 AliaseeGV
= cast
<llvm::GlobalValue
>(Aliasee
);
699 if (const SectionAttr
*SA
= D
->getAttr
<SectionAttr
>()) {
700 StringRef AliasSection
= SA
->getName();
701 if (AliasSection
!= AliaseeGV
->getSection())
702 Diags
.Report(SA
->getLocation(), diag::warn_alias_with_section
)
703 << AliasSection
<< IsIFunc
<< IsIFunc
;
706 // We have to handle alias to weak aliases in here. LLVM itself disallows
707 // this since the object semantics would not match the IL one. For
708 // compatibility with gcc we implement it by just pointing the alias
709 // to its aliasee's aliasee. We also warn, since the user is probably
710 // expecting the link to be weak.
711 if (auto *GA
= dyn_cast
<llvm::GlobalAlias
>(AliaseeGV
)) {
712 if (GA
->isInterposable()) {
713 Diags
.Report(Location
, diag::warn_alias_to_weak_alias
)
714 << GV
->getName() << GA
->getName() << IsIFunc
;
715 Aliasee
= llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
716 GA
->getAliasee(), Alias
->getType());
719 cast
<llvm::GlobalIFunc
>(Alias
)->setResolver(Aliasee
);
721 cast
<llvm::GlobalAlias
>(Alias
)->setAliasee(Aliasee
);
724 // ifunc resolvers are usually implemented to run before sanitizer
725 // initialization. Disable instrumentation to prevent the ordering issue.
727 cast
<llvm::Function
>(Aliasee
)->addFnAttr(
728 llvm::Attribute::DisableSanitizerInstrumentation
);
733 for (const GlobalDecl
&GD
: Aliases
) {
734 StringRef MangledName
= getMangledName(GD
);
735 llvm::GlobalValue
*Alias
= GetGlobalValue(MangledName
);
736 Alias
->replaceAllUsesWith(llvm::PoisonValue::get(Alias
->getType()));
737 Alias
->eraseFromParent();
741 void CodeGenModule::clear() {
742 DeferredDeclsToEmit
.clear();
743 EmittedDeferredDecls
.clear();
744 DeferredAnnotations
.clear();
746 OpenMPRuntime
->clear();
749 void InstrProfStats::reportDiagnostics(DiagnosticsEngine
&Diags
,
750 StringRef MainFile
) {
751 if (!hasDiagnostics())
753 if (VisitedInMainFile
> 0 && VisitedInMainFile
== MissingInMainFile
) {
754 if (MainFile
.empty())
755 MainFile
= "<stdin>";
756 Diags
.Report(diag::warn_profile_data_unprofiled
) << MainFile
;
759 Diags
.Report(diag::warn_profile_data_out_of_date
) << Visited
<< Mismatched
;
762 Diags
.Report(diag::warn_profile_data_missing
) << Visited
<< Missing
;
766 static std::optional
<llvm::GlobalValue::VisibilityTypes
>
767 getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K
) {
768 // Map to LLVM visibility.
770 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep
:
772 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default
:
773 return llvm::GlobalValue::DefaultVisibility
;
774 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden
:
775 return llvm::GlobalValue::HiddenVisibility
;
776 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected
:
777 return llvm::GlobalValue::ProtectedVisibility
;
779 llvm_unreachable("unknown option value!");
783 setLLVMVisibility(llvm::GlobalValue
&GV
,
784 std::optional
<llvm::GlobalValue::VisibilityTypes
> V
) {
788 // Reset DSO locality before setting the visibility. This removes
789 // any effects that visibility options and annotations may have
790 // had on the DSO locality. Setting the visibility will implicitly set
791 // appropriate globals to DSO Local; however, this will be pessimistic
792 // w.r.t. to the normal compiler IRGen.
793 GV
.setDSOLocal(false);
794 GV
.setVisibility(*V
);
797 static void setVisibilityFromDLLStorageClass(const clang::LangOptions
&LO
,
799 if (!LO
.VisibilityFromDLLStorageClass
)
802 std::optional
<llvm::GlobalValue::VisibilityTypes
> DLLExportVisibility
=
803 getLLVMVisibility(LO
.getDLLExportVisibility());
805 std::optional
<llvm::GlobalValue::VisibilityTypes
>
806 NoDLLStorageClassVisibility
=
807 getLLVMVisibility(LO
.getNoDLLStorageClassVisibility());
809 std::optional
<llvm::GlobalValue::VisibilityTypes
>
810 ExternDeclDLLImportVisibility
=
811 getLLVMVisibility(LO
.getExternDeclDLLImportVisibility());
813 std::optional
<llvm::GlobalValue::VisibilityTypes
>
814 ExternDeclNoDLLStorageClassVisibility
=
815 getLLVMVisibility(LO
.getExternDeclNoDLLStorageClassVisibility());
817 for (llvm::GlobalValue
&GV
: M
.global_values()) {
818 if (GV
.hasAppendingLinkage() || GV
.hasLocalLinkage())
821 if (GV
.isDeclarationForLinker())
822 setLLVMVisibility(GV
, GV
.getDLLStorageClass() ==
823 llvm::GlobalValue::DLLImportStorageClass
824 ? ExternDeclDLLImportVisibility
825 : ExternDeclNoDLLStorageClassVisibility
);
827 setLLVMVisibility(GV
, GV
.getDLLStorageClass() ==
828 llvm::GlobalValue::DLLExportStorageClass
829 ? DLLExportVisibility
830 : NoDLLStorageClassVisibility
);
832 GV
.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass
);
836 static bool isStackProtectorOn(const LangOptions
&LangOpts
,
837 const llvm::Triple
&Triple
,
838 clang::LangOptions::StackProtectorMode Mode
) {
839 if (Triple
.isAMDGPU() || Triple
.isNVPTX())
841 return LangOpts
.getStackProtector() == Mode
;
844 void CodeGenModule::Release() {
845 Module
*Primary
= getContext().getCurrentNamedModule();
846 if (CXX20ModuleInits
&& Primary
&& !Primary
->isHeaderLikeModule())
847 EmitModuleInitializers(Primary
);
849 DeferredDecls
.insert(EmittedDeferredDecls
.begin(),
850 EmittedDeferredDecls
.end());
851 EmittedDeferredDecls
.clear();
852 EmitVTablesOpportunistically();
853 applyGlobalValReplacements();
855 emitMultiVersionFunctions();
857 if (Context
.getLangOpts().IncrementalExtensions
&&
858 GlobalTopLevelStmtBlockInFlight
.first
) {
859 const TopLevelStmtDecl
*TLSD
= GlobalTopLevelStmtBlockInFlight
.second
;
860 GlobalTopLevelStmtBlockInFlight
.first
->FinishFunction(TLSD
->getEndLoc());
861 GlobalTopLevelStmtBlockInFlight
= {nullptr, nullptr};
864 // Module implementations are initialized the same way as a regular TU that
865 // imports one or more modules.
866 if (CXX20ModuleInits
&& Primary
&& Primary
->isInterfaceOrPartition())
867 EmitCXXModuleInitFunc(Primary
);
869 EmitCXXGlobalInitFunc();
870 EmitCXXGlobalCleanUpFunc();
871 registerGlobalDtorsWithAtExit();
872 EmitCXXThreadLocalInitFunc();
874 if (llvm::Function
*ObjCInitFunction
= ObjCRuntime
->ModuleInitFunction())
875 AddGlobalCtor(ObjCInitFunction
);
876 if (Context
.getLangOpts().CUDA
&& CUDARuntime
) {
877 if (llvm::Function
*CudaCtorFunction
= CUDARuntime
->finalizeModule())
878 AddGlobalCtor(CudaCtorFunction
);
881 OpenMPRuntime
->createOffloadEntriesAndInfoMetadata();
882 OpenMPRuntime
->clear();
885 getModule().setProfileSummary(
886 PGOReader
->getSummary(/* UseCS */ false).getMD(VMContext
),
887 llvm::ProfileSummary::PSK_Instr
);
888 if (PGOStats
.hasDiagnostics())
889 PGOStats
.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName
);
891 llvm::stable_sort(GlobalCtors
, [](const Structor
&L
, const Structor
&R
) {
892 return L
.LexOrder
< R
.LexOrder
;
894 EmitCtorList(GlobalCtors
, "llvm.global_ctors");
895 EmitCtorList(GlobalDtors
, "llvm.global_dtors");
896 EmitGlobalAnnotations();
897 EmitStaticExternCAliases();
899 EmitDeferredUnusedCoverageMappings();
900 CodeGenPGO(*this).setValueProfilingFlag(getModule());
901 CodeGenPGO(*this).setProfileVersion(getModule());
903 CoverageMapping
->emit();
904 if (CodeGenOpts
.SanitizeCfiCrossDso
) {
905 CodeGenFunction(*this).EmitCfiCheckFail();
906 CodeGenFunction(*this).EmitCfiCheckStub();
908 if (LangOpts
.Sanitize
.has(SanitizerKind::KCFI
))
910 emitAtAvailableLinkGuard();
911 if (Context
.getTargetInfo().getTriple().isWasm())
914 if (getTriple().isAMDGPU() ||
915 (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD
)) {
916 // Emit amdhsa_code_object_version module flag, which is code object version
918 if (getTarget().getTargetOpts().CodeObjectVersion
!=
919 llvm::CodeObjectVersionKind::COV_None
) {
920 getModule().addModuleFlag(llvm::Module::Error
,
921 "amdhsa_code_object_version",
922 getTarget().getTargetOpts().CodeObjectVersion
);
925 // Currently, "-mprintf-kind" option is only supported for HIP
927 auto *MDStr
= llvm::MDString::get(
928 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal
==
929 TargetOptions::AMDGPUPrintfKind::Hostcall
)
932 getModule().addModuleFlag(llvm::Module::Error
, "amdgpu_printf_kind",
937 // Emit a global array containing all external kernels or device variables
938 // used by host functions and mark it as used for CUDA/HIP. This is necessary
939 // to get kernels or device variables in archives linked in even if these
940 // kernels or device variables are only used in host functions.
941 if (!Context
.CUDAExternalDeviceDeclODRUsedByHost
.empty()) {
942 SmallVector
<llvm::Constant
*, 8> UsedArray
;
943 for (auto D
: Context
.CUDAExternalDeviceDeclODRUsedByHost
) {
945 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
))
946 GD
= GlobalDecl(FD
, KernelReferenceKind::Kernel
);
949 UsedArray
.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
950 GetAddrOfGlobal(GD
), Int8PtrTy
));
953 llvm::ArrayType
*ATy
= llvm::ArrayType::get(Int8PtrTy
, UsedArray
.size());
955 auto *GV
= new llvm::GlobalVariable(
956 getModule(), ATy
, false, llvm::GlobalValue::InternalLinkage
,
957 llvm::ConstantArray::get(ATy
, UsedArray
), "__clang_gpu_used_external");
958 addCompilerUsedGlobal(GV
);
960 if (LangOpts
.HIP
&& !getLangOpts().OffloadingNewDriver
) {
961 // Emit a unique ID so that host and device binaries from the same
962 // compilation unit can be associated.
963 auto *GV
= new llvm::GlobalVariable(
964 getModule(), Int8Ty
, false, llvm::GlobalValue::ExternalLinkage
,
965 llvm::Constant::getNullValue(Int8Ty
),
966 "__hip_cuid_" + getContext().getCUIDHash());
967 addCompilerUsedGlobal(GV
);
973 if (CodeGenOpts
.Autolink
&&
974 (Context
.getLangOpts().Modules
|| !LinkerOptionsMetadata
.empty())) {
975 EmitModuleLinkOptions();
978 // On ELF we pass the dependent library specifiers directly to the linker
979 // without manipulating them. This is in contrast to other platforms where
980 // they are mapped to a specific linker option by the compiler. This
981 // difference is a result of the greater variety of ELF linkers and the fact
982 // that ELF linkers tend to handle libraries in a more complicated fashion
983 // than on other platforms. This forces us to defer handling the dependent
984 // libs to the linker.
986 // CUDA/HIP device and host libraries are different. Currently there is no
987 // way to differentiate dependent libraries for host or device. Existing
988 // usage of #pragma comment(lib, *) is intended for host libraries on
989 // Windows. Therefore emit llvm.dependent-libraries only for host.
990 if (!ELFDependentLibraries
.empty() && !Context
.getLangOpts().CUDAIsDevice
) {
991 auto *NMD
= getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
992 for (auto *MD
: ELFDependentLibraries
)
996 if (CodeGenOpts
.DwarfVersion
) {
997 getModule().addModuleFlag(llvm::Module::Max
, "Dwarf Version",
998 CodeGenOpts
.DwarfVersion
);
1001 if (CodeGenOpts
.Dwarf64
)
1002 getModule().addModuleFlag(llvm::Module::Max
, "DWARF64", 1);
1004 if (Context
.getLangOpts().SemanticInterposition
)
1005 // Require various optimization to respect semantic interposition.
1006 getModule().setSemanticInterposition(true);
1008 if (CodeGenOpts
.EmitCodeView
) {
1009 // Indicate that we want CodeView in the metadata.
1010 getModule().addModuleFlag(llvm::Module::Warning
, "CodeView", 1);
1012 if (CodeGenOpts
.CodeViewGHash
) {
1013 getModule().addModuleFlag(llvm::Module::Warning
, "CodeViewGHash", 1);
1015 if (CodeGenOpts
.ControlFlowGuard
) {
1016 // Function ID tables and checks for Control Flow Guard (cfguard=2).
1017 getModule().addModuleFlag(llvm::Module::Warning
, "cfguard", 2);
1018 } else if (CodeGenOpts
.ControlFlowGuardNoChecks
) {
1019 // Function ID tables for Control Flow Guard (cfguard=1).
1020 getModule().addModuleFlag(llvm::Module::Warning
, "cfguard", 1);
1022 if (CodeGenOpts
.EHContGuard
) {
1023 // Function ID tables for EH Continuation Guard.
1024 getModule().addModuleFlag(llvm::Module::Warning
, "ehcontguard", 1);
1026 if (Context
.getLangOpts().Kernel
) {
1027 // Note if we are compiling with /kernel.
1028 getModule().addModuleFlag(llvm::Module::Warning
, "ms-kernel", 1);
1030 if (CodeGenOpts
.OptimizationLevel
> 0 && CodeGenOpts
.StrictVTablePointers
) {
1031 // We don't support LTO with 2 with different StrictVTablePointers
1032 // FIXME: we could support it by stripping all the information introduced
1033 // by StrictVTablePointers.
1035 getModule().addModuleFlag(llvm::Module::Error
, "StrictVTablePointers",1);
1037 llvm::Metadata
*Ops
[2] = {
1038 llvm::MDString::get(VMContext
, "StrictVTablePointers"),
1039 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1040 llvm::Type::getInt32Ty(VMContext
), 1))};
1042 getModule().addModuleFlag(llvm::Module::Require
,
1043 "StrictVTablePointersRequirement",
1044 llvm::MDNode::get(VMContext
, Ops
));
1046 if (getModuleDebugInfo())
1047 // We support a single version in the linked module. The LLVM
1048 // parser will drop debug info with a different version number
1049 // (and warn about it, too).
1050 getModule().addModuleFlag(llvm::Module::Warning
, "Debug Info Version",
1051 llvm::DEBUG_METADATA_VERSION
);
1053 // We need to record the widths of enums and wchar_t, so that we can generate
1054 // the correct build attributes in the ARM backend. wchar_size is also used by
1055 // TargetLibraryInfo.
1056 uint64_t WCharWidth
=
1057 Context
.getTypeSizeInChars(Context
.getWideCharType()).getQuantity();
1058 getModule().addModuleFlag(llvm::Module::Error
, "wchar_size", WCharWidth
);
1060 if (getTriple().isOSzOS()) {
1061 getModule().addModuleFlag(llvm::Module::Warning
,
1062 "zos_product_major_version",
1063 uint32_t(CLANG_VERSION_MAJOR
));
1064 getModule().addModuleFlag(llvm::Module::Warning
,
1065 "zos_product_minor_version",
1066 uint32_t(CLANG_VERSION_MINOR
));
1067 getModule().addModuleFlag(llvm::Module::Warning
, "zos_product_patchlevel",
1068 uint32_t(CLANG_VERSION_PATCHLEVEL
));
1069 std::string ProductId
= getClangVendor() + "clang";
1070 getModule().addModuleFlag(llvm::Module::Error
, "zos_product_id",
1071 llvm::MDString::get(VMContext
, ProductId
));
1073 // Record the language because we need it for the PPA2.
1074 StringRef lang_str
= languageToString(
1075 LangStandard::getLangStandardForKind(LangOpts
.LangStd
).Language
);
1076 getModule().addModuleFlag(llvm::Module::Error
, "zos_cu_language",
1077 llvm::MDString::get(VMContext
, lang_str
));
1079 time_t TT
= PreprocessorOpts
.SourceDateEpoch
1080 ? *PreprocessorOpts
.SourceDateEpoch
1081 : std::time(nullptr);
1082 getModule().addModuleFlag(llvm::Module::Max
, "zos_translation_time",
1083 static_cast<uint64_t>(TT
));
1085 // Multiple modes will be supported here.
1086 getModule().addModuleFlag(llvm::Module::Error
, "zos_le_char_mode",
1087 llvm::MDString::get(VMContext
, "ascii"));
1090 llvm::Triple T
= Context
.getTargetInfo().getTriple();
1091 if (T
.isARM() || T
.isThumb()) {
1092 // The minimum width of an enum in bytes
1093 uint64_t EnumWidth
= Context
.getLangOpts().ShortEnums
? 1 : 4;
1094 getModule().addModuleFlag(llvm::Module::Error
, "min_enum_size", EnumWidth
);
1098 StringRef ABIStr
= Target
.getABI();
1099 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
1100 getModule().addModuleFlag(llvm::Module::Error
, "target-abi",
1101 llvm::MDString::get(Ctx
, ABIStr
));
1103 // Add the canonical ISA string as metadata so the backend can set the ELF
1104 // attributes correctly. We use AppendUnique so LTO will keep all of the
1105 // unique ISA strings that were linked together.
1106 const std::vector
<std::string
> &Features
=
1107 getTarget().getTargetOpts().Features
;
1109 llvm::RISCVISAInfo::parseFeatures(T
.isRISCV64() ? 64 : 32, Features
);
1110 if (!errorToBool(ParseResult
.takeError()))
1111 getModule().addModuleFlag(
1112 llvm::Module::AppendUnique
, "riscv-isa",
1114 Ctx
, llvm::MDString::get(Ctx
, (*ParseResult
)->toString())));
1117 if (CodeGenOpts
.SanitizeCfiCrossDso
) {
1118 // Indicate that we want cross-DSO control flow integrity checks.
1119 getModule().addModuleFlag(llvm::Module::Override
, "Cross-DSO CFI", 1);
1122 if (CodeGenOpts
.WholeProgramVTables
) {
1123 // Indicate whether VFE was enabled for this module, so that the
1124 // vcall_visibility metadata added under whole program vtables is handled
1125 // appropriately in the optimizer.
1126 getModule().addModuleFlag(llvm::Module::Error
, "Virtual Function Elim",
1127 CodeGenOpts
.VirtualFunctionElimination
);
1130 if (LangOpts
.Sanitize
.has(SanitizerKind::CFIICall
)) {
1131 getModule().addModuleFlag(llvm::Module::Override
,
1132 "CFI Canonical Jump Tables",
1133 CodeGenOpts
.SanitizeCfiCanonicalJumpTables
);
1136 if (CodeGenOpts
.SanitizeCfiICallNormalizeIntegers
) {
1137 getModule().addModuleFlag(llvm::Module::Override
, "cfi-normalize-integers",
1141 if (LangOpts
.Sanitize
.has(SanitizerKind::KCFI
)) {
1142 getModule().addModuleFlag(llvm::Module::Override
, "kcfi", 1);
1143 // KCFI assumes patchable-function-prefix is the same for all indirectly
1144 // called functions. Store the expected offset for code generation.
1145 if (CodeGenOpts
.PatchableFunctionEntryOffset
)
1146 getModule().addModuleFlag(llvm::Module::Override
, "kcfi-offset",
1147 CodeGenOpts
.PatchableFunctionEntryOffset
);
1150 if (CodeGenOpts
.CFProtectionReturn
&&
1151 Target
.checkCFProtectionReturnSupported(getDiags())) {
1152 // Indicate that we want to instrument return control flow protection.
1153 getModule().addModuleFlag(llvm::Module::Min
, "cf-protection-return",
1157 if (CodeGenOpts
.CFProtectionBranch
&&
1158 Target
.checkCFProtectionBranchSupported(getDiags())) {
1159 // Indicate that we want to instrument branch control flow protection.
1160 getModule().addModuleFlag(llvm::Module::Min
, "cf-protection-branch",
1163 auto Scheme
= CodeGenOpts
.getCFBranchLabelScheme();
1164 if (Target
.checkCFBranchLabelSchemeSupported(Scheme
, getDiags())) {
1165 if (Scheme
== CFBranchLabelSchemeKind::Default
)
1166 Scheme
= Target
.getDefaultCFBranchLabelScheme();
1167 getModule().addModuleFlag(
1168 llvm::Module::Error
, "cf-branch-label-scheme",
1169 llvm::MDString::get(getLLVMContext(),
1170 getCFBranchLabelSchemeFlagVal(Scheme
)));
1174 if (CodeGenOpts
.FunctionReturnThunks
)
1175 getModule().addModuleFlag(llvm::Module::Override
, "function_return_thunk_extern", 1);
1177 if (CodeGenOpts
.IndirectBranchCSPrefix
)
1178 getModule().addModuleFlag(llvm::Module::Override
, "indirect_branch_cs_prefix", 1);
1180 // Add module metadata for return address signing (ignoring
1181 // non-leaf/all) and stack tagging. These are actually turned on by function
1182 // attributes, but we use module metadata to emit build attributes. This is
1183 // needed for LTO, where the function attributes are inside bitcode
1184 // serialised into a global variable by the time build attributes are
1185 // emitted, so we can't access them. LTO objects could be compiled with
1186 // different flags therefore module flags are set to "Min" behavior to achieve
1187 // the same end result of the normal build where e.g BTI is off if any object
1188 // doesn't support it.
1189 if (Context
.getTargetInfo().hasFeature("ptrauth") &&
1190 LangOpts
.getSignReturnAddressScope() !=
1191 LangOptions::SignReturnAddressScopeKind::None
)
1192 getModule().addModuleFlag(llvm::Module::Override
,
1193 "sign-return-address-buildattr", 1);
1194 if (LangOpts
.Sanitize
.has(SanitizerKind::MemtagStack
))
1195 getModule().addModuleFlag(llvm::Module::Override
,
1196 "tag-stack-memory-buildattr", 1);
1198 if (T
.isARM() || T
.isThumb() || T
.isAArch64()) {
1199 if (LangOpts
.BranchTargetEnforcement
)
1200 getModule().addModuleFlag(llvm::Module::Min
, "branch-target-enforcement",
1202 if (LangOpts
.BranchProtectionPAuthLR
)
1203 getModule().addModuleFlag(llvm::Module::Min
, "branch-protection-pauth-lr",
1205 if (LangOpts
.GuardedControlStack
)
1206 getModule().addModuleFlag(llvm::Module::Min
, "guarded-control-stack", 1);
1207 if (LangOpts
.hasSignReturnAddress())
1208 getModule().addModuleFlag(llvm::Module::Min
, "sign-return-address", 1);
1209 if (LangOpts
.isSignReturnAddressScopeAll())
1210 getModule().addModuleFlag(llvm::Module::Min
, "sign-return-address-all",
1212 if (!LangOpts
.isSignReturnAddressWithAKey())
1213 getModule().addModuleFlag(llvm::Module::Min
,
1214 "sign-return-address-with-bkey", 1);
1216 if (LangOpts
.PointerAuthELFGOT
)
1217 getModule().addModuleFlag(llvm::Module::Min
, "ptrauth-elf-got", 1);
1219 if (getTriple().isOSLinux()) {
1220 assert(getTriple().isOSBinFormatELF());
1221 using namespace llvm::ELF
;
1222 uint64_t PAuthABIVersion
=
1223 (LangOpts
.PointerAuthIntrinsics
1224 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS
) |
1225 (LangOpts
.PointerAuthCalls
1226 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS
) |
1227 (LangOpts
.PointerAuthReturns
1228 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS
) |
1229 (LangOpts
.PointerAuthAuthTraps
1230 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS
) |
1231 (LangOpts
.PointerAuthVTPtrAddressDiscrimination
1232 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR
) |
1233 (LangOpts
.PointerAuthVTPtrTypeDiscrimination
1234 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR
) |
1235 (LangOpts
.PointerAuthInitFini
1236 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI
) |
1237 (LangOpts
.PointerAuthInitFiniAddressDiscrimination
1238 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC
) |
1239 (LangOpts
.PointerAuthELFGOT
1240 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT
) |
1241 (LangOpts
.PointerAuthIndirectGotos
1242 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS
) |
1243 (LangOpts
.PointerAuthTypeInfoVTPtrDiscrimination
1244 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR
) |
1245 (LangOpts
.PointerAuthFunctionTypeDiscrimination
1246 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR
);
1247 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR
==
1248 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST
,
1249 "Update when new enum items are defined");
1250 if (PAuthABIVersion
!= 0) {
1251 getModule().addModuleFlag(llvm::Module::Error
,
1252 "aarch64-elf-pauthabi-platform",
1253 AARCH64_PAUTH_PLATFORM_LLVM_LINUX
);
1254 getModule().addModuleFlag(llvm::Module::Error
,
1255 "aarch64-elf-pauthabi-version",
1261 if (CodeGenOpts
.StackClashProtector
)
1262 getModule().addModuleFlag(
1263 llvm::Module::Override
, "probe-stack",
1264 llvm::MDString::get(TheModule
.getContext(), "inline-asm"));
1266 if (CodeGenOpts
.StackProbeSize
&& CodeGenOpts
.StackProbeSize
!= 4096)
1267 getModule().addModuleFlag(llvm::Module::Min
, "stack-probe-size",
1268 CodeGenOpts
.StackProbeSize
);
1270 if (!CodeGenOpts
.MemoryProfileOutput
.empty()) {
1271 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
1272 getModule().addModuleFlag(
1273 llvm::Module::Error
, "MemProfProfileFilename",
1274 llvm::MDString::get(Ctx
, CodeGenOpts
.MemoryProfileOutput
));
1277 if (LangOpts
.CUDAIsDevice
&& getTriple().isNVPTX()) {
1278 // Indicate whether __nvvm_reflect should be configured to flush denormal
1279 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
1281 getModule().addModuleFlag(llvm::Module::Override
, "nvvm-reflect-ftz",
1282 CodeGenOpts
.FP32DenormalMode
.Output
!=
1283 llvm::DenormalMode::IEEE
);
1286 if (LangOpts
.EHAsynch
)
1287 getModule().addModuleFlag(llvm::Module::Warning
, "eh-asynch", 1);
1289 // Indicate whether this Module was compiled with -fopenmp
1290 if (getLangOpts().OpenMP
&& !getLangOpts().OpenMPSimd
)
1291 getModule().addModuleFlag(llvm::Module::Max
, "openmp", LangOpts
.OpenMP
);
1292 if (getLangOpts().OpenMPIsTargetDevice
)
1293 getModule().addModuleFlag(llvm::Module::Max
, "openmp-device",
1296 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
1297 if (LangOpts
.OpenCL
|| (LangOpts
.CUDAIsDevice
&& getTriple().isSPIRV())) {
1298 EmitOpenCLMetadata();
1299 // Emit SPIR version.
1300 if (getTriple().isSPIR()) {
1301 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
1302 // opencl.spir.version named metadata.
1303 // C++ for OpenCL has a distinct mapping for version compatibility with
1305 auto Version
= LangOpts
.getOpenCLCompatibleVersion();
1306 llvm::Metadata
*SPIRVerElts
[] = {
1307 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1308 Int32Ty
, Version
/ 100)),
1309 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1310 Int32Ty
, (Version
/ 100 > 1) ? 0 : 2))};
1311 llvm::NamedMDNode
*SPIRVerMD
=
1312 TheModule
.getOrInsertNamedMetadata("opencl.spir.version");
1313 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
1314 SPIRVerMD
->addOperand(llvm::MDNode::get(Ctx
, SPIRVerElts
));
1318 // HLSL related end of code gen work items.
1320 getHLSLRuntime().finishCodeGen();
1322 if (uint32_t PLevel
= Context
.getLangOpts().PICLevel
) {
1323 assert(PLevel
< 3 && "Invalid PIC Level");
1324 getModule().setPICLevel(static_cast<llvm::PICLevel::Level
>(PLevel
));
1325 if (Context
.getLangOpts().PIE
)
1326 getModule().setPIELevel(static_cast<llvm::PIELevel::Level
>(PLevel
));
1329 if (getCodeGenOpts().CodeModel
.size() > 0) {
1330 unsigned CM
= llvm::StringSwitch
<unsigned>(getCodeGenOpts().CodeModel
)
1331 .Case("tiny", llvm::CodeModel::Tiny
)
1332 .Case("small", llvm::CodeModel::Small
)
1333 .Case("kernel", llvm::CodeModel::Kernel
)
1334 .Case("medium", llvm::CodeModel::Medium
)
1335 .Case("large", llvm::CodeModel::Large
)
1338 llvm::CodeModel::Model codeModel
= static_cast<llvm::CodeModel::Model
>(CM
);
1339 getModule().setCodeModel(codeModel
);
1341 if ((CM
== llvm::CodeModel::Medium
|| CM
== llvm::CodeModel::Large
) &&
1342 Context
.getTargetInfo().getTriple().getArch() ==
1343 llvm::Triple::x86_64
) {
1344 getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold
);
1349 if (CodeGenOpts
.NoPLT
)
1350 getModule().setRtLibUseGOT();
1351 if (getTriple().isOSBinFormatELF() &&
1352 CodeGenOpts
.DirectAccessExternalData
!=
1353 getModule().getDirectAccessExternalData()) {
1354 getModule().setDirectAccessExternalData(
1355 CodeGenOpts
.DirectAccessExternalData
);
1357 if (CodeGenOpts
.UnwindTables
)
1358 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts
.UnwindTables
));
1360 switch (CodeGenOpts
.getFramePointer()) {
1361 case CodeGenOptions::FramePointerKind::None
:
1362 // 0 ("none") is the default.
1364 case CodeGenOptions::FramePointerKind::Reserved
:
1365 getModule().setFramePointer(llvm::FramePointerKind::Reserved
);
1367 case CodeGenOptions::FramePointerKind::NonLeaf
:
1368 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf
);
1370 case CodeGenOptions::FramePointerKind::All
:
1371 getModule().setFramePointer(llvm::FramePointerKind::All
);
1375 SimplifyPersonality();
1377 if (getCodeGenOpts().EmitDeclMetadata
)
1380 if (getCodeGenOpts().CoverageNotesFile
.size() ||
1381 getCodeGenOpts().CoverageDataFile
.size())
1384 if (CGDebugInfo
*DI
= getModuleDebugInfo())
1387 if (getCodeGenOpts().EmitVersionIdentMetadata
)
1388 EmitVersionIdentMetadata();
1390 if (!getCodeGenOpts().RecordCommandLine
.empty())
1391 EmitCommandLineMetadata();
1393 if (!getCodeGenOpts().StackProtectorGuard
.empty())
1394 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard
);
1395 if (!getCodeGenOpts().StackProtectorGuardReg
.empty())
1396 getModule().setStackProtectorGuardReg(
1397 getCodeGenOpts().StackProtectorGuardReg
);
1398 if (!getCodeGenOpts().StackProtectorGuardSymbol
.empty())
1399 getModule().setStackProtectorGuardSymbol(
1400 getCodeGenOpts().StackProtectorGuardSymbol
);
1401 if (getCodeGenOpts().StackProtectorGuardOffset
!= INT_MAX
)
1402 getModule().setStackProtectorGuardOffset(
1403 getCodeGenOpts().StackProtectorGuardOffset
);
1404 if (getCodeGenOpts().StackAlignment
)
1405 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment
);
1406 if (getCodeGenOpts().SkipRaxSetup
)
1407 getModule().addModuleFlag(llvm::Module::Override
, "SkipRaxSetup", 1);
1408 if (getLangOpts().RegCall4
)
1409 getModule().addModuleFlag(llvm::Module::Override
, "RegCallv4", 1);
1411 if (getContext().getTargetInfo().getMaxTLSAlign())
1412 getModule().addModuleFlag(llvm::Module::Error
, "MaxTLSAlign",
1413 getContext().getTargetInfo().getMaxTLSAlign());
1415 getTargetCodeGenInfo().emitTargetGlobals(*this);
1417 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames
);
1419 EmitBackendOptionsMetadata(getCodeGenOpts());
1421 // If there is device offloading code embed it in the host now.
1422 EmbedObject(&getModule(), CodeGenOpts
, getDiags());
1424 // Set visibility from DLL storage class
1425 // We do this at the end of LLVM IR generation; after any operation
1426 // that might affect the DLL storage class or the visibility, and
1427 // before anything that might act on these.
1428 setVisibilityFromDLLStorageClass(LangOpts
, getModule());
1430 // Check the tail call symbols are truly undefined.
1431 if (getTriple().isPPC() && !MustTailCallUndefinedGlobals
.empty()) {
1432 for (auto &I
: MustTailCallUndefinedGlobals
) {
1433 if (!I
.first
->isDefined())
1434 getDiags().Report(I
.second
, diag::err_ppc_impossible_musttail
) << 2;
1436 StringRef MangledName
= getMangledName(GlobalDecl(I
.first
));
1437 llvm::GlobalValue
*Entry
= GetGlobalValue(MangledName
);
1438 if (!Entry
|| Entry
->isWeakForLinker() ||
1439 Entry
->isDeclarationForLinker())
1440 getDiags().Report(I
.second
, diag::err_ppc_impossible_musttail
) << 2;
1446 void CodeGenModule::EmitOpenCLMetadata() {
1447 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1448 // opencl.ocl.version named metadata node.
1449 // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL.
1450 auto CLVersion
= LangOpts
.getOpenCLCompatibleVersion();
1452 auto EmitVersion
= [this](StringRef MDName
, int Version
) {
1453 llvm::Metadata
*OCLVerElts
[] = {
1454 llvm::ConstantAsMetadata::get(
1455 llvm::ConstantInt::get(Int32Ty
, Version
/ 100)),
1456 llvm::ConstantAsMetadata::get(
1457 llvm::ConstantInt::get(Int32Ty
, (Version
% 100) / 10))};
1458 llvm::NamedMDNode
*OCLVerMD
= TheModule
.getOrInsertNamedMetadata(MDName
);
1459 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
1460 OCLVerMD
->addOperand(llvm::MDNode::get(Ctx
, OCLVerElts
));
1463 EmitVersion("opencl.ocl.version", CLVersion
);
1464 if (LangOpts
.OpenCLCPlusPlus
) {
1465 // In addition to the OpenCL compatible version, emit the C++ version.
1466 EmitVersion("opencl.cxx.version", LangOpts
.OpenCLCPlusPlusVersion
);
1470 void CodeGenModule::EmitBackendOptionsMetadata(
1471 const CodeGenOptions
&CodeGenOpts
) {
1472 if (getTriple().isRISCV()) {
1473 getModule().addModuleFlag(llvm::Module::Min
, "SmallDataLimit",
1474 CodeGenOpts
.SmallDataLimit
);
1478 void CodeGenModule::UpdateCompletedType(const TagDecl
*TD
) {
1479 // Make sure that this type is translated.
1480 getTypes().UpdateCompletedType(TD
);
1483 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl
*RD
) {
1484 // Make sure that this type is translated.
1485 getTypes().RefreshTypeCacheForClass(RD
);
1488 llvm::MDNode
*CodeGenModule::getTBAATypeInfo(QualType QTy
) {
1491 return TBAA
->getTypeInfo(QTy
);
1494 TBAAAccessInfo
CodeGenModule::getTBAAAccessInfo(QualType AccessType
) {
1496 return TBAAAccessInfo();
1497 if (getLangOpts().CUDAIsDevice
) {
1498 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1500 if (AccessType
->isCUDADeviceBuiltinSurfaceType()) {
1501 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1503 return TBAAAccessInfo();
1504 } else if (AccessType
->isCUDADeviceBuiltinTextureType()) {
1505 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1507 return TBAAAccessInfo();
1510 return TBAA
->getAccessInfo(AccessType
);
1514 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type
*VTablePtrType
) {
1516 return TBAAAccessInfo();
1517 return TBAA
->getVTablePtrAccessInfo(VTablePtrType
);
1520 llvm::MDNode
*CodeGenModule::getTBAAStructInfo(QualType QTy
) {
1523 return TBAA
->getTBAAStructInfo(QTy
);
1526 llvm::MDNode
*CodeGenModule::getTBAABaseTypeInfo(QualType QTy
) {
1529 return TBAA
->getBaseTypeInfo(QTy
);
1532 llvm::MDNode
*CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info
) {
1535 return TBAA
->getAccessTagInfo(Info
);
1538 TBAAAccessInfo
CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo
,
1539 TBAAAccessInfo TargetInfo
) {
1541 return TBAAAccessInfo();
1542 return TBAA
->mergeTBAAInfoForCast(SourceInfo
, TargetInfo
);
1546 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA
,
1547 TBAAAccessInfo InfoB
) {
1549 return TBAAAccessInfo();
1550 return TBAA
->mergeTBAAInfoForConditionalOperator(InfoA
, InfoB
);
1554 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo
,
1555 TBAAAccessInfo SrcInfo
) {
1557 return TBAAAccessInfo();
1558 return TBAA
->mergeTBAAInfoForConditionalOperator(DestInfo
, SrcInfo
);
1561 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction
*Inst
,
1562 TBAAAccessInfo TBAAInfo
) {
1563 if (llvm::MDNode
*Tag
= getTBAAAccessTagInfo(TBAAInfo
))
1564 Inst
->setMetadata(llvm::LLVMContext::MD_tbaa
, Tag
);
1567 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1568 llvm::Instruction
*I
, const CXXRecordDecl
*RD
) {
1569 I
->setMetadata(llvm::LLVMContext::MD_invariant_group
,
1570 llvm::MDNode::get(getLLVMContext(), {}));
1573 void CodeGenModule::Error(SourceLocation loc
, StringRef message
) {
1574 unsigned diagID
= getDiags().getCustomDiagID(DiagnosticsEngine::Error
, "%0");
1575 getDiags().Report(Context
.getFullLoc(loc
), diagID
) << message
;
1578 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1579 /// specified stmt yet.
1580 void CodeGenModule::ErrorUnsupported(const Stmt
*S
, const char *Type
) {
1581 unsigned DiagID
= getDiags().getCustomDiagID(DiagnosticsEngine::Error
,
1582 "cannot compile this %0 yet");
1583 std::string Msg
= Type
;
1584 getDiags().Report(Context
.getFullLoc(S
->getBeginLoc()), DiagID
)
1585 << Msg
<< S
->getSourceRange();
1588 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1589 /// specified decl yet.
1590 void CodeGenModule::ErrorUnsupported(const Decl
*D
, const char *Type
) {
1591 unsigned DiagID
= getDiags().getCustomDiagID(DiagnosticsEngine::Error
,
1592 "cannot compile this %0 yet");
1593 std::string Msg
= Type
;
1594 getDiags().Report(Context
.getFullLoc(D
->getLocation()), DiagID
) << Msg
;
1597 void CodeGenModule::runWithSufficientStackSpace(SourceLocation Loc
,
1598 llvm::function_ref
<void()> Fn
) {
1599 StackHandler
.runWithSufficientStackSpace(Loc
, Fn
);
1602 llvm::ConstantInt
*CodeGenModule::getSize(CharUnits size
) {
1603 return llvm::ConstantInt::get(SizeTy
, size
.getQuantity());
1606 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue
*GV
,
1607 const NamedDecl
*D
) const {
1608 // Internal definitions always have default visibility.
1609 if (GV
->hasLocalLinkage()) {
1610 GV
->setVisibility(llvm::GlobalValue::DefaultVisibility
);
1616 // Set visibility for definitions, and for declarations if requested globally
1617 // or set explicitly.
1618 LinkageInfo LV
= D
->getLinkageAndVisibility();
1620 // OpenMP declare target variables must be visible to the host so they can
1621 // be registered. We require protected visibility unless the variable has
1622 // the DT_nohost modifier and does not need to be registered.
1623 if (Context
.getLangOpts().OpenMP
&&
1624 Context
.getLangOpts().OpenMPIsTargetDevice
&& isa
<VarDecl
>(D
) &&
1625 D
->hasAttr
<OMPDeclareTargetDeclAttr
>() &&
1626 D
->getAttr
<OMPDeclareTargetDeclAttr
>()->getDevType() !=
1627 OMPDeclareTargetDeclAttr::DT_NoHost
&&
1628 LV
.getVisibility() == HiddenVisibility
) {
1629 GV
->setVisibility(llvm::GlobalValue::ProtectedVisibility
);
1633 if (GV
->hasDLLExportStorageClass() || GV
->hasDLLImportStorageClass()) {
1634 // Reject incompatible dlllstorage and visibility annotations.
1635 if (!LV
.isVisibilityExplicit())
1637 if (GV
->hasDLLExportStorageClass()) {
1638 if (LV
.getVisibility() == HiddenVisibility
)
1639 getDiags().Report(D
->getLocation(),
1640 diag::err_hidden_visibility_dllexport
);
1641 } else if (LV
.getVisibility() != DefaultVisibility
) {
1642 getDiags().Report(D
->getLocation(),
1643 diag::err_non_default_visibility_dllimport
);
1648 if (LV
.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls
||
1649 !GV
->isDeclarationForLinker())
1650 GV
->setVisibility(GetLLVMVisibility(LV
.getVisibility()));
1653 static bool shouldAssumeDSOLocal(const CodeGenModule
&CGM
,
1654 llvm::GlobalValue
*GV
) {
1655 if (GV
->hasLocalLinkage())
1658 if (!GV
->hasDefaultVisibility() && !GV
->hasExternalWeakLinkage())
1661 // DLLImport explicitly marks the GV as external.
1662 if (GV
->hasDLLImportStorageClass())
1665 const llvm::Triple
&TT
= CGM
.getTriple();
1666 const auto &CGOpts
= CGM
.getCodeGenOpts();
1667 if (TT
.isWindowsGNUEnvironment()) {
1668 // In MinGW, variables without DLLImport can still be automatically
1669 // imported from a DLL by the linker; don't mark variables that
1670 // potentially could come from another DLL as DSO local.
1672 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1673 // (and this actually happens in the public interface of libstdc++), so
1674 // such variables can't be marked as DSO local. (Native TLS variables
1675 // can't be dllimported at all, though.)
1676 if (GV
->isDeclarationForLinker() && isa
<llvm::GlobalVariable
>(GV
) &&
1677 (!GV
->isThreadLocal() || CGM
.getCodeGenOpts().EmulatedTLS
) &&
1682 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1683 // remain unresolved in the link, they can be resolved to zero, which is
1684 // outside the current DSO.
1685 if (TT
.isOSBinFormatCOFF() && GV
->hasExternalWeakLinkage())
1688 // Every other GV is local on COFF.
1689 // Make an exception for windows OS in the triple: Some firmware builds use
1690 // *-win32-macho triples. This (accidentally?) produced windows relocations
1691 // without GOT tables in older clang versions; Keep this behaviour.
1692 // FIXME: even thread local variables?
1693 if (TT
.isOSBinFormatCOFF() || (TT
.isOSWindows() && TT
.isOSBinFormatMachO()))
1696 // Only handle COFF and ELF for now.
1697 if (!TT
.isOSBinFormatELF())
1700 // If this is not an executable, don't assume anything is local.
1701 llvm::Reloc::Model RM
= CGOpts
.RelocationModel
;
1702 const auto &LOpts
= CGM
.getLangOpts();
1703 if (RM
!= llvm::Reloc::Static
&& !LOpts
.PIE
) {
1704 // On ELF, if -fno-semantic-interposition is specified and the target
1705 // supports local aliases, there will be neither CC1
1706 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1707 // dso_local on the function if using a local alias is preferable (can avoid
1708 // PLT indirection).
1709 if (!(isa
<llvm::Function
>(GV
) && GV
->canBenefitFromLocalAlias()))
1711 return !(CGM
.getLangOpts().SemanticInterposition
||
1712 CGM
.getLangOpts().HalfNoSemanticInterposition
);
1715 // A definition cannot be preempted from an executable.
1716 if (!GV
->isDeclarationForLinker())
1719 // Most PIC code sequences that assume that a symbol is local cannot produce a
1720 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1721 // depended, it seems worth it to handle it here.
1722 if (RM
== llvm::Reloc::PIC_
&& GV
->hasExternalWeakLinkage())
1725 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1729 if (CGOpts
.DirectAccessExternalData
) {
1730 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1731 // for non-thread-local variables. If the symbol is not defined in the
1732 // executable, a copy relocation will be needed at link time. dso_local is
1733 // excluded for thread-local variables because they generally don't support
1734 // copy relocations.
1735 if (auto *Var
= dyn_cast
<llvm::GlobalVariable
>(GV
))
1736 if (!Var
->isThreadLocal())
1739 // -fno-pic sets dso_local on a function declaration to allow direct
1740 // accesses when taking its address (similar to a data symbol). If the
1741 // function is not defined in the executable, a canonical PLT entry will be
1742 // needed at link time. -fno-direct-access-external-data can avoid the
1743 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1744 // it could just cause trouble without providing perceptible benefits.
1745 if (isa
<llvm::Function
>(GV
) && !CGOpts
.NoPLT
&& RM
== llvm::Reloc::Static
)
1749 // If we can use copy relocations we can assume it is local.
1751 // Otherwise don't assume it is local.
1755 void CodeGenModule::setDSOLocal(llvm::GlobalValue
*GV
) const {
1756 GV
->setDSOLocal(shouldAssumeDSOLocal(*this, GV
));
1759 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue
*GV
,
1760 GlobalDecl GD
) const {
1761 const auto *D
= dyn_cast
<NamedDecl
>(GD
.getDecl());
1762 // C++ destructors have a few C++ ABI specific special cases.
1763 if (const auto *Dtor
= dyn_cast_or_null
<CXXDestructorDecl
>(D
)) {
1764 getCXXABI().setCXXDestructorDLLStorage(GV
, Dtor
, GD
.getDtorType());
1767 setDLLImportDLLExport(GV
, D
);
1770 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue
*GV
,
1771 const NamedDecl
*D
) const {
1772 if (D
&& D
->isExternallyVisible()) {
1773 if (D
->hasAttr
<DLLImportAttr
>())
1774 GV
->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass
);
1775 else if ((D
->hasAttr
<DLLExportAttr
>() ||
1776 shouldMapVisibilityToDLLExport(D
)) &&
1777 !GV
->isDeclarationForLinker())
1778 GV
->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass
);
1782 void CodeGenModule::setGVProperties(llvm::GlobalValue
*GV
,
1783 GlobalDecl GD
) const {
1784 setDLLImportDLLExport(GV
, GD
);
1785 setGVPropertiesAux(GV
, dyn_cast
<NamedDecl
>(GD
.getDecl()));
1788 void CodeGenModule::setGVProperties(llvm::GlobalValue
*GV
,
1789 const NamedDecl
*D
) const {
1790 setDLLImportDLLExport(GV
, D
);
1791 setGVPropertiesAux(GV
, D
);
1794 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue
*GV
,
1795 const NamedDecl
*D
) const {
1796 setGlobalVisibility(GV
, D
);
1798 GV
->setPartition(CodeGenOpts
.SymbolPartition
);
1801 static llvm::GlobalVariable::ThreadLocalMode
GetLLVMTLSModel(StringRef S
) {
1802 return llvm::StringSwitch
<llvm::GlobalVariable::ThreadLocalMode
>(S
)
1803 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel
)
1804 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel
)
1805 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel
)
1806 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel
);
1809 llvm::GlobalVariable::ThreadLocalMode
1810 CodeGenModule::GetDefaultLLVMTLSModel() const {
1811 switch (CodeGenOpts
.getDefaultTLSModel()) {
1812 case CodeGenOptions::GeneralDynamicTLSModel
:
1813 return llvm::GlobalVariable::GeneralDynamicTLSModel
;
1814 case CodeGenOptions::LocalDynamicTLSModel
:
1815 return llvm::GlobalVariable::LocalDynamicTLSModel
;
1816 case CodeGenOptions::InitialExecTLSModel
:
1817 return llvm::GlobalVariable::InitialExecTLSModel
;
1818 case CodeGenOptions::LocalExecTLSModel
:
1819 return llvm::GlobalVariable::LocalExecTLSModel
;
1821 llvm_unreachable("Invalid TLS model!");
1824 void CodeGenModule::setTLSMode(llvm::GlobalValue
*GV
, const VarDecl
&D
) const {
1825 assert(D
.getTLSKind() && "setting TLS mode on non-TLS var!");
1827 llvm::GlobalValue::ThreadLocalMode TLM
;
1828 TLM
= GetDefaultLLVMTLSModel();
1830 // Override the TLS model if it is explicitly specified.
1831 if (const TLSModelAttr
*Attr
= D
.getAttr
<TLSModelAttr
>()) {
1832 TLM
= GetLLVMTLSModel(Attr
->getModel());
1835 GV
->setThreadLocalMode(TLM
);
1838 static std::string
getCPUSpecificMangling(const CodeGenModule
&CGM
,
1840 const TargetInfo
&Target
= CGM
.getTarget();
1841 return (Twine('.') + Twine(Target
.CPUSpecificManglingCharacter(Name
))).str();
1844 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule
&CGM
,
1845 const CPUSpecificAttr
*Attr
,
1848 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1851 Out
<< getCPUSpecificMangling(CGM
, Attr
->getCPUName(CPUIndex
)->getName());
1852 else if (CGM
.getTarget().supportsIFunc())
1856 // Returns true if GD is a function decl with internal linkage and
1857 // needs a unique suffix after the mangled name.
1858 static bool isUniqueInternalLinkageDecl(GlobalDecl GD
,
1859 CodeGenModule
&CGM
) {
1860 const Decl
*D
= GD
.getDecl();
1861 return !CGM
.getModuleNameHash().empty() && isa
<FunctionDecl
>(D
) &&
1862 (CGM
.getFunctionLinkage(GD
) == llvm::GlobalValue::InternalLinkage
);
1865 static std::string
getMangledNameImpl(CodeGenModule
&CGM
, GlobalDecl GD
,
1866 const NamedDecl
*ND
,
1867 bool OmitMultiVersionMangling
= false) {
1868 SmallString
<256> Buffer
;
1869 llvm::raw_svector_ostream
Out(Buffer
);
1870 MangleContext
&MC
= CGM
.getCXXABI().getMangleContext();
1871 if (!CGM
.getModuleNameHash().empty())
1872 MC
.needsUniqueInternalLinkageNames();
1873 bool ShouldMangle
= MC
.shouldMangleDeclName(ND
);
1875 MC
.mangleName(GD
.getWithDecl(ND
), Out
);
1877 IdentifierInfo
*II
= ND
->getIdentifier();
1878 assert(II
&& "Attempt to mangle unnamed decl.");
1879 const auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
1882 FD
->getType()->castAs
<FunctionType
>()->getCallConv() == CC_X86RegCall
) {
1883 if (CGM
.getLangOpts().RegCall4
)
1884 Out
<< "__regcall4__" << II
->getName();
1886 Out
<< "__regcall3__" << II
->getName();
1887 } else if (FD
&& FD
->hasAttr
<CUDAGlobalAttr
>() &&
1888 GD
.getKernelReferenceKind() == KernelReferenceKind::Stub
) {
1889 Out
<< "__device_stub__" << II
->getName();
1891 Out
<< II
->getName();
1895 // Check if the module name hash should be appended for internal linkage
1896 // symbols. This should come before multi-version target suffixes are
1897 // appended. This is to keep the name and module hash suffix of the
1898 // internal linkage function together. The unique suffix should only be
1899 // added when name mangling is done to make sure that the final name can
1900 // be properly demangled. For example, for C functions without prototypes,
1901 // name mangling is not done and the unique suffix should not be appeneded
1903 if (ShouldMangle
&& isUniqueInternalLinkageDecl(GD
, CGM
)) {
1904 assert(CGM
.getCodeGenOpts().UniqueInternalLinkageNames
&&
1905 "Hash computed when not explicitly requested");
1906 Out
<< CGM
.getModuleNameHash();
1909 if (const auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
1910 if (FD
->isMultiVersion() && !OmitMultiVersionMangling
) {
1911 switch (FD
->getMultiVersionKind()) {
1912 case MultiVersionKind::CPUDispatch
:
1913 case MultiVersionKind::CPUSpecific
:
1914 AppendCPUSpecificCPUDispatchMangling(CGM
,
1915 FD
->getAttr
<CPUSpecificAttr
>(),
1916 GD
.getMultiVersionIndex(), Out
);
1918 case MultiVersionKind::Target
: {
1919 auto *Attr
= FD
->getAttr
<TargetAttr
>();
1920 assert(Attr
&& "Expected TargetAttr to be present "
1921 "for attribute mangling");
1922 const ABIInfo
&Info
= CGM
.getTargetCodeGenInfo().getABIInfo();
1923 Info
.appendAttributeMangling(Attr
, Out
);
1926 case MultiVersionKind::TargetVersion
: {
1927 auto *Attr
= FD
->getAttr
<TargetVersionAttr
>();
1928 assert(Attr
&& "Expected TargetVersionAttr to be present "
1929 "for attribute mangling");
1930 const ABIInfo
&Info
= CGM
.getTargetCodeGenInfo().getABIInfo();
1931 Info
.appendAttributeMangling(Attr
, Out
);
1934 case MultiVersionKind::TargetClones
: {
1935 auto *Attr
= FD
->getAttr
<TargetClonesAttr
>();
1936 assert(Attr
&& "Expected TargetClonesAttr to be present "
1937 "for attribute mangling");
1938 unsigned Index
= GD
.getMultiVersionIndex();
1939 const ABIInfo
&Info
= CGM
.getTargetCodeGenInfo().getABIInfo();
1940 Info
.appendAttributeMangling(Attr
, Index
, Out
);
1943 case MultiVersionKind::None
:
1944 llvm_unreachable("None multiversion type isn't valid here");
1948 // Make unique name for device side static file-scope variable for HIP.
1949 if (CGM
.getContext().shouldExternalize(ND
) &&
1950 CGM
.getLangOpts().GPURelocatableDeviceCode
&&
1951 CGM
.getLangOpts().CUDAIsDevice
)
1952 CGM
.printPostfixForExternalizedDecl(Out
, ND
);
1954 return std::string(Out
.str());
1957 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD
,
1958 const FunctionDecl
*FD
,
1959 StringRef
&CurName
) {
1960 if (!FD
->isMultiVersion())
1963 // Get the name of what this would be without the 'target' attribute. This
1964 // allows us to lookup the version that was emitted when this wasn't a
1965 // multiversion function.
1966 std::string NonTargetName
=
1967 getMangledNameImpl(*this, GD
, FD
, /*OmitMultiVersionMangling=*/true);
1969 if (lookupRepresentativeDecl(NonTargetName
, OtherGD
)) {
1970 assert(OtherGD
.getCanonicalDecl()
1973 ->isMultiVersion() &&
1974 "Other GD should now be a multiversioned function");
1975 // OtherFD is the version of this function that was mangled BEFORE
1976 // becoming a MultiVersion function. It potentially needs to be updated.
1977 const FunctionDecl
*OtherFD
= OtherGD
.getCanonicalDecl()
1980 ->getMostRecentDecl();
1981 std::string OtherName
= getMangledNameImpl(*this, OtherGD
, OtherFD
);
1982 // This is so that if the initial version was already the 'default'
1983 // version, we don't try to update it.
1984 if (OtherName
!= NonTargetName
) {
1985 // Remove instead of erase, since others may have stored the StringRef
1987 const auto ExistingRecord
= Manglings
.find(NonTargetName
);
1988 if (ExistingRecord
!= std::end(Manglings
))
1989 Manglings
.remove(&(*ExistingRecord
));
1990 auto Result
= Manglings
.insert(std::make_pair(OtherName
, OtherGD
));
1991 StringRef OtherNameRef
= MangledDeclNames
[OtherGD
.getCanonicalDecl()] =
1992 Result
.first
->first();
1993 // If this is the current decl is being created, make sure we update the name.
1994 if (GD
.getCanonicalDecl() == OtherGD
.getCanonicalDecl())
1995 CurName
= OtherNameRef
;
1996 if (llvm::GlobalValue
*Entry
= GetGlobalValue(NonTargetName
))
1997 Entry
->setName(OtherName
);
2002 StringRef
CodeGenModule::getMangledName(GlobalDecl GD
) {
2003 GlobalDecl CanonicalGD
= GD
.getCanonicalDecl();
2005 // Some ABIs don't have constructor variants. Make sure that base and
2006 // complete constructors get mangled the same.
2007 if (const auto *CD
= dyn_cast
<CXXConstructorDecl
>(CanonicalGD
.getDecl())) {
2008 if (!getTarget().getCXXABI().hasConstructorVariants()) {
2009 CXXCtorType OrigCtorType
= GD
.getCtorType();
2010 assert(OrigCtorType
== Ctor_Base
|| OrigCtorType
== Ctor_Complete
);
2011 if (OrigCtorType
== Ctor_Base
)
2012 CanonicalGD
= GlobalDecl(CD
, Ctor_Complete
);
2016 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
2017 // static device variable depends on whether the variable is referenced by
2018 // a host or device host function. Therefore the mangled name cannot be
2020 if (!LangOpts
.CUDAIsDevice
|| !getContext().mayExternalize(GD
.getDecl())) {
2021 auto FoundName
= MangledDeclNames
.find(CanonicalGD
);
2022 if (FoundName
!= MangledDeclNames
.end())
2023 return FoundName
->second
;
2026 // Keep the first result in the case of a mangling collision.
2027 const auto *ND
= cast
<NamedDecl
>(GD
.getDecl());
2028 std::string MangledName
= getMangledNameImpl(*this, GD
, ND
);
2030 // Ensure either we have different ABIs between host and device compilations,
2031 // says host compilation following MSVC ABI but device compilation follows
2032 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
2033 // mangling should be the same after name stubbing. The later checking is
2034 // very important as the device kernel name being mangled in host-compilation
2035 // is used to resolve the device binaries to be executed. Inconsistent naming
2036 // result in undefined behavior. Even though we cannot check that naming
2037 // directly between host- and device-compilations, the host- and
2038 // device-mangling in host compilation could help catching certain ones.
2039 assert(!isa
<FunctionDecl
>(ND
) || !ND
->hasAttr
<CUDAGlobalAttr
>() ||
2040 getContext().shouldExternalize(ND
) || getLangOpts().CUDAIsDevice
||
2041 (getContext().getAuxTargetInfo() &&
2042 (getContext().getAuxTargetInfo()->getCXXABI() !=
2043 getContext().getTargetInfo().getCXXABI())) ||
2044 getCUDARuntime().getDeviceSideName(ND
) ==
2047 GD
.getWithKernelReferenceKind(KernelReferenceKind::Kernel
),
2050 auto Result
= Manglings
.insert(std::make_pair(MangledName
, GD
));
2051 return MangledDeclNames
[CanonicalGD
] = Result
.first
->first();
2054 StringRef
CodeGenModule::getBlockMangledName(GlobalDecl GD
,
2055 const BlockDecl
*BD
) {
2056 MangleContext
&MangleCtx
= getCXXABI().getMangleContext();
2057 const Decl
*D
= GD
.getDecl();
2059 SmallString
<256> Buffer
;
2060 llvm::raw_svector_ostream
Out(Buffer
);
2062 MangleCtx
.mangleGlobalBlock(BD
,
2063 dyn_cast_or_null
<VarDecl
>(initializedGlobalDecl
.getDecl()), Out
);
2064 else if (const auto *CD
= dyn_cast
<CXXConstructorDecl
>(D
))
2065 MangleCtx
.mangleCtorBlock(CD
, GD
.getCtorType(), BD
, Out
);
2066 else if (const auto *DD
= dyn_cast
<CXXDestructorDecl
>(D
))
2067 MangleCtx
.mangleDtorBlock(DD
, GD
.getDtorType(), BD
, Out
);
2069 MangleCtx
.mangleBlock(cast
<DeclContext
>(D
), BD
, Out
);
2071 auto Result
= Manglings
.insert(std::make_pair(Out
.str(), BD
));
2072 return Result
.first
->first();
2075 const GlobalDecl
CodeGenModule::getMangledNameDecl(StringRef Name
) {
2076 auto it
= MangledDeclNames
.begin();
2077 while (it
!= MangledDeclNames
.end()) {
2078 if (it
->second
== Name
)
2082 return GlobalDecl();
2085 llvm::GlobalValue
*CodeGenModule::GetGlobalValue(StringRef Name
) {
2086 return getModule().getNamedValue(Name
);
2089 /// AddGlobalCtor - Add a function to the list that will be called before
2091 void CodeGenModule::AddGlobalCtor(llvm::Function
*Ctor
, int Priority
,
2093 llvm::Constant
*AssociatedData
) {
2094 // FIXME: Type coercion of void()* types.
2095 GlobalCtors
.push_back(Structor(Priority
, LexOrder
, Ctor
, AssociatedData
));
2098 /// AddGlobalDtor - Add a function to the list that will be called
2099 /// when the module is unloaded.
2100 void CodeGenModule::AddGlobalDtor(llvm::Function
*Dtor
, int Priority
,
2101 bool IsDtorAttrFunc
) {
2102 if (CodeGenOpts
.RegisterGlobalDtorsWithAtExit
&&
2103 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc
)) {
2104 DtorsUsingAtExit
[Priority
].push_back(Dtor
);
2108 // FIXME: Type coercion of void()* types.
2109 GlobalDtors
.push_back(Structor(Priority
, ~0U, Dtor
, nullptr));
2112 void CodeGenModule::EmitCtorList(CtorList
&Fns
, const char *GlobalName
) {
2113 if (Fns
.empty()) return;
2115 const PointerAuthSchema
&InitFiniAuthSchema
=
2116 getCodeGenOpts().PointerAuth
.InitFiniPointers
;
2118 // Ctor function type is ptr.
2119 llvm::PointerType
*PtrTy
= llvm::PointerType::get(
2120 getLLVMContext(), TheModule
.getDataLayout().getProgramAddressSpace());
2122 // Get the type of a ctor entry, { i32, ptr, ptr }.
2123 llvm::StructType
*CtorStructTy
= llvm::StructType::get(Int32Ty
, PtrTy
, PtrTy
);
2125 // Construct the constructor and destructor arrays.
2126 ConstantInitBuilder
Builder(*this);
2127 auto Ctors
= Builder
.beginArray(CtorStructTy
);
2128 for (const auto &I
: Fns
) {
2129 auto Ctor
= Ctors
.beginStruct(CtorStructTy
);
2130 Ctor
.addInt(Int32Ty
, I
.Priority
);
2131 if (InitFiniAuthSchema
) {
2132 llvm::Constant
*StorageAddress
=
2133 (InitFiniAuthSchema
.isAddressDiscriminated()
2134 ? llvm::ConstantExpr::getIntToPtr(
2135 llvm::ConstantInt::get(
2137 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors
),
2140 llvm::Constant
*SignedCtorPtr
= getConstantSignedPointer(
2141 I
.Initializer
, InitFiniAuthSchema
.getKey(), StorageAddress
,
2142 llvm::ConstantInt::get(
2143 SizeTy
, InitFiniAuthSchema
.getConstantDiscrimination()));
2144 Ctor
.add(SignedCtorPtr
);
2146 Ctor
.add(I
.Initializer
);
2148 if (I
.AssociatedData
)
2149 Ctor
.add(I
.AssociatedData
);
2151 Ctor
.addNullPointer(PtrTy
);
2152 Ctor
.finishAndAddTo(Ctors
);
2155 auto List
= Ctors
.finishAndCreateGlobal(GlobalName
, getPointerAlign(),
2157 llvm::GlobalValue::AppendingLinkage
);
2159 // The LTO linker doesn't seem to like it when we set an alignment
2160 // on appending variables. Take it off as a workaround.
2161 List
->setAlignment(std::nullopt
);
2166 llvm::GlobalValue::LinkageTypes
2167 CodeGenModule::getFunctionLinkage(GlobalDecl GD
) {
2168 const auto *D
= cast
<FunctionDecl
>(GD
.getDecl());
2170 GVALinkage Linkage
= getContext().GetGVALinkageForFunction(D
);
2172 if (const auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(D
))
2173 return getCXXABI().getCXXDestructorLinkage(Linkage
, Dtor
, GD
.getDtorType());
2175 return getLLVMLinkageForDeclarator(D
, Linkage
);
2178 llvm::ConstantInt
*CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata
*MD
) {
2179 llvm::MDString
*MDS
= dyn_cast
<llvm::MDString
>(MD
);
2180 if (!MDS
) return nullptr;
2182 return llvm::ConstantInt::get(Int64Ty
, llvm::MD5Hash(MDS
->getString()));
2185 llvm::ConstantInt
*CodeGenModule::CreateKCFITypeId(QualType T
) {
2186 if (auto *FnType
= T
->getAs
<FunctionProtoType
>())
2187 T
= getContext().getFunctionType(
2188 FnType
->getReturnType(), FnType
->getParamTypes(),
2189 FnType
->getExtProtoInfo().withExceptionSpec(EST_None
));
2191 std::string OutName
;
2192 llvm::raw_string_ostream
Out(OutName
);
2193 getCXXABI().getMangleContext().mangleCanonicalTypeName(
2194 T
, Out
, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers
);
2196 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers
)
2197 Out
<< ".normalized";
2199 return llvm::ConstantInt::get(Int32Ty
,
2200 static_cast<uint32_t>(llvm::xxHash64(OutName
)));
2203 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD
,
2204 const CGFunctionInfo
&Info
,
2205 llvm::Function
*F
, bool IsThunk
) {
2206 unsigned CallingConv
;
2207 llvm::AttributeList PAL
;
2208 ConstructAttributeList(F
->getName(), Info
, GD
, PAL
, CallingConv
,
2209 /*AttrOnCallSite=*/false, IsThunk
);
2210 if (CallingConv
== llvm::CallingConv::X86_VectorCall
&&
2211 getTarget().getTriple().isWindowsArm64EC()) {
2213 if (const Decl
*D
= GD
.getDecl())
2214 Loc
= D
->getLocation();
2216 Error(Loc
, "__vectorcall calling convention is not currently supported");
2218 F
->setAttributes(PAL
);
2219 F
->setCallingConv(static_cast<llvm::CallingConv::ID
>(CallingConv
));
2222 static void removeImageAccessQualifier(std::string
& TyName
) {
2223 std::string
ReadOnlyQual("__read_only");
2224 std::string::size_type ReadOnlyPos
= TyName
.find(ReadOnlyQual
);
2225 if (ReadOnlyPos
!= std::string::npos
)
2226 // "+ 1" for the space after access qualifier.
2227 TyName
.erase(ReadOnlyPos
, ReadOnlyQual
.size() + 1);
2229 std::string
WriteOnlyQual("__write_only");
2230 std::string::size_type WriteOnlyPos
= TyName
.find(WriteOnlyQual
);
2231 if (WriteOnlyPos
!= std::string::npos
)
2232 TyName
.erase(WriteOnlyPos
, WriteOnlyQual
.size() + 1);
2234 std::string
ReadWriteQual("__read_write");
2235 std::string::size_type ReadWritePos
= TyName
.find(ReadWriteQual
);
2236 if (ReadWritePos
!= std::string::npos
)
2237 TyName
.erase(ReadWritePos
, ReadWriteQual
.size() + 1);
2242 // Returns the address space id that should be produced to the
2243 // kernel_arg_addr_space metadata. This is always fixed to the ids
2244 // as specified in the SPIR 2.0 specification in order to differentiate
2245 // for example in clGetKernelArgInfo() implementation between the address
2246 // spaces with targets without unique mapping to the OpenCL address spaces
2247 // (basically all single AS CPUs).
2248 static unsigned ArgInfoAddressSpace(LangAS AS
) {
2250 case LangAS::opencl_global
:
2252 case LangAS::opencl_constant
:
2254 case LangAS::opencl_local
:
2256 case LangAS::opencl_generic
:
2257 return 4; // Not in SPIR 2.0 specs.
2258 case LangAS::opencl_global_device
:
2260 case LangAS::opencl_global_host
:
2263 return 0; // Assume private.
2267 void CodeGenModule::GenKernelArgMetadata(llvm::Function
*Fn
,
2268 const FunctionDecl
*FD
,
2269 CodeGenFunction
*CGF
) {
2270 assert(((FD
&& CGF
) || (!FD
&& !CGF
)) &&
2271 "Incorrect use - FD and CGF should either be both null or not!");
2272 // Create MDNodes that represent the kernel arg metadata.
2273 // Each MDNode is a list in the form of "key", N number of values which is
2274 // the same number of values as their are kernel arguments.
2276 const PrintingPolicy
&Policy
= Context
.getPrintingPolicy();
2278 // MDNode for the kernel argument address space qualifiers.
2279 SmallVector
<llvm::Metadata
*, 8> addressQuals
;
2281 // MDNode for the kernel argument access qualifiers (images only).
2282 SmallVector
<llvm::Metadata
*, 8> accessQuals
;
2284 // MDNode for the kernel argument type names.
2285 SmallVector
<llvm::Metadata
*, 8> argTypeNames
;
2287 // MDNode for the kernel argument base type names.
2288 SmallVector
<llvm::Metadata
*, 8> argBaseTypeNames
;
2290 // MDNode for the kernel argument type qualifiers.
2291 SmallVector
<llvm::Metadata
*, 8> argTypeQuals
;
2293 // MDNode for the kernel argument names.
2294 SmallVector
<llvm::Metadata
*, 8> argNames
;
2297 for (unsigned i
= 0, e
= FD
->getNumParams(); i
!= e
; ++i
) {
2298 const ParmVarDecl
*parm
= FD
->getParamDecl(i
);
2299 // Get argument name.
2300 argNames
.push_back(llvm::MDString::get(VMContext
, parm
->getName()));
2302 if (!getLangOpts().OpenCL
)
2304 QualType ty
= parm
->getType();
2305 std::string typeQuals
;
2307 // Get image and pipe access qualifier:
2308 if (ty
->isImageType() || ty
->isPipeType()) {
2309 const Decl
*PDecl
= parm
;
2310 if (const auto *TD
= ty
->getAs
<TypedefType
>())
2311 PDecl
= TD
->getDecl();
2312 const OpenCLAccessAttr
*A
= PDecl
->getAttr
<OpenCLAccessAttr
>();
2313 if (A
&& A
->isWriteOnly())
2314 accessQuals
.push_back(llvm::MDString::get(VMContext
, "write_only"));
2315 else if (A
&& A
->isReadWrite())
2316 accessQuals
.push_back(llvm::MDString::get(VMContext
, "read_write"));
2318 accessQuals
.push_back(llvm::MDString::get(VMContext
, "read_only"));
2320 accessQuals
.push_back(llvm::MDString::get(VMContext
, "none"));
2322 auto getTypeSpelling
= [&](QualType Ty
) {
2323 auto typeName
= Ty
.getUnqualifiedType().getAsString(Policy
);
2325 if (Ty
.isCanonical()) {
2326 StringRef typeNameRef
= typeName
;
2327 // Turn "unsigned type" to "utype"
2328 if (typeNameRef
.consume_front("unsigned "))
2329 return std::string("u") + typeNameRef
.str();
2330 if (typeNameRef
.consume_front("signed "))
2331 return typeNameRef
.str();
2337 if (ty
->isPointerType()) {
2338 QualType pointeeTy
= ty
->getPointeeType();
2340 // Get address qualifier.
2341 addressQuals
.push_back(
2342 llvm::ConstantAsMetadata::get(CGF
->Builder
.getInt32(
2343 ArgInfoAddressSpace(pointeeTy
.getAddressSpace()))));
2345 // Get argument type name.
2346 std::string typeName
= getTypeSpelling(pointeeTy
) + "*";
2347 std::string baseTypeName
=
2348 getTypeSpelling(pointeeTy
.getCanonicalType()) + "*";
2349 argTypeNames
.push_back(llvm::MDString::get(VMContext
, typeName
));
2350 argBaseTypeNames
.push_back(
2351 llvm::MDString::get(VMContext
, baseTypeName
));
2353 // Get argument type qualifiers:
2354 if (ty
.isRestrictQualified())
2355 typeQuals
= "restrict";
2356 if (pointeeTy
.isConstQualified() ||
2357 (pointeeTy
.getAddressSpace() == LangAS::opencl_constant
))
2358 typeQuals
+= typeQuals
.empty() ? "const" : " const";
2359 if (pointeeTy
.isVolatileQualified())
2360 typeQuals
+= typeQuals
.empty() ? "volatile" : " volatile";
2362 uint32_t AddrSpc
= 0;
2363 bool isPipe
= ty
->isPipeType();
2364 if (ty
->isImageType() || isPipe
)
2365 AddrSpc
= ArgInfoAddressSpace(LangAS::opencl_global
);
2367 addressQuals
.push_back(
2368 llvm::ConstantAsMetadata::get(CGF
->Builder
.getInt32(AddrSpc
)));
2370 // Get argument type name.
2371 ty
= isPipe
? ty
->castAs
<PipeType
>()->getElementType() : ty
;
2372 std::string typeName
= getTypeSpelling(ty
);
2373 std::string baseTypeName
= getTypeSpelling(ty
.getCanonicalType());
2375 // Remove access qualifiers on images
2376 // (as they are inseparable from type in clang implementation,
2377 // but OpenCL spec provides a special query to get access qualifier
2378 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2379 if (ty
->isImageType()) {
2380 removeImageAccessQualifier(typeName
);
2381 removeImageAccessQualifier(baseTypeName
);
2384 argTypeNames
.push_back(llvm::MDString::get(VMContext
, typeName
));
2385 argBaseTypeNames
.push_back(
2386 llvm::MDString::get(VMContext
, baseTypeName
));
2391 argTypeQuals
.push_back(llvm::MDString::get(VMContext
, typeQuals
));
2394 if (getLangOpts().OpenCL
) {
2395 Fn
->setMetadata("kernel_arg_addr_space",
2396 llvm::MDNode::get(VMContext
, addressQuals
));
2397 Fn
->setMetadata("kernel_arg_access_qual",
2398 llvm::MDNode::get(VMContext
, accessQuals
));
2399 Fn
->setMetadata("kernel_arg_type",
2400 llvm::MDNode::get(VMContext
, argTypeNames
));
2401 Fn
->setMetadata("kernel_arg_base_type",
2402 llvm::MDNode::get(VMContext
, argBaseTypeNames
));
2403 Fn
->setMetadata("kernel_arg_type_qual",
2404 llvm::MDNode::get(VMContext
, argTypeQuals
));
2406 if (getCodeGenOpts().EmitOpenCLArgMetadata
||
2407 getCodeGenOpts().HIPSaveKernelArgName
)
2408 Fn
->setMetadata("kernel_arg_name",
2409 llvm::MDNode::get(VMContext
, argNames
));
2412 /// Determines whether the language options require us to model
2413 /// unwind exceptions. We treat -fexceptions as mandating this
2414 /// except under the fragile ObjC ABI with only ObjC exceptions
2415 /// enabled. This means, for example, that C with -fexceptions
2417 static bool hasUnwindExceptions(const LangOptions
&LangOpts
) {
2418 // If exceptions are completely disabled, obviously this is false.
2419 if (!LangOpts
.Exceptions
) return false;
2421 // If C++ exceptions are enabled, this is true.
2422 if (LangOpts
.CXXExceptions
) return true;
2424 // If ObjC exceptions are enabled, this depends on the ABI.
2425 if (LangOpts
.ObjCExceptions
) {
2426 return LangOpts
.ObjCRuntime
.hasUnwindExceptions();
2432 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule
&CGM
,
2433 const CXXMethodDecl
*MD
) {
2434 // Check that the type metadata can ever actually be used by a call.
2435 if (!CGM
.getCodeGenOpts().LTOUnit
||
2436 !CGM
.HasHiddenLTOVisibility(MD
->getParent()))
2439 // Only functions whose address can be taken with a member function pointer
2440 // need this sort of type metadata.
2441 return MD
->isImplicitObjectMemberFunction() && !MD
->isVirtual() &&
2442 !isa
<CXXConstructorDecl
, CXXDestructorDecl
>(MD
);
2445 SmallVector
<const CXXRecordDecl
*, 0>
2446 CodeGenModule::getMostBaseClasses(const CXXRecordDecl
*RD
) {
2447 llvm::SetVector
<const CXXRecordDecl
*> MostBases
;
2449 std::function
<void (const CXXRecordDecl
*)> CollectMostBases
;
2450 CollectMostBases
= [&](const CXXRecordDecl
*RD
) {
2451 if (RD
->getNumBases() == 0)
2452 MostBases
.insert(RD
);
2453 for (const CXXBaseSpecifier
&B
: RD
->bases())
2454 CollectMostBases(B
.getType()->getAsCXXRecordDecl());
2456 CollectMostBases(RD
);
2457 return MostBases
.takeVector();
2460 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl
*D
,
2461 llvm::Function
*F
) {
2462 llvm::AttrBuilder
B(F
->getContext());
2464 if ((!D
|| !D
->hasAttr
<NoUwtableAttr
>()) && CodeGenOpts
.UnwindTables
)
2465 B
.addUWTableAttr(llvm::UWTableKind(CodeGenOpts
.UnwindTables
));
2467 if (CodeGenOpts
.StackClashProtector
)
2468 B
.addAttribute("probe-stack", "inline-asm");
2470 if (CodeGenOpts
.StackProbeSize
&& CodeGenOpts
.StackProbeSize
!= 4096)
2471 B
.addAttribute("stack-probe-size",
2472 std::to_string(CodeGenOpts
.StackProbeSize
));
2474 if (!hasUnwindExceptions(LangOpts
))
2475 B
.addAttribute(llvm::Attribute::NoUnwind
);
2477 if (D
&& D
->hasAttr
<NoStackProtectorAttr
>())
2479 else if (D
&& D
->hasAttr
<StrictGuardStackCheckAttr
>() &&
2480 isStackProtectorOn(LangOpts
, getTriple(), LangOptions::SSPOn
))
2481 B
.addAttribute(llvm::Attribute::StackProtectStrong
);
2482 else if (isStackProtectorOn(LangOpts
, getTriple(), LangOptions::SSPOn
))
2483 B
.addAttribute(llvm::Attribute::StackProtect
);
2484 else if (isStackProtectorOn(LangOpts
, getTriple(), LangOptions::SSPStrong
))
2485 B
.addAttribute(llvm::Attribute::StackProtectStrong
);
2486 else if (isStackProtectorOn(LangOpts
, getTriple(), LangOptions::SSPReq
))
2487 B
.addAttribute(llvm::Attribute::StackProtectReq
);
2490 // Non-entry HLSL functions must always be inlined.
2491 if (getLangOpts().HLSL
&& !F
->hasFnAttribute(llvm::Attribute::NoInline
))
2492 B
.addAttribute(llvm::Attribute::AlwaysInline
);
2493 // If we don't have a declaration to control inlining, the function isn't
2494 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2495 // disabled, mark the function as noinline.
2496 else if (!F
->hasFnAttribute(llvm::Attribute::AlwaysInline
) &&
2497 CodeGenOpts
.getInlining() == CodeGenOptions::OnlyAlwaysInlining
)
2498 B
.addAttribute(llvm::Attribute::NoInline
);
2504 // Handle SME attributes that apply to function definitions,
2505 // rather than to function prototypes.
2506 if (D
->hasAttr
<ArmLocallyStreamingAttr
>())
2507 B
.addAttribute("aarch64_pstate_sm_body");
2509 if (auto *Attr
= D
->getAttr
<ArmNewAttr
>()) {
2510 if (Attr
->isNewZA())
2511 B
.addAttribute("aarch64_new_za");
2512 if (Attr
->isNewZT0())
2513 B
.addAttribute("aarch64_new_zt0");
2516 // Track whether we need to add the optnone LLVM attribute,
2517 // starting with the default for this optimization level.
2518 bool ShouldAddOptNone
=
2519 !CodeGenOpts
.DisableO0ImplyOptNone
&& CodeGenOpts
.OptimizationLevel
== 0;
2520 // We can't add optnone in the following cases, it won't pass the verifier.
2521 ShouldAddOptNone
&= !D
->hasAttr
<MinSizeAttr
>();
2522 ShouldAddOptNone
&= !D
->hasAttr
<AlwaysInlineAttr
>();
2524 // Non-entry HLSL functions must always be inlined.
2525 if (getLangOpts().HLSL
&& !F
->hasFnAttribute(llvm::Attribute::NoInline
) &&
2526 !D
->hasAttr
<NoInlineAttr
>()) {
2527 B
.addAttribute(llvm::Attribute::AlwaysInline
);
2528 } else if ((ShouldAddOptNone
|| D
->hasAttr
<OptimizeNoneAttr
>()) &&
2529 !F
->hasFnAttribute(llvm::Attribute::AlwaysInline
)) {
2530 // Add optnone, but do so only if the function isn't always_inline.
2531 B
.addAttribute(llvm::Attribute::OptimizeNone
);
2533 // OptimizeNone implies noinline; we should not be inlining such functions.
2534 B
.addAttribute(llvm::Attribute::NoInline
);
2536 // We still need to handle naked functions even though optnone subsumes
2537 // much of their semantics.
2538 if (D
->hasAttr
<NakedAttr
>())
2539 B
.addAttribute(llvm::Attribute::Naked
);
2541 // OptimizeNone wins over OptimizeForSize and MinSize.
2542 F
->removeFnAttr(llvm::Attribute::OptimizeForSize
);
2543 F
->removeFnAttr(llvm::Attribute::MinSize
);
2544 } else if (D
->hasAttr
<NakedAttr
>()) {
2545 // Naked implies noinline: we should not be inlining such functions.
2546 B
.addAttribute(llvm::Attribute::Naked
);
2547 B
.addAttribute(llvm::Attribute::NoInline
);
2548 } else if (D
->hasAttr
<NoDuplicateAttr
>()) {
2549 B
.addAttribute(llvm::Attribute::NoDuplicate
);
2550 } else if (D
->hasAttr
<NoInlineAttr
>() &&
2551 !F
->hasFnAttribute(llvm::Attribute::AlwaysInline
)) {
2552 // Add noinline if the function isn't always_inline.
2553 B
.addAttribute(llvm::Attribute::NoInline
);
2554 } else if (D
->hasAttr
<AlwaysInlineAttr
>() &&
2555 !F
->hasFnAttribute(llvm::Attribute::NoInline
)) {
2556 // (noinline wins over always_inline, and we can't specify both in IR)
2557 B
.addAttribute(llvm::Attribute::AlwaysInline
);
2558 } else if (CodeGenOpts
.getInlining() == CodeGenOptions::OnlyAlwaysInlining
) {
2559 // If we're not inlining, then force everything that isn't always_inline to
2560 // carry an explicit noinline attribute.
2561 if (!F
->hasFnAttribute(llvm::Attribute::AlwaysInline
))
2562 B
.addAttribute(llvm::Attribute::NoInline
);
2564 // Otherwise, propagate the inline hint attribute and potentially use its
2565 // absence to mark things as noinline.
2566 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
2567 // Search function and template pattern redeclarations for inline.
2568 auto CheckForInline
= [](const FunctionDecl
*FD
) {
2569 auto CheckRedeclForInline
= [](const FunctionDecl
*Redecl
) {
2570 return Redecl
->isInlineSpecified();
2572 if (any_of(FD
->redecls(), CheckRedeclForInline
))
2574 const FunctionDecl
*Pattern
= FD
->getTemplateInstantiationPattern();
2577 return any_of(Pattern
->redecls(), CheckRedeclForInline
);
2579 if (CheckForInline(FD
)) {
2580 B
.addAttribute(llvm::Attribute::InlineHint
);
2581 } else if (CodeGenOpts
.getInlining() ==
2582 CodeGenOptions::OnlyHintInlining
&&
2584 !F
->hasFnAttribute(llvm::Attribute::AlwaysInline
)) {
2585 B
.addAttribute(llvm::Attribute::NoInline
);
2590 // Add other optimization related attributes if we are optimizing this
2592 if (!D
->hasAttr
<OptimizeNoneAttr
>()) {
2593 if (D
->hasAttr
<ColdAttr
>()) {
2594 if (!ShouldAddOptNone
)
2595 B
.addAttribute(llvm::Attribute::OptimizeForSize
);
2596 B
.addAttribute(llvm::Attribute::Cold
);
2598 if (D
->hasAttr
<HotAttr
>())
2599 B
.addAttribute(llvm::Attribute::Hot
);
2600 if (D
->hasAttr
<MinSizeAttr
>())
2601 B
.addAttribute(llvm::Attribute::MinSize
);
2606 unsigned alignment
= D
->getMaxAlignment() / Context
.getCharWidth();
2608 F
->setAlignment(llvm::Align(alignment
));
2610 if (!D
->hasAttr
<AlignedAttr
>())
2611 if (LangOpts
.FunctionAlignment
)
2612 F
->setAlignment(llvm::Align(1ull << LangOpts
.FunctionAlignment
));
2614 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2615 // reserve a bit for differentiating between virtual and non-virtual member
2616 // functions. If the current target's C++ ABI requires this and this is a
2617 // member function, set its alignment accordingly.
2618 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2619 if (isa
<CXXMethodDecl
>(D
) && F
->getPointerAlignment(getDataLayout()) < 2)
2620 F
->setAlignment(std::max(llvm::Align(2), F
->getAlign().valueOrOne()));
2623 // In the cross-dso CFI mode with canonical jump tables, we want !type
2624 // attributes on definitions only.
2625 if (CodeGenOpts
.SanitizeCfiCrossDso
&&
2626 CodeGenOpts
.SanitizeCfiCanonicalJumpTables
) {
2627 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
2628 // Skip available_externally functions. They won't be codegen'ed in the
2629 // current module anyway.
2630 if (getContext().GetGVALinkageForFunction(FD
) != GVA_AvailableExternally
)
2631 CreateFunctionTypeMetadataForIcall(FD
, F
);
2635 // Emit type metadata on member functions for member function pointer checks.
2636 // These are only ever necessary on definitions; we're guaranteed that the
2637 // definition will be present in the LTO unit as a result of LTO visibility.
2638 auto *MD
= dyn_cast
<CXXMethodDecl
>(D
);
2639 if (MD
&& requiresMemberFunctionPointerTypeMetadata(*this, MD
)) {
2640 for (const CXXRecordDecl
*Base
: getMostBaseClasses(MD
->getParent())) {
2641 llvm::Metadata
*Id
=
2642 CreateMetadataIdentifierForType(Context
.getMemberPointerType(
2643 MD
->getType(), Context
.getRecordType(Base
).getTypePtr()));
2644 F
->addTypeMetadata(0, Id
);
2649 void CodeGenModule::SetCommonAttributes(GlobalDecl GD
, llvm::GlobalValue
*GV
) {
2650 const Decl
*D
= GD
.getDecl();
2651 if (isa_and_nonnull
<NamedDecl
>(D
))
2652 setGVProperties(GV
, GD
);
2654 GV
->setVisibility(llvm::GlobalValue::DefaultVisibility
);
2656 if (D
&& D
->hasAttr
<UsedAttr
>())
2657 addUsedOrCompilerUsedGlobal(GV
);
2659 if (const auto *VD
= dyn_cast_if_present
<VarDecl
>(D
);
2661 ((CodeGenOpts
.KeepPersistentStorageVariables
&&
2662 (VD
->getStorageDuration() == SD_Static
||
2663 VD
->getStorageDuration() == SD_Thread
)) ||
2664 (CodeGenOpts
.KeepStaticConsts
&& VD
->getStorageDuration() == SD_Static
&&
2665 VD
->getType().isConstQualified())))
2666 addUsedOrCompilerUsedGlobal(GV
);
2669 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD
,
2670 llvm::AttrBuilder
&Attrs
,
2671 bool SetTargetFeatures
) {
2672 // Add target-cpu and target-features attributes to functions. If
2673 // we have a decl for the function and it has a target attribute then
2674 // parse that and add it to the feature set.
2675 StringRef TargetCPU
= getTarget().getTargetOpts().CPU
;
2676 StringRef TuneCPU
= getTarget().getTargetOpts().TuneCPU
;
2677 std::vector
<std::string
> Features
;
2678 const auto *FD
= dyn_cast_or_null
<FunctionDecl
>(GD
.getDecl());
2679 FD
= FD
? FD
->getMostRecentDecl() : FD
;
2680 const auto *TD
= FD
? FD
->getAttr
<TargetAttr
>() : nullptr;
2681 const auto *TV
= FD
? FD
->getAttr
<TargetVersionAttr
>() : nullptr;
2682 assert((!TD
|| !TV
) && "both target_version and target specified");
2683 const auto *SD
= FD
? FD
->getAttr
<CPUSpecificAttr
>() : nullptr;
2684 const auto *TC
= FD
? FD
->getAttr
<TargetClonesAttr
>() : nullptr;
2685 bool AddedAttr
= false;
2686 if (TD
|| TV
|| SD
|| TC
) {
2687 llvm::StringMap
<bool> FeatureMap
;
2688 getContext().getFunctionFeatureMap(FeatureMap
, GD
);
2690 // Produce the canonical string for this set of features.
2691 for (const llvm::StringMap
<bool>::value_type
&Entry
: FeatureMap
)
2692 Features
.push_back((Entry
.getValue() ? "+" : "-") + Entry
.getKey().str());
2694 // Now add the target-cpu and target-features to the function.
2695 // While we populated the feature map above, we still need to
2696 // get and parse the target attribute so we can get the cpu for
2699 ParsedTargetAttr ParsedAttr
=
2700 Target
.parseTargetAttr(TD
->getFeaturesStr());
2701 if (!ParsedAttr
.CPU
.empty() &&
2702 getTarget().isValidCPUName(ParsedAttr
.CPU
)) {
2703 TargetCPU
= ParsedAttr
.CPU
;
2704 TuneCPU
= ""; // Clear the tune CPU.
2706 if (!ParsedAttr
.Tune
.empty() &&
2707 getTarget().isValidCPUName(ParsedAttr
.Tune
))
2708 TuneCPU
= ParsedAttr
.Tune
;
2712 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2713 // favor this processor.
2714 TuneCPU
= SD
->getCPUName(GD
.getMultiVersionIndex())->getName();
2717 // Otherwise just add the existing target cpu and target features to the
2719 Features
= getTarget().getTargetOpts().Features
;
2722 if (!TargetCPU
.empty()) {
2723 Attrs
.addAttribute("target-cpu", TargetCPU
);
2726 if (!TuneCPU
.empty()) {
2727 Attrs
.addAttribute("tune-cpu", TuneCPU
);
2730 if (!Features
.empty() && SetTargetFeatures
) {
2731 llvm::erase_if(Features
, [&](const std::string
& F
) {
2732 return getTarget().isReadOnlyFeature(F
.substr(1));
2734 llvm::sort(Features
);
2735 Attrs
.addAttribute("target-features", llvm::join(Features
, ","));
2742 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD
,
2743 llvm::GlobalObject
*GO
) {
2744 const Decl
*D
= GD
.getDecl();
2745 SetCommonAttributes(GD
, GO
);
2748 if (auto *GV
= dyn_cast
<llvm::GlobalVariable
>(GO
)) {
2749 if (D
->hasAttr
<RetainAttr
>())
2751 if (auto *SA
= D
->getAttr
<PragmaClangBSSSectionAttr
>())
2752 GV
->addAttribute("bss-section", SA
->getName());
2753 if (auto *SA
= D
->getAttr
<PragmaClangDataSectionAttr
>())
2754 GV
->addAttribute("data-section", SA
->getName());
2755 if (auto *SA
= D
->getAttr
<PragmaClangRodataSectionAttr
>())
2756 GV
->addAttribute("rodata-section", SA
->getName());
2757 if (auto *SA
= D
->getAttr
<PragmaClangRelroSectionAttr
>())
2758 GV
->addAttribute("relro-section", SA
->getName());
2761 if (auto *F
= dyn_cast
<llvm::Function
>(GO
)) {
2762 if (D
->hasAttr
<RetainAttr
>())
2764 if (auto *SA
= D
->getAttr
<PragmaClangTextSectionAttr
>())
2765 if (!D
->getAttr
<SectionAttr
>())
2766 F
->setSection(SA
->getName());
2768 llvm::AttrBuilder
Attrs(F
->getContext());
2769 if (GetCPUAndFeaturesAttributes(GD
, Attrs
)) {
2770 // We know that GetCPUAndFeaturesAttributes will always have the
2771 // newest set, since it has the newest possible FunctionDecl, so the
2772 // new ones should replace the old.
2773 llvm::AttributeMask RemoveAttrs
;
2774 RemoveAttrs
.addAttribute("target-cpu");
2775 RemoveAttrs
.addAttribute("target-features");
2776 RemoveAttrs
.addAttribute("tune-cpu");
2777 F
->removeFnAttrs(RemoveAttrs
);
2778 F
->addFnAttrs(Attrs
);
2782 if (const auto *CSA
= D
->getAttr
<CodeSegAttr
>())
2783 GO
->setSection(CSA
->getName());
2784 else if (const auto *SA
= D
->getAttr
<SectionAttr
>())
2785 GO
->setSection(SA
->getName());
2788 getTargetCodeGenInfo().setTargetAttributes(D
, GO
, *this);
2791 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD
,
2793 const CGFunctionInfo
&FI
) {
2794 const Decl
*D
= GD
.getDecl();
2795 SetLLVMFunctionAttributes(GD
, FI
, F
, /*IsThunk=*/false);
2796 SetLLVMFunctionAttributesForDefinition(D
, F
);
2798 F
->setLinkage(llvm::Function::InternalLinkage
);
2800 setNonAliasAttributes(GD
, F
);
2803 static void setLinkageForGV(llvm::GlobalValue
*GV
, const NamedDecl
*ND
) {
2804 // Set linkage and visibility in case we never see a definition.
2805 LinkageInfo LV
= ND
->getLinkageAndVisibility();
2806 // Don't set internal linkage on declarations.
2807 // "extern_weak" is overloaded in LLVM; we probably should have
2808 // separate linkage types for this.
2809 if (isExternallyVisible(LV
.getLinkage()) &&
2810 (ND
->hasAttr
<WeakAttr
>() || ND
->isWeakImported()))
2811 GV
->setLinkage(llvm::GlobalValue::ExternalWeakLinkage
);
2814 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl
*FD
,
2815 llvm::Function
*F
) {
2816 // Only if we are checking indirect calls.
2817 if (!LangOpts
.Sanitize
.has(SanitizerKind::CFIICall
))
2820 // Non-static class methods are handled via vtable or member function pointer
2821 // checks elsewhere.
2822 if (isa
<CXXMethodDecl
>(FD
) && !cast
<CXXMethodDecl
>(FD
)->isStatic())
2825 llvm::Metadata
*MD
= CreateMetadataIdentifierForType(FD
->getType());
2826 F
->addTypeMetadata(0, MD
);
2827 F
->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD
->getType()));
2829 // Emit a hash-based bit set entry for cross-DSO calls.
2830 if (CodeGenOpts
.SanitizeCfiCrossDso
)
2831 if (auto CrossDsoTypeId
= CreateCrossDsoCfiTypeId(MD
))
2832 F
->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId
));
2835 void CodeGenModule::setKCFIType(const FunctionDecl
*FD
, llvm::Function
*F
) {
2836 llvm::LLVMContext
&Ctx
= F
->getContext();
2837 llvm::MDBuilder
MDB(Ctx
);
2838 F
->setMetadata(llvm::LLVMContext::MD_kcfi_type
,
2840 Ctx
, MDB
.createConstant(CreateKCFITypeId(FD
->getType()))));
2843 static bool allowKCFIIdentifier(StringRef Name
) {
2844 // KCFI type identifier constants are only necessary for external assembly
2845 // functions, which means it's safe to skip unusual names. Subset of
2846 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2847 return llvm::all_of(Name
, [](const char &C
) {
2848 return llvm::isAlnum(C
) || C
== '_' || C
== '.';
2852 void CodeGenModule::finalizeKCFITypes() {
2853 llvm::Module
&M
= getModule();
2854 for (auto &F
: M
.functions()) {
2855 // Remove KCFI type metadata from non-address-taken local functions.
2856 bool AddressTaken
= F
.hasAddressTaken();
2857 if (!AddressTaken
&& F
.hasLocalLinkage())
2858 F
.eraseMetadata(llvm::LLVMContext::MD_kcfi_type
);
2860 // Generate a constant with the expected KCFI type identifier for all
2861 // address-taken function declarations to support annotating indirectly
2862 // called assembly functions.
2863 if (!AddressTaken
|| !F
.isDeclaration())
2866 const llvm::ConstantInt
*Type
;
2867 if (const llvm::MDNode
*MD
= F
.getMetadata(llvm::LLVMContext::MD_kcfi_type
))
2868 Type
= llvm::mdconst::extract
<llvm::ConstantInt
>(MD
->getOperand(0));
2872 StringRef Name
= F
.getName();
2873 if (!allowKCFIIdentifier(Name
))
2876 std::string Asm
= (".weak __kcfi_typeid_" + Name
+ "\n.set __kcfi_typeid_" +
2877 Name
+ ", " + Twine(Type
->getZExtValue()) + "\n")
2879 M
.appendModuleInlineAsm(Asm
);
2883 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD
, llvm::Function
*F
,
2884 bool IsIncompleteFunction
,
2887 if (llvm::Intrinsic::ID IID
= F
->getIntrinsicID()) {
2888 // If this is an intrinsic function, set the function's attributes
2889 // to the intrinsic's attributes.
2890 F
->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID
));
2894 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
2896 if (!IsIncompleteFunction
)
2897 SetLLVMFunctionAttributes(GD
, getTypes().arrangeGlobalDeclaration(GD
), F
,
2900 // Add the Returned attribute for "this", except for iOS 5 and earlier
2901 // where substantial code, including the libstdc++ dylib, was compiled with
2902 // GCC and does not actually return "this".
2903 if (!IsThunk
&& getCXXABI().HasThisReturn(GD
) &&
2904 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2905 assert(!F
->arg_empty() &&
2906 F
->arg_begin()->getType()
2907 ->canLosslesslyBitCastTo(F
->getReturnType()) &&
2908 "unexpected this return");
2909 F
->addParamAttr(0, llvm::Attribute::Returned
);
2912 // Only a few attributes are set on declarations; these may later be
2913 // overridden by a definition.
2915 setLinkageForGV(F
, FD
);
2916 setGVProperties(F
, FD
);
2918 // Setup target-specific attributes.
2919 if (!IsIncompleteFunction
&& F
->isDeclaration())
2920 getTargetCodeGenInfo().setTargetAttributes(FD
, F
, *this);
2922 if (const auto *CSA
= FD
->getAttr
<CodeSegAttr
>())
2923 F
->setSection(CSA
->getName());
2924 else if (const auto *SA
= FD
->getAttr
<SectionAttr
>())
2925 F
->setSection(SA
->getName());
2927 if (const auto *EA
= FD
->getAttr
<ErrorAttr
>()) {
2929 F
->addFnAttr("dontcall-error", EA
->getUserDiagnostic());
2930 else if (EA
->isWarning())
2931 F
->addFnAttr("dontcall-warn", EA
->getUserDiagnostic());
2934 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2935 if (FD
->isInlineBuiltinDeclaration()) {
2936 const FunctionDecl
*FDBody
;
2937 bool HasBody
= FD
->hasBody(FDBody
);
2939 assert(HasBody
&& "Inline builtin declarations should always have an "
2941 if (shouldEmitFunction(FDBody
))
2942 F
->addFnAttr(llvm::Attribute::NoBuiltin
);
2945 if (FD
->isReplaceableGlobalAllocationFunction()) {
2946 // A replaceable global allocation function does not act like a builtin by
2947 // default, only if it is invoked by a new-expression or delete-expression.
2948 F
->addFnAttr(llvm::Attribute::NoBuiltin
);
2951 if (isa
<CXXConstructorDecl
>(FD
) || isa
<CXXDestructorDecl
>(FD
))
2952 F
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
2953 else if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
))
2954 if (MD
->isVirtual())
2955 F
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
2957 // Don't emit entries for function declarations in the cross-DSO mode. This
2958 // is handled with better precision by the receiving DSO. But if jump tables
2959 // are non-canonical then we need type metadata in order to produce the local
2961 if (!CodeGenOpts
.SanitizeCfiCrossDso
||
2962 !CodeGenOpts
.SanitizeCfiCanonicalJumpTables
)
2963 CreateFunctionTypeMetadataForIcall(FD
, F
);
2965 if (LangOpts
.Sanitize
.has(SanitizerKind::KCFI
))
2968 if (getLangOpts().OpenMP
&& FD
->hasAttr
<OMPDeclareSimdDeclAttr
>())
2969 getOpenMPRuntime().emitDeclareSimdFunction(FD
, F
);
2971 if (CodeGenOpts
.InlineMaxStackSize
!= UINT_MAX
)
2972 F
->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts
.InlineMaxStackSize
));
2974 if (const auto *CB
= FD
->getAttr
<CallbackAttr
>()) {
2975 // Annotate the callback behavior as metadata:
2976 // - The callback callee (as argument number).
2977 // - The callback payloads (as argument numbers).
2978 llvm::LLVMContext
&Ctx
= F
->getContext();
2979 llvm::MDBuilder
MDB(Ctx
);
2981 // The payload indices are all but the first one in the encoding. The first
2982 // identifies the callback callee.
2983 int CalleeIdx
= *CB
->encoding_begin();
2984 ArrayRef
<int> PayloadIndices(CB
->encoding_begin() + 1, CB
->encoding_end());
2985 F
->addMetadata(llvm::LLVMContext::MD_callback
,
2986 *llvm::MDNode::get(Ctx
, {MDB
.createCallbackEncoding(
2987 CalleeIdx
, PayloadIndices
,
2988 /* VarArgsArePassed */ false)}));
2992 void CodeGenModule::addUsedGlobal(llvm::GlobalValue
*GV
) {
2993 assert((isa
<llvm::Function
>(GV
) || !GV
->isDeclaration()) &&
2994 "Only globals with definition can force usage.");
2995 LLVMUsed
.emplace_back(GV
);
2998 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue
*GV
) {
2999 assert(!GV
->isDeclaration() &&
3000 "Only globals with definition can force usage.");
3001 LLVMCompilerUsed
.emplace_back(GV
);
3004 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue
*GV
) {
3005 assert((isa
<llvm::Function
>(GV
) || !GV
->isDeclaration()) &&
3006 "Only globals with definition can force usage.");
3007 if (getTriple().isOSBinFormatELF())
3008 LLVMCompilerUsed
.emplace_back(GV
);
3010 LLVMUsed
.emplace_back(GV
);
3013 static void emitUsed(CodeGenModule
&CGM
, StringRef Name
,
3014 std::vector
<llvm::WeakTrackingVH
> &List
) {
3015 // Don't create llvm.used if there is no need.
3019 // Convert List to what ConstantArray needs.
3020 SmallVector
<llvm::Constant
*, 8> UsedArray
;
3021 UsedArray
.resize(List
.size());
3022 for (unsigned i
= 0, e
= List
.size(); i
!= e
; ++i
) {
3024 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3025 cast
<llvm::Constant
>(&*List
[i
]), CGM
.Int8PtrTy
);
3028 if (UsedArray
.empty())
3030 llvm::ArrayType
*ATy
= llvm::ArrayType::get(CGM
.Int8PtrTy
, UsedArray
.size());
3032 auto *GV
= new llvm::GlobalVariable(
3033 CGM
.getModule(), ATy
, false, llvm::GlobalValue::AppendingLinkage
,
3034 llvm::ConstantArray::get(ATy
, UsedArray
), Name
);
3036 GV
->setSection("llvm.metadata");
3039 void CodeGenModule::emitLLVMUsed() {
3040 emitUsed(*this, "llvm.used", LLVMUsed
);
3041 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed
);
3044 void CodeGenModule::AppendLinkerOptions(StringRef Opts
) {
3045 auto *MDOpts
= llvm::MDString::get(getLLVMContext(), Opts
);
3046 LinkerOptionsMetadata
.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts
));
3049 void CodeGenModule::AddDetectMismatch(StringRef Name
, StringRef Value
) {
3050 llvm::SmallString
<32> Opt
;
3051 getTargetCodeGenInfo().getDetectMismatchOption(Name
, Value
, Opt
);
3054 auto *MDOpts
= llvm::MDString::get(getLLVMContext(), Opt
);
3055 LinkerOptionsMetadata
.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts
));
3058 void CodeGenModule::AddDependentLib(StringRef Lib
) {
3059 auto &C
= getLLVMContext();
3060 if (getTarget().getTriple().isOSBinFormatELF()) {
3061 ELFDependentLibraries
.push_back(
3062 llvm::MDNode::get(C
, llvm::MDString::get(C
, Lib
)));
3066 llvm::SmallString
<24> Opt
;
3067 getTargetCodeGenInfo().getDependentLibraryOption(Lib
, Opt
);
3068 auto *MDOpts
= llvm::MDString::get(getLLVMContext(), Opt
);
3069 LinkerOptionsMetadata
.push_back(llvm::MDNode::get(C
, MDOpts
));
3072 /// Add link options implied by the given module, including modules
3073 /// it depends on, using a postorder walk.
3074 static void addLinkOptionsPostorder(CodeGenModule
&CGM
, Module
*Mod
,
3075 SmallVectorImpl
<llvm::MDNode
*> &Metadata
,
3076 llvm::SmallPtrSet
<Module
*, 16> &Visited
) {
3077 // Import this module's parent.
3078 if (Mod
->Parent
&& Visited
.insert(Mod
->Parent
).second
) {
3079 addLinkOptionsPostorder(CGM
, Mod
->Parent
, Metadata
, Visited
);
3082 // Import this module's dependencies.
3083 for (Module
*Import
: llvm::reverse(Mod
->Imports
)) {
3084 if (Visited
.insert(Import
).second
)
3085 addLinkOptionsPostorder(CGM
, Import
, Metadata
, Visited
);
3088 // Add linker options to link against the libraries/frameworks
3089 // described by this module.
3090 llvm::LLVMContext
&Context
= CGM
.getLLVMContext();
3091 bool IsELF
= CGM
.getTarget().getTriple().isOSBinFormatELF();
3093 // For modules that use export_as for linking, use that module
3095 if (Mod
->UseExportAsModuleLinkName
)
3098 for (const Module::LinkLibrary
&LL
: llvm::reverse(Mod
->LinkLibraries
)) {
3099 // Link against a framework. Frameworks are currently Darwin only, so we
3100 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3101 if (LL
.IsFramework
) {
3102 llvm::Metadata
*Args
[2] = {llvm::MDString::get(Context
, "-framework"),
3103 llvm::MDString::get(Context
, LL
.Library
)};
3105 Metadata
.push_back(llvm::MDNode::get(Context
, Args
));
3109 // Link against a library.
3111 llvm::Metadata
*Args
[2] = {
3112 llvm::MDString::get(Context
, "lib"),
3113 llvm::MDString::get(Context
, LL
.Library
),
3115 Metadata
.push_back(llvm::MDNode::get(Context
, Args
));
3117 llvm::SmallString
<24> Opt
;
3118 CGM
.getTargetCodeGenInfo().getDependentLibraryOption(LL
.Library
, Opt
);
3119 auto *OptString
= llvm::MDString::get(Context
, Opt
);
3120 Metadata
.push_back(llvm::MDNode::get(Context
, OptString
));
3125 void CodeGenModule::EmitModuleInitializers(clang::Module
*Primary
) {
3126 assert(Primary
->isNamedModuleUnit() &&
3127 "We should only emit module initializers for named modules.");
3129 // Emit the initializers in the order that sub-modules appear in the
3130 // source, first Global Module Fragments, if present.
3131 if (auto GMF
= Primary
->getGlobalModuleFragment()) {
3132 for (Decl
*D
: getContext().getModuleInitializers(GMF
)) {
3133 if (isa
<ImportDecl
>(D
))
3135 assert(isa
<VarDecl
>(D
) && "GMF initializer decl is not a var?");
3136 EmitTopLevelDecl(D
);
3139 // Second any associated with the module, itself.
3140 for (Decl
*D
: getContext().getModuleInitializers(Primary
)) {
3141 // Skip import decls, the inits for those are called explicitly.
3142 if (isa
<ImportDecl
>(D
))
3144 EmitTopLevelDecl(D
);
3146 // Third any associated with the Privat eMOdule Fragment, if present.
3147 if (auto PMF
= Primary
->getPrivateModuleFragment()) {
3148 for (Decl
*D
: getContext().getModuleInitializers(PMF
)) {
3149 // Skip import decls, the inits for those are called explicitly.
3150 if (isa
<ImportDecl
>(D
))
3152 assert(isa
<VarDecl
>(D
) && "PMF initializer decl is not a var?");
3153 EmitTopLevelDecl(D
);
3158 void CodeGenModule::EmitModuleLinkOptions() {
3159 // Collect the set of all of the modules we want to visit to emit link
3160 // options, which is essentially the imported modules and all of their
3161 // non-explicit child modules.
3162 llvm::SetVector
<clang::Module
*> LinkModules
;
3163 llvm::SmallPtrSet
<clang::Module
*, 16> Visited
;
3164 SmallVector
<clang::Module
*, 16> Stack
;
3166 // Seed the stack with imported modules.
3167 for (Module
*M
: ImportedModules
) {
3168 // Do not add any link flags when an implementation TU of a module imports
3169 // a header of that same module.
3170 if (M
->getTopLevelModuleName() == getLangOpts().CurrentModule
&&
3171 !getLangOpts().isCompilingModule())
3173 if (Visited
.insert(M
).second
)
3177 // Find all of the modules to import, making a little effort to prune
3178 // non-leaf modules.
3179 while (!Stack
.empty()) {
3180 clang::Module
*Mod
= Stack
.pop_back_val();
3182 bool AnyChildren
= false;
3184 // Visit the submodules of this module.
3185 for (const auto &SM
: Mod
->submodules()) {
3186 // Skip explicit children; they need to be explicitly imported to be
3191 if (Visited
.insert(SM
).second
) {
3192 Stack
.push_back(SM
);
3197 // We didn't find any children, so add this module to the list of
3198 // modules to link against.
3200 LinkModules
.insert(Mod
);
3204 // Add link options for all of the imported modules in reverse topological
3205 // order. We don't do anything to try to order import link flags with respect
3206 // to linker options inserted by things like #pragma comment().
3207 SmallVector
<llvm::MDNode
*, 16> MetadataArgs
;
3209 for (Module
*M
: LinkModules
)
3210 if (Visited
.insert(M
).second
)
3211 addLinkOptionsPostorder(*this, M
, MetadataArgs
, Visited
);
3212 std::reverse(MetadataArgs
.begin(), MetadataArgs
.end());
3213 LinkerOptionsMetadata
.append(MetadataArgs
.begin(), MetadataArgs
.end());
3215 // Add the linker options metadata flag.
3216 auto *NMD
= getModule().getOrInsertNamedMetadata("llvm.linker.options");
3217 for (auto *MD
: LinkerOptionsMetadata
)
3218 NMD
->addOperand(MD
);
3221 void CodeGenModule::EmitDeferred() {
3222 // Emit deferred declare target declarations.
3223 if (getLangOpts().OpenMP
&& !getLangOpts().OpenMPSimd
)
3224 getOpenMPRuntime().emitDeferredTargetDecls();
3226 // Emit code for any potentially referenced deferred decls. Since a
3227 // previously unused static decl may become used during the generation of code
3228 // for a static function, iterate until no changes are made.
3230 if (!DeferredVTables
.empty()) {
3231 EmitDeferredVTables();
3233 // Emitting a vtable doesn't directly cause more vtables to
3234 // become deferred, although it can cause functions to be
3235 // emitted that then need those vtables.
3236 assert(DeferredVTables
.empty());
3239 // Emit CUDA/HIP static device variables referenced by host code only.
3240 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3241 // needed for further handling.
3242 if (getLangOpts().CUDA
&& getLangOpts().CUDAIsDevice
)
3243 llvm::append_range(DeferredDeclsToEmit
,
3244 getContext().CUDADeviceVarODRUsedByHost
);
3246 // Stop if we're out of both deferred vtables and deferred declarations.
3247 if (DeferredDeclsToEmit
.empty())
3250 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3251 // work, it will not interfere with this.
3252 std::vector
<GlobalDecl
> CurDeclsToEmit
;
3253 CurDeclsToEmit
.swap(DeferredDeclsToEmit
);
3255 for (GlobalDecl
&D
: CurDeclsToEmit
) {
3256 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3257 // to get GlobalValue with exactly the type we need, not something that
3258 // might had been created for another decl with the same mangled name but
3260 llvm::GlobalValue
*GV
= dyn_cast
<llvm::GlobalValue
>(
3261 GetAddrOfGlobal(D
, ForDefinition
));
3263 // In case of different address spaces, we may still get a cast, even with
3264 // IsForDefinition equal to true. Query mangled names table to get
3267 GV
= GetGlobalValue(getMangledName(D
));
3269 // Make sure GetGlobalValue returned non-null.
3272 // Check to see if we've already emitted this. This is necessary
3273 // for a couple of reasons: first, decls can end up in the
3274 // deferred-decls queue multiple times, and second, decls can end
3275 // up with definitions in unusual ways (e.g. by an extern inline
3276 // function acquiring a strong function redefinition). Just
3277 // ignore these cases.
3278 if (!GV
->isDeclaration())
3281 // If this is OpenMP, check if it is legal to emit this global normally.
3282 if (LangOpts
.OpenMP
&& OpenMPRuntime
&& OpenMPRuntime
->emitTargetGlobal(D
))
3285 // Otherwise, emit the definition and move on to the next one.
3286 EmitGlobalDefinition(D
, GV
);
3288 // If we found out that we need to emit more decls, do that recursively.
3289 // This has the advantage that the decls are emitted in a DFS and related
3290 // ones are close together, which is convenient for testing.
3291 if (!DeferredVTables
.empty() || !DeferredDeclsToEmit
.empty()) {
3293 assert(DeferredVTables
.empty() && DeferredDeclsToEmit
.empty());
3298 void CodeGenModule::EmitVTablesOpportunistically() {
3299 // Try to emit external vtables as available_externally if they have emitted
3300 // all inlined virtual functions. It runs after EmitDeferred() and therefore
3301 // is not allowed to create new references to things that need to be emitted
3302 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3304 assert((OpportunisticVTables
.empty() || shouldOpportunisticallyEmitVTables())
3305 && "Only emit opportunistic vtables with optimizations");
3307 for (const CXXRecordDecl
*RD
: OpportunisticVTables
) {
3308 assert(getVTables().isVTableExternal(RD
) &&
3309 "This queue should only contain external vtables");
3310 if (getCXXABI().canSpeculativelyEmitVTable(RD
))
3311 VTables
.GenerateClassData(RD
);
3313 OpportunisticVTables
.clear();
3316 void CodeGenModule::EmitGlobalAnnotations() {
3317 for (const auto& [MangledName
, VD
] : DeferredAnnotations
) {
3318 llvm::GlobalValue
*GV
= GetGlobalValue(MangledName
);
3320 AddGlobalAnnotations(VD
, GV
);
3322 DeferredAnnotations
.clear();
3324 if (Annotations
.empty())
3327 // Create a new global variable for the ConstantStruct in the Module.
3328 llvm::Constant
*Array
= llvm::ConstantArray::get(llvm::ArrayType::get(
3329 Annotations
[0]->getType(), Annotations
.size()), Annotations
);
3330 auto *gv
= new llvm::GlobalVariable(getModule(), Array
->getType(), false,
3331 llvm::GlobalValue::AppendingLinkage
,
3332 Array
, "llvm.global.annotations");
3333 gv
->setSection(AnnotationSection
);
3336 llvm::Constant
*CodeGenModule::EmitAnnotationString(StringRef Str
) {
3337 llvm::Constant
*&AStr
= AnnotationStrings
[Str
];
3341 // Not found yet, create a new global.
3342 llvm::Constant
*s
= llvm::ConstantDataArray::getString(getLLVMContext(), Str
);
3343 auto *gv
= new llvm::GlobalVariable(
3344 getModule(), s
->getType(), true, llvm::GlobalValue::PrivateLinkage
, s
,
3345 ".str", nullptr, llvm::GlobalValue::NotThreadLocal
,
3346 ConstGlobalsPtrTy
->getAddressSpace());
3347 gv
->setSection(AnnotationSection
);
3348 gv
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
3353 llvm::Constant
*CodeGenModule::EmitAnnotationUnit(SourceLocation Loc
) {
3354 SourceManager
&SM
= getContext().getSourceManager();
3355 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
);
3357 return EmitAnnotationString(PLoc
.getFilename());
3358 return EmitAnnotationString(SM
.getBufferName(Loc
));
3361 llvm::Constant
*CodeGenModule::EmitAnnotationLineNo(SourceLocation L
) {
3362 SourceManager
&SM
= getContext().getSourceManager();
3363 PresumedLoc PLoc
= SM
.getPresumedLoc(L
);
3364 unsigned LineNo
= PLoc
.isValid() ? PLoc
.getLine() :
3365 SM
.getExpansionLineNumber(L
);
3366 return llvm::ConstantInt::get(Int32Ty
, LineNo
);
3369 llvm::Constant
*CodeGenModule::EmitAnnotationArgs(const AnnotateAttr
*Attr
) {
3370 ArrayRef
<Expr
*> Exprs
= {Attr
->args_begin(), Attr
->args_size()};
3372 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy
);
3374 llvm::FoldingSetNodeID ID
;
3375 for (Expr
*E
: Exprs
) {
3376 ID
.Add(cast
<clang::ConstantExpr
>(E
)->getAPValueResult());
3378 llvm::Constant
*&Lookup
= AnnotationArgs
[ID
.ComputeHash()];
3382 llvm::SmallVector
<llvm::Constant
*, 4> LLVMArgs
;
3383 LLVMArgs
.reserve(Exprs
.size());
3384 ConstantEmitter
ConstEmiter(*this);
3385 llvm::transform(Exprs
, std::back_inserter(LLVMArgs
), [&](const Expr
*E
) {
3386 const auto *CE
= cast
<clang::ConstantExpr
>(E
);
3387 return ConstEmiter
.emitAbstract(CE
->getBeginLoc(), CE
->getAPValueResult(),
3390 auto *Struct
= llvm::ConstantStruct::getAnon(LLVMArgs
);
3391 auto *GV
= new llvm::GlobalVariable(getModule(), Struct
->getType(), true,
3392 llvm::GlobalValue::PrivateLinkage
, Struct
,
3394 GV
->setSection(AnnotationSection
);
3395 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
3401 llvm::Constant
*CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue
*GV
,
3402 const AnnotateAttr
*AA
,
3404 // Get the globals for file name, annotation, and the line number.
3405 llvm::Constant
*AnnoGV
= EmitAnnotationString(AA
->getAnnotation()),
3406 *UnitGV
= EmitAnnotationUnit(L
),
3407 *LineNoCst
= EmitAnnotationLineNo(L
),
3408 *Args
= EmitAnnotationArgs(AA
);
3410 llvm::Constant
*GVInGlobalsAS
= GV
;
3411 if (GV
->getAddressSpace() !=
3412 getDataLayout().getDefaultGlobalsAddressSpace()) {
3413 GVInGlobalsAS
= llvm::ConstantExpr::getAddrSpaceCast(
3415 llvm::PointerType::get(
3416 GV
->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3419 // Create the ConstantStruct for the global annotation.
3420 llvm::Constant
*Fields
[] = {
3421 GVInGlobalsAS
, AnnoGV
, UnitGV
, LineNoCst
, Args
,
3423 return llvm::ConstantStruct::getAnon(Fields
);
3426 void CodeGenModule::AddGlobalAnnotations(const ValueDecl
*D
,
3427 llvm::GlobalValue
*GV
) {
3428 assert(D
->hasAttr
<AnnotateAttr
>() && "no annotate attribute");
3429 // Get the struct elements for these annotations.
3430 for (const auto *I
: D
->specific_attrs
<AnnotateAttr
>())
3431 Annotations
.push_back(EmitAnnotateAttr(GV
, I
, D
->getLocation()));
3434 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind
, llvm::Function
*Fn
,
3435 SourceLocation Loc
) const {
3436 const auto &NoSanitizeL
= getContext().getNoSanitizeList();
3437 // NoSanitize by function name.
3438 if (NoSanitizeL
.containsFunction(Kind
, Fn
->getName()))
3440 // NoSanitize by location. Check "mainfile" prefix.
3441 auto &SM
= Context
.getSourceManager();
3442 FileEntryRef MainFile
= *SM
.getFileEntryRefForID(SM
.getMainFileID());
3443 if (NoSanitizeL
.containsMainFile(Kind
, MainFile
.getName()))
3446 // Check "src" prefix.
3448 return NoSanitizeL
.containsLocation(Kind
, Loc
);
3449 // If location is unknown, this may be a compiler-generated function. Assume
3450 // it's located in the main file.
3451 return NoSanitizeL
.containsFile(Kind
, MainFile
.getName());
3454 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind
,
3455 llvm::GlobalVariable
*GV
,
3456 SourceLocation Loc
, QualType Ty
,
3457 StringRef Category
) const {
3458 const auto &NoSanitizeL
= getContext().getNoSanitizeList();
3459 if (NoSanitizeL
.containsGlobal(Kind
, GV
->getName(), Category
))
3461 auto &SM
= Context
.getSourceManager();
3462 if (NoSanitizeL
.containsMainFile(
3463 Kind
, SM
.getFileEntryRefForID(SM
.getMainFileID())->getName(),
3466 if (NoSanitizeL
.containsLocation(Kind
, Loc
, Category
))
3469 // Check global type.
3471 // Drill down the array types: if global variable of a fixed type is
3472 // not sanitized, we also don't instrument arrays of them.
3473 while (auto AT
= dyn_cast
<ArrayType
>(Ty
.getTypePtr()))
3474 Ty
= AT
->getElementType();
3475 Ty
= Ty
.getCanonicalType().getUnqualifiedType();
3476 // Only record types (classes, structs etc.) are ignored.
3477 if (Ty
->isRecordType()) {
3478 std::string TypeStr
= Ty
.getAsString(getContext().getPrintingPolicy());
3479 if (NoSanitizeL
.containsType(Kind
, TypeStr
, Category
))
3486 bool CodeGenModule::imbueXRayAttrs(llvm::Function
*Fn
, SourceLocation Loc
,
3487 StringRef Category
) const {
3488 const auto &XRayFilter
= getContext().getXRayFilter();
3489 using ImbueAttr
= XRayFunctionFilter::ImbueAttribute
;
3490 auto Attr
= ImbueAttr::NONE
;
3492 Attr
= XRayFilter
.shouldImbueLocation(Loc
, Category
);
3493 if (Attr
== ImbueAttr::NONE
)
3494 Attr
= XRayFilter
.shouldImbueFunction(Fn
->getName());
3496 case ImbueAttr::NONE
:
3498 case ImbueAttr::ALWAYS
:
3499 Fn
->addFnAttr("function-instrument", "xray-always");
3501 case ImbueAttr::ALWAYS_ARG1
:
3502 Fn
->addFnAttr("function-instrument", "xray-always");
3503 Fn
->addFnAttr("xray-log-args", "1");
3505 case ImbueAttr::NEVER
:
3506 Fn
->addFnAttr("function-instrument", "xray-never");
3512 ProfileList::ExclusionType
3513 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function
*Fn
,
3514 SourceLocation Loc
) const {
3515 const auto &ProfileList
= getContext().getProfileList();
3516 // If the profile list is empty, then instrument everything.
3517 if (ProfileList
.isEmpty())
3518 return ProfileList::Allow
;
3519 CodeGenOptions::ProfileInstrKind Kind
= getCodeGenOpts().getProfileInstr();
3520 // First, check the function name.
3521 if (auto V
= ProfileList
.isFunctionExcluded(Fn
->getName(), Kind
))
3523 // Next, check the source location.
3525 if (auto V
= ProfileList
.isLocationExcluded(Loc
, Kind
))
3527 // If location is unknown, this may be a compiler-generated function. Assume
3528 // it's located in the main file.
3529 auto &SM
= Context
.getSourceManager();
3530 if (auto MainFile
= SM
.getFileEntryRefForID(SM
.getMainFileID()))
3531 if (auto V
= ProfileList
.isFileExcluded(MainFile
->getName(), Kind
))
3533 return ProfileList
.getDefault(Kind
);
3536 ProfileList::ExclusionType
3537 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function
*Fn
,
3538 SourceLocation Loc
) const {
3539 auto V
= isFunctionBlockedByProfileList(Fn
, Loc
);
3540 if (V
!= ProfileList::Allow
)
3543 auto NumGroups
= getCodeGenOpts().ProfileTotalFunctionGroups
;
3544 if (NumGroups
> 1) {
3545 auto Group
= llvm::crc32(arrayRefFromStringRef(Fn
->getName())) % NumGroups
;
3546 if (Group
!= getCodeGenOpts().ProfileSelectedFunctionGroup
)
3547 return ProfileList::Skip
;
3549 return ProfileList::Allow
;
3552 bool CodeGenModule::MustBeEmitted(const ValueDecl
*Global
) {
3553 // Never defer when EmitAllDecls is specified.
3554 if (LangOpts
.EmitAllDecls
)
3557 const auto *VD
= dyn_cast
<VarDecl
>(Global
);
3559 ((CodeGenOpts
.KeepPersistentStorageVariables
&&
3560 (VD
->getStorageDuration() == SD_Static
||
3561 VD
->getStorageDuration() == SD_Thread
)) ||
3562 (CodeGenOpts
.KeepStaticConsts
&& VD
->getStorageDuration() == SD_Static
&&
3563 VD
->getType().isConstQualified())))
3566 return getContext().DeclMustBeEmitted(Global
);
3569 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl
*Global
) {
3570 // In OpenMP 5.0 variables and function may be marked as
3571 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3572 // that they must be emitted on the host/device. To be sure we need to have
3573 // seen a declare target with an explicit mentioning of the function, we know
3574 // we have if the level of the declare target attribute is -1. Note that we
3575 // check somewhere else if we should emit this at all.
3576 if (LangOpts
.OpenMP
>= 50 && !LangOpts
.OpenMPSimd
) {
3577 std::optional
<OMPDeclareTargetDeclAttr
*> ActiveAttr
=
3578 OMPDeclareTargetDeclAttr::getActiveAttr(Global
);
3579 if (!ActiveAttr
|| (*ActiveAttr
)->getLevel() != (unsigned)-1)
3583 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Global
)) {
3584 if (FD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
3585 // Implicit template instantiations may change linkage if they are later
3586 // explicitly instantiated, so they should not be emitted eagerly.
3588 // Defer until all versions have been semantically checked.
3589 if (FD
->hasAttr
<TargetVersionAttr
>() && !FD
->isMultiVersion())
3592 if (const auto *VD
= dyn_cast
<VarDecl
>(Global
)) {
3593 if (Context
.getInlineVariableDefinitionKind(VD
) ==
3594 ASTContext::InlineVariableDefinitionKind::WeakUnknown
)
3595 // A definition of an inline constexpr static data member may change
3596 // linkage later if it's redeclared outside the class.
3598 if (CXX20ModuleInits
&& VD
->getOwningModule() &&
3599 !VD
->getOwningModule()->isModuleMapModule()) {
3600 // For CXX20, module-owned initializers need to be deferred, since it is
3601 // not known at this point if they will be run for the current module or
3602 // as part of the initializer for an imported one.
3606 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3607 // codegen for global variables, because they may be marked as threadprivate.
3608 if (LangOpts
.OpenMP
&& LangOpts
.OpenMPUseTLS
&&
3609 getContext().getTargetInfo().isTLSSupported() && isa
<VarDecl
>(Global
) &&
3610 !Global
->getType().isConstantStorage(getContext(), false, false) &&
3611 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global
))
3617 ConstantAddress
CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl
*GD
) {
3618 StringRef Name
= getMangledName(GD
);
3620 // The UUID descriptor should be pointer aligned.
3621 CharUnits Alignment
= CharUnits::fromQuantity(PointerAlignInBytes
);
3623 // Look for an existing global.
3624 if (llvm::GlobalVariable
*GV
= getModule().getNamedGlobal(Name
))
3625 return ConstantAddress(GV
, GV
->getValueType(), Alignment
);
3627 ConstantEmitter
Emitter(*this);
3628 llvm::Constant
*Init
;
3630 APValue
&V
= GD
->getAsAPValue();
3631 if (!V
.isAbsent()) {
3632 // If possible, emit the APValue version of the initializer. In particular,
3633 // this gets the type of the constant right.
3634 Init
= Emitter
.emitForInitializer(
3635 GD
->getAsAPValue(), GD
->getType().getAddressSpace(), GD
->getType());
3637 // As a fallback, directly construct the constant.
3638 // FIXME: This may get padding wrong under esoteric struct layout rules.
3639 // MSVC appears to create a complete type 'struct __s_GUID' that it
3640 // presumably uses to represent these constants.
3641 MSGuidDecl::Parts Parts
= GD
->getParts();
3642 llvm::Constant
*Fields
[4] = {
3643 llvm::ConstantInt::get(Int32Ty
, Parts
.Part1
),
3644 llvm::ConstantInt::get(Int16Ty
, Parts
.Part2
),
3645 llvm::ConstantInt::get(Int16Ty
, Parts
.Part3
),
3646 llvm::ConstantDataArray::getRaw(
3647 StringRef(reinterpret_cast<char *>(Parts
.Part4And5
), 8), 8,
3649 Init
= llvm::ConstantStruct::getAnon(Fields
);
3652 auto *GV
= new llvm::GlobalVariable(
3653 getModule(), Init
->getType(),
3654 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage
, Init
, Name
);
3655 if (supportsCOMDAT())
3656 GV
->setComdat(TheModule
.getOrInsertComdat(GV
->getName()));
3659 if (!V
.isAbsent()) {
3660 Emitter
.finalize(GV
);
3661 return ConstantAddress(GV
, GV
->getValueType(), Alignment
);
3664 llvm::Type
*Ty
= getTypes().ConvertTypeForMem(GD
->getType());
3665 return ConstantAddress(GV
, Ty
, Alignment
);
3668 ConstantAddress
CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3669 const UnnamedGlobalConstantDecl
*GCD
) {
3670 CharUnits Alignment
= getContext().getTypeAlignInChars(GCD
->getType());
3672 llvm::GlobalVariable
**Entry
= nullptr;
3673 Entry
= &UnnamedGlobalConstantDeclMap
[GCD
];
3675 return ConstantAddress(*Entry
, (*Entry
)->getValueType(), Alignment
);
3677 ConstantEmitter
Emitter(*this);
3678 llvm::Constant
*Init
;
3680 const APValue
&V
= GCD
->getValue();
3682 assert(!V
.isAbsent());
3683 Init
= Emitter
.emitForInitializer(V
, GCD
->getType().getAddressSpace(),
3686 auto *GV
= new llvm::GlobalVariable(getModule(), Init
->getType(),
3687 /*isConstant=*/true,
3688 llvm::GlobalValue::PrivateLinkage
, Init
,
3690 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
3691 GV
->setAlignment(Alignment
.getAsAlign());
3693 Emitter
.finalize(GV
);
3696 return ConstantAddress(GV
, GV
->getValueType(), Alignment
);
3699 ConstantAddress
CodeGenModule::GetAddrOfTemplateParamObject(
3700 const TemplateParamObjectDecl
*TPO
) {
3701 StringRef Name
= getMangledName(TPO
);
3702 CharUnits Alignment
= getNaturalTypeAlignment(TPO
->getType());
3704 if (llvm::GlobalVariable
*GV
= getModule().getNamedGlobal(Name
))
3705 return ConstantAddress(GV
, GV
->getValueType(), Alignment
);
3707 ConstantEmitter
Emitter(*this);
3708 llvm::Constant
*Init
= Emitter
.emitForInitializer(
3709 TPO
->getValue(), TPO
->getType().getAddressSpace(), TPO
->getType());
3712 ErrorUnsupported(TPO
, "template parameter object");
3713 return ConstantAddress::invalid();
3716 llvm::GlobalValue::LinkageTypes Linkage
=
3717 isExternallyVisible(TPO
->getLinkageAndVisibility().getLinkage())
3718 ? llvm::GlobalValue::LinkOnceODRLinkage
3719 : llvm::GlobalValue::InternalLinkage
;
3720 auto *GV
= new llvm::GlobalVariable(getModule(), Init
->getType(),
3721 /*isConstant=*/true, Linkage
, Init
, Name
);
3722 setGVProperties(GV
, TPO
);
3723 if (supportsCOMDAT())
3724 GV
->setComdat(TheModule
.getOrInsertComdat(GV
->getName()));
3725 Emitter
.finalize(GV
);
3727 return ConstantAddress(GV
, GV
->getValueType(), Alignment
);
3730 ConstantAddress
CodeGenModule::GetWeakRefReference(const ValueDecl
*VD
) {
3731 const AliasAttr
*AA
= VD
->getAttr
<AliasAttr
>();
3732 assert(AA
&& "No alias?");
3734 CharUnits Alignment
= getContext().getDeclAlign(VD
);
3735 llvm::Type
*DeclTy
= getTypes().ConvertTypeForMem(VD
->getType());
3737 // See if there is already something with the target's name in the module.
3738 llvm::GlobalValue
*Entry
= GetGlobalValue(AA
->getAliasee());
3740 return ConstantAddress(Entry
, DeclTy
, Alignment
);
3742 llvm::Constant
*Aliasee
;
3743 if (isa
<llvm::FunctionType
>(DeclTy
))
3744 Aliasee
= GetOrCreateLLVMFunction(AA
->getAliasee(), DeclTy
,
3745 GlobalDecl(cast
<FunctionDecl
>(VD
)),
3746 /*ForVTable=*/false);
3748 Aliasee
= GetOrCreateLLVMGlobal(AA
->getAliasee(), DeclTy
, LangAS::Default
,
3751 auto *F
= cast
<llvm::GlobalValue
>(Aliasee
);
3752 F
->setLinkage(llvm::Function::ExternalWeakLinkage
);
3753 WeakRefReferences
.insert(F
);
3755 return ConstantAddress(Aliasee
, DeclTy
, Alignment
);
3758 template <typename AttrT
> static bool hasImplicitAttr(const ValueDecl
*D
) {
3761 if (auto *A
= D
->getAttr
<AttrT
>())
3762 return A
->isImplicit();
3763 return D
->isImplicit();
3766 bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl
*Global
) const {
3767 assert(LangOpts
.CUDA
&& "Should not be called by non-CUDA languages");
3768 // We need to emit host-side 'shadows' for all global
3769 // device-side variables because the CUDA runtime needs their
3770 // size and host-side address in order to provide access to
3771 // their device-side incarnations.
3772 return !LangOpts
.CUDAIsDevice
|| Global
->hasAttr
<CUDADeviceAttr
>() ||
3773 Global
->hasAttr
<CUDAConstantAttr
>() ||
3774 Global
->hasAttr
<CUDASharedAttr
>() ||
3775 Global
->getType()->isCUDADeviceBuiltinSurfaceType() ||
3776 Global
->getType()->isCUDADeviceBuiltinTextureType();
3779 void CodeGenModule::EmitGlobal(GlobalDecl GD
) {
3780 const auto *Global
= cast
<ValueDecl
>(GD
.getDecl());
3782 // Weak references don't produce any output by themselves.
3783 if (Global
->hasAttr
<WeakRefAttr
>())
3786 // If this is an alias definition (which otherwise looks like a declaration)
3788 if (Global
->hasAttr
<AliasAttr
>())
3789 return EmitAliasDefinition(GD
);
3791 // IFunc like an alias whose value is resolved at runtime by calling resolver.
3792 if (Global
->hasAttr
<IFuncAttr
>())
3793 return emitIFuncDefinition(GD
);
3795 // If this is a cpu_dispatch multiversion function, emit the resolver.
3796 if (Global
->hasAttr
<CPUDispatchAttr
>())
3797 return emitCPUDispatchDefinition(GD
);
3799 // If this is CUDA, be selective about which declarations we emit.
3800 // Non-constexpr non-lambda implicit host device functions are not emitted
3801 // unless they are used on device side.
3802 if (LangOpts
.CUDA
) {
3803 assert((isa
<FunctionDecl
>(Global
) || isa
<VarDecl
>(Global
)) &&
3804 "Expected Variable or Function");
3805 if (const auto *VD
= dyn_cast
<VarDecl
>(Global
)) {
3806 if (!shouldEmitCUDAGlobalVar(VD
))
3808 } else if (LangOpts
.CUDAIsDevice
) {
3809 const auto *FD
= dyn_cast
<FunctionDecl
>(Global
);
3810 if ((!Global
->hasAttr
<CUDADeviceAttr
>() ||
3811 (LangOpts
.OffloadImplicitHostDeviceTemplates
&&
3812 hasImplicitAttr
<CUDAHostAttr
>(FD
) &&
3813 hasImplicitAttr
<CUDADeviceAttr
>(FD
) && !FD
->isConstexpr() &&
3814 !isLambdaCallOperator(FD
) &&
3815 !getContext().CUDAImplicitHostDeviceFunUsedByDevice
.count(FD
))) &&
3816 !Global
->hasAttr
<CUDAGlobalAttr
>() &&
3817 !(LangOpts
.HIPStdPar
&& isa
<FunctionDecl
>(Global
) &&
3818 !Global
->hasAttr
<CUDAHostAttr
>()))
3820 // Device-only functions are the only things we skip.
3821 } else if (!Global
->hasAttr
<CUDAHostAttr
>() &&
3822 Global
->hasAttr
<CUDADeviceAttr
>())
3826 if (LangOpts
.OpenMP
) {
3827 // If this is OpenMP, check if it is legal to emit this global normally.
3828 if (OpenMPRuntime
&& OpenMPRuntime
->emitTargetGlobal(GD
))
3830 if (auto *DRD
= dyn_cast
<OMPDeclareReductionDecl
>(Global
)) {
3831 if (MustBeEmitted(Global
))
3832 EmitOMPDeclareReduction(DRD
);
3835 if (auto *DMD
= dyn_cast
<OMPDeclareMapperDecl
>(Global
)) {
3836 if (MustBeEmitted(Global
))
3837 EmitOMPDeclareMapper(DMD
);
3842 // Ignore declarations, they will be emitted on their first use.
3843 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Global
)) {
3844 // Update deferred annotations with the latest declaration if the function
3845 // function was already used or defined.
3846 if (FD
->hasAttr
<AnnotateAttr
>()) {
3847 StringRef MangledName
= getMangledName(GD
);
3848 if (GetGlobalValue(MangledName
))
3849 DeferredAnnotations
[MangledName
] = FD
;
3852 // Forward declarations are emitted lazily on first use.
3853 if (!FD
->doesThisDeclarationHaveABody()) {
3854 if (!FD
->doesDeclarationForceExternallyVisibleDefinition() &&
3855 (!FD
->isMultiVersion() || !getTarget().getTriple().isAArch64()))
3858 StringRef MangledName
= getMangledName(GD
);
3860 // Compute the function info and LLVM type.
3861 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(GD
);
3862 llvm::Type
*Ty
= getTypes().GetFunctionType(FI
);
3864 GetOrCreateLLVMFunction(MangledName
, Ty
, GD
, /*ForVTable=*/false,
3865 /*DontDefer=*/false);
3869 const auto *VD
= cast
<VarDecl
>(Global
);
3870 assert(VD
->isFileVarDecl() && "Cannot emit local var decl as global.");
3871 if (VD
->isThisDeclarationADefinition() != VarDecl::Definition
&&
3872 !Context
.isMSStaticDataMemberInlineDefinition(VD
)) {
3873 if (LangOpts
.OpenMP
) {
3874 // Emit declaration of the must-be-emitted declare target variable.
3875 if (std::optional
<OMPDeclareTargetDeclAttr::MapTypeTy
> Res
=
3876 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD
)) {
3878 // If this variable has external storage and doesn't require special
3879 // link handling we defer to its canonical definition.
3880 if (VD
->hasExternalStorage() &&
3881 Res
!= OMPDeclareTargetDeclAttr::MT_Link
)
3884 bool UnifiedMemoryEnabled
=
3885 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3886 if ((*Res
== OMPDeclareTargetDeclAttr::MT_To
||
3887 *Res
== OMPDeclareTargetDeclAttr::MT_Enter
) &&
3888 !UnifiedMemoryEnabled
) {
3889 (void)GetAddrOfGlobalVar(VD
);
3891 assert(((*Res
== OMPDeclareTargetDeclAttr::MT_Link
) ||
3892 ((*Res
== OMPDeclareTargetDeclAttr::MT_To
||
3893 *Res
== OMPDeclareTargetDeclAttr::MT_Enter
) &&
3894 UnifiedMemoryEnabled
)) &&
3895 "Link clause or to clause with unified memory expected.");
3896 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD
);
3902 // If this declaration may have caused an inline variable definition to
3903 // change linkage, make sure that it's emitted.
3904 if (Context
.getInlineVariableDefinitionKind(VD
) ==
3905 ASTContext::InlineVariableDefinitionKind::Strong
)
3906 GetAddrOfGlobalVar(VD
);
3911 // Defer code generation to first use when possible, e.g. if this is an inline
3912 // function. If the global must always be emitted, do it eagerly if possible
3913 // to benefit from cache locality.
3914 if (MustBeEmitted(Global
) && MayBeEmittedEagerly(Global
)) {
3915 // Emit the definition if it can't be deferred.
3916 EmitGlobalDefinition(GD
);
3917 addEmittedDeferredDecl(GD
);
3921 // If we're deferring emission of a C++ variable with an
3922 // initializer, remember the order in which it appeared in the file.
3923 if (getLangOpts().CPlusPlus
&& isa
<VarDecl
>(Global
) &&
3924 cast
<VarDecl
>(Global
)->hasInit()) {
3925 DelayedCXXInitPosition
[Global
] = CXXGlobalInits
.size();
3926 CXXGlobalInits
.push_back(nullptr);
3929 StringRef MangledName
= getMangledName(GD
);
3930 if (GetGlobalValue(MangledName
) != nullptr) {
3931 // The value has already been used and should therefore be emitted.
3932 addDeferredDeclToEmit(GD
);
3933 } else if (MustBeEmitted(Global
)) {
3934 // The value must be emitted, but cannot be emitted eagerly.
3935 assert(!MayBeEmittedEagerly(Global
));
3936 addDeferredDeclToEmit(GD
);
3938 // Otherwise, remember that we saw a deferred decl with this name. The
3939 // first use of the mangled name will cause it to move into
3940 // DeferredDeclsToEmit.
3941 DeferredDecls
[MangledName
] = GD
;
3945 // Check if T is a class type with a destructor that's not dllimport.
3946 static bool HasNonDllImportDtor(QualType T
) {
3947 if (const auto *RT
= T
->getBaseElementTypeUnsafe()->getAs
<RecordType
>())
3948 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl()))
3949 if (RD
->getDestructor() && !RD
->getDestructor()->hasAttr
<DLLImportAttr
>())
3956 struct FunctionIsDirectlyRecursive
3957 : public ConstStmtVisitor
<FunctionIsDirectlyRecursive
, bool> {
3958 const StringRef Name
;
3959 const Builtin::Context
&BI
;
3960 FunctionIsDirectlyRecursive(StringRef N
, const Builtin::Context
&C
)
3963 bool VisitCallExpr(const CallExpr
*E
) {
3964 const FunctionDecl
*FD
= E
->getDirectCallee();
3967 AsmLabelAttr
*Attr
= FD
->getAttr
<AsmLabelAttr
>();
3968 if (Attr
&& Name
== Attr
->getLabel())
3970 unsigned BuiltinID
= FD
->getBuiltinID();
3971 if (!BuiltinID
|| !BI
.isLibFunction(BuiltinID
))
3973 StringRef BuiltinName
= BI
.getName(BuiltinID
);
3974 if (BuiltinName
.starts_with("__builtin_") &&
3975 Name
== BuiltinName
.slice(strlen("__builtin_"), StringRef::npos
)) {
3981 bool VisitStmt(const Stmt
*S
) {
3982 for (const Stmt
*Child
: S
->children())
3983 if (Child
&& this->Visit(Child
))
3989 // Make sure we're not referencing non-imported vars or functions.
3990 struct DLLImportFunctionVisitor
3991 : public RecursiveASTVisitor
<DLLImportFunctionVisitor
> {
3992 bool SafeToInline
= true;
3994 bool shouldVisitImplicitCode() const { return true; }
3996 bool VisitVarDecl(VarDecl
*VD
) {
3997 if (VD
->getTLSKind()) {
3998 // A thread-local variable cannot be imported.
3999 SafeToInline
= false;
4000 return SafeToInline
;
4003 // A variable definition might imply a destructor call.
4004 if (VD
->isThisDeclarationADefinition())
4005 SafeToInline
= !HasNonDllImportDtor(VD
->getType());
4007 return SafeToInline
;
4010 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr
*E
) {
4011 if (const auto *D
= E
->getTemporary()->getDestructor())
4012 SafeToInline
= D
->hasAttr
<DLLImportAttr
>();
4013 return SafeToInline
;
4016 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
4017 ValueDecl
*VD
= E
->getDecl();
4018 if (isa
<FunctionDecl
>(VD
))
4019 SafeToInline
= VD
->hasAttr
<DLLImportAttr
>();
4020 else if (VarDecl
*V
= dyn_cast
<VarDecl
>(VD
))
4021 SafeToInline
= !V
->hasGlobalStorage() || V
->hasAttr
<DLLImportAttr
>();
4022 return SafeToInline
;
4025 bool VisitCXXConstructExpr(CXXConstructExpr
*E
) {
4026 SafeToInline
= E
->getConstructor()->hasAttr
<DLLImportAttr
>();
4027 return SafeToInline
;
4030 bool VisitCXXMemberCallExpr(CXXMemberCallExpr
*E
) {
4031 CXXMethodDecl
*M
= E
->getMethodDecl();
4033 // Call through a pointer to member function. This is safe to inline.
4034 SafeToInline
= true;
4036 SafeToInline
= M
->hasAttr
<DLLImportAttr
>();
4038 return SafeToInline
;
4041 bool VisitCXXDeleteExpr(CXXDeleteExpr
*E
) {
4042 SafeToInline
= E
->getOperatorDelete()->hasAttr
<DLLImportAttr
>();
4043 return SafeToInline
;
4046 bool VisitCXXNewExpr(CXXNewExpr
*E
) {
4047 SafeToInline
= E
->getOperatorNew()->hasAttr
<DLLImportAttr
>();
4048 return SafeToInline
;
4053 // isTriviallyRecursive - Check if this function calls another
4054 // decl that, because of the asm attribute or the other decl being a builtin,
4055 // ends up pointing to itself.
4057 CodeGenModule::isTriviallyRecursive(const FunctionDecl
*FD
) {
4059 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD
)) {
4060 // asm labels are a special kind of mangling we have to support.
4061 AsmLabelAttr
*Attr
= FD
->getAttr
<AsmLabelAttr
>();
4064 Name
= Attr
->getLabel();
4066 Name
= FD
->getName();
4069 FunctionIsDirectlyRecursive
Walker(Name
, Context
.BuiltinInfo
);
4070 const Stmt
*Body
= FD
->getBody();
4071 return Body
? Walker
.Visit(Body
) : false;
4074 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD
) {
4075 if (getFunctionLinkage(GD
) != llvm::Function::AvailableExternallyLinkage
)
4078 const auto *F
= cast
<FunctionDecl
>(GD
.getDecl());
4079 // Inline builtins declaration must be emitted. They often are fortified
4081 if (F
->isInlineBuiltinDeclaration())
4084 if (CodeGenOpts
.OptimizationLevel
== 0 && !F
->hasAttr
<AlwaysInlineAttr
>())
4087 // We don't import function bodies from other named module units since that
4088 // behavior may break ABI compatibility of the current unit.
4089 if (const Module
*M
= F
->getOwningModule();
4090 M
&& M
->getTopLevelModule()->isNamedModule() &&
4091 getContext().getCurrentNamedModule() != M
->getTopLevelModule()) {
4092 // There are practices to mark template member function as always-inline
4093 // and mark the template as extern explicit instantiation but not give
4094 // the definition for member function. So we have to emit the function
4095 // from explicitly instantiation with always-inline.
4097 // See https://github.com/llvm/llvm-project/issues/86893 for details.
4099 // TODO: Maybe it is better to give it a warning if we call a non-inline
4100 // function from other module units which is marked as always-inline.
4101 if (!F
->isTemplateInstantiation() || !F
->hasAttr
<AlwaysInlineAttr
>()) {
4106 if (F
->hasAttr
<NoInlineAttr
>())
4109 if (F
->hasAttr
<DLLImportAttr
>() && !F
->hasAttr
<AlwaysInlineAttr
>()) {
4110 // Check whether it would be safe to inline this dllimport function.
4111 DLLImportFunctionVisitor Visitor
;
4112 Visitor
.TraverseFunctionDecl(const_cast<FunctionDecl
*>(F
));
4113 if (!Visitor
.SafeToInline
)
4116 if (const CXXDestructorDecl
*Dtor
= dyn_cast
<CXXDestructorDecl
>(F
)) {
4117 // Implicit destructor invocations aren't captured in the AST, so the
4118 // check above can't see them. Check for them manually here.
4119 for (const Decl
*Member
: Dtor
->getParent()->decls())
4120 if (isa
<FieldDecl
>(Member
))
4121 if (HasNonDllImportDtor(cast
<FieldDecl
>(Member
)->getType()))
4123 for (const CXXBaseSpecifier
&B
: Dtor
->getParent()->bases())
4124 if (HasNonDllImportDtor(B
.getType()))
4129 // PR9614. Avoid cases where the source code is lying to us. An available
4130 // externally function should have an equivalent function somewhere else,
4131 // but a function that calls itself through asm label/`__builtin_` trickery is
4132 // clearly not equivalent to the real implementation.
4133 // This happens in glibc's btowc and in some configure checks.
4134 return !isTriviallyRecursive(F
);
4137 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4138 return CodeGenOpts
.OptimizationLevel
> 0;
4141 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD
,
4142 llvm::GlobalValue
*GV
) {
4143 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4145 if (FD
->isCPUSpecificMultiVersion()) {
4146 auto *Spec
= FD
->getAttr
<CPUSpecificAttr
>();
4147 for (unsigned I
= 0; I
< Spec
->cpus_size(); ++I
)
4148 EmitGlobalFunctionDefinition(GD
.getWithMultiVersionIndex(I
), nullptr);
4149 } else if (auto *TC
= FD
->getAttr
<TargetClonesAttr
>()) {
4150 for (unsigned I
= 0; I
< TC
->featuresStrs_size(); ++I
)
4151 // AArch64 favors the default target version over the clone if any.
4152 if ((!TC
->isDefaultVersion(I
) || !getTarget().getTriple().isAArch64()) &&
4153 TC
->isFirstOfVersion(I
))
4154 EmitGlobalFunctionDefinition(GD
.getWithMultiVersionIndex(I
), nullptr);
4155 // Ensure that the resolver function is also emitted.
4156 GetOrCreateMultiVersionResolver(GD
);
4158 EmitGlobalFunctionDefinition(GD
, GV
);
4160 // Defer the resolver emission until we can reason whether the TU
4161 // contains a default target version implementation.
4162 if (FD
->isTargetVersionMultiVersion())
4163 AddDeferredMultiVersionResolverToEmit(GD
);
4166 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD
, llvm::GlobalValue
*GV
) {
4167 const auto *D
= cast
<ValueDecl
>(GD
.getDecl());
4169 PrettyStackTraceDecl
CrashInfo(const_cast<ValueDecl
*>(D
), D
->getLocation(),
4170 Context
.getSourceManager(),
4171 "Generating code for declaration");
4173 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
4174 // At -O0, don't generate IR for functions with available_externally
4176 if (!shouldEmitFunction(GD
))
4179 llvm::TimeTraceScope
TimeScope("CodeGen Function", [&]() {
4181 llvm::raw_string_ostream
OS(Name
);
4182 FD
->getNameForDiagnostic(OS
, getContext().getPrintingPolicy(),
4183 /*Qualified=*/true);
4187 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
4188 // Make sure to emit the definition(s) before we emit the thunks.
4189 // This is necessary for the generation of certain thunks.
4190 if (isa
<CXXConstructorDecl
>(Method
) || isa
<CXXDestructorDecl
>(Method
))
4191 ABI
->emitCXXStructor(GD
);
4192 else if (FD
->isMultiVersion())
4193 EmitMultiVersionFunctionDefinition(GD
, GV
);
4195 EmitGlobalFunctionDefinition(GD
, GV
);
4197 if (Method
->isVirtual())
4198 getVTables().EmitThunks(GD
);
4203 if (FD
->isMultiVersion())
4204 return EmitMultiVersionFunctionDefinition(GD
, GV
);
4205 return EmitGlobalFunctionDefinition(GD
, GV
);
4208 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
4209 return EmitGlobalVarDefinition(VD
, !VD
->hasDefinition());
4211 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4214 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue
*Old
,
4215 llvm::Function
*NewFn
);
4218 TargetMVPriority(const TargetInfo
&TI
,
4219 const CodeGenFunction::MultiVersionResolverOption
&RO
) {
4220 unsigned Priority
= 0;
4221 unsigned NumFeatures
= 0;
4222 for (StringRef Feat
: RO
.Conditions
.Features
) {
4223 Priority
= std::max(Priority
, TI
.multiVersionSortPriority(Feat
));
4227 if (!RO
.Conditions
.Architecture
.empty())
4228 Priority
= std::max(
4229 Priority
, TI
.multiVersionSortPriority(RO
.Conditions
.Architecture
));
4231 Priority
+= TI
.multiVersionFeatureCost() * NumFeatures
;
4236 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4237 // TU can forward declare the function without causing problems. Particularly
4238 // in the cases of CPUDispatch, this causes issues. This also makes sure we
4239 // work with internal linkage functions, so that the same function name can be
4240 // used with internal linkage in multiple TUs.
4241 static llvm::GlobalValue::LinkageTypes
4242 getMultiversionLinkage(CodeGenModule
&CGM
, GlobalDecl GD
) {
4243 const FunctionDecl
*FD
= cast
<FunctionDecl
>(GD
.getDecl());
4244 if (FD
->getFormalLinkage() == Linkage::Internal
)
4245 return llvm::GlobalValue::InternalLinkage
;
4246 return llvm::GlobalValue::WeakODRLinkage
;
4249 void CodeGenModule::emitMultiVersionFunctions() {
4250 std::vector
<GlobalDecl
> MVFuncsToEmit
;
4251 MultiVersionFuncs
.swap(MVFuncsToEmit
);
4252 for (GlobalDecl GD
: MVFuncsToEmit
) {
4253 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4254 assert(FD
&& "Expected a FunctionDecl");
4256 auto createFunction
= [&](const FunctionDecl
*Decl
, unsigned MVIdx
= 0) {
4257 GlobalDecl CurGD
{Decl
->isDefined() ? Decl
->getDefinition() : Decl
, MVIdx
};
4258 StringRef MangledName
= getMangledName(CurGD
);
4259 llvm::Constant
*Func
= GetGlobalValue(MangledName
);
4261 if (Decl
->isDefined()) {
4262 EmitGlobalFunctionDefinition(CurGD
, nullptr);
4263 Func
= GetGlobalValue(MangledName
);
4265 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(CurGD
);
4266 llvm::FunctionType
*Ty
= getTypes().GetFunctionType(FI
);
4267 Func
= GetAddrOfFunction(CurGD
, Ty
, /*ForVTable=*/false,
4268 /*DontDefer=*/false, ForDefinition
);
4270 assert(Func
&& "This should have just been created");
4272 return cast
<llvm::Function
>(Func
);
4275 // For AArch64, a resolver is only emitted if a function marked with
4276 // target_version("default")) or target_clones() is present and defined
4277 // in this TU. For other architectures it is always emitted.
4278 bool ShouldEmitResolver
= !getTarget().getTriple().isAArch64();
4279 SmallVector
<CodeGenFunction::MultiVersionResolverOption
, 10> Options
;
4281 getContext().forEachMultiversionedFunctionVersion(
4282 FD
, [&](const FunctionDecl
*CurFD
) {
4283 llvm::SmallVector
<StringRef
, 8> Feats
;
4284 bool IsDefined
= CurFD
->doesThisDeclarationHaveABody();
4286 if (const auto *TA
= CurFD
->getAttr
<TargetAttr
>()) {
4287 TA
->getAddedFeatures(Feats
);
4288 llvm::Function
*Func
= createFunction(CurFD
);
4289 Options
.emplace_back(Func
, TA
->getArchitecture(), Feats
);
4290 } else if (const auto *TVA
= CurFD
->getAttr
<TargetVersionAttr
>()) {
4291 if (TVA
->isDefaultVersion() && IsDefined
)
4292 ShouldEmitResolver
= true;
4293 llvm::Function
*Func
= createFunction(CurFD
);
4294 if (getTarget().getTriple().isRISCV()) {
4295 Feats
.push_back(TVA
->getName());
4297 assert(getTarget().getTriple().isAArch64());
4298 TVA
->getFeatures(Feats
);
4300 Options
.emplace_back(Func
, /*Architecture*/ "", Feats
);
4301 } else if (const auto *TC
= CurFD
->getAttr
<TargetClonesAttr
>()) {
4303 ShouldEmitResolver
= true;
4304 for (unsigned I
= 0; I
< TC
->featuresStrs_size(); ++I
) {
4305 if (!TC
->isFirstOfVersion(I
))
4308 llvm::Function
*Func
= createFunction(CurFD
, I
);
4309 StringRef Architecture
;
4311 if (getTarget().getTriple().isAArch64())
4312 TC
->getFeatures(Feats
, I
);
4313 else if (getTarget().getTriple().isRISCV()) {
4314 StringRef Version
= TC
->getFeatureStr(I
);
4315 Feats
.push_back(Version
);
4317 StringRef Version
= TC
->getFeatureStr(I
);
4318 if (Version
.starts_with("arch="))
4319 Architecture
= Version
.drop_front(sizeof("arch=") - 1);
4320 else if (Version
!= "default")
4321 Feats
.push_back(Version
);
4323 Options
.emplace_back(Func
, Architecture
, Feats
);
4326 llvm_unreachable("unexpected MultiVersionKind");
4329 if (!ShouldEmitResolver
)
4332 llvm::Constant
*ResolverConstant
= GetOrCreateMultiVersionResolver(GD
);
4333 if (auto *IFunc
= dyn_cast
<llvm::GlobalIFunc
>(ResolverConstant
)) {
4334 ResolverConstant
= IFunc
->getResolver();
4335 if (FD
->isTargetClonesMultiVersion() &&
4336 !getTarget().getTriple().isAArch64()) {
4337 std::string MangledName
= getMangledNameImpl(
4338 *this, GD
, FD
, /*OmitMultiVersionMangling=*/true);
4339 if (!GetGlobalValue(MangledName
+ ".ifunc")) {
4340 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(GD
);
4341 llvm::FunctionType
*DeclTy
= getTypes().GetFunctionType(FI
);
4342 // In prior versions of Clang, the mangling for ifuncs incorrectly
4343 // included an .ifunc suffix. This alias is generated for backward
4344 // compatibility. It is deprecated, and may be removed in the future.
4345 auto *Alias
= llvm::GlobalAlias::create(
4346 DeclTy
, 0, getMultiversionLinkage(*this, GD
),
4347 MangledName
+ ".ifunc", IFunc
, &getModule());
4348 SetCommonAttributes(FD
, Alias
);
4352 llvm::Function
*ResolverFunc
= cast
<llvm::Function
>(ResolverConstant
);
4354 ResolverFunc
->setLinkage(getMultiversionLinkage(*this, GD
));
4356 if (!ResolverFunc
->hasLocalLinkage() && supportsCOMDAT())
4357 ResolverFunc
->setComdat(
4358 getModule().getOrInsertComdat(ResolverFunc
->getName()));
4360 const TargetInfo
&TI
= getTarget();
4362 Options
, [&TI
](const CodeGenFunction::MultiVersionResolverOption
&LHS
,
4363 const CodeGenFunction::MultiVersionResolverOption
&RHS
) {
4364 return TargetMVPriority(TI
, LHS
) > TargetMVPriority(TI
, RHS
);
4366 CodeGenFunction
CGF(*this);
4367 CGF
.EmitMultiVersionResolver(ResolverFunc
, Options
);
4370 // Ensure that any additions to the deferred decls list caused by emitting a
4371 // variant are emitted. This can happen when the variant itself is inline and
4372 // calls a function without linkage.
4373 if (!MVFuncsToEmit
.empty())
4376 // Ensure that any additions to the multiversion funcs list from either the
4377 // deferred decls or the multiversion functions themselves are emitted.
4378 if (!MultiVersionFuncs
.empty())
4379 emitMultiVersionFunctions();
4382 static void replaceDeclarationWith(llvm::GlobalValue
*Old
,
4383 llvm::Constant
*New
) {
4384 assert(cast
<llvm::Function
>(Old
)->isDeclaration() && "Not a declaration");
4386 Old
->replaceAllUsesWith(New
);
4387 Old
->eraseFromParent();
4390 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD
) {
4391 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4392 assert(FD
&& "Not a FunctionDecl?");
4393 assert(FD
->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4394 const auto *DD
= FD
->getAttr
<CPUDispatchAttr
>();
4395 assert(DD
&& "Not a cpu_dispatch Function?");
4397 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(GD
);
4398 llvm::FunctionType
*DeclTy
= getTypes().GetFunctionType(FI
);
4400 StringRef ResolverName
= getMangledName(GD
);
4401 UpdateMultiVersionNames(GD
, FD
, ResolverName
);
4403 llvm::Type
*ResolverType
;
4404 GlobalDecl ResolverGD
;
4405 if (getTarget().supportsIFunc()) {
4406 ResolverType
= llvm::FunctionType::get(
4407 llvm::PointerType::get(DeclTy
,
4408 getTypes().getTargetAddressSpace(FD
->getType())),
4412 ResolverType
= DeclTy
;
4416 auto *ResolverFunc
= cast
<llvm::Function
>(GetOrCreateLLVMFunction(
4417 ResolverName
, ResolverType
, ResolverGD
, /*ForVTable=*/false));
4418 ResolverFunc
->setLinkage(getMultiversionLinkage(*this, GD
));
4419 if (supportsCOMDAT())
4420 ResolverFunc
->setComdat(
4421 getModule().getOrInsertComdat(ResolverFunc
->getName()));
4423 SmallVector
<CodeGenFunction::MultiVersionResolverOption
, 10> Options
;
4424 const TargetInfo
&Target
= getTarget();
4426 for (const IdentifierInfo
*II
: DD
->cpus()) {
4427 // Get the name of the target function so we can look it up/create it.
4428 std::string MangledName
= getMangledNameImpl(*this, GD
, FD
, true) +
4429 getCPUSpecificMangling(*this, II
->getName());
4431 llvm::Constant
*Func
= GetGlobalValue(MangledName
);
4434 GlobalDecl ExistingDecl
= Manglings
.lookup(MangledName
);
4435 if (ExistingDecl
.getDecl() &&
4436 ExistingDecl
.getDecl()->getAsFunction()->isDefined()) {
4437 EmitGlobalFunctionDefinition(ExistingDecl
, nullptr);
4438 Func
= GetGlobalValue(MangledName
);
4440 if (!ExistingDecl
.getDecl())
4441 ExistingDecl
= GD
.getWithMultiVersionIndex(Index
);
4443 Func
= GetOrCreateLLVMFunction(
4444 MangledName
, DeclTy
, ExistingDecl
,
4445 /*ForVTable=*/false, /*DontDefer=*/true,
4446 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition
);
4450 llvm::SmallVector
<StringRef
, 32> Features
;
4451 Target
.getCPUSpecificCPUDispatchFeatures(II
->getName(), Features
);
4452 llvm::transform(Features
, Features
.begin(),
4453 [](StringRef Str
) { return Str
.substr(1); });
4454 llvm::erase_if(Features
, [&Target
](StringRef Feat
) {
4455 return !Target
.validateCpuSupports(Feat
);
4457 Options
.emplace_back(cast
<llvm::Function
>(Func
), StringRef
{}, Features
);
4462 Options
, [](const CodeGenFunction::MultiVersionResolverOption
&LHS
,
4463 const CodeGenFunction::MultiVersionResolverOption
&RHS
) {
4464 return llvm::X86::getCpuSupportsMask(LHS
.Conditions
.Features
) >
4465 llvm::X86::getCpuSupportsMask(RHS
.Conditions
.Features
);
4468 // If the list contains multiple 'default' versions, such as when it contains
4469 // 'pentium' and 'generic', don't emit the call to the generic one (since we
4470 // always run on at least a 'pentium'). We do this by deleting the 'least
4471 // advanced' (read, lowest mangling letter).
4472 while (Options
.size() > 1 &&
4473 llvm::all_of(llvm::X86::getCpuSupportsMask(
4474 (Options
.end() - 2)->Conditions
.Features
),
4475 [](auto X
) { return X
== 0; })) {
4476 StringRef LHSName
= (Options
.end() - 2)->Function
->getName();
4477 StringRef RHSName
= (Options
.end() - 1)->Function
->getName();
4478 if (LHSName
.compare(RHSName
) < 0)
4479 Options
.erase(Options
.end() - 2);
4481 Options
.erase(Options
.end() - 1);
4484 CodeGenFunction
CGF(*this);
4485 CGF
.EmitMultiVersionResolver(ResolverFunc
, Options
);
4487 if (getTarget().supportsIFunc()) {
4488 llvm::GlobalValue::LinkageTypes Linkage
= getMultiversionLinkage(*this, GD
);
4489 auto *IFunc
= cast
<llvm::GlobalValue
>(GetOrCreateMultiVersionResolver(GD
));
4490 unsigned AS
= IFunc
->getType()->getPointerAddressSpace();
4492 // Fix up function declarations that were created for cpu_specific before
4493 // cpu_dispatch was known
4494 if (!isa
<llvm::GlobalIFunc
>(IFunc
)) {
4495 auto *GI
= llvm::GlobalIFunc::create(DeclTy
, AS
, Linkage
, "",
4496 ResolverFunc
, &getModule());
4497 replaceDeclarationWith(IFunc
, GI
);
4501 std::string AliasName
= getMangledNameImpl(
4502 *this, GD
, FD
, /*OmitMultiVersionMangling=*/true);
4503 llvm::Constant
*AliasFunc
= GetGlobalValue(AliasName
);
4505 auto *GA
= llvm::GlobalAlias::create(DeclTy
, AS
, Linkage
, AliasName
,
4506 IFunc
, &getModule());
4507 SetCommonAttributes(GD
, GA
);
4512 /// Adds a declaration to the list of multi version functions if not present.
4513 void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD
) {
4514 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4515 assert(FD
&& "Not a FunctionDecl?");
4517 if (FD
->isTargetVersionMultiVersion() || FD
->isTargetClonesMultiVersion()) {
4518 std::string MangledName
=
4519 getMangledNameImpl(*this, GD
, FD
, /*OmitMultiVersionMangling=*/true);
4520 if (!DeferredResolversToEmit
.insert(MangledName
).second
)
4523 MultiVersionFuncs
.push_back(GD
);
4526 /// If a dispatcher for the specified mangled name is not in the module, create
4527 /// and return it. The dispatcher is either an llvm Function with the specified
4528 /// type, or a global ifunc.
4529 llvm::Constant
*CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD
) {
4530 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4531 assert(FD
&& "Not a FunctionDecl?");
4533 std::string MangledName
=
4534 getMangledNameImpl(*this, GD
, FD
, /*OmitMultiVersionMangling=*/true);
4536 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4537 // a separate resolver).
4538 std::string ResolverName
= MangledName
;
4539 if (getTarget().supportsIFunc()) {
4540 switch (FD
->getMultiVersionKind()) {
4541 case MultiVersionKind::None
:
4542 llvm_unreachable("unexpected MultiVersionKind::None for resolver");
4543 case MultiVersionKind::Target
:
4544 case MultiVersionKind::CPUSpecific
:
4545 case MultiVersionKind::CPUDispatch
:
4546 ResolverName
+= ".ifunc";
4548 case MultiVersionKind::TargetClones
:
4549 case MultiVersionKind::TargetVersion
:
4552 } else if (FD
->isTargetMultiVersion()) {
4553 ResolverName
+= ".resolver";
4556 // If the resolver has already been created, just return it. This lookup may
4557 // yield a function declaration instead of a resolver on AArch64. That is
4558 // because we didn't know whether a resolver will be generated when we first
4559 // encountered a use of the symbol named after this resolver. Therefore,
4560 // targets which support ifuncs should not return here unless we actually
4562 llvm::GlobalValue
*ResolverGV
= GetGlobalValue(ResolverName
);
4564 (isa
<llvm::GlobalIFunc
>(ResolverGV
) || !getTarget().supportsIFunc()))
4567 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(GD
);
4568 llvm::FunctionType
*DeclTy
= getTypes().GetFunctionType(FI
);
4570 // The resolver needs to be created. For target and target_clones, defer
4571 // creation until the end of the TU.
4572 if (FD
->isTargetMultiVersion() || FD
->isTargetClonesMultiVersion())
4573 AddDeferredMultiVersionResolverToEmit(GD
);
4575 // For cpu_specific, don't create an ifunc yet because we don't know if the
4576 // cpu_dispatch will be emitted in this translation unit.
4577 if (getTarget().supportsIFunc() && !FD
->isCPUSpecificMultiVersion()) {
4578 unsigned AS
= getTypes().getTargetAddressSpace(FD
->getType());
4579 llvm::Type
*ResolverType
=
4580 llvm::FunctionType::get(llvm::PointerType::get(DeclTy
, AS
), false);
4581 llvm::Constant
*Resolver
= GetOrCreateLLVMFunction(
4582 MangledName
+ ".resolver", ResolverType
, GlobalDecl
{},
4583 /*ForVTable=*/false);
4584 llvm::GlobalIFunc
*GIF
=
4585 llvm::GlobalIFunc::create(DeclTy
, AS
, getMultiversionLinkage(*this, GD
),
4586 "", Resolver
, &getModule());
4587 GIF
->setName(ResolverName
);
4588 SetCommonAttributes(FD
, GIF
);
4590 replaceDeclarationWith(ResolverGV
, GIF
);
4594 llvm::Constant
*Resolver
= GetOrCreateLLVMFunction(
4595 ResolverName
, DeclTy
, GlobalDecl
{}, /*ForVTable=*/false);
4596 assert(isa
<llvm::GlobalValue
>(Resolver
) &&
4597 "Resolver should be created for the first time");
4598 SetCommonAttributes(FD
, cast
<llvm::GlobalValue
>(Resolver
));
4600 replaceDeclarationWith(ResolverGV
, Resolver
);
4604 bool CodeGenModule::shouldDropDLLAttribute(const Decl
*D
,
4605 const llvm::GlobalValue
*GV
) const {
4606 auto SC
= GV
->getDLLStorageClass();
4607 if (SC
== llvm::GlobalValue::DefaultStorageClass
)
4609 const Decl
*MRD
= D
->getMostRecentDecl();
4610 return (((SC
== llvm::GlobalValue::DLLImportStorageClass
&&
4611 !MRD
->hasAttr
<DLLImportAttr
>()) ||
4612 (SC
== llvm::GlobalValue::DLLExportStorageClass
&&
4613 !MRD
->hasAttr
<DLLExportAttr
>())) &&
4614 !shouldMapVisibilityToDLLExport(cast
<NamedDecl
>(MRD
)));
4617 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
4618 /// module, create and return an llvm Function with the specified type. If there
4619 /// is something in the module with the specified name, return it potentially
4620 /// bitcasted to the right type.
4622 /// If D is non-null, it specifies a decl that correspond to this. This is used
4623 /// to set the attributes on the function when it is first created.
4624 llvm::Constant
*CodeGenModule::GetOrCreateLLVMFunction(
4625 StringRef MangledName
, llvm::Type
*Ty
, GlobalDecl GD
, bool ForVTable
,
4626 bool DontDefer
, bool IsThunk
, llvm::AttributeList ExtraAttrs
,
4627 ForDefinition_t IsForDefinition
) {
4628 const Decl
*D
= GD
.getDecl();
4630 std::string NameWithoutMultiVersionMangling
;
4631 // Any attempts to use a MultiVersion function should result in retrieving
4632 // the iFunc instead. Name Mangling will handle the rest of the changes.
4633 if (const FunctionDecl
*FD
= cast_or_null
<FunctionDecl
>(D
)) {
4634 // For the device mark the function as one that should be emitted.
4635 if (getLangOpts().OpenMPIsTargetDevice
&& OpenMPRuntime
&&
4636 !OpenMPRuntime
->markAsGlobalTarget(GD
) && FD
->isDefined() &&
4637 !DontDefer
&& !IsForDefinition
) {
4638 if (const FunctionDecl
*FDDef
= FD
->getDefinition()) {
4640 if (const auto *CD
= dyn_cast
<CXXConstructorDecl
>(FDDef
))
4641 GDDef
= GlobalDecl(CD
, GD
.getCtorType());
4642 else if (const auto *DD
= dyn_cast
<CXXDestructorDecl
>(FDDef
))
4643 GDDef
= GlobalDecl(DD
, GD
.getDtorType());
4645 GDDef
= GlobalDecl(FDDef
);
4650 if (FD
->isMultiVersion()) {
4651 UpdateMultiVersionNames(GD
, FD
, MangledName
);
4652 if (!IsForDefinition
) {
4653 // On AArch64 we do not immediatelly emit an ifunc resolver when a
4654 // function is used. Instead we defer the emission until we see a
4655 // default definition. In the meantime we just reference the symbol
4656 // without FMV mangling (it may or may not be replaced later).
4657 if (getTarget().getTriple().isAArch64()) {
4658 AddDeferredMultiVersionResolverToEmit(GD
);
4659 NameWithoutMultiVersionMangling
= getMangledNameImpl(
4660 *this, GD
, FD
, /*OmitMultiVersionMangling=*/true);
4662 return GetOrCreateMultiVersionResolver(GD
);
4667 if (!NameWithoutMultiVersionMangling
.empty())
4668 MangledName
= NameWithoutMultiVersionMangling
;
4670 // Lookup the entry, lazily creating it if necessary.
4671 llvm::GlobalValue
*Entry
= GetGlobalValue(MangledName
);
4673 if (WeakRefReferences
.erase(Entry
)) {
4674 const FunctionDecl
*FD
= cast_or_null
<FunctionDecl
>(D
);
4675 if (FD
&& !FD
->hasAttr
<WeakAttr
>())
4676 Entry
->setLinkage(llvm::Function::ExternalLinkage
);
4679 // Handle dropped DLL attributes.
4680 if (D
&& shouldDropDLLAttribute(D
, Entry
)) {
4681 Entry
->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass
);
4685 // If there are two attempts to define the same mangled name, issue an
4687 if (IsForDefinition
&& !Entry
->isDeclaration()) {
4689 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4690 // to make sure that we issue an error only once.
4691 if (lookupRepresentativeDecl(MangledName
, OtherGD
) &&
4692 (GD
.getCanonicalDecl().getDecl() !=
4693 OtherGD
.getCanonicalDecl().getDecl()) &&
4694 DiagnosedConflictingDefinitions
.insert(GD
).second
) {
4695 getDiags().Report(D
->getLocation(), diag::err_duplicate_mangled_name
)
4697 getDiags().Report(OtherGD
.getDecl()->getLocation(),
4698 diag::note_previous_definition
);
4702 if ((isa
<llvm::Function
>(Entry
) || isa
<llvm::GlobalAlias
>(Entry
)) &&
4703 (Entry
->getValueType() == Ty
)) {
4707 // Make sure the result is of the correct type.
4708 // (If function is requested for a definition, we always need to create a new
4709 // function, not just return a bitcast.)
4710 if (!IsForDefinition
)
4714 // This function doesn't have a complete type (for example, the return
4715 // type is an incomplete struct). Use a fake type instead, and make
4716 // sure not to try to set attributes.
4717 bool IsIncompleteFunction
= false;
4719 llvm::FunctionType
*FTy
;
4720 if (isa
<llvm::FunctionType
>(Ty
)) {
4721 FTy
= cast
<llvm::FunctionType
>(Ty
);
4723 FTy
= llvm::FunctionType::get(VoidTy
, false);
4724 IsIncompleteFunction
= true;
4728 llvm::Function::Create(FTy
, llvm::Function::ExternalLinkage
,
4729 Entry
? StringRef() : MangledName
, &getModule());
4731 // Store the declaration associated with this function so it is potentially
4732 // updated by further declarations or definitions and emitted at the end.
4733 if (D
&& D
->hasAttr
<AnnotateAttr
>())
4734 DeferredAnnotations
[MangledName
] = cast
<ValueDecl
>(D
);
4736 // If we already created a function with the same mangled name (but different
4737 // type) before, take its name and add it to the list of functions to be
4738 // replaced with F at the end of CodeGen.
4740 // This happens if there is a prototype for a function (e.g. "int f()") and
4741 // then a definition of a different type (e.g. "int f(int x)").
4745 // This might be an implementation of a function without a prototype, in
4746 // which case, try to do special replacement of calls which match the new
4747 // prototype. The really key thing here is that we also potentially drop
4748 // arguments from the call site so as to make a direct call, which makes the
4749 // inliner happier and suppresses a number of optimizer warnings (!) about
4750 // dropping arguments.
4751 if (!Entry
->use_empty()) {
4752 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry
, F
);
4753 Entry
->removeDeadConstantUsers();
4756 addGlobalValReplacement(Entry
, F
);
4759 assert(F
->getName() == MangledName
&& "name was uniqued!");
4761 SetFunctionAttributes(GD
, F
, IsIncompleteFunction
, IsThunk
);
4762 if (ExtraAttrs
.hasFnAttrs()) {
4763 llvm::AttrBuilder
B(F
->getContext(), ExtraAttrs
.getFnAttrs());
4768 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4769 // each other bottoming out with the base dtor. Therefore we emit non-base
4770 // dtors on usage, even if there is no dtor definition in the TU.
4771 if (isa_and_nonnull
<CXXDestructorDecl
>(D
) &&
4772 getCXXABI().useThunkForDtorVariant(cast
<CXXDestructorDecl
>(D
),
4774 addDeferredDeclToEmit(GD
);
4776 // This is the first use or definition of a mangled name. If there is a
4777 // deferred decl with this name, remember that we need to emit it at the end
4779 auto DDI
= DeferredDecls
.find(MangledName
);
4780 if (DDI
!= DeferredDecls
.end()) {
4781 // Move the potentially referenced deferred decl to the
4782 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4783 // don't need it anymore).
4784 addDeferredDeclToEmit(DDI
->second
);
4785 DeferredDecls
.erase(DDI
);
4787 // Otherwise, there are cases we have to worry about where we're
4788 // using a declaration for which we must emit a definition but where
4789 // we might not find a top-level definition:
4790 // - member functions defined inline in their classes
4791 // - friend functions defined inline in some class
4792 // - special member functions with implicit definitions
4793 // If we ever change our AST traversal to walk into class methods,
4794 // this will be unnecessary.
4796 // We also don't emit a definition for a function if it's going to be an
4797 // entry in a vtable, unless it's already marked as used.
4798 } else if (getLangOpts().CPlusPlus
&& D
) {
4799 // Look for a declaration that's lexically in a record.
4800 for (const auto *FD
= cast
<FunctionDecl
>(D
)->getMostRecentDecl(); FD
;
4801 FD
= FD
->getPreviousDecl()) {
4802 if (isa
<CXXRecordDecl
>(FD
->getLexicalDeclContext())) {
4803 if (FD
->doesThisDeclarationHaveABody()) {
4804 addDeferredDeclToEmit(GD
.getWithDecl(FD
));
4812 // Make sure the result is of the requested type.
4813 if (!IsIncompleteFunction
) {
4814 assert(F
->getFunctionType() == Ty
);
4821 /// GetAddrOfFunction - Return the address of the given function. If Ty is
4822 /// non-null, then this function will use the specified type if it has to
4823 /// create it (this occurs when we see a definition of the function).
4825 CodeGenModule::GetAddrOfFunction(GlobalDecl GD
, llvm::Type
*Ty
, bool ForVTable
,
4827 ForDefinition_t IsForDefinition
) {
4828 // If there was no specific requested type, just convert it now.
4830 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4831 Ty
= getTypes().ConvertType(FD
->getType());
4834 // Devirtualized destructor calls may come through here instead of via
4835 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4836 // of the complete destructor when necessary.
4837 if (const auto *DD
= dyn_cast
<CXXDestructorDecl
>(GD
.getDecl())) {
4838 if (getTarget().getCXXABI().isMicrosoft() &&
4839 GD
.getDtorType() == Dtor_Complete
&&
4840 DD
->getParent()->getNumVBases() == 0)
4841 GD
= GlobalDecl(DD
, Dtor_Base
);
4844 StringRef MangledName
= getMangledName(GD
);
4845 auto *F
= GetOrCreateLLVMFunction(MangledName
, Ty
, GD
, ForVTable
, DontDefer
,
4846 /*IsThunk=*/false, llvm::AttributeList(),
4848 // Returns kernel handle for HIP kernel stub function.
4849 if (LangOpts
.CUDA
&& !LangOpts
.CUDAIsDevice
&&
4850 cast
<FunctionDecl
>(GD
.getDecl())->hasAttr
<CUDAGlobalAttr
>()) {
4851 auto *Handle
= getCUDARuntime().getKernelHandle(
4852 cast
<llvm::Function
>(F
->stripPointerCasts()), GD
);
4853 if (IsForDefinition
)
4860 llvm::Constant
*CodeGenModule::GetFunctionStart(const ValueDecl
*Decl
) {
4861 llvm::GlobalValue
*F
=
4862 cast
<llvm::GlobalValue
>(GetAddrOfFunction(Decl
)->stripPointerCasts());
4864 return llvm::NoCFIValue::get(F
);
4867 static const FunctionDecl
*
4868 GetRuntimeFunctionDecl(ASTContext
&C
, StringRef Name
) {
4869 TranslationUnitDecl
*TUDecl
= C
.getTranslationUnitDecl();
4870 DeclContext
*DC
= TranslationUnitDecl::castToDeclContext(TUDecl
);
4872 IdentifierInfo
&CII
= C
.Idents
.get(Name
);
4873 for (const auto *Result
: DC
->lookup(&CII
))
4874 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Result
))
4877 if (!C
.getLangOpts().CPlusPlus
)
4880 // Demangle the premangled name from getTerminateFn()
4881 IdentifierInfo
&CXXII
=
4882 (Name
== "_ZSt9terminatev" || Name
== "?terminate@@YAXXZ")
4883 ? C
.Idents
.get("terminate")
4884 : C
.Idents
.get(Name
);
4886 for (const auto &N
: {"__cxxabiv1", "std"}) {
4887 IdentifierInfo
&NS
= C
.Idents
.get(N
);
4888 for (const auto *Result
: DC
->lookup(&NS
)) {
4889 const NamespaceDecl
*ND
= dyn_cast
<NamespaceDecl
>(Result
);
4890 if (auto *LSD
= dyn_cast
<LinkageSpecDecl
>(Result
))
4891 for (const auto *Result
: LSD
->lookup(&NS
))
4892 if ((ND
= dyn_cast
<NamespaceDecl
>(Result
)))
4896 for (const auto *Result
: ND
->lookup(&CXXII
))
4897 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Result
))
4905 static void setWindowsItaniumDLLImport(CodeGenModule
&CGM
, bool Local
,
4906 llvm::Function
*F
, StringRef Name
) {
4907 // In Windows Itanium environments, try to mark runtime functions
4908 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4909 // will link their standard library statically or dynamically. Marking
4910 // functions imported when they are not imported can cause linker errors
4912 if (!Local
&& CGM
.getTriple().isWindowsItaniumEnvironment() &&
4913 !CGM
.getCodeGenOpts().LTOVisibilityPublicStd
) {
4914 const FunctionDecl
*FD
= GetRuntimeFunctionDecl(CGM
.getContext(), Name
);
4915 if (!FD
|| FD
->hasAttr
<DLLImportAttr
>()) {
4916 F
->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass
);
4917 F
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
4922 llvm::FunctionCallee
CodeGenModule::CreateRuntimeFunction(
4923 QualType ReturnTy
, ArrayRef
<QualType
> ArgTys
, StringRef Name
,
4924 llvm::AttributeList ExtraAttrs
, bool Local
, bool AssumeConvergent
) {
4925 if (AssumeConvergent
) {
4927 ExtraAttrs
.addFnAttribute(VMContext
, llvm::Attribute::Convergent
);
4930 QualType FTy
= Context
.getFunctionType(ReturnTy
, ArgTys
,
4931 FunctionProtoType::ExtProtoInfo());
4932 const CGFunctionInfo
&Info
= getTypes().arrangeFreeFunctionType(
4933 Context
.getCanonicalType(FTy
).castAs
<FunctionProtoType
>());
4934 auto *ConvTy
= getTypes().GetFunctionType(Info
);
4935 llvm::Constant
*C
= GetOrCreateLLVMFunction(
4936 Name
, ConvTy
, GlobalDecl(), /*ForVTable=*/false,
4937 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs
);
4939 if (auto *F
= dyn_cast
<llvm::Function
>(C
)) {
4941 SetLLVMFunctionAttributes(GlobalDecl(), Info
, F
, /*IsThunk*/ false);
4942 // FIXME: Set calling-conv properly in ExtProtoInfo
4943 F
->setCallingConv(getRuntimeCC());
4944 setWindowsItaniumDLLImport(*this, Local
, F
, Name
);
4951 /// CreateRuntimeFunction - Create a new runtime function with the specified
4953 llvm::FunctionCallee
4954 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType
*FTy
, StringRef Name
,
4955 llvm::AttributeList ExtraAttrs
, bool Local
,
4956 bool AssumeConvergent
) {
4957 if (AssumeConvergent
) {
4959 ExtraAttrs
.addFnAttribute(VMContext
, llvm::Attribute::Convergent
);
4963 GetOrCreateLLVMFunction(Name
, FTy
, GlobalDecl(), /*ForVTable=*/false,
4964 /*DontDefer=*/false, /*IsThunk=*/false,
4967 if (auto *F
= dyn_cast
<llvm::Function
>(C
)) {
4969 F
->setCallingConv(getRuntimeCC());
4970 setWindowsItaniumDLLImport(*this, Local
, F
, Name
);
4972 // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
4973 // of trying to approximate the attributes using the LLVM function
4974 // signature. The other overload of CreateRuntimeFunction does this; it
4975 // should be used for new code.
4976 markRegisterParameterAttributes(F
);
4983 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4984 /// create and return an llvm GlobalVariable with the specified type and address
4985 /// space. If there is something in the module with the specified name, return
4986 /// it potentially bitcasted to the right type.
4988 /// If D is non-null, it specifies a decl that correspond to this. This is used
4989 /// to set the attributes on the global when it is first created.
4991 /// If IsForDefinition is true, it is guaranteed that an actual global with
4992 /// type Ty will be returned, not conversion of a variable with the same
4993 /// mangled name but some other type.
4995 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName
, llvm::Type
*Ty
,
4996 LangAS AddrSpace
, const VarDecl
*D
,
4997 ForDefinition_t IsForDefinition
) {
4998 // Lookup the entry, lazily creating it if necessary.
4999 llvm::GlobalValue
*Entry
= GetGlobalValue(MangledName
);
5000 unsigned TargetAS
= getContext().getTargetAddressSpace(AddrSpace
);
5002 if (WeakRefReferences
.erase(Entry
)) {
5003 if (D
&& !D
->hasAttr
<WeakAttr
>())
5004 Entry
->setLinkage(llvm::Function::ExternalLinkage
);
5007 // Handle dropped DLL attributes.
5008 if (D
&& shouldDropDLLAttribute(D
, Entry
))
5009 Entry
->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass
);
5011 if (LangOpts
.OpenMP
&& !LangOpts
.OpenMPSimd
&& D
)
5012 getOpenMPRuntime().registerTargetGlobalVariable(D
, Entry
);
5014 if (Entry
->getValueType() == Ty
&& Entry
->getAddressSpace() == TargetAS
)
5017 // If there are two attempts to define the same mangled name, issue an
5019 if (IsForDefinition
&& !Entry
->isDeclaration()) {
5021 const VarDecl
*OtherD
;
5023 // Check that D is not yet in DiagnosedConflictingDefinitions is required
5024 // to make sure that we issue an error only once.
5025 if (D
&& lookupRepresentativeDecl(MangledName
, OtherGD
) &&
5026 (D
->getCanonicalDecl() != OtherGD
.getCanonicalDecl().getDecl()) &&
5027 (OtherD
= dyn_cast
<VarDecl
>(OtherGD
.getDecl())) &&
5028 OtherD
->hasInit() &&
5029 DiagnosedConflictingDefinitions
.insert(D
).second
) {
5030 getDiags().Report(D
->getLocation(), diag::err_duplicate_mangled_name
)
5032 getDiags().Report(OtherGD
.getDecl()->getLocation(),
5033 diag::note_previous_definition
);
5037 // Make sure the result is of the correct type.
5038 if (Entry
->getType()->getAddressSpace() != TargetAS
)
5039 return llvm::ConstantExpr::getAddrSpaceCast(
5040 Entry
, llvm::PointerType::get(Ty
->getContext(), TargetAS
));
5042 // (If global is requested for a definition, we always need to create a new
5043 // global, not just return a bitcast.)
5044 if (!IsForDefinition
)
5048 auto DAddrSpace
= GetGlobalVarAddressSpace(D
);
5050 auto *GV
= new llvm::GlobalVariable(
5051 getModule(), Ty
, false, llvm::GlobalValue::ExternalLinkage
, nullptr,
5052 MangledName
, nullptr, llvm::GlobalVariable::NotThreadLocal
,
5053 getContext().getTargetAddressSpace(DAddrSpace
));
5055 // If we already created a global with the same mangled name (but different
5056 // type) before, take its name and remove it from its parent.
5058 GV
->takeName(Entry
);
5060 if (!Entry
->use_empty()) {
5061 Entry
->replaceAllUsesWith(GV
);
5064 Entry
->eraseFromParent();
5067 // This is the first use or definition of a mangled name. If there is a
5068 // deferred decl with this name, remember that we need to emit it at the end
5070 auto DDI
= DeferredDecls
.find(MangledName
);
5071 if (DDI
!= DeferredDecls
.end()) {
5072 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
5073 // list, and remove it from DeferredDecls (since we don't need it anymore).
5074 addDeferredDeclToEmit(DDI
->second
);
5075 DeferredDecls
.erase(DDI
);
5078 // Handle things which are present even on external declarations.
5080 if (LangOpts
.OpenMP
&& !LangOpts
.OpenMPSimd
)
5081 getOpenMPRuntime().registerTargetGlobalVariable(D
, GV
);
5083 // FIXME: This code is overly simple and should be merged with other global
5085 GV
->setConstant(D
->getType().isConstantStorage(getContext(), false, false));
5087 GV
->setAlignment(getContext().getDeclAlign(D
).getAsAlign());
5089 setLinkageForGV(GV
, D
);
5091 if (D
->getTLSKind()) {
5092 if (D
->getTLSKind() == VarDecl::TLS_Dynamic
)
5093 CXXThreadLocals
.push_back(D
);
5097 setGVProperties(GV
, D
);
5099 // If required by the ABI, treat declarations of static data members with
5100 // inline initializers as definitions.
5101 if (getContext().isMSStaticDataMemberInlineDefinition(D
)) {
5102 EmitGlobalVarDefinition(D
);
5105 // Emit section information for extern variables.
5106 if (D
->hasExternalStorage()) {
5107 if (const SectionAttr
*SA
= D
->getAttr
<SectionAttr
>())
5108 GV
->setSection(SA
->getName());
5111 // Handle XCore specific ABI requirements.
5112 if (getTriple().getArch() == llvm::Triple::xcore
&&
5113 D
->getLanguageLinkage() == CLanguageLinkage
&&
5114 D
->getType().isConstant(Context
) &&
5115 isExternallyVisible(D
->getLinkageAndVisibility().getLinkage()))
5116 GV
->setSection(".cp.rodata");
5118 // Handle code model attribute
5119 if (const auto *CMA
= D
->getAttr
<CodeModelAttr
>())
5120 GV
->setCodeModel(CMA
->getModel());
5122 // Check if we a have a const declaration with an initializer, we may be
5123 // able to emit it as available_externally to expose it's value to the
5125 if (Context
.getLangOpts().CPlusPlus
&& GV
->hasExternalLinkage() &&
5126 D
->getType().isConstQualified() && !GV
->hasInitializer() &&
5127 !D
->hasDefinition() && D
->hasInit() && !D
->hasAttr
<DLLImportAttr
>()) {
5128 const auto *Record
=
5129 Context
.getBaseElementType(D
->getType())->getAsCXXRecordDecl();
5130 bool HasMutableFields
= Record
&& Record
->hasMutableFields();
5131 if (!HasMutableFields
) {
5132 const VarDecl
*InitDecl
;
5133 const Expr
*InitExpr
= D
->getAnyInitializer(InitDecl
);
5135 ConstantEmitter
emitter(*this);
5136 llvm::Constant
*Init
= emitter
.tryEmitForInitializer(*InitDecl
);
5138 auto *InitType
= Init
->getType();
5139 if (GV
->getValueType() != InitType
) {
5140 // The type of the initializer does not match the definition.
5141 // This happens when an initializer has a different type from
5142 // the type of the global (because of padding at the end of a
5143 // structure for instance).
5144 GV
->setName(StringRef());
5145 // Make a new global with the correct type, this is now guaranteed
5147 auto *NewGV
= cast
<llvm::GlobalVariable
>(
5148 GetAddrOfGlobalVar(D
, InitType
, IsForDefinition
)
5149 ->stripPointerCasts());
5151 // Erase the old global, since it is no longer used.
5152 GV
->eraseFromParent();
5155 GV
->setInitializer(Init
);
5156 GV
->setConstant(true);
5157 GV
->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage
);
5159 emitter
.finalize(GV
);
5167 D
->isThisDeclarationADefinition(Context
) == VarDecl::DeclarationOnly
) {
5168 getTargetCodeGenInfo().setTargetAttributes(D
, GV
, *this);
5169 // External HIP managed variables needed to be recorded for transformation
5170 // in both device and host compilations.
5171 if (getLangOpts().CUDA
&& D
&& D
->hasAttr
<HIPManagedAttr
>() &&
5172 D
->hasExternalStorage())
5173 getCUDARuntime().handleVarRegistration(D
, *GV
);
5177 SanitizerMD
->reportGlobal(GV
, *D
);
5180 D
? D
->getType().getAddressSpace()
5181 : (LangOpts
.OpenCL
? LangAS::opencl_global
: LangAS::Default
);
5182 assert(getContext().getTargetAddressSpace(ExpectedAS
) == TargetAS
);
5183 if (DAddrSpace
!= ExpectedAS
) {
5184 return getTargetCodeGenInfo().performAddrSpaceCast(
5185 *this, GV
, DAddrSpace
, ExpectedAS
,
5186 llvm::PointerType::get(getLLVMContext(), TargetAS
));
5193 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD
, ForDefinition_t IsForDefinition
) {
5194 const Decl
*D
= GD
.getDecl();
5196 if (isa
<CXXConstructorDecl
>(D
) || isa
<CXXDestructorDecl
>(D
))
5197 return getAddrOfCXXStructor(GD
, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
5198 /*DontDefer=*/false, IsForDefinition
);
5200 if (isa
<CXXMethodDecl
>(D
)) {
5202 &getTypes().arrangeCXXMethodDeclaration(cast
<CXXMethodDecl
>(D
));
5203 auto Ty
= getTypes().GetFunctionType(*FInfo
);
5204 return GetAddrOfFunction(GD
, Ty
, /*ForVTable=*/false, /*DontDefer=*/false,
5208 if (isa
<FunctionDecl
>(D
)) {
5209 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(GD
);
5210 llvm::FunctionType
*Ty
= getTypes().GetFunctionType(FI
);
5211 return GetAddrOfFunction(GD
, Ty
, /*ForVTable=*/false, /*DontDefer=*/false,
5215 return GetAddrOfGlobalVar(cast
<VarDecl
>(D
), /*Ty=*/nullptr, IsForDefinition
);
5218 llvm::GlobalVariable
*CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
5219 StringRef Name
, llvm::Type
*Ty
, llvm::GlobalValue::LinkageTypes Linkage
,
5220 llvm::Align Alignment
) {
5221 llvm::GlobalVariable
*GV
= getModule().getNamedGlobal(Name
);
5222 llvm::GlobalVariable
*OldGV
= nullptr;
5225 // Check if the variable has the right type.
5226 if (GV
->getValueType() == Ty
)
5229 // Because C++ name mangling, the only way we can end up with an already
5230 // existing global with the same name is if it has been declared extern "C".
5231 assert(GV
->isDeclaration() && "Declaration has wrong type!");
5235 // Create a new variable.
5236 GV
= new llvm::GlobalVariable(getModule(), Ty
, /*isConstant=*/true,
5237 Linkage
, nullptr, Name
);
5240 // Replace occurrences of the old variable if needed.
5241 GV
->takeName(OldGV
);
5243 if (!OldGV
->use_empty()) {
5244 OldGV
->replaceAllUsesWith(GV
);
5247 OldGV
->eraseFromParent();
5250 if (supportsCOMDAT() && GV
->isWeakForLinker() &&
5251 !GV
->hasAvailableExternallyLinkage())
5252 GV
->setComdat(TheModule
.getOrInsertComdat(GV
->getName()));
5254 GV
->setAlignment(Alignment
);
5259 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
5260 /// given global variable. If Ty is non-null and if the global doesn't exist,
5261 /// then it will be created with the specified type instead of whatever the
5262 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
5263 /// that an actual global with type Ty will be returned, not conversion of a
5264 /// variable with the same mangled name but some other type.
5265 llvm::Constant
*CodeGenModule::GetAddrOfGlobalVar(const VarDecl
*D
,
5267 ForDefinition_t IsForDefinition
) {
5268 assert(D
->hasGlobalStorage() && "Not a global variable");
5269 QualType ASTTy
= D
->getType();
5271 Ty
= getTypes().ConvertTypeForMem(ASTTy
);
5273 StringRef MangledName
= getMangledName(D
);
5274 return GetOrCreateLLVMGlobal(MangledName
, Ty
, ASTTy
.getAddressSpace(), D
,
5278 /// CreateRuntimeVariable - Create a new runtime global variable with the
5279 /// specified type and name.
5281 CodeGenModule::CreateRuntimeVariable(llvm::Type
*Ty
,
5283 LangAS AddrSpace
= getContext().getLangOpts().OpenCL
? LangAS::opencl_global
5285 auto *Ret
= GetOrCreateLLVMGlobal(Name
, Ty
, AddrSpace
, nullptr);
5286 setDSOLocal(cast
<llvm::GlobalValue
>(Ret
->stripPointerCasts()));
5290 void CodeGenModule::EmitTentativeDefinition(const VarDecl
*D
) {
5291 assert(!D
->getInit() && "Cannot emit definite definitions here!");
5293 StringRef MangledName
= getMangledName(D
);
5294 llvm::GlobalValue
*GV
= GetGlobalValue(MangledName
);
5296 // We already have a definition, not declaration, with the same mangled name.
5297 // Emitting of declaration is not required (and actually overwrites emitted
5299 if (GV
&& !GV
->isDeclaration())
5302 // If we have not seen a reference to this variable yet, place it into the
5303 // deferred declarations table to be emitted if needed later.
5304 if (!MustBeEmitted(D
) && !GV
) {
5305 DeferredDecls
[MangledName
] = D
;
5309 // The tentative definition is the only definition.
5310 EmitGlobalVarDefinition(D
);
5313 void CodeGenModule::EmitExternalDeclaration(const DeclaratorDecl
*D
) {
5314 if (auto const *V
= dyn_cast
<const VarDecl
>(D
))
5315 EmitExternalVarDeclaration(V
);
5316 if (auto const *FD
= dyn_cast
<const FunctionDecl
>(D
))
5317 EmitExternalFunctionDeclaration(FD
);
5320 CharUnits
CodeGenModule::GetTargetTypeStoreSize(llvm::Type
*Ty
) const {
5321 return Context
.toCharUnitsFromBits(
5322 getDataLayout().getTypeStoreSizeInBits(Ty
));
5325 LangAS
CodeGenModule::GetGlobalVarAddressSpace(const VarDecl
*D
) {
5326 if (LangOpts
.OpenCL
) {
5327 LangAS AS
= D
? D
->getType().getAddressSpace() : LangAS::opencl_global
;
5328 assert(AS
== LangAS::opencl_global
||
5329 AS
== LangAS::opencl_global_device
||
5330 AS
== LangAS::opencl_global_host
||
5331 AS
== LangAS::opencl_constant
||
5332 AS
== LangAS::opencl_local
||
5333 AS
>= LangAS::FirstTargetAddressSpace
);
5337 if (LangOpts
.SYCLIsDevice
&&
5338 (!D
|| D
->getType().getAddressSpace() == LangAS::Default
))
5339 return LangAS::sycl_global
;
5341 if (LangOpts
.CUDA
&& LangOpts
.CUDAIsDevice
) {
5343 if (D
->hasAttr
<CUDAConstantAttr
>())
5344 return LangAS::cuda_constant
;
5345 if (D
->hasAttr
<CUDASharedAttr
>())
5346 return LangAS::cuda_shared
;
5347 if (D
->hasAttr
<CUDADeviceAttr
>())
5348 return LangAS::cuda_device
;
5349 if (D
->getType().isConstQualified())
5350 return LangAS::cuda_constant
;
5352 return LangAS::cuda_device
;
5355 if (LangOpts
.OpenMP
) {
5357 if (OpenMPRuntime
->hasAllocateAttributeForGlobalVar(D
, AS
))
5360 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D
);
5363 LangAS
CodeGenModule::GetGlobalConstantAddressSpace() const {
5364 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
5365 if (LangOpts
.OpenCL
)
5366 return LangAS::opencl_constant
;
5367 if (LangOpts
.SYCLIsDevice
)
5368 return LangAS::sycl_global
;
5369 if (LangOpts
.HIP
&& LangOpts
.CUDAIsDevice
&& getTriple().isSPIRV())
5370 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5371 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5372 // with OpVariable instructions with Generic storage class which is not
5373 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5374 // UniformConstant storage class is not viable as pointers to it may not be
5375 // casted to Generic pointers which are used to model HIP's "flat" pointers.
5376 return LangAS::cuda_device
;
5377 if (auto AS
= getTarget().getConstantAddressSpace())
5379 return LangAS::Default
;
5382 // In address space agnostic languages, string literals are in default address
5383 // space in AST. However, certain targets (e.g. amdgcn) request them to be
5384 // emitted in constant address space in LLVM IR. To be consistent with other
5385 // parts of AST, string literal global variables in constant address space
5386 // need to be casted to default address space before being put into address
5387 // map and referenced by other part of CodeGen.
5388 // In OpenCL, string literals are in constant address space in AST, therefore
5389 // they should not be casted to default address space.
5390 static llvm::Constant
*
5391 castStringLiteralToDefaultAddressSpace(CodeGenModule
&CGM
,
5392 llvm::GlobalVariable
*GV
) {
5393 llvm::Constant
*Cast
= GV
;
5394 if (!CGM
.getLangOpts().OpenCL
) {
5395 auto AS
= CGM
.GetGlobalConstantAddressSpace();
5396 if (AS
!= LangAS::Default
)
5397 Cast
= CGM
.getTargetCodeGenInfo().performAddrSpaceCast(
5398 CGM
, GV
, AS
, LangAS::Default
,
5399 llvm::PointerType::get(
5400 CGM
.getLLVMContext(),
5401 CGM
.getContext().getTargetAddressSpace(LangAS::Default
)));
5406 template<typename SomeDecl
>
5407 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl
*D
,
5408 llvm::GlobalValue
*GV
) {
5409 if (!getLangOpts().CPlusPlus
)
5412 // Must have 'used' attribute, or else inline assembly can't rely on
5413 // the name existing.
5414 if (!D
->template hasAttr
<UsedAttr
>())
5417 // Must have internal linkage and an ordinary name.
5418 if (!D
->getIdentifier() || D
->getFormalLinkage() != Linkage::Internal
)
5421 // Must be in an extern "C" context. Entities declared directly within
5422 // a record are not extern "C" even if the record is in such a context.
5423 const SomeDecl
*First
= D
->getFirstDecl();
5424 if (First
->getDeclContext()->isRecord() || !First
->isInExternCContext())
5427 // OK, this is an internal linkage entity inside an extern "C" linkage
5428 // specification. Make a note of that so we can give it the "expected"
5429 // mangled name if nothing else is using that name.
5430 std::pair
<StaticExternCMap::iterator
, bool> R
=
5431 StaticExternCValues
.insert(std::make_pair(D
->getIdentifier(), GV
));
5433 // If we have multiple internal linkage entities with the same name
5434 // in extern "C" regions, none of them gets that name.
5436 R
.first
->second
= nullptr;
5439 static bool shouldBeInCOMDAT(CodeGenModule
&CGM
, const Decl
&D
) {
5440 if (!CGM
.supportsCOMDAT())
5443 if (D
.hasAttr
<SelectAnyAttr
>())
5447 if (auto *VD
= dyn_cast
<VarDecl
>(&D
))
5448 Linkage
= CGM
.getContext().GetGVALinkageForVariable(VD
);
5450 Linkage
= CGM
.getContext().GetGVALinkageForFunction(cast
<FunctionDecl
>(&D
));
5454 case GVA_AvailableExternally
:
5455 case GVA_StrongExternal
:
5457 case GVA_DiscardableODR
:
5461 llvm_unreachable("No such linkage");
5464 bool CodeGenModule::supportsCOMDAT() const {
5465 return getTriple().supportsCOMDAT();
5468 void CodeGenModule::maybeSetTrivialComdat(const Decl
&D
,
5469 llvm::GlobalObject
&GO
) {
5470 if (!shouldBeInCOMDAT(*this, D
))
5472 GO
.setComdat(TheModule
.getOrInsertComdat(GO
.getName()));
5475 const ABIInfo
&CodeGenModule::getABIInfo() {
5476 return getTargetCodeGenInfo().getABIInfo();
5479 /// Pass IsTentative as true if you want to create a tentative definition.
5480 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl
*D
,
5482 // OpenCL global variables of sampler type are translated to function calls,
5483 // therefore no need to be translated.
5484 QualType ASTTy
= D
->getType();
5485 if (getLangOpts().OpenCL
&& ASTTy
->isSamplerT())
5488 // If this is OpenMP device, check if it is legal to emit this global
5490 if (LangOpts
.OpenMPIsTargetDevice
&& OpenMPRuntime
&&
5491 OpenMPRuntime
->emitTargetGlobalVariable(D
))
5494 llvm::TrackingVH
<llvm::Constant
> Init
;
5495 bool NeedsGlobalCtor
= false;
5496 // Whether the definition of the variable is available externally.
5497 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5498 // since this is the job for its original source.
5499 bool IsDefinitionAvailableExternally
=
5500 getContext().GetGVALinkageForVariable(D
) == GVA_AvailableExternally
;
5501 bool NeedsGlobalDtor
=
5502 !IsDefinitionAvailableExternally
&&
5503 D
->needsDestruction(getContext()) == QualType::DK_cxx_destructor
;
5505 // It is helpless to emit the definition for an available_externally variable
5506 // which can't be marked as const.
5507 // We don't need to check if it needs global ctor or dtor. See the above
5508 // comment for ideas.
5509 if (IsDefinitionAvailableExternally
&&
5510 (!D
->hasConstantInitialization() ||
5511 // TODO: Update this when we have interface to check constexpr
5513 D
->needsDestruction(getContext()) ||
5514 !D
->getType().isConstantStorage(getContext(), true, true)))
5517 const VarDecl
*InitDecl
;
5518 const Expr
*InitExpr
= D
->getAnyInitializer(InitDecl
);
5520 std::optional
<ConstantEmitter
> emitter
;
5522 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5523 // as part of their declaration." Sema has already checked for
5524 // error cases, so we just need to set Init to UndefValue.
5525 bool IsCUDASharedVar
=
5526 getLangOpts().CUDAIsDevice
&& D
->hasAttr
<CUDASharedAttr
>();
5527 // Shadows of initialized device-side global variables are also left
5529 // Managed Variables should be initialized on both host side and device side.
5530 bool IsCUDAShadowVar
=
5531 !getLangOpts().CUDAIsDevice
&& !D
->hasAttr
<HIPManagedAttr
>() &&
5532 (D
->hasAttr
<CUDAConstantAttr
>() || D
->hasAttr
<CUDADeviceAttr
>() ||
5533 D
->hasAttr
<CUDASharedAttr
>());
5534 bool IsCUDADeviceShadowVar
=
5535 getLangOpts().CUDAIsDevice
&& !D
->hasAttr
<HIPManagedAttr
>() &&
5536 (D
->getType()->isCUDADeviceBuiltinSurfaceType() ||
5537 D
->getType()->isCUDADeviceBuiltinTextureType());
5538 if (getLangOpts().CUDA
&&
5539 (IsCUDASharedVar
|| IsCUDAShadowVar
|| IsCUDADeviceShadowVar
))
5540 Init
= llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy
));
5541 else if (D
->hasAttr
<LoaderUninitializedAttr
>())
5542 Init
= llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy
));
5543 else if (!InitExpr
) {
5544 // This is a tentative definition; tentative definitions are
5545 // implicitly initialized with { 0 }.
5547 // Note that tentative definitions are only emitted at the end of
5548 // a translation unit, so they should never have incomplete
5549 // type. In addition, EmitTentativeDefinition makes sure that we
5550 // never attempt to emit a tentative definition if a real one
5551 // exists. A use may still exists, however, so we still may need
5553 assert(!ASTTy
->isIncompleteType() && "Unexpected incomplete type");
5554 Init
= EmitNullConstant(D
->getType());
5556 initializedGlobalDecl
= GlobalDecl(D
);
5557 emitter
.emplace(*this);
5558 llvm::Constant
*Initializer
= emitter
->tryEmitForInitializer(*InitDecl
);
5560 QualType T
= InitExpr
->getType();
5561 if (D
->getType()->isReferenceType())
5564 if (getLangOpts().CPlusPlus
) {
5565 Init
= EmitNullConstant(T
);
5566 if (!IsDefinitionAvailableExternally
)
5567 NeedsGlobalCtor
= true;
5568 if (InitDecl
->hasFlexibleArrayInit(getContext())) {
5569 ErrorUnsupported(D
, "flexible array initializer");
5570 // We cannot create ctor for flexible array initializer
5571 NeedsGlobalCtor
= false;
5574 ErrorUnsupported(D
, "static initializer");
5575 Init
= llvm::PoisonValue::get(getTypes().ConvertType(T
));
5579 // We don't need an initializer, so remove the entry for the delayed
5580 // initializer position (just in case this entry was delayed) if we
5581 // also don't need to register a destructor.
5582 if (getLangOpts().CPlusPlus
&& !NeedsGlobalDtor
)
5583 DelayedCXXInitPosition
.erase(D
);
5586 CharUnits VarSize
= getContext().getTypeSizeInChars(ASTTy
) +
5587 InitDecl
->getFlexibleArrayInitChars(getContext());
5588 CharUnits CstSize
= CharUnits::fromQuantity(
5589 getDataLayout().getTypeAllocSize(Init
->getType()));
5590 assert(VarSize
== CstSize
&& "Emitted constant has unexpected size");
5595 llvm::Type
* InitType
= Init
->getType();
5596 llvm::Constant
*Entry
=
5597 GetAddrOfGlobalVar(D
, InitType
, ForDefinition_t(!IsTentative
));
5599 // Strip off pointer casts if we got them.
5600 Entry
= Entry
->stripPointerCasts();
5602 // Entry is now either a Function or GlobalVariable.
5603 auto *GV
= dyn_cast
<llvm::GlobalVariable
>(Entry
);
5605 // We have a definition after a declaration with the wrong type.
5606 // We must make a new GlobalVariable* and update everything that used OldGV
5607 // (a declaration or tentative definition) with the new GlobalVariable*
5608 // (which will be a definition).
5610 // This happens if there is a prototype for a global (e.g.
5611 // "extern int x[];") and then a definition of a different type (e.g.
5612 // "int x[10];"). This also happens when an initializer has a different type
5613 // from the type of the global (this happens with unions).
5614 if (!GV
|| GV
->getValueType() != InitType
||
5615 GV
->getType()->getAddressSpace() !=
5616 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D
))) {
5618 // Move the old entry aside so that we'll create a new one.
5619 Entry
->setName(StringRef());
5621 // Make a new global with the correct type, this is now guaranteed to work.
5622 GV
= cast
<llvm::GlobalVariable
>(
5623 GetAddrOfGlobalVar(D
, InitType
, ForDefinition_t(!IsTentative
))
5624 ->stripPointerCasts());
5626 // Replace all uses of the old global with the new global
5627 llvm::Constant
*NewPtrForOldDecl
=
5628 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV
,
5630 Entry
->replaceAllUsesWith(NewPtrForOldDecl
);
5632 // Erase the old global, since it is no longer used.
5633 cast
<llvm::GlobalValue
>(Entry
)->eraseFromParent();
5636 MaybeHandleStaticInExternC(D
, GV
);
5638 if (D
->hasAttr
<AnnotateAttr
>())
5639 AddGlobalAnnotations(D
, GV
);
5641 // Set the llvm linkage type as appropriate.
5642 llvm::GlobalValue::LinkageTypes Linkage
= getLLVMLinkageVarDefinition(D
);
5644 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
5645 // the device. [...]"
5646 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
5647 // __device__, declares a variable that: [...]
5648 // Is accessible from all the threads within the grid and from the host
5649 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
5650 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
5651 if (LangOpts
.CUDA
) {
5652 if (LangOpts
.CUDAIsDevice
) {
5653 if (Linkage
!= llvm::GlobalValue::InternalLinkage
&&
5654 (D
->hasAttr
<CUDADeviceAttr
>() || D
->hasAttr
<CUDAConstantAttr
>() ||
5655 D
->getType()->isCUDADeviceBuiltinSurfaceType() ||
5656 D
->getType()->isCUDADeviceBuiltinTextureType()))
5657 GV
->setExternallyInitialized(true);
5659 getCUDARuntime().internalizeDeviceSideVar(D
, Linkage
);
5661 getCUDARuntime().handleVarRegistration(D
, *GV
);
5665 getHLSLRuntime().handleGlobalVarDefinition(D
, GV
);
5667 GV
->setInitializer(Init
);
5669 emitter
->finalize(GV
);
5671 // If it is safe to mark the global 'constant', do so now.
5672 GV
->setConstant((D
->hasAttr
<CUDAConstantAttr
>() && LangOpts
.CUDAIsDevice
) ||
5673 (!NeedsGlobalCtor
&& !NeedsGlobalDtor
&&
5674 D
->getType().isConstantStorage(getContext(), true, true)));
5676 // If it is in a read-only section, mark it 'constant'.
5677 if (const SectionAttr
*SA
= D
->getAttr
<SectionAttr
>()) {
5678 const ASTContext::SectionInfo
&SI
= Context
.SectionInfos
[SA
->getName()];
5679 if ((SI
.SectionFlags
& ASTContext::PSF_Write
) == 0)
5680 GV
->setConstant(true);
5683 CharUnits AlignVal
= getContext().getDeclAlign(D
);
5684 // Check for alignment specifed in an 'omp allocate' directive.
5685 if (std::optional
<CharUnits
> AlignValFromAllocate
=
5686 getOMPAllocateAlignment(D
))
5687 AlignVal
= *AlignValFromAllocate
;
5688 GV
->setAlignment(AlignVal
.getAsAlign());
5690 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5691 // function is only defined alongside the variable, not also alongside
5692 // callers. Normally, all accesses to a thread_local go through the
5693 // thread-wrapper in order to ensure initialization has occurred, underlying
5694 // variable will never be used other than the thread-wrapper, so it can be
5695 // converted to internal linkage.
5697 // However, if the variable has the 'constinit' attribute, it _can_ be
5698 // referenced directly, without calling the thread-wrapper, so the linkage
5699 // must not be changed.
5701 // Additionally, if the variable isn't plain external linkage, e.g. if it's
5702 // weak or linkonce, the de-duplication semantics are important to preserve,
5703 // so we don't change the linkage.
5704 if (D
->getTLSKind() == VarDecl::TLS_Dynamic
&&
5705 Linkage
== llvm::GlobalValue::ExternalLinkage
&&
5706 Context
.getTargetInfo().getTriple().isOSDarwin() &&
5707 !D
->hasAttr
<ConstInitAttr
>())
5708 Linkage
= llvm::GlobalValue::InternalLinkage
;
5710 GV
->setLinkage(Linkage
);
5711 if (D
->hasAttr
<DLLImportAttr
>())
5712 GV
->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass
);
5713 else if (D
->hasAttr
<DLLExportAttr
>())
5714 GV
->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass
);
5716 GV
->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass
);
5718 if (Linkage
== llvm::GlobalVariable::CommonLinkage
) {
5719 // common vars aren't constant even if declared const.
5720 GV
->setConstant(false);
5721 // Tentative definition of global variables may be initialized with
5722 // non-zero null pointers. In this case they should have weak linkage
5723 // since common linkage must have zero initializer and must not have
5724 // explicit section therefore cannot have non-zero initial value.
5725 if (!GV
->getInitializer()->isNullValue())
5726 GV
->setLinkage(llvm::GlobalVariable::WeakAnyLinkage
);
5729 setNonAliasAttributes(D
, GV
);
5731 if (D
->getTLSKind() && !GV
->isThreadLocal()) {
5732 if (D
->getTLSKind() == VarDecl::TLS_Dynamic
)
5733 CXXThreadLocals
.push_back(D
);
5737 maybeSetTrivialComdat(*D
, *GV
);
5739 // Emit the initializer function if necessary.
5740 if (NeedsGlobalCtor
|| NeedsGlobalDtor
)
5741 EmitCXXGlobalVarDeclInitFunc(D
, GV
, NeedsGlobalCtor
);
5743 SanitizerMD
->reportGlobal(GV
, *D
, NeedsGlobalCtor
);
5745 // Emit global variable debug information.
5746 if (CGDebugInfo
*DI
= getModuleDebugInfo())
5747 if (getCodeGenOpts().hasReducedDebugInfo())
5748 DI
->EmitGlobalVariable(GV
, D
);
5751 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl
*D
) {
5752 if (CGDebugInfo
*DI
= getModuleDebugInfo())
5753 if (getCodeGenOpts().hasReducedDebugInfo()) {
5754 QualType ASTTy
= D
->getType();
5755 llvm::Type
*Ty
= getTypes().ConvertTypeForMem(D
->getType());
5756 llvm::Constant
*GV
=
5757 GetOrCreateLLVMGlobal(D
->getName(), Ty
, ASTTy
.getAddressSpace(), D
);
5758 DI
->EmitExternalVariable(
5759 cast
<llvm::GlobalVariable
>(GV
->stripPointerCasts()), D
);
5763 void CodeGenModule::EmitExternalFunctionDeclaration(const FunctionDecl
*FD
) {
5764 if (CGDebugInfo
*DI
= getModuleDebugInfo())
5765 if (getCodeGenOpts().hasReducedDebugInfo()) {
5766 auto *Ty
= getTypes().ConvertType(FD
->getType());
5767 StringRef MangledName
= getMangledName(FD
);
5768 auto *Fn
= cast
<llvm::Function
>(
5769 GetOrCreateLLVMFunction(MangledName
, Ty
, FD
, /* ForVTable */ false));
5770 if (!Fn
->getSubprogram())
5771 DI
->EmitFunctionDecl(FD
, FD
->getLocation(), FD
->getType(), Fn
);
5775 static bool isVarDeclStrongDefinition(const ASTContext
&Context
,
5776 CodeGenModule
&CGM
, const VarDecl
*D
,
5778 // Don't give variables common linkage if -fno-common was specified unless it
5779 // was overridden by a NoCommon attribute.
5780 if ((NoCommon
|| D
->hasAttr
<NoCommonAttr
>()) && !D
->hasAttr
<CommonAttr
>())
5784 // A declaration of an identifier for an object that has file scope without
5785 // an initializer, and without a storage-class specifier or with the
5786 // storage-class specifier static, constitutes a tentative definition.
5787 if (D
->getInit() || D
->hasExternalStorage())
5790 // A variable cannot be both common and exist in a section.
5791 if (D
->hasAttr
<SectionAttr
>())
5794 // A variable cannot be both common and exist in a section.
5795 // We don't try to determine which is the right section in the front-end.
5796 // If no specialized section name is applicable, it will resort to default.
5797 if (D
->hasAttr
<PragmaClangBSSSectionAttr
>() ||
5798 D
->hasAttr
<PragmaClangDataSectionAttr
>() ||
5799 D
->hasAttr
<PragmaClangRelroSectionAttr
>() ||
5800 D
->hasAttr
<PragmaClangRodataSectionAttr
>())
5803 // Thread local vars aren't considered common linkage.
5804 if (D
->getTLSKind())
5807 // Tentative definitions marked with WeakImportAttr are true definitions.
5808 if (D
->hasAttr
<WeakImportAttr
>())
5811 // A variable cannot be both common and exist in a comdat.
5812 if (shouldBeInCOMDAT(CGM
, *D
))
5815 // Declarations with a required alignment do not have common linkage in MSVC
5817 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
5818 if (D
->hasAttr
<AlignedAttr
>())
5820 QualType VarType
= D
->getType();
5821 if (Context
.isAlignmentRequired(VarType
))
5824 if (const auto *RT
= VarType
->getAs
<RecordType
>()) {
5825 const RecordDecl
*RD
= RT
->getDecl();
5826 for (const FieldDecl
*FD
: RD
->fields()) {
5827 if (FD
->isBitField())
5829 if (FD
->hasAttr
<AlignedAttr
>())
5831 if (Context
.isAlignmentRequired(FD
->getType()))
5837 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5838 // common symbols, so symbols with greater alignment requirements cannot be
5840 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5841 // alignments for common symbols via the aligncomm directive, so this
5842 // restriction only applies to MSVC environments.
5843 if (Context
.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5844 Context
.getTypeAlignIfKnown(D
->getType()) >
5845 Context
.toBits(CharUnits::fromQuantity(32)))
5851 llvm::GlobalValue::LinkageTypes
5852 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl
*D
,
5853 GVALinkage Linkage
) {
5854 if (Linkage
== GVA_Internal
)
5855 return llvm::Function::InternalLinkage
;
5857 if (D
->hasAttr
<WeakAttr
>())
5858 return llvm::GlobalVariable::WeakAnyLinkage
;
5860 if (const auto *FD
= D
->getAsFunction())
5861 if (FD
->isMultiVersion() && Linkage
== GVA_AvailableExternally
)
5862 return llvm::GlobalVariable::LinkOnceAnyLinkage
;
5864 // We are guaranteed to have a strong definition somewhere else,
5865 // so we can use available_externally linkage.
5866 if (Linkage
== GVA_AvailableExternally
)
5867 return llvm::GlobalValue::AvailableExternallyLinkage
;
5869 // Note that Apple's kernel linker doesn't support symbol
5870 // coalescing, so we need to avoid linkonce and weak linkages there.
5871 // Normally, this means we just map to internal, but for explicit
5872 // instantiations we'll map to external.
5874 // In C++, the compiler has to emit a definition in every translation unit
5875 // that references the function. We should use linkonce_odr because
5876 // a) if all references in this translation unit are optimized away, we
5877 // don't need to codegen it. b) if the function persists, it needs to be
5878 // merged with other definitions. c) C++ has the ODR, so we know the
5879 // definition is dependable.
5880 if (Linkage
== GVA_DiscardableODR
)
5881 return !Context
.getLangOpts().AppleKext
? llvm::Function::LinkOnceODRLinkage
5882 : llvm::Function::InternalLinkage
;
5884 // An explicit instantiation of a template has weak linkage, since
5885 // explicit instantiations can occur in multiple translation units
5886 // and must all be equivalent. However, we are not allowed to
5887 // throw away these explicit instantiations.
5889 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5890 // so say that CUDA templates are either external (for kernels) or internal.
5891 // This lets llvm perform aggressive inter-procedural optimizations. For
5892 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5893 // therefore we need to follow the normal linkage paradigm.
5894 if (Linkage
== GVA_StrongODR
) {
5895 if (getLangOpts().AppleKext
)
5896 return llvm::Function::ExternalLinkage
;
5897 if (getLangOpts().CUDA
&& getLangOpts().CUDAIsDevice
&&
5898 !getLangOpts().GPURelocatableDeviceCode
)
5899 return D
->hasAttr
<CUDAGlobalAttr
>() ? llvm::Function::ExternalLinkage
5900 : llvm::Function::InternalLinkage
;
5901 return llvm::Function::WeakODRLinkage
;
5904 // C++ doesn't have tentative definitions and thus cannot have common
5906 if (!getLangOpts().CPlusPlus
&& isa
<VarDecl
>(D
) &&
5907 !isVarDeclStrongDefinition(Context
, *this, cast
<VarDecl
>(D
),
5908 CodeGenOpts
.NoCommon
))
5909 return llvm::GlobalVariable::CommonLinkage
;
5911 // selectany symbols are externally visible, so use weak instead of
5912 // linkonce. MSVC optimizes away references to const selectany globals, so
5913 // all definitions should be the same and ODR linkage should be used.
5914 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5915 if (D
->hasAttr
<SelectAnyAttr
>())
5916 return llvm::GlobalVariable::WeakODRLinkage
;
5918 // Otherwise, we have strong external linkage.
5919 assert(Linkage
== GVA_StrongExternal
);
5920 return llvm::GlobalVariable::ExternalLinkage
;
5923 llvm::GlobalValue::LinkageTypes
5924 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl
*VD
) {
5925 GVALinkage Linkage
= getContext().GetGVALinkageForVariable(VD
);
5926 return getLLVMLinkageForDeclarator(VD
, Linkage
);
5929 /// Replace the uses of a function that was declared with a non-proto type.
5930 /// We want to silently drop extra arguments from call sites
5931 static void replaceUsesOfNonProtoConstant(llvm::Constant
*old
,
5932 llvm::Function
*newFn
) {
5934 if (old
->use_empty())
5937 llvm::Type
*newRetTy
= newFn
->getReturnType();
5938 SmallVector
<llvm::Value
*, 4> newArgs
;
5940 SmallVector
<llvm::CallBase
*> callSitesToBeRemovedFromParent
;
5942 for (llvm::Value::use_iterator ui
= old
->use_begin(), ue
= old
->use_end();
5944 llvm::User
*user
= ui
->getUser();
5946 // Recognize and replace uses of bitcasts. Most calls to
5947 // unprototyped functions will use bitcasts.
5948 if (auto *bitcast
= dyn_cast
<llvm::ConstantExpr
>(user
)) {
5949 if (bitcast
->getOpcode() == llvm::Instruction::BitCast
)
5950 replaceUsesOfNonProtoConstant(bitcast
, newFn
);
5954 // Recognize calls to the function.
5955 llvm::CallBase
*callSite
= dyn_cast
<llvm::CallBase
>(user
);
5958 if (!callSite
->isCallee(&*ui
))
5961 // If the return types don't match exactly, then we can't
5962 // transform this call unless it's dead.
5963 if (callSite
->getType() != newRetTy
&& !callSite
->use_empty())
5966 // Get the call site's attribute list.
5967 SmallVector
<llvm::AttributeSet
, 8> newArgAttrs
;
5968 llvm::AttributeList oldAttrs
= callSite
->getAttributes();
5970 // If the function was passed too few arguments, don't transform.
5971 unsigned newNumArgs
= newFn
->arg_size();
5972 if (callSite
->arg_size() < newNumArgs
)
5975 // If extra arguments were passed, we silently drop them.
5976 // If any of the types mismatch, we don't transform.
5978 bool dontTransform
= false;
5979 for (llvm::Argument
&A
: newFn
->args()) {
5980 if (callSite
->getArgOperand(argNo
)->getType() != A
.getType()) {
5981 dontTransform
= true;
5985 // Add any parameter attributes.
5986 newArgAttrs
.push_back(oldAttrs
.getParamAttrs(argNo
));
5992 // Okay, we can transform this. Create the new call instruction and copy
5993 // over the required information.
5994 newArgs
.append(callSite
->arg_begin(), callSite
->arg_begin() + argNo
);
5996 // Copy over any operand bundles.
5997 SmallVector
<llvm::OperandBundleDef
, 1> newBundles
;
5998 callSite
->getOperandBundlesAsDefs(newBundles
);
6000 llvm::CallBase
*newCall
;
6001 if (isa
<llvm::CallInst
>(callSite
)) {
6002 newCall
= llvm::CallInst::Create(newFn
, newArgs
, newBundles
, "",
6003 callSite
->getIterator());
6005 auto *oldInvoke
= cast
<llvm::InvokeInst
>(callSite
);
6006 newCall
= llvm::InvokeInst::Create(
6007 newFn
, oldInvoke
->getNormalDest(), oldInvoke
->getUnwindDest(),
6008 newArgs
, newBundles
, "", callSite
->getIterator());
6010 newArgs
.clear(); // for the next iteration
6012 if (!newCall
->getType()->isVoidTy())
6013 newCall
->takeName(callSite
);
6014 newCall
->setAttributes(
6015 llvm::AttributeList::get(newFn
->getContext(), oldAttrs
.getFnAttrs(),
6016 oldAttrs
.getRetAttrs(), newArgAttrs
));
6017 newCall
->setCallingConv(callSite
->getCallingConv());
6019 // Finally, remove the old call, replacing any uses with the new one.
6020 if (!callSite
->use_empty())
6021 callSite
->replaceAllUsesWith(newCall
);
6023 // Copy debug location attached to CI.
6024 if (callSite
->getDebugLoc())
6025 newCall
->setDebugLoc(callSite
->getDebugLoc());
6027 callSitesToBeRemovedFromParent
.push_back(callSite
);
6030 for (auto *callSite
: callSitesToBeRemovedFromParent
) {
6031 callSite
->eraseFromParent();
6035 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
6036 /// implement a function with no prototype, e.g. "int foo() {}". If there are
6037 /// existing call uses of the old function in the module, this adjusts them to
6038 /// call the new function directly.
6040 /// This is not just a cleanup: the always_inline pass requires direct calls to
6041 /// functions to be able to inline them. If there is a bitcast in the way, it
6042 /// won't inline them. Instcombine normally deletes these calls, but it isn't
6044 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue
*Old
,
6045 llvm::Function
*NewFn
) {
6046 // If we're redefining a global as a function, don't transform it.
6047 if (!isa
<llvm::Function
>(Old
)) return;
6049 replaceUsesOfNonProtoConstant(Old
, NewFn
);
6052 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl
*VD
) {
6053 auto DK
= VD
->isThisDeclarationADefinition();
6054 if ((DK
== VarDecl::Definition
&& VD
->hasAttr
<DLLImportAttr
>()) ||
6055 (LangOpts
.CUDA
&& !shouldEmitCUDAGlobalVar(VD
)))
6058 TemplateSpecializationKind TSK
= VD
->getTemplateSpecializationKind();
6059 // If we have a definition, this might be a deferred decl. If the
6060 // instantiation is explicit, make sure we emit it at the end.
6061 if (VD
->getDefinition() && TSK
== TSK_ExplicitInstantiationDefinition
)
6062 GetAddrOfGlobalVar(VD
);
6064 EmitTopLevelDecl(VD
);
6067 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD
,
6068 llvm::GlobalValue
*GV
) {
6069 const auto *D
= cast
<FunctionDecl
>(GD
.getDecl());
6071 // Compute the function info and LLVM type.
6072 const CGFunctionInfo
&FI
= getTypes().arrangeGlobalDeclaration(GD
);
6073 llvm::FunctionType
*Ty
= getTypes().GetFunctionType(FI
);
6075 // Get or create the prototype for the function.
6076 if (!GV
|| (GV
->getValueType() != Ty
))
6077 GV
= cast
<llvm::GlobalValue
>(GetAddrOfFunction(GD
, Ty
, /*ForVTable=*/false,
6082 if (!GV
->isDeclaration())
6085 // We need to set linkage and visibility on the function before
6086 // generating code for it because various parts of IR generation
6087 // want to propagate this information down (e.g. to local static
6089 auto *Fn
= cast
<llvm::Function
>(GV
);
6090 setFunctionLinkage(GD
, Fn
);
6092 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
6093 setGVProperties(Fn
, GD
);
6095 MaybeHandleStaticInExternC(D
, Fn
);
6097 maybeSetTrivialComdat(*D
, *Fn
);
6099 CodeGenFunction(*this).GenerateCode(GD
, Fn
, FI
);
6101 setNonAliasAttributes(GD
, Fn
);
6102 SetLLVMFunctionAttributesForDefinition(D
, Fn
);
6104 if (const ConstructorAttr
*CA
= D
->getAttr
<ConstructorAttr
>())
6105 AddGlobalCtor(Fn
, CA
->getPriority());
6106 if (const DestructorAttr
*DA
= D
->getAttr
<DestructorAttr
>())
6107 AddGlobalDtor(Fn
, DA
->getPriority(), true);
6108 if (getLangOpts().OpenMP
&& D
->hasAttr
<OMPDeclareTargetDeclAttr
>())
6109 getOpenMPRuntime().emitDeclareTargetFunction(D
, GV
);
6112 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD
) {
6113 const auto *D
= cast
<ValueDecl
>(GD
.getDecl());
6114 const AliasAttr
*AA
= D
->getAttr
<AliasAttr
>();
6115 assert(AA
&& "Not an alias?");
6117 StringRef MangledName
= getMangledName(GD
);
6119 if (AA
->getAliasee() == MangledName
) {
6120 Diags
.Report(AA
->getLocation(), diag::err_cyclic_alias
) << 0;
6124 // If there is a definition in the module, then it wins over the alias.
6125 // This is dubious, but allow it to be safe. Just ignore the alias.
6126 llvm::GlobalValue
*Entry
= GetGlobalValue(MangledName
);
6127 if (Entry
&& !Entry
->isDeclaration())
6130 Aliases
.push_back(GD
);
6132 llvm::Type
*DeclTy
= getTypes().ConvertTypeForMem(D
->getType());
6134 // Create a reference to the named value. This ensures that it is emitted
6135 // if a deferred decl.
6136 llvm::Constant
*Aliasee
;
6137 llvm::GlobalValue::LinkageTypes LT
;
6138 if (isa
<llvm::FunctionType
>(DeclTy
)) {
6139 Aliasee
= GetOrCreateLLVMFunction(AA
->getAliasee(), DeclTy
, GD
,
6140 /*ForVTable=*/false);
6141 LT
= getFunctionLinkage(GD
);
6143 Aliasee
= GetOrCreateLLVMGlobal(AA
->getAliasee(), DeclTy
, LangAS::Default
,
6145 if (const auto *VD
= dyn_cast
<VarDecl
>(GD
.getDecl()))
6146 LT
= getLLVMLinkageVarDefinition(VD
);
6148 LT
= getFunctionLinkage(GD
);
6151 // Create the new alias itself, but don't set a name yet.
6152 unsigned AS
= Aliasee
->getType()->getPointerAddressSpace();
6154 llvm::GlobalAlias::create(DeclTy
, AS
, LT
, "", Aliasee
, &getModule());
6157 if (GA
->getAliasee() == Entry
) {
6158 Diags
.Report(AA
->getLocation(), diag::err_cyclic_alias
) << 0;
6162 assert(Entry
->isDeclaration());
6164 // If there is a declaration in the module, then we had an extern followed
6165 // by the alias, as in:
6166 // extern int test6();
6168 // int test6() __attribute__((alias("test7")));
6170 // Remove it and replace uses of it with the alias.
6171 GA
->takeName(Entry
);
6173 Entry
->replaceAllUsesWith(GA
);
6174 Entry
->eraseFromParent();
6176 GA
->setName(MangledName
);
6179 // Set attributes which are particular to an alias; this is a
6180 // specialization of the attributes which may be set on a global
6181 // variable/function.
6182 if (D
->hasAttr
<WeakAttr
>() || D
->hasAttr
<WeakRefAttr
>() ||
6183 D
->isWeakImported()) {
6184 GA
->setLinkage(llvm::Function::WeakAnyLinkage
);
6187 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
6188 if (VD
->getTLSKind())
6189 setTLSMode(GA
, *VD
);
6191 SetCommonAttributes(GD
, GA
);
6193 // Emit global alias debug information.
6194 if (isa
<VarDecl
>(D
))
6195 if (CGDebugInfo
*DI
= getModuleDebugInfo())
6196 DI
->EmitGlobalAlias(cast
<llvm::GlobalValue
>(GA
->getAliasee()->stripPointerCasts()), GD
);
6199 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD
) {
6200 const auto *D
= cast
<ValueDecl
>(GD
.getDecl());
6201 const IFuncAttr
*IFA
= D
->getAttr
<IFuncAttr
>();
6202 assert(IFA
&& "Not an ifunc?");
6204 StringRef MangledName
= getMangledName(GD
);
6206 if (IFA
->getResolver() == MangledName
) {
6207 Diags
.Report(IFA
->getLocation(), diag::err_cyclic_alias
) << 1;
6211 // Report an error if some definition overrides ifunc.
6212 llvm::GlobalValue
*Entry
= GetGlobalValue(MangledName
);
6213 if (Entry
&& !Entry
->isDeclaration()) {
6215 if (lookupRepresentativeDecl(MangledName
, OtherGD
) &&
6216 DiagnosedConflictingDefinitions
.insert(GD
).second
) {
6217 Diags
.Report(D
->getLocation(), diag::err_duplicate_mangled_name
)
6219 Diags
.Report(OtherGD
.getDecl()->getLocation(),
6220 diag::note_previous_definition
);
6225 Aliases
.push_back(GD
);
6227 // The resolver might not be visited yet. Specify a dummy non-function type to
6228 // indicate IsIncompleteFunction. Either the type is ignored (if the resolver
6229 // was emitted) or the whole function will be replaced (if the resolver has
6230 // not been emitted).
6231 llvm::Constant
*Resolver
=
6232 GetOrCreateLLVMFunction(IFA
->getResolver(), VoidTy
, {},
6233 /*ForVTable=*/false);
6234 llvm::Type
*DeclTy
= getTypes().ConvertTypeForMem(D
->getType());
6235 unsigned AS
= getTypes().getTargetAddressSpace(D
->getType());
6236 llvm::GlobalIFunc
*GIF
= llvm::GlobalIFunc::create(
6237 DeclTy
, AS
, llvm::Function::ExternalLinkage
, "", Resolver
, &getModule());
6239 if (GIF
->getResolver() == Entry
) {
6240 Diags
.Report(IFA
->getLocation(), diag::err_cyclic_alias
) << 1;
6243 assert(Entry
->isDeclaration());
6245 // If there is a declaration in the module, then we had an extern followed
6246 // by the ifunc, as in:
6247 // extern int test();
6249 // int test() __attribute__((ifunc("resolver")));
6251 // Remove it and replace uses of it with the ifunc.
6252 GIF
->takeName(Entry
);
6254 Entry
->replaceAllUsesWith(GIF
);
6255 Entry
->eraseFromParent();
6257 GIF
->setName(MangledName
);
6258 SetCommonAttributes(GD
, GIF
);
6261 llvm::Function
*CodeGenModule::getIntrinsic(unsigned IID
,
6262 ArrayRef
<llvm::Type
*> Tys
) {
6263 return llvm::Intrinsic::getOrInsertDeclaration(&getModule(),
6264 (llvm::Intrinsic::ID
)IID
, Tys
);
6267 static llvm::StringMapEntry
<llvm::GlobalVariable
*> &
6268 GetConstantCFStringEntry(llvm::StringMap
<llvm::GlobalVariable
*> &Map
,
6269 const StringLiteral
*Literal
, bool TargetIsLSB
,
6270 bool &IsUTF16
, unsigned &StringLength
) {
6271 StringRef String
= Literal
->getString();
6272 unsigned NumBytes
= String
.size();
6274 // Check for simple case.
6275 if (!Literal
->containsNonAsciiOrNull()) {
6276 StringLength
= NumBytes
;
6277 return *Map
.insert(std::make_pair(String
, nullptr)).first
;
6280 // Otherwise, convert the UTF8 literals into a string of shorts.
6283 SmallVector
<llvm::UTF16
, 128> ToBuf(NumBytes
+ 1); // +1 for ending nulls.
6284 const llvm::UTF8
*FromPtr
= (const llvm::UTF8
*)String
.data();
6285 llvm::UTF16
*ToPtr
= &ToBuf
[0];
6287 (void)llvm::ConvertUTF8toUTF16(&FromPtr
, FromPtr
+ NumBytes
, &ToPtr
,
6288 ToPtr
+ NumBytes
, llvm::strictConversion
);
6290 // ConvertUTF8toUTF16 returns the length in ToPtr.
6291 StringLength
= ToPtr
- &ToBuf
[0];
6293 // Add an explicit null.
6295 return *Map
.insert(std::make_pair(
6296 StringRef(reinterpret_cast<const char *>(ToBuf
.data()),
6297 (StringLength
+ 1) * 2),
6302 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral
*Literal
) {
6303 unsigned StringLength
= 0;
6304 bool isUTF16
= false;
6305 llvm::StringMapEntry
<llvm::GlobalVariable
*> &Entry
=
6306 GetConstantCFStringEntry(CFConstantStringMap
, Literal
,
6307 getDataLayout().isLittleEndian(), isUTF16
,
6310 if (auto *C
= Entry
.second
)
6311 return ConstantAddress(
6312 C
, C
->getValueType(), CharUnits::fromQuantity(C
->getAlignment()));
6314 const ASTContext
&Context
= getContext();
6315 const llvm::Triple
&Triple
= getTriple();
6317 const auto CFRuntime
= getLangOpts().CFRuntime
;
6318 const bool IsSwiftABI
=
6319 static_cast<unsigned>(CFRuntime
) >=
6320 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift
);
6321 const bool IsSwift4_1
= CFRuntime
== LangOptions::CoreFoundationABI::Swift4_1
;
6323 // If we don't already have it, get __CFConstantStringClassReference.
6324 if (!CFConstantStringClassRef
) {
6325 const char *CFConstantStringClassName
= "__CFConstantStringClassReference";
6326 llvm::Type
*Ty
= getTypes().ConvertType(getContext().IntTy
);
6327 Ty
= llvm::ArrayType::get(Ty
, 0);
6329 switch (CFRuntime
) {
6331 case LangOptions::CoreFoundationABI::Swift
: [[fallthrough
]];
6332 case LangOptions::CoreFoundationABI::Swift5_0
:
6333 CFConstantStringClassName
=
6334 Triple
.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
6335 : "$s10Foundation19_NSCFConstantStringCN";
6338 case LangOptions::CoreFoundationABI::Swift4_2
:
6339 CFConstantStringClassName
=
6340 Triple
.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
6341 : "$S10Foundation19_NSCFConstantStringCN";
6344 case LangOptions::CoreFoundationABI::Swift4_1
:
6345 CFConstantStringClassName
=
6346 Triple
.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
6347 : "__T010Foundation19_NSCFConstantStringCN";
6352 llvm::Constant
*C
= CreateRuntimeVariable(Ty
, CFConstantStringClassName
);
6354 if (Triple
.isOSBinFormatELF() || Triple
.isOSBinFormatCOFF()) {
6355 llvm::GlobalValue
*GV
= nullptr;
6357 if ((GV
= dyn_cast
<llvm::GlobalValue
>(C
))) {
6358 IdentifierInfo
&II
= Context
.Idents
.get(GV
->getName());
6359 TranslationUnitDecl
*TUDecl
= Context
.getTranslationUnitDecl();
6360 DeclContext
*DC
= TranslationUnitDecl::castToDeclContext(TUDecl
);
6362 const VarDecl
*VD
= nullptr;
6363 for (const auto *Result
: DC
->lookup(&II
))
6364 if ((VD
= dyn_cast
<VarDecl
>(Result
)))
6367 if (Triple
.isOSBinFormatELF()) {
6369 GV
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
6371 GV
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
6372 if (!VD
|| !VD
->hasAttr
<DLLExportAttr
>())
6373 GV
->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass
);
6375 GV
->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
6382 // Decay array -> ptr
6383 CFConstantStringClassRef
=
6384 IsSwiftABI
? llvm::ConstantExpr::getPtrToInt(C
, Ty
) : C
;
6387 QualType CFTy
= Context
.getCFConstantStringType();
6389 auto *STy
= cast
<llvm::StructType
>(getTypes().ConvertType(CFTy
));
6391 ConstantInitBuilder
Builder(*this);
6392 auto Fields
= Builder
.beginStruct(STy
);
6395 Fields
.add(cast
<llvm::Constant
>(CFConstantStringClassRef
));
6399 Fields
.addInt(IntPtrTy
, IsSwift4_1
? 0x05 : 0x01);
6400 Fields
.addInt(Int64Ty
, isUTF16
? 0x07d0 : 0x07c8);
6402 Fields
.addInt(IntTy
, isUTF16
? 0x07d0 : 0x07C8);
6406 llvm::Constant
*C
= nullptr;
6408 auto Arr
= llvm::ArrayRef(
6409 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry
.first().data())),
6410 Entry
.first().size() / 2);
6411 C
= llvm::ConstantDataArray::get(VMContext
, Arr
);
6413 C
= llvm::ConstantDataArray::getString(VMContext
, Entry
.first());
6416 // Note: -fwritable-strings doesn't make the backing store strings of
6417 // CFStrings writable.
6419 new llvm::GlobalVariable(getModule(), C
->getType(), /*isConstant=*/true,
6420 llvm::GlobalValue::PrivateLinkage
, C
, ".str");
6421 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
6422 // Don't enforce the target's minimum global alignment, since the only use
6423 // of the string is via this class initializer.
6424 CharUnits Align
= isUTF16
? Context
.getTypeAlignInChars(Context
.ShortTy
)
6425 : Context
.getTypeAlignInChars(Context
.CharTy
);
6426 GV
->setAlignment(Align
.getAsAlign());
6428 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
6429 // Without it LLVM can merge the string with a non unnamed_addr one during
6430 // LTO. Doing that changes the section it ends in, which surprises ld64.
6431 if (Triple
.isOSBinFormatMachO())
6432 GV
->setSection(isUTF16
? "__TEXT,__ustring"
6433 : "__TEXT,__cstring,cstring_literals");
6434 // Make sure the literal ends up in .rodata to allow for safe ICF and for
6435 // the static linker to adjust permissions to read-only later on.
6436 else if (Triple
.isOSBinFormatELF())
6437 GV
->setSection(".rodata");
6443 llvm::IntegerType
*LengthTy
=
6444 llvm::IntegerType::get(getModule().getContext(),
6445 Context
.getTargetInfo().getLongWidth());
6447 if (CFRuntime
== LangOptions::CoreFoundationABI::Swift4_1
||
6448 CFRuntime
== LangOptions::CoreFoundationABI::Swift4_2
)
6451 LengthTy
= IntPtrTy
;
6453 Fields
.addInt(LengthTy
, StringLength
);
6455 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6456 // properly aligned on 32-bit platforms.
6457 CharUnits Alignment
=
6458 IsSwiftABI
? Context
.toCharUnitsFromBits(64) : getPointerAlign();
6461 GV
= Fields
.finishAndCreateGlobal("_unnamed_cfstring_", Alignment
,
6462 /*isConstant=*/false,
6463 llvm::GlobalVariable::PrivateLinkage
);
6464 GV
->addAttribute("objc_arc_inert");
6465 switch (Triple
.getObjectFormat()) {
6466 case llvm::Triple::UnknownObjectFormat
:
6467 llvm_unreachable("unknown file format");
6468 case llvm::Triple::DXContainer
:
6469 case llvm::Triple::GOFF
:
6470 case llvm::Triple::SPIRV
:
6471 case llvm::Triple::XCOFF
:
6472 llvm_unreachable("unimplemented");
6473 case llvm::Triple::COFF
:
6474 case llvm::Triple::ELF
:
6475 case llvm::Triple::Wasm
:
6476 GV
->setSection("cfstring");
6478 case llvm::Triple::MachO
:
6479 GV
->setSection("__DATA,__cfstring");
6484 return ConstantAddress(GV
, GV
->getValueType(), Alignment
);
6487 bool CodeGenModule::getExpressionLocationsEnabled() const {
6488 return !CodeGenOpts
.EmitCodeView
|| CodeGenOpts
.DebugColumnInfo
;
6491 QualType
CodeGenModule::getObjCFastEnumerationStateType() {
6492 if (ObjCFastEnumerationStateType
.isNull()) {
6493 RecordDecl
*D
= Context
.buildImplicitRecord("__objcFastEnumerationState");
6494 D
->startDefinition();
6496 QualType FieldTypes
[] = {
6497 Context
.UnsignedLongTy
, Context
.getPointerType(Context
.getObjCIdType()),
6498 Context
.getPointerType(Context
.UnsignedLongTy
),
6499 Context
.getConstantArrayType(Context
.UnsignedLongTy
, llvm::APInt(32, 5),
6500 nullptr, ArraySizeModifier::Normal
, 0)};
6502 for (size_t i
= 0; i
< 4; ++i
) {
6503 FieldDecl
*Field
= FieldDecl::Create(Context
,
6506 SourceLocation(), nullptr,
6507 FieldTypes
[i
], /*TInfo=*/nullptr,
6508 /*BitWidth=*/nullptr,
6511 Field
->setAccess(AS_public
);
6515 D
->completeDefinition();
6516 ObjCFastEnumerationStateType
= Context
.getTagDeclType(D
);
6519 return ObjCFastEnumerationStateType
;
6523 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral
*E
) {
6524 assert(!E
->getType()->isPointerType() && "Strings are always arrays");
6526 // Don't emit it as the address of the string, emit the string data itself
6527 // as an inline array.
6528 if (E
->getCharByteWidth() == 1) {
6529 SmallString
<64> Str(E
->getString());
6531 // Resize the string to the right size, which is indicated by its type.
6532 const ConstantArrayType
*CAT
= Context
.getAsConstantArrayType(E
->getType());
6533 assert(CAT
&& "String literal not of constant array type!");
6534 Str
.resize(CAT
->getZExtSize());
6535 return llvm::ConstantDataArray::getString(VMContext
, Str
, false);
6538 auto *AType
= cast
<llvm::ArrayType
>(getTypes().ConvertType(E
->getType()));
6539 llvm::Type
*ElemTy
= AType
->getElementType();
6540 unsigned NumElements
= AType
->getNumElements();
6542 // Wide strings have either 2-byte or 4-byte elements.
6543 if (ElemTy
->getPrimitiveSizeInBits() == 16) {
6544 SmallVector
<uint16_t, 32> Elements
;
6545 Elements
.reserve(NumElements
);
6547 for(unsigned i
= 0, e
= E
->getLength(); i
!= e
; ++i
)
6548 Elements
.push_back(E
->getCodeUnit(i
));
6549 Elements
.resize(NumElements
);
6550 return llvm::ConstantDataArray::get(VMContext
, Elements
);
6553 assert(ElemTy
->getPrimitiveSizeInBits() == 32);
6554 SmallVector
<uint32_t, 32> Elements
;
6555 Elements
.reserve(NumElements
);
6557 for(unsigned i
= 0, e
= E
->getLength(); i
!= e
; ++i
)
6558 Elements
.push_back(E
->getCodeUnit(i
));
6559 Elements
.resize(NumElements
);
6560 return llvm::ConstantDataArray::get(VMContext
, Elements
);
6563 static llvm::GlobalVariable
*
6564 GenerateStringLiteral(llvm::Constant
*C
, llvm::GlobalValue::LinkageTypes LT
,
6565 CodeGenModule
&CGM
, StringRef GlobalName
,
6566 CharUnits Alignment
) {
6567 unsigned AddrSpace
= CGM
.getContext().getTargetAddressSpace(
6568 CGM
.GetGlobalConstantAddressSpace());
6570 llvm::Module
&M
= CGM
.getModule();
6571 // Create a global variable for this string
6572 auto *GV
= new llvm::GlobalVariable(
6573 M
, C
->getType(), !CGM
.getLangOpts().WritableStrings
, LT
, C
, GlobalName
,
6574 nullptr, llvm::GlobalVariable::NotThreadLocal
, AddrSpace
);
6575 GV
->setAlignment(Alignment
.getAsAlign());
6576 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
6577 if (GV
->isWeakForLinker()) {
6578 assert(CGM
.supportsCOMDAT() && "Only COFF uses weak string literals");
6579 GV
->setComdat(M
.getOrInsertComdat(GV
->getName()));
6581 CGM
.setDSOLocal(GV
);
6586 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
6587 /// constant array for the given string literal.
6589 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral
*S
,
6591 CharUnits Alignment
=
6592 getContext().getAlignOfGlobalVarInChars(S
->getType(), /*VD=*/nullptr);
6594 llvm::Constant
*C
= GetConstantArrayFromStringLiteral(S
);
6595 llvm::GlobalVariable
**Entry
= nullptr;
6596 if (!LangOpts
.WritableStrings
) {
6597 Entry
= &ConstantStringMap
[C
];
6598 if (auto GV
= *Entry
) {
6599 if (uint64_t(Alignment
.getQuantity()) > GV
->getAlignment())
6600 GV
->setAlignment(Alignment
.getAsAlign());
6601 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV
),
6602 GV
->getValueType(), Alignment
);
6606 SmallString
<256> MangledNameBuffer
;
6607 StringRef GlobalVariableName
;
6608 llvm::GlobalValue::LinkageTypes LT
;
6610 // Mangle the string literal if that's how the ABI merges duplicate strings.
6611 // Don't do it if they are writable, since we don't want writes in one TU to
6612 // affect strings in another.
6613 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S
) &&
6614 !LangOpts
.WritableStrings
) {
6615 llvm::raw_svector_ostream
Out(MangledNameBuffer
);
6616 getCXXABI().getMangleContext().mangleStringLiteral(S
, Out
);
6617 LT
= llvm::GlobalValue::LinkOnceODRLinkage
;
6618 GlobalVariableName
= MangledNameBuffer
;
6620 LT
= llvm::GlobalValue::PrivateLinkage
;
6621 GlobalVariableName
= Name
;
6624 auto GV
= GenerateStringLiteral(C
, LT
, *this, GlobalVariableName
, Alignment
);
6626 CGDebugInfo
*DI
= getModuleDebugInfo();
6627 if (DI
&& getCodeGenOpts().hasReducedDebugInfo())
6628 DI
->AddStringLiteralDebugInfo(GV
, S
);
6633 SanitizerMD
->reportGlobal(GV
, S
->getStrTokenLoc(0), "<string literal>");
6635 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV
),
6636 GV
->getValueType(), Alignment
);
6639 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
6640 /// array for the given ObjCEncodeExpr node.
6642 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr
*E
) {
6644 getContext().getObjCEncodingForType(E
->getEncodedType(), Str
);
6646 return GetAddrOfConstantCString(Str
);
6649 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
6650 /// the literal and a terminating '\0' character.
6651 /// The result has pointer to array type.
6652 ConstantAddress
CodeGenModule::GetAddrOfConstantCString(
6653 const std::string
&Str
, const char *GlobalName
) {
6654 StringRef
StrWithNull(Str
.c_str(), Str
.size() + 1);
6655 CharUnits Alignment
= getContext().getAlignOfGlobalVarInChars(
6656 getContext().CharTy
, /*VD=*/nullptr);
6659 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull
, false);
6661 // Don't share any string literals if strings aren't constant.
6662 llvm::GlobalVariable
**Entry
= nullptr;
6663 if (!LangOpts
.WritableStrings
) {
6664 Entry
= &ConstantStringMap
[C
];
6665 if (auto GV
= *Entry
) {
6666 if (uint64_t(Alignment
.getQuantity()) > GV
->getAlignment())
6667 GV
->setAlignment(Alignment
.getAsAlign());
6668 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV
),
6669 GV
->getValueType(), Alignment
);
6673 // Get the default prefix if a name wasn't specified.
6675 GlobalName
= ".str";
6676 // Create a global variable for this.
6677 auto GV
= GenerateStringLiteral(C
, llvm::GlobalValue::PrivateLinkage
, *this,
6678 GlobalName
, Alignment
);
6682 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV
),
6683 GV
->getValueType(), Alignment
);
6686 ConstantAddress
CodeGenModule::GetAddrOfGlobalTemporary(
6687 const MaterializeTemporaryExpr
*E
, const Expr
*Init
) {
6688 assert((E
->getStorageDuration() == SD_Static
||
6689 E
->getStorageDuration() == SD_Thread
) && "not a global temporary");
6690 const auto *VD
= cast
<VarDecl
>(E
->getExtendingDecl());
6692 // If we're not materializing a subobject of the temporary, keep the
6693 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6694 QualType MaterializedType
= Init
->getType();
6695 if (Init
== E
->getSubExpr())
6696 MaterializedType
= E
->getType();
6698 CharUnits Align
= getContext().getTypeAlignInChars(MaterializedType
);
6700 auto InsertResult
= MaterializedGlobalTemporaryMap
.insert({E
, nullptr});
6701 if (!InsertResult
.second
) {
6702 // We've seen this before: either we already created it or we're in the
6703 // process of doing so.
6704 if (!InsertResult
.first
->second
) {
6705 // We recursively re-entered this function, probably during emission of
6706 // the initializer. Create a placeholder. We'll clean this up in the
6707 // outer call, at the end of this function.
6708 llvm::Type
*Type
= getTypes().ConvertTypeForMem(MaterializedType
);
6709 InsertResult
.first
->second
= new llvm::GlobalVariable(
6710 getModule(), Type
, false, llvm::GlobalVariable::InternalLinkage
,
6713 return ConstantAddress(InsertResult
.first
->second
,
6714 llvm::cast
<llvm::GlobalVariable
>(
6715 InsertResult
.first
->second
->stripPointerCasts())
6720 // FIXME: If an externally-visible declaration extends multiple temporaries,
6721 // we need to give each temporary the same name in every translation unit (and
6722 // we also need to make the temporaries externally-visible).
6723 SmallString
<256> Name
;
6724 llvm::raw_svector_ostream
Out(Name
);
6725 getCXXABI().getMangleContext().mangleReferenceTemporary(
6726 VD
, E
->getManglingNumber(), Out
);
6728 APValue
*Value
= nullptr;
6729 if (E
->getStorageDuration() == SD_Static
&& VD
->evaluateValue()) {
6730 // If the initializer of the extending declaration is a constant
6731 // initializer, we should have a cached constant initializer for this
6732 // temporary. Note that this might have a different value from the value
6733 // computed by evaluating the initializer if the surrounding constant
6734 // expression modifies the temporary.
6735 Value
= E
->getOrCreateValue(false);
6738 // Try evaluating it now, it might have a constant initializer.
6739 Expr::EvalResult EvalResult
;
6740 if (!Value
&& Init
->EvaluateAsRValue(EvalResult
, getContext()) &&
6741 !EvalResult
.hasSideEffects())
6742 Value
= &EvalResult
.Val
;
6744 LangAS AddrSpace
= GetGlobalVarAddressSpace(VD
);
6746 std::optional
<ConstantEmitter
> emitter
;
6747 llvm::Constant
*InitialValue
= nullptr;
6748 bool Constant
= false;
6751 // The temporary has a constant initializer, use it.
6752 emitter
.emplace(*this);
6753 InitialValue
= emitter
->emitForInitializer(*Value
, AddrSpace
,
6756 MaterializedType
.isConstantStorage(getContext(), /*ExcludeCtor*/ Value
,
6757 /*ExcludeDtor*/ false);
6758 Type
= InitialValue
->getType();
6760 // No initializer, the initialization will be provided when we
6761 // initialize the declaration which performed lifetime extension.
6762 Type
= getTypes().ConvertTypeForMem(MaterializedType
);
6765 // Create a global variable for this lifetime-extended temporary.
6766 llvm::GlobalValue::LinkageTypes Linkage
= getLLVMLinkageVarDefinition(VD
);
6767 if (Linkage
== llvm::GlobalVariable::ExternalLinkage
) {
6768 const VarDecl
*InitVD
;
6769 if (VD
->isStaticDataMember() && VD
->getAnyInitializer(InitVD
) &&
6770 isa
<CXXRecordDecl
>(InitVD
->getLexicalDeclContext())) {
6771 // Temporaries defined inside a class get linkonce_odr linkage because the
6772 // class can be defined in multiple translation units.
6773 Linkage
= llvm::GlobalVariable::LinkOnceODRLinkage
;
6775 // There is no need for this temporary to have external linkage if the
6776 // VarDecl has external linkage.
6777 Linkage
= llvm::GlobalVariable::InternalLinkage
;
6780 auto TargetAS
= getContext().getTargetAddressSpace(AddrSpace
);
6781 auto *GV
= new llvm::GlobalVariable(
6782 getModule(), Type
, Constant
, Linkage
, InitialValue
, Name
.c_str(),
6783 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal
, TargetAS
);
6784 if (emitter
) emitter
->finalize(GV
);
6785 // Don't assign dllimport or dllexport to local linkage globals.
6786 if (!llvm::GlobalValue::isLocalLinkage(Linkage
)) {
6787 setGVProperties(GV
, VD
);
6788 if (GV
->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass
)
6789 // The reference temporary should never be dllexport.
6790 GV
->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass
);
6792 GV
->setAlignment(Align
.getAsAlign());
6793 if (supportsCOMDAT() && GV
->isWeakForLinker())
6794 GV
->setComdat(TheModule
.getOrInsertComdat(GV
->getName()));
6795 if (VD
->getTLSKind())
6796 setTLSMode(GV
, *VD
);
6797 llvm::Constant
*CV
= GV
;
6798 if (AddrSpace
!= LangAS::Default
)
6799 CV
= getTargetCodeGenInfo().performAddrSpaceCast(
6800 *this, GV
, AddrSpace
, LangAS::Default
,
6801 llvm::PointerType::get(
6803 getContext().getTargetAddressSpace(LangAS::Default
)));
6805 // Update the map with the new temporary. If we created a placeholder above,
6806 // replace it with the new global now.
6807 llvm::Constant
*&Entry
= MaterializedGlobalTemporaryMap
[E
];
6809 Entry
->replaceAllUsesWith(CV
);
6810 llvm::cast
<llvm::GlobalVariable
>(Entry
)->eraseFromParent();
6814 return ConstantAddress(CV
, Type
, Align
);
6817 /// EmitObjCPropertyImplementations - Emit information for synthesized
6818 /// properties for an implementation.
6819 void CodeGenModule::EmitObjCPropertyImplementations(const
6820 ObjCImplementationDecl
*D
) {
6821 for (const auto *PID
: D
->property_impls()) {
6822 // Dynamic is just for type-checking.
6823 if (PID
->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize
) {
6824 ObjCPropertyDecl
*PD
= PID
->getPropertyDecl();
6826 // Determine which methods need to be implemented, some may have
6827 // been overridden. Note that ::isPropertyAccessor is not the method
6828 // we want, that just indicates if the decl came from a
6829 // property. What we want to know is if the method is defined in
6830 // this implementation.
6831 auto *Getter
= PID
->getGetterMethodDecl();
6832 if (!Getter
|| Getter
->isSynthesizedAccessorStub())
6833 CodeGenFunction(*this).GenerateObjCGetter(
6834 const_cast<ObjCImplementationDecl
*>(D
), PID
);
6835 auto *Setter
= PID
->getSetterMethodDecl();
6836 if (!PD
->isReadOnly() && (!Setter
|| Setter
->isSynthesizedAccessorStub()))
6837 CodeGenFunction(*this).GenerateObjCSetter(
6838 const_cast<ObjCImplementationDecl
*>(D
), PID
);
6843 static bool needsDestructMethod(ObjCImplementationDecl
*impl
) {
6844 const ObjCInterfaceDecl
*iface
= impl
->getClassInterface();
6845 for (const ObjCIvarDecl
*ivar
= iface
->all_declared_ivar_begin();
6846 ivar
; ivar
= ivar
->getNextIvar())
6847 if (ivar
->getType().isDestructedType())
6853 static bool AllTrivialInitializers(CodeGenModule
&CGM
,
6854 ObjCImplementationDecl
*D
) {
6855 CodeGenFunction
CGF(CGM
);
6856 for (ObjCImplementationDecl::init_iterator B
= D
->init_begin(),
6857 E
= D
->init_end(); B
!= E
; ++B
) {
6858 CXXCtorInitializer
*CtorInitExp
= *B
;
6859 Expr
*Init
= CtorInitExp
->getInit();
6860 if (!CGF
.isTrivialInitializer(Init
))
6866 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6867 /// for an implementation.
6868 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl
*D
) {
6869 // We might need a .cxx_destruct even if we don't have any ivar initializers.
6870 if (needsDestructMethod(D
)) {
6871 const IdentifierInfo
*II
= &getContext().Idents
.get(".cxx_destruct");
6872 Selector cxxSelector
= getContext().Selectors
.getSelector(0, &II
);
6873 ObjCMethodDecl
*DTORMethod
= ObjCMethodDecl::Create(
6874 getContext(), D
->getLocation(), D
->getLocation(), cxxSelector
,
6875 getContext().VoidTy
, nullptr, D
,
6876 /*isInstance=*/true, /*isVariadic=*/false,
6877 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6878 /*isImplicitlyDeclared=*/true,
6879 /*isDefined=*/false, ObjCImplementationControl::Required
);
6880 D
->addInstanceMethod(DTORMethod
);
6881 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D
, DTORMethod
, false);
6882 D
->setHasDestructors(true);
6885 // If the implementation doesn't have any ivar initializers, we don't need
6886 // a .cxx_construct.
6887 if (D
->getNumIvarInitializers() == 0 ||
6888 AllTrivialInitializers(*this, D
))
6891 const IdentifierInfo
*II
= &getContext().Idents
.get(".cxx_construct");
6892 Selector cxxSelector
= getContext().Selectors
.getSelector(0, &II
);
6893 // The constructor returns 'self'.
6894 ObjCMethodDecl
*CTORMethod
= ObjCMethodDecl::Create(
6895 getContext(), D
->getLocation(), D
->getLocation(), cxxSelector
,
6896 getContext().getObjCIdType(), nullptr, D
, /*isInstance=*/true,
6897 /*isVariadic=*/false,
6898 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6899 /*isImplicitlyDeclared=*/true,
6900 /*isDefined=*/false, ObjCImplementationControl::Required
);
6901 D
->addInstanceMethod(CTORMethod
);
6902 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D
, CTORMethod
, true);
6903 D
->setHasNonZeroConstructors(true);
6906 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6907 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl
*LSD
) {
6908 if (LSD
->getLanguage() != LinkageSpecLanguageIDs::C
&&
6909 LSD
->getLanguage() != LinkageSpecLanguageIDs::CXX
) {
6910 ErrorUnsupported(LSD
, "linkage spec");
6914 EmitDeclContext(LSD
);
6917 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl
*D
) {
6918 // Device code should not be at top level.
6919 if (LangOpts
.CUDA
&& LangOpts
.CUDAIsDevice
)
6922 std::unique_ptr
<CodeGenFunction
> &CurCGF
=
6923 GlobalTopLevelStmtBlockInFlight
.first
;
6925 // We emitted a top-level stmt but after it there is initialization.
6926 // Stop squashing the top-level stmts into a single function.
6927 if (CurCGF
&& CXXGlobalInits
.back() != CurCGF
->CurFn
) {
6928 CurCGF
->FinishFunction(D
->getEndLoc());
6933 // void __stmts__N(void)
6934 // FIXME: Ask the ABI name mangler to pick a name.
6935 std::string Name
= "__stmts__" + llvm::utostr(CXXGlobalInits
.size());
6936 FunctionArgList Args
;
6937 QualType RetTy
= getContext().VoidTy
;
6938 const CGFunctionInfo
&FnInfo
=
6939 getTypes().arrangeBuiltinFunctionDeclaration(RetTy
, Args
);
6940 llvm::FunctionType
*FnTy
= getTypes().GetFunctionType(FnInfo
);
6941 llvm::Function
*Fn
= llvm::Function::Create(
6942 FnTy
, llvm::GlobalValue::InternalLinkage
, Name
, &getModule());
6944 CurCGF
.reset(new CodeGenFunction(*this));
6945 GlobalTopLevelStmtBlockInFlight
.second
= D
;
6946 CurCGF
->StartFunction(GlobalDecl(), RetTy
, Fn
, FnInfo
, Args
,
6947 D
->getBeginLoc(), D
->getBeginLoc());
6948 CXXGlobalInits
.push_back(Fn
);
6951 CurCGF
->EmitStmt(D
->getStmt());
6954 void CodeGenModule::EmitDeclContext(const DeclContext
*DC
) {
6955 for (auto *I
: DC
->decls()) {
6956 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6957 // are themselves considered "top-level", so EmitTopLevelDecl on an
6958 // ObjCImplDecl does not recursively visit them. We need to do that in
6959 // case they're nested inside another construct (LinkageSpecDecl /
6960 // ExportDecl) that does stop them from being considered "top-level".
6961 if (auto *OID
= dyn_cast
<ObjCImplDecl
>(I
)) {
6962 for (auto *M
: OID
->methods())
6963 EmitTopLevelDecl(M
);
6966 EmitTopLevelDecl(I
);
6970 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6971 void CodeGenModule::EmitTopLevelDecl(Decl
*D
) {
6972 // Ignore dependent declarations.
6973 if (D
->isTemplated())
6976 // Consteval function shouldn't be emitted.
6977 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
); FD
&& FD
->isImmediateFunction())
6980 switch (D
->getKind()) {
6981 case Decl::CXXConversion
:
6982 case Decl::CXXMethod
:
6983 case Decl::Function
:
6984 EmitGlobal(cast
<FunctionDecl
>(D
));
6985 // Always provide some coverage mapping
6986 // even for the functions that aren't emitted.
6987 AddDeferredUnusedCoverageMapping(D
);
6990 case Decl::CXXDeductionGuide
:
6991 // Function-like, but does not result in code emission.
6995 case Decl::Decomposition
:
6996 case Decl::VarTemplateSpecialization
:
6997 EmitGlobal(cast
<VarDecl
>(D
));
6998 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
))
6999 for (auto *B
: DD
->bindings())
7000 if (auto *HD
= B
->getHoldingVar())
7004 // Indirect fields from global anonymous structs and unions can be
7005 // ignored; only the actual variable requires IR gen support.
7006 case Decl::IndirectField
:
7010 case Decl::Namespace
:
7011 EmitDeclContext(cast
<NamespaceDecl
>(D
));
7013 case Decl::ClassTemplateSpecialization
: {
7014 const auto *Spec
= cast
<ClassTemplateSpecializationDecl
>(D
);
7015 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7016 if (Spec
->getSpecializationKind() ==
7017 TSK_ExplicitInstantiationDefinition
&&
7018 Spec
->hasDefinition())
7019 DI
->completeTemplateDefinition(*Spec
);
7021 case Decl::CXXRecord
: {
7022 CXXRecordDecl
*CRD
= cast
<CXXRecordDecl
>(D
);
7023 if (CGDebugInfo
*DI
= getModuleDebugInfo()) {
7024 if (CRD
->hasDefinition())
7025 DI
->EmitAndRetainType(getContext().getRecordType(cast
<RecordDecl
>(D
)));
7026 if (auto *ES
= D
->getASTContext().getExternalSource())
7027 if (ES
->hasExternalDefinitions(D
) == ExternalASTSource::EK_Never
)
7028 DI
->completeUnusedClass(*CRD
);
7030 // Emit any static data members, they may be definitions.
7031 for (auto *I
: CRD
->decls())
7032 if (isa
<VarDecl
>(I
) || isa
<CXXRecordDecl
>(I
))
7033 EmitTopLevelDecl(I
);
7036 // No code generation needed.
7037 case Decl::UsingShadow
:
7038 case Decl::ClassTemplate
:
7039 case Decl::VarTemplate
:
7041 case Decl::VarTemplatePartialSpecialization
:
7042 case Decl::FunctionTemplate
:
7043 case Decl::TypeAliasTemplate
:
7048 case Decl::Using
: // using X; [C++]
7049 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7050 DI
->EmitUsingDecl(cast
<UsingDecl
>(*D
));
7052 case Decl::UsingEnum
: // using enum X; [C++]
7053 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7054 DI
->EmitUsingEnumDecl(cast
<UsingEnumDecl
>(*D
));
7056 case Decl::NamespaceAlias
:
7057 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7058 DI
->EmitNamespaceAlias(cast
<NamespaceAliasDecl
>(*D
));
7060 case Decl::UsingDirective
: // using namespace X; [C++]
7061 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7062 DI
->EmitUsingDirective(cast
<UsingDirectiveDecl
>(*D
));
7064 case Decl::CXXConstructor
:
7065 getCXXABI().EmitCXXConstructors(cast
<CXXConstructorDecl
>(D
));
7067 case Decl::CXXDestructor
:
7068 getCXXABI().EmitCXXDestructors(cast
<CXXDestructorDecl
>(D
));
7071 case Decl::StaticAssert
:
7075 // Objective-C Decls
7077 // Forward declarations, no (immediate) code generation.
7078 case Decl::ObjCInterface
:
7079 case Decl::ObjCCategory
:
7082 case Decl::ObjCProtocol
: {
7083 auto *Proto
= cast
<ObjCProtocolDecl
>(D
);
7084 if (Proto
->isThisDeclarationADefinition())
7085 ObjCRuntime
->GenerateProtocol(Proto
);
7089 case Decl::ObjCCategoryImpl
:
7090 // Categories have properties but don't support synthesize so we
7091 // can ignore them here.
7092 ObjCRuntime
->GenerateCategory(cast
<ObjCCategoryImplDecl
>(D
));
7095 case Decl::ObjCImplementation
: {
7096 auto *OMD
= cast
<ObjCImplementationDecl
>(D
);
7097 EmitObjCPropertyImplementations(OMD
);
7098 EmitObjCIvarInitializations(OMD
);
7099 ObjCRuntime
->GenerateClass(OMD
);
7100 // Emit global variable debug information.
7101 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7102 if (getCodeGenOpts().hasReducedDebugInfo())
7103 DI
->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
7104 OMD
->getClassInterface()), OMD
->getLocation());
7107 case Decl::ObjCMethod
: {
7108 auto *OMD
= cast
<ObjCMethodDecl
>(D
);
7109 // If this is not a prototype, emit the body.
7111 CodeGenFunction(*this).GenerateObjCMethod(OMD
);
7114 case Decl::ObjCCompatibleAlias
:
7115 ObjCRuntime
->RegisterAlias(cast
<ObjCCompatibleAliasDecl
>(D
));
7118 case Decl::PragmaComment
: {
7119 const auto *PCD
= cast
<PragmaCommentDecl
>(D
);
7120 switch (PCD
->getCommentKind()) {
7122 llvm_unreachable("unexpected pragma comment kind");
7124 AppendLinkerOptions(PCD
->getArg());
7127 AddDependentLib(PCD
->getArg());
7132 break; // We ignore all of these.
7137 case Decl::PragmaDetectMismatch
: {
7138 const auto *PDMD
= cast
<PragmaDetectMismatchDecl
>(D
);
7139 AddDetectMismatch(PDMD
->getName(), PDMD
->getValue());
7143 case Decl::LinkageSpec
:
7144 EmitLinkageSpec(cast
<LinkageSpecDecl
>(D
));
7147 case Decl::FileScopeAsm
: {
7148 // File-scope asm is ignored during device-side CUDA compilation.
7149 if (LangOpts
.CUDA
&& LangOpts
.CUDAIsDevice
)
7151 // File-scope asm is ignored during device-side OpenMP compilation.
7152 if (LangOpts
.OpenMPIsTargetDevice
)
7154 // File-scope asm is ignored during device-side SYCL compilation.
7155 if (LangOpts
.SYCLIsDevice
)
7157 auto *AD
= cast
<FileScopeAsmDecl
>(D
);
7158 getModule().appendModuleInlineAsm(AD
->getAsmString()->getString());
7162 case Decl::TopLevelStmt
:
7163 EmitTopLevelStmt(cast
<TopLevelStmtDecl
>(D
));
7166 case Decl::Import
: {
7167 auto *Import
= cast
<ImportDecl
>(D
);
7169 // If we've already imported this module, we're done.
7170 if (!ImportedModules
.insert(Import
->getImportedModule()))
7173 // Emit debug information for direct imports.
7174 if (!Import
->getImportedOwningModule()) {
7175 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7176 DI
->EmitImportDecl(*Import
);
7179 // For C++ standard modules we are done - we will call the module
7180 // initializer for imported modules, and that will likewise call those for
7181 // any imports it has.
7182 if (CXX20ModuleInits
&& Import
->getImportedModule() &&
7183 Import
->getImportedModule()->isNamedModule())
7186 // For clang C++ module map modules the initializers for sub-modules are
7189 // Find all of the submodules and emit the module initializers.
7190 llvm::SmallPtrSet
<clang::Module
*, 16> Visited
;
7191 SmallVector
<clang::Module
*, 16> Stack
;
7192 Visited
.insert(Import
->getImportedModule());
7193 Stack
.push_back(Import
->getImportedModule());
7195 while (!Stack
.empty()) {
7196 clang::Module
*Mod
= Stack
.pop_back_val();
7197 if (!EmittedModuleInitializers
.insert(Mod
).second
)
7200 for (auto *D
: Context
.getModuleInitializers(Mod
))
7201 EmitTopLevelDecl(D
);
7203 // Visit the submodules of this module.
7204 for (auto *Submodule
: Mod
->submodules()) {
7205 // Skip explicit children; they need to be explicitly imported to emit
7206 // the initializers.
7207 if (Submodule
->IsExplicit
)
7210 if (Visited
.insert(Submodule
).second
)
7211 Stack
.push_back(Submodule
);
7218 EmitDeclContext(cast
<ExportDecl
>(D
));
7221 case Decl::OMPThreadPrivate
:
7222 EmitOMPThreadPrivateDecl(cast
<OMPThreadPrivateDecl
>(D
));
7225 case Decl::OMPAllocate
:
7226 EmitOMPAllocateDecl(cast
<OMPAllocateDecl
>(D
));
7229 case Decl::OMPDeclareReduction
:
7230 EmitOMPDeclareReduction(cast
<OMPDeclareReductionDecl
>(D
));
7233 case Decl::OMPDeclareMapper
:
7234 EmitOMPDeclareMapper(cast
<OMPDeclareMapperDecl
>(D
));
7237 case Decl::OMPRequires
:
7238 EmitOMPRequiresDecl(cast
<OMPRequiresDecl
>(D
));
7242 case Decl::TypeAlias
: // using foo = bar; [C++11]
7243 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7244 DI
->EmitAndRetainType(
7245 getContext().getTypedefType(cast
<TypedefNameDecl
>(D
)));
7249 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7250 if (cast
<RecordDecl
>(D
)->getDefinition())
7251 DI
->EmitAndRetainType(getContext().getRecordType(cast
<RecordDecl
>(D
)));
7255 if (CGDebugInfo
*DI
= getModuleDebugInfo())
7256 if (cast
<EnumDecl
>(D
)->getDefinition())
7257 DI
->EmitAndRetainType(getContext().getEnumType(cast
<EnumDecl
>(D
)));
7260 case Decl::HLSLBuffer
:
7261 getHLSLRuntime().addBuffer(cast
<HLSLBufferDecl
>(D
));
7265 // Make sure we handled everything we should, every other kind is a
7266 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
7267 // function. Need to recode Decl::Kind to do that easily.
7268 assert(isa
<TypeDecl
>(D
) && "Unsupported decl kind");
7273 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl
*D
) {
7274 // Do we need to generate coverage mapping?
7275 if (!CodeGenOpts
.CoverageMapping
)
7277 switch (D
->getKind()) {
7278 case Decl::CXXConversion
:
7279 case Decl::CXXMethod
:
7280 case Decl::Function
:
7281 case Decl::ObjCMethod
:
7282 case Decl::CXXConstructor
:
7283 case Decl::CXXDestructor
: {
7284 if (!cast
<FunctionDecl
>(D
)->doesThisDeclarationHaveABody())
7286 SourceManager
&SM
= getContext().getSourceManager();
7287 if (LimitedCoverage
&& SM
.getMainFileID() != SM
.getFileID(D
->getBeginLoc()))
7289 if (!llvm::coverage::SystemHeadersCoverage
&&
7290 SM
.isInSystemHeader(D
->getBeginLoc()))
7292 DeferredEmptyCoverageMappingDecls
.try_emplace(D
, true);
7300 void CodeGenModule::ClearUnusedCoverageMapping(const Decl
*D
) {
7301 // Do we need to generate coverage mapping?
7302 if (!CodeGenOpts
.CoverageMapping
)
7304 if (const auto *Fn
= dyn_cast
<FunctionDecl
>(D
)) {
7305 if (Fn
->isTemplateInstantiation())
7306 ClearUnusedCoverageMapping(Fn
->getTemplateInstantiationPattern());
7308 DeferredEmptyCoverageMappingDecls
.insert_or_assign(D
, false);
7311 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
7312 // We call takeVector() here to avoid use-after-free.
7313 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
7314 // we deserialize function bodies to emit coverage info for them, and that
7315 // deserializes more declarations. How should we handle that case?
7316 for (const auto &Entry
: DeferredEmptyCoverageMappingDecls
.takeVector()) {
7319 const Decl
*D
= Entry
.first
;
7320 switch (D
->getKind()) {
7321 case Decl::CXXConversion
:
7322 case Decl::CXXMethod
:
7323 case Decl::Function
:
7324 case Decl::ObjCMethod
: {
7325 CodeGenPGO
PGO(*this);
7326 GlobalDecl
GD(cast
<FunctionDecl
>(D
));
7327 PGO
.emitEmptyCounterMapping(D
, getMangledName(GD
),
7328 getFunctionLinkage(GD
));
7331 case Decl::CXXConstructor
: {
7332 CodeGenPGO
PGO(*this);
7333 GlobalDecl
GD(cast
<CXXConstructorDecl
>(D
), Ctor_Base
);
7334 PGO
.emitEmptyCounterMapping(D
, getMangledName(GD
),
7335 getFunctionLinkage(GD
));
7338 case Decl::CXXDestructor
: {
7339 CodeGenPGO
PGO(*this);
7340 GlobalDecl
GD(cast
<CXXDestructorDecl
>(D
), Dtor_Base
);
7341 PGO
.emitEmptyCounterMapping(D
, getMangledName(GD
),
7342 getFunctionLinkage(GD
));
7351 void CodeGenModule::EmitMainVoidAlias() {
7352 // In order to transition away from "__original_main" gracefully, emit an
7353 // alias for "main" in the no-argument case so that libc can detect when
7354 // new-style no-argument main is in used.
7355 if (llvm::Function
*F
= getModule().getFunction("main")) {
7356 if (!F
->isDeclaration() && F
->arg_size() == 0 && !F
->isVarArg() &&
7357 F
->getReturnType()->isIntegerTy(Context
.getTargetInfo().getIntWidth())) {
7358 auto *GA
= llvm::GlobalAlias::create("__main_void", F
);
7359 GA
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
7364 /// Turns the given pointer into a constant.
7365 static llvm::Constant
*GetPointerConstant(llvm::LLVMContext
&Context
,
7367 uintptr_t PtrInt
= reinterpret_cast<uintptr_t>(Ptr
);
7368 llvm::Type
*i64
= llvm::Type::getInt64Ty(Context
);
7369 return llvm::ConstantInt::get(i64
, PtrInt
);
7372 static void EmitGlobalDeclMetadata(CodeGenModule
&CGM
,
7373 llvm::NamedMDNode
*&GlobalMetadata
,
7375 llvm::GlobalValue
*Addr
) {
7376 if (!GlobalMetadata
)
7378 CGM
.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
7380 // TODO: should we report variant information for ctors/dtors?
7381 llvm::Metadata
*Ops
[] = {llvm::ConstantAsMetadata::get(Addr
),
7382 llvm::ConstantAsMetadata::get(GetPointerConstant(
7383 CGM
.getLLVMContext(), D
.getDecl()))};
7384 GlobalMetadata
->addOperand(llvm::MDNode::get(CGM
.getLLVMContext(), Ops
));
7387 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue
*Elem
,
7388 llvm::GlobalValue
*CppFunc
) {
7389 // Store the list of ifuncs we need to replace uses in.
7390 llvm::SmallVector
<llvm::GlobalIFunc
*> IFuncs
;
7391 // List of ConstantExprs that we should be able to delete when we're done
7393 llvm::SmallVector
<llvm::ConstantExpr
*> CEs
;
7395 // It isn't valid to replace the extern-C ifuncs if all we find is itself!
7396 if (Elem
== CppFunc
)
7399 // First make sure that all users of this are ifuncs (or ifuncs via a
7400 // bitcast), and collect the list of ifuncs and CEs so we can work on them
7402 for (llvm::User
*User
: Elem
->users()) {
7403 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
7404 // ifunc directly. In any other case, just give up, as we don't know what we
7405 // could break by changing those.
7406 if (auto *ConstExpr
= dyn_cast
<llvm::ConstantExpr
>(User
)) {
7407 if (ConstExpr
->getOpcode() != llvm::Instruction::BitCast
)
7410 for (llvm::User
*CEUser
: ConstExpr
->users()) {
7411 if (auto *IFunc
= dyn_cast
<llvm::GlobalIFunc
>(CEUser
)) {
7412 IFuncs
.push_back(IFunc
);
7417 CEs
.push_back(ConstExpr
);
7418 } else if (auto *IFunc
= dyn_cast
<llvm::GlobalIFunc
>(User
)) {
7419 IFuncs
.push_back(IFunc
);
7421 // This user is one we don't know how to handle, so fail redirection. This
7422 // will result in an ifunc retaining a resolver name that will ultimately
7423 // fail to be resolved to a defined function.
7428 // Now we know this is a valid case where we can do this alias replacement, we
7429 // need to remove all of the references to Elem (and the bitcasts!) so we can
7431 for (llvm::GlobalIFunc
*IFunc
: IFuncs
)
7432 IFunc
->setResolver(nullptr);
7433 for (llvm::ConstantExpr
*ConstExpr
: CEs
)
7434 ConstExpr
->destroyConstant();
7436 // We should now be out of uses for the 'old' version of this function, so we
7437 // can erase it as well.
7438 Elem
->eraseFromParent();
7440 for (llvm::GlobalIFunc
*IFunc
: IFuncs
) {
7441 // The type of the resolver is always just a function-type that returns the
7442 // type of the IFunc, so create that here. If the type of the actual
7443 // resolver doesn't match, it just gets bitcast to the right thing.
7445 llvm::FunctionType::get(IFunc
->getType(), /*isVarArg*/ false);
7446 llvm::Constant
*Resolver
= GetOrCreateLLVMFunction(
7447 CppFunc
->getName(), ResolverTy
, {}, /*ForVTable*/ false);
7448 IFunc
->setResolver(Resolver
);
7453 /// For each function which is declared within an extern "C" region and marked
7454 /// as 'used', but has internal linkage, create an alias from the unmangled
7455 /// name to the mangled name if possible. People expect to be able to refer
7456 /// to such functions with an unmangled name from inline assembly within the
7457 /// same translation unit.
7458 void CodeGenModule::EmitStaticExternCAliases() {
7459 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7461 for (auto &I
: StaticExternCValues
) {
7462 const IdentifierInfo
*Name
= I
.first
;
7463 llvm::GlobalValue
*Val
= I
.second
;
7465 // If Val is null, that implies there were multiple declarations that each
7466 // had a claim to the unmangled name. In this case, generation of the alias
7467 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7471 llvm::GlobalValue
*ExistingElem
=
7472 getModule().getNamedValue(Name
->getName());
7474 // If there is either not something already by this name, or we were able to
7475 // replace all uses from IFuncs, create the alias.
7476 if (!ExistingElem
|| CheckAndReplaceExternCIFuncs(ExistingElem
, Val
))
7477 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name
->getName(), Val
));
7481 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName
,
7482 GlobalDecl
&Result
) const {
7483 auto Res
= Manglings
.find(MangledName
);
7484 if (Res
== Manglings
.end())
7486 Result
= Res
->getValue();
7490 /// Emits metadata nodes associating all the global values in the
7491 /// current module with the Decls they came from. This is useful for
7492 /// projects using IR gen as a subroutine.
7494 /// Since there's currently no way to associate an MDNode directly
7495 /// with an llvm::GlobalValue, we create a global named metadata
7496 /// with the name 'clang.global.decl.ptrs'.
7497 void CodeGenModule::EmitDeclMetadata() {
7498 llvm::NamedMDNode
*GlobalMetadata
= nullptr;
7500 for (auto &I
: MangledDeclNames
) {
7501 llvm::GlobalValue
*Addr
= getModule().getNamedValue(I
.second
);
7502 // Some mangled names don't necessarily have an associated GlobalValue
7503 // in this module, e.g. if we mangled it for DebugInfo.
7505 EmitGlobalDeclMetadata(*this, GlobalMetadata
, I
.first
, Addr
);
7509 /// Emits metadata nodes for all the local variables in the current
7511 void CodeGenFunction::EmitDeclMetadata() {
7512 if (LocalDeclMap
.empty()) return;
7514 llvm::LLVMContext
&Context
= getLLVMContext();
7516 // Find the unique metadata ID for this name.
7517 unsigned DeclPtrKind
= Context
.getMDKindID("clang.decl.ptr");
7519 llvm::NamedMDNode
*GlobalMetadata
= nullptr;
7521 for (auto &I
: LocalDeclMap
) {
7522 const Decl
*D
= I
.first
;
7523 llvm::Value
*Addr
= I
.second
.emitRawPointer(*this);
7524 if (auto *Alloca
= dyn_cast
<llvm::AllocaInst
>(Addr
)) {
7525 llvm::Value
*DAddr
= GetPointerConstant(getLLVMContext(), D
);
7526 Alloca
->setMetadata(
7527 DeclPtrKind
, llvm::MDNode::get(
7528 Context
, llvm::ValueAsMetadata::getConstant(DAddr
)));
7529 } else if (auto *GV
= dyn_cast
<llvm::GlobalValue
>(Addr
)) {
7530 GlobalDecl GD
= GlobalDecl(cast
<VarDecl
>(D
));
7531 EmitGlobalDeclMetadata(CGM
, GlobalMetadata
, GD
, GV
);
7536 void CodeGenModule::EmitVersionIdentMetadata() {
7537 llvm::NamedMDNode
*IdentMetadata
=
7538 TheModule
.getOrInsertNamedMetadata("llvm.ident");
7539 std::string Version
= getClangFullVersion();
7540 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
7542 llvm::Metadata
*IdentNode
[] = {llvm::MDString::get(Ctx
, Version
)};
7543 IdentMetadata
->addOperand(llvm::MDNode::get(Ctx
, IdentNode
));
7546 void CodeGenModule::EmitCommandLineMetadata() {
7547 llvm::NamedMDNode
*CommandLineMetadata
=
7548 TheModule
.getOrInsertNamedMetadata("llvm.commandline");
7549 std::string CommandLine
= getCodeGenOpts().RecordCommandLine
;
7550 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
7552 llvm::Metadata
*CommandLineNode
[] = {llvm::MDString::get(Ctx
, CommandLine
)};
7553 CommandLineMetadata
->addOperand(llvm::MDNode::get(Ctx
, CommandLineNode
));
7556 void CodeGenModule::EmitCoverageFile() {
7557 llvm::NamedMDNode
*CUNode
= TheModule
.getNamedMetadata("llvm.dbg.cu");
7561 llvm::NamedMDNode
*GCov
= TheModule
.getOrInsertNamedMetadata("llvm.gcov");
7562 llvm::LLVMContext
&Ctx
= TheModule
.getContext();
7563 auto *CoverageDataFile
=
7564 llvm::MDString::get(Ctx
, getCodeGenOpts().CoverageDataFile
);
7565 auto *CoverageNotesFile
=
7566 llvm::MDString::get(Ctx
, getCodeGenOpts().CoverageNotesFile
);
7567 for (int i
= 0, e
= CUNode
->getNumOperands(); i
!= e
; ++i
) {
7568 llvm::MDNode
*CU
= CUNode
->getOperand(i
);
7569 llvm::Metadata
*Elts
[] = {CoverageNotesFile
, CoverageDataFile
, CU
};
7570 GCov
->addOperand(llvm::MDNode::get(Ctx
, Elts
));
7574 llvm::Constant
*CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty
,
7576 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
7577 // FIXME: should we even be calling this method if RTTI is disabled
7578 // and it's not for EH?
7579 if (!shouldEmitRTTI(ForEH
))
7580 return llvm::Constant::getNullValue(GlobalsInt8PtrTy
);
7582 if (ForEH
&& Ty
->isObjCObjectPointerType() &&
7583 LangOpts
.ObjCRuntime
.isGNUFamily())
7584 return ObjCRuntime
->GetEHType(Ty
);
7586 return getCXXABI().getAddrOfRTTIDescriptor(Ty
);
7589 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl
*D
) {
7590 // Do not emit threadprivates in simd-only mode.
7591 if (LangOpts
.OpenMP
&& LangOpts
.OpenMPSimd
)
7593 for (auto RefExpr
: D
->varlist()) {
7594 auto *VD
= cast
<VarDecl
>(cast
<DeclRefExpr
>(RefExpr
)->getDecl());
7596 VD
->getAnyInitializer() &&
7597 !VD
->getAnyInitializer()->isConstantInitializer(getContext(),
7600 Address
Addr(GetAddrOfGlobalVar(VD
),
7601 getTypes().ConvertTypeForMem(VD
->getType()),
7602 getContext().getDeclAlign(VD
));
7603 if (auto InitFunction
= getOpenMPRuntime().emitThreadPrivateVarDefinition(
7604 VD
, Addr
, RefExpr
->getBeginLoc(), PerformInit
))
7605 CXXGlobalInits
.push_back(InitFunction
);
7610 CodeGenModule::CreateMetadataIdentifierImpl(QualType T
, MetadataTypeMap
&Map
,
7612 if (auto *FnType
= T
->getAs
<FunctionProtoType
>())
7613 T
= getContext().getFunctionType(
7614 FnType
->getReturnType(), FnType
->getParamTypes(),
7615 FnType
->getExtProtoInfo().withExceptionSpec(EST_None
));
7617 llvm::Metadata
*&InternalId
= Map
[T
.getCanonicalType()];
7621 if (isExternallyVisible(T
->getLinkage())) {
7622 std::string OutName
;
7623 llvm::raw_string_ostream
Out(OutName
);
7624 getCXXABI().getMangleContext().mangleCanonicalTypeName(
7625 T
, Out
, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers
);
7627 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers
)
7628 Out
<< ".normalized";
7632 InternalId
= llvm::MDString::get(getLLVMContext(), Out
.str());
7634 InternalId
= llvm::MDNode::getDistinct(getLLVMContext(),
7635 llvm::ArrayRef
<llvm::Metadata
*>());
7641 llvm::Metadata
*CodeGenModule::CreateMetadataIdentifierForType(QualType T
) {
7642 return CreateMetadataIdentifierImpl(T
, MetadataIdMap
, "");
7646 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T
) {
7647 return CreateMetadataIdentifierImpl(T
, VirtualMetadataIdMap
, ".virtual");
7650 // Generalize pointer types to a void pointer with the qualifiers of the
7651 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
7652 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
7654 static QualType
GeneralizeType(ASTContext
&Ctx
, QualType Ty
) {
7655 if (!Ty
->isPointerType())
7658 return Ctx
.getPointerType(
7659 QualType(Ctx
.VoidTy
).withCVRQualifiers(
7660 Ty
->getPointeeType().getCVRQualifiers()));
7663 // Apply type generalization to a FunctionType's return and argument types
7664 static QualType
GeneralizeFunctionType(ASTContext
&Ctx
, QualType Ty
) {
7665 if (auto *FnType
= Ty
->getAs
<FunctionProtoType
>()) {
7666 SmallVector
<QualType
, 8> GeneralizedParams
;
7667 for (auto &Param
: FnType
->param_types())
7668 GeneralizedParams
.push_back(GeneralizeType(Ctx
, Param
));
7670 return Ctx
.getFunctionType(
7671 GeneralizeType(Ctx
, FnType
->getReturnType()),
7672 GeneralizedParams
, FnType
->getExtProtoInfo());
7675 if (auto *FnType
= Ty
->getAs
<FunctionNoProtoType
>())
7676 return Ctx
.getFunctionNoProtoType(
7677 GeneralizeType(Ctx
, FnType
->getReturnType()));
7679 llvm_unreachable("Encountered unknown FunctionType");
7682 llvm::Metadata
*CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T
) {
7683 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T
),
7684 GeneralizedMetadataIdMap
, ".generalized");
7687 /// Returns whether this module needs the "all-vtables" type identifier.
7688 bool CodeGenModule::NeedAllVtablesTypeId() const {
7689 // Returns true if at least one of vtable-based CFI checkers is enabled and
7690 // is not in the trapping mode.
7691 return ((LangOpts
.Sanitize
.has(SanitizerKind::CFIVCall
) &&
7692 !CodeGenOpts
.SanitizeTrap
.has(SanitizerKind::CFIVCall
)) ||
7693 (LangOpts
.Sanitize
.has(SanitizerKind::CFINVCall
) &&
7694 !CodeGenOpts
.SanitizeTrap
.has(SanitizerKind::CFINVCall
)) ||
7695 (LangOpts
.Sanitize
.has(SanitizerKind::CFIDerivedCast
) &&
7696 !CodeGenOpts
.SanitizeTrap
.has(SanitizerKind::CFIDerivedCast
)) ||
7697 (LangOpts
.Sanitize
.has(SanitizerKind::CFIUnrelatedCast
) &&
7698 !CodeGenOpts
.SanitizeTrap
.has(SanitizerKind::CFIUnrelatedCast
)));
7701 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable
*VTable
,
7703 const CXXRecordDecl
*RD
) {
7704 llvm::Metadata
*MD
=
7705 CreateMetadataIdentifierForType(QualType(RD
->getTypeForDecl(), 0));
7706 VTable
->addTypeMetadata(Offset
.getQuantity(), MD
);
7708 if (CodeGenOpts
.SanitizeCfiCrossDso
)
7709 if (auto CrossDsoTypeId
= CreateCrossDsoCfiTypeId(MD
))
7710 VTable
->addTypeMetadata(Offset
.getQuantity(),
7711 llvm::ConstantAsMetadata::get(CrossDsoTypeId
));
7713 if (NeedAllVtablesTypeId()) {
7714 llvm::Metadata
*MD
= llvm::MDString::get(getLLVMContext(), "all-vtables");
7715 VTable
->addTypeMetadata(Offset
.getQuantity(), MD
);
7719 llvm::SanitizerStatReport
&CodeGenModule::getSanStats() {
7721 SanStats
= std::make_unique
<llvm::SanitizerStatReport
>(&getModule());
7727 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr
*E
,
7728 CodeGenFunction
&CGF
) {
7729 llvm::Constant
*C
= ConstantEmitter(CGF
).emitAbstract(E
, E
->getType());
7730 auto *SamplerT
= getOpenCLRuntime().getSamplerType(E
->getType().getTypePtr());
7731 auto *FTy
= llvm::FunctionType::get(SamplerT
, {C
->getType()}, false);
7732 auto *Call
= CGF
.EmitRuntimeCall(
7733 CreateRuntimeFunction(FTy
, "__translate_sampler_initializer"), {C
});
7737 CharUnits
CodeGenModule::getNaturalPointeeTypeAlignment(
7738 QualType T
, LValueBaseInfo
*BaseInfo
, TBAAAccessInfo
*TBAAInfo
) {
7739 return getNaturalTypeAlignment(T
->getPointeeType(), BaseInfo
, TBAAInfo
,
7740 /* forPointeeType= */ true);
7743 CharUnits
CodeGenModule::getNaturalTypeAlignment(QualType T
,
7744 LValueBaseInfo
*BaseInfo
,
7745 TBAAAccessInfo
*TBAAInfo
,
7746 bool forPointeeType
) {
7748 *TBAAInfo
= getTBAAAccessInfo(T
);
7750 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7751 // that doesn't return the information we need to compute BaseInfo.
7753 // Honor alignment typedef attributes even on incomplete types.
7754 // We also honor them straight for C++ class types, even as pointees;
7755 // there's an expressivity gap here.
7756 if (auto TT
= T
->getAs
<TypedefType
>()) {
7757 if (auto Align
= TT
->getDecl()->getMaxAlignment()) {
7759 *BaseInfo
= LValueBaseInfo(AlignmentSource::AttributedType
);
7760 return getContext().toCharUnitsFromBits(Align
);
7764 bool AlignForArray
= T
->isArrayType();
7766 // Analyze the base element type, so we don't get confused by incomplete
7768 T
= getContext().getBaseElementType(T
);
7770 if (T
->isIncompleteType()) {
7771 // We could try to replicate the logic from
7772 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7773 // type is incomplete, so it's impossible to test. We could try to reuse
7774 // getTypeAlignIfKnown, but that doesn't return the information we need
7775 // to set BaseInfo. So just ignore the possibility that the alignment is
7776 // greater than one.
7778 *BaseInfo
= LValueBaseInfo(AlignmentSource::Type
);
7779 return CharUnits::One();
7783 *BaseInfo
= LValueBaseInfo(AlignmentSource::Type
);
7785 CharUnits Alignment
;
7786 const CXXRecordDecl
*RD
;
7787 if (T
.getQualifiers().hasUnaligned()) {
7788 Alignment
= CharUnits::One();
7789 } else if (forPointeeType
&& !AlignForArray
&&
7790 (RD
= T
->getAsCXXRecordDecl())) {
7791 // For C++ class pointees, we don't know whether we're pointing at a
7792 // base or a complete object, so we generally need to use the
7793 // non-virtual alignment.
7794 Alignment
= getClassPointerAlignment(RD
);
7796 Alignment
= getContext().getTypeAlignInChars(T
);
7799 // Cap to the global maximum type alignment unless the alignment
7800 // was somehow explicit on the type.
7801 if (unsigned MaxAlign
= getLangOpts().MaxTypeAlign
) {
7802 if (Alignment
.getQuantity() > MaxAlign
&&
7803 !getContext().isAlignmentRequired(T
))
7804 Alignment
= CharUnits::fromQuantity(MaxAlign
);
7809 bool CodeGenModule::stopAutoInit() {
7810 unsigned StopAfter
= getContext().getLangOpts().TrivialAutoVarInitStopAfter
;
7812 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7814 if (NumAutoVarInit
>= StopAfter
) {
7817 if (!NumAutoVarInit
) {
7818 unsigned DiagID
= getDiags().getCustomDiagID(
7819 DiagnosticsEngine::Warning
,
7820 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7821 "number of times ftrivial-auto-var-init=%1 gets applied.");
7822 getDiags().Report(DiagID
)
7824 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7825 LangOptions::TrivialAutoVarInitKind::Zero
7834 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream
&OS
,
7835 const Decl
*D
) const {
7836 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7837 // postfix beginning with '.' since the symbol name can be demangled.
7839 OS
<< (isa
<VarDecl
>(D
) ? ".static." : ".intern.");
7841 OS
<< (isa
<VarDecl
>(D
) ? "__static__" : "__intern__");
7843 // If the CUID is not specified we try to generate a unique postfix.
7844 if (getLangOpts().CUID
.empty()) {
7845 SourceManager
&SM
= getContext().getSourceManager();
7846 PresumedLoc PLoc
= SM
.getPresumedLoc(D
->getLocation());
7847 assert(PLoc
.isValid() && "Source location is expected to be valid.");
7849 // Get the hash of the user defined macros.
7851 llvm::MD5::MD5Result Result
;
7852 for (const auto &Arg
: PreprocessorOpts
.Macros
)
7853 Hash
.update(Arg
.first
);
7856 // Get the UniqueID for the file containing the decl.
7857 llvm::sys::fs::UniqueID ID
;
7858 if (llvm::sys::fs::getUniqueID(PLoc
.getFilename(), ID
)) {
7859 PLoc
= SM
.getPresumedLoc(D
->getLocation(), /*UseLineDirectives=*/false);
7860 assert(PLoc
.isValid() && "Source location is expected to be valid.");
7861 if (auto EC
= llvm::sys::fs::getUniqueID(PLoc
.getFilename(), ID
))
7862 SM
.getDiagnostics().Report(diag::err_cannot_open_file
)
7863 << PLoc
.getFilename() << EC
.message();
7865 OS
<< llvm::format("%x", ID
.getFile()) << llvm::format("%x", ID
.getDevice())
7866 << "_" << llvm::utohexstr(Result
.low(), /*LowerCase=*/true, /*Width=*/8);
7868 OS
<< getContext().getCUIDHash();
7872 void CodeGenModule::moveLazyEmissionStates(CodeGenModule
*NewBuilder
) {
7873 assert(DeferredDeclsToEmit
.empty() &&
7874 "Should have emitted all decls deferred to emit.");
7875 assert(NewBuilder
->DeferredDecls
.empty() &&
7876 "Newly created module should not have deferred decls");
7877 NewBuilder
->DeferredDecls
= std::move(DeferredDecls
);
7878 assert(EmittedDeferredDecls
.empty() &&
7879 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7881 assert(NewBuilder
->DeferredVTables
.empty() &&
7882 "Newly created module should not have deferred vtables");
7883 NewBuilder
->DeferredVTables
= std::move(DeferredVTables
);
7885 assert(NewBuilder
->MangledDeclNames
.empty() &&
7886 "Newly created module should not have mangled decl names");
7887 assert(NewBuilder
->Manglings
.empty() &&
7888 "Newly created module should not have manglings");
7889 NewBuilder
->Manglings
= std::move(Manglings
);
7891 NewBuilder
->WeakRefReferences
= std::move(WeakRefReferences
);
7893 NewBuilder
->ABI
->MangleCtx
= std::move(ABI
->MangleCtx
);