[clang-repl] [codegen] Reduce the state in TBAA. NFC for static compilation. (#98138)
[llvm-project.git] / clang / lib / CodeGen / CodeGenModule.cpp
blobcf5e29e5a3db8d15834fc5943bef5c8d8c900e66
1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This coordinates the per-module state used while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenModule.h"
14 #include "ABIInfo.h"
15 #include "CGBlocks.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGCall.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/CharInfo.h"
42 #include "clang/Basic/CodeGenOptions.h"
43 #include "clang/Basic/Diagnostic.h"
44 #include "clang/Basic/FileManager.h"
45 #include "clang/Basic/Module.h"
46 #include "clang/Basic/SourceManager.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "clang/Basic/Version.h"
49 #include "clang/CodeGen/BackendUtil.h"
50 #include "clang/CodeGen/ConstantInitBuilder.h"
51 #include "clang/Frontend/FrontendDiagnostic.h"
52 #include "llvm/ADT/STLExtras.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/ADT/StringSwitch.h"
55 #include "llvm/Analysis/TargetLibraryInfo.h"
56 #include "llvm/BinaryFormat/ELF.h"
57 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
58 #include "llvm/IR/AttributeMask.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/DataLayout.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/ProfileSummary.h"
65 #include "llvm/ProfileData/InstrProfReader.h"
66 #include "llvm/ProfileData/SampleProf.h"
67 #include "llvm/Support/CRC.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/ConvertUTF.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/TimeProfiler.h"
73 #include "llvm/Support/xxhash.h"
74 #include "llvm/TargetParser/RISCVISAInfo.h"
75 #include "llvm/TargetParser/Triple.h"
76 #include "llvm/TargetParser/X86TargetParser.h"
77 #include "llvm/Transforms/Utils/BuildLibCalls.h"
78 #include <optional>
80 using namespace clang;
81 using namespace CodeGen;
83 static llvm::cl::opt<bool> LimitedCoverage(
84 "limited-coverage-experimental", llvm::cl::Hidden,
85 llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
87 static const char AnnotationSection[] = "llvm.metadata";
89 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
90 switch (CGM.getContext().getCXXABIKind()) {
91 case TargetCXXABI::AppleARM64:
92 case TargetCXXABI::Fuchsia:
93 case TargetCXXABI::GenericAArch64:
94 case TargetCXXABI::GenericARM:
95 case TargetCXXABI::iOS:
96 case TargetCXXABI::WatchOS:
97 case TargetCXXABI::GenericMIPS:
98 case TargetCXXABI::GenericItanium:
99 case TargetCXXABI::WebAssembly:
100 case TargetCXXABI::XL:
101 return CreateItaniumCXXABI(CGM);
102 case TargetCXXABI::Microsoft:
103 return CreateMicrosoftCXXABI(CGM);
106 llvm_unreachable("invalid C++ ABI kind");
109 static std::unique_ptr<TargetCodeGenInfo>
110 createTargetCodeGenInfo(CodeGenModule &CGM) {
111 const TargetInfo &Target = CGM.getTarget();
112 const llvm::Triple &Triple = Target.getTriple();
113 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
115 switch (Triple.getArch()) {
116 default:
117 return createDefaultTargetCodeGenInfo(CGM);
119 case llvm::Triple::le32:
120 return createPNaClTargetCodeGenInfo(CGM);
121 case llvm::Triple::m68k:
122 return createM68kTargetCodeGenInfo(CGM);
123 case llvm::Triple::mips:
124 case llvm::Triple::mipsel:
125 if (Triple.getOS() == llvm::Triple::NaCl)
126 return createPNaClTargetCodeGenInfo(CGM);
127 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
129 case llvm::Triple::mips64:
130 case llvm::Triple::mips64el:
131 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
133 case llvm::Triple::avr: {
134 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
135 // on avrtiny. For passing return value, R18~R25 are used on avr, and
136 // R22~R25 are used on avrtiny.
137 unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
138 unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
139 return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
142 case llvm::Triple::aarch64:
143 case llvm::Triple::aarch64_32:
144 case llvm::Triple::aarch64_be: {
145 AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
146 if (Target.getABI() == "darwinpcs")
147 Kind = AArch64ABIKind::DarwinPCS;
148 else if (Triple.isOSWindows())
149 return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
150 else if (Target.getABI() == "aapcs-soft")
151 Kind = AArch64ABIKind::AAPCSSoft;
152 else if (Target.getABI() == "pauthtest")
153 Kind = AArch64ABIKind::PAuthTest;
155 return createAArch64TargetCodeGenInfo(CGM, Kind);
158 case llvm::Triple::wasm32:
159 case llvm::Triple::wasm64: {
160 WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
161 if (Target.getABI() == "experimental-mv")
162 Kind = WebAssemblyABIKind::ExperimentalMV;
163 return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
166 case llvm::Triple::arm:
167 case llvm::Triple::armeb:
168 case llvm::Triple::thumb:
169 case llvm::Triple::thumbeb: {
170 if (Triple.getOS() == llvm::Triple::Win32)
171 return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
173 ARMABIKind Kind = ARMABIKind::AAPCS;
174 StringRef ABIStr = Target.getABI();
175 if (ABIStr == "apcs-gnu")
176 Kind = ARMABIKind::APCS;
177 else if (ABIStr == "aapcs16")
178 Kind = ARMABIKind::AAPCS16_VFP;
179 else if (CodeGenOpts.FloatABI == "hard" ||
180 (CodeGenOpts.FloatABI != "soft" &&
181 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
182 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
183 Triple.getEnvironment() == llvm::Triple::EABIHF)))
184 Kind = ARMABIKind::AAPCS_VFP;
186 return createARMTargetCodeGenInfo(CGM, Kind);
189 case llvm::Triple::ppc: {
190 if (Triple.isOSAIX())
191 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
193 bool IsSoftFloat =
194 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
195 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
197 case llvm::Triple::ppcle: {
198 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
199 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
201 case llvm::Triple::ppc64:
202 if (Triple.isOSAIX())
203 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
205 if (Triple.isOSBinFormatELF()) {
206 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
207 if (Target.getABI() == "elfv2")
208 Kind = PPC64_SVR4_ABIKind::ELFv2;
209 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
211 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
213 return createPPC64TargetCodeGenInfo(CGM);
214 case llvm::Triple::ppc64le: {
215 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
216 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
217 if (Target.getABI() == "elfv1")
218 Kind = PPC64_SVR4_ABIKind::ELFv1;
219 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
221 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
224 case llvm::Triple::nvptx:
225 case llvm::Triple::nvptx64:
226 return createNVPTXTargetCodeGenInfo(CGM);
228 case llvm::Triple::msp430:
229 return createMSP430TargetCodeGenInfo(CGM);
231 case llvm::Triple::riscv32:
232 case llvm::Triple::riscv64: {
233 StringRef ABIStr = Target.getABI();
234 unsigned XLen = Target.getPointerWidth(LangAS::Default);
235 unsigned ABIFLen = 0;
236 if (ABIStr.ends_with("f"))
237 ABIFLen = 32;
238 else if (ABIStr.ends_with("d"))
239 ABIFLen = 64;
240 bool EABI = ABIStr.ends_with("e");
241 return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI);
244 case llvm::Triple::systemz: {
245 bool SoftFloat = CodeGenOpts.FloatABI == "soft";
246 bool HasVector = !SoftFloat && Target.getABI() == "vector";
247 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
250 case llvm::Triple::tce:
251 case llvm::Triple::tcele:
252 return createTCETargetCodeGenInfo(CGM);
254 case llvm::Triple::x86: {
255 bool IsDarwinVectorABI = Triple.isOSDarwin();
256 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
258 if (Triple.getOS() == llvm::Triple::Win32) {
259 return createWinX86_32TargetCodeGenInfo(
260 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
261 CodeGenOpts.NumRegisterParameters);
263 return createX86_32TargetCodeGenInfo(
264 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
265 CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
268 case llvm::Triple::x86_64: {
269 StringRef ABI = Target.getABI();
270 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
271 : ABI == "avx" ? X86AVXABILevel::AVX
272 : X86AVXABILevel::None);
274 switch (Triple.getOS()) {
275 case llvm::Triple::Win32:
276 return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
277 default:
278 return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
281 case llvm::Triple::hexagon:
282 return createHexagonTargetCodeGenInfo(CGM);
283 case llvm::Triple::lanai:
284 return createLanaiTargetCodeGenInfo(CGM);
285 case llvm::Triple::r600:
286 return createAMDGPUTargetCodeGenInfo(CGM);
287 case llvm::Triple::amdgcn:
288 return createAMDGPUTargetCodeGenInfo(CGM);
289 case llvm::Triple::sparc:
290 return createSparcV8TargetCodeGenInfo(CGM);
291 case llvm::Triple::sparcv9:
292 return createSparcV9TargetCodeGenInfo(CGM);
293 case llvm::Triple::xcore:
294 return createXCoreTargetCodeGenInfo(CGM);
295 case llvm::Triple::arc:
296 return createARCTargetCodeGenInfo(CGM);
297 case llvm::Triple::spir:
298 case llvm::Triple::spir64:
299 return createCommonSPIRTargetCodeGenInfo(CGM);
300 case llvm::Triple::spirv32:
301 case llvm::Triple::spirv64:
302 return createSPIRVTargetCodeGenInfo(CGM);
303 case llvm::Triple::ve:
304 return createVETargetCodeGenInfo(CGM);
305 case llvm::Triple::csky: {
306 bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
307 bool hasFP64 =
308 Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
309 return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
310 : hasFP64 ? 64
311 : 32);
313 case llvm::Triple::bpfeb:
314 case llvm::Triple::bpfel:
315 return createBPFTargetCodeGenInfo(CGM);
316 case llvm::Triple::loongarch32:
317 case llvm::Triple::loongarch64: {
318 StringRef ABIStr = Target.getABI();
319 unsigned ABIFRLen = 0;
320 if (ABIStr.ends_with("f"))
321 ABIFRLen = 32;
322 else if (ABIStr.ends_with("d"))
323 ABIFRLen = 64;
324 return createLoongArchTargetCodeGenInfo(
325 CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
330 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
331 if (!TheTargetCodeGenInfo)
332 TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
333 return *TheTargetCodeGenInfo;
336 CodeGenModule::CodeGenModule(ASTContext &C,
337 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
338 const HeaderSearchOptions &HSO,
339 const PreprocessorOptions &PPO,
340 const CodeGenOptions &CGO, llvm::Module &M,
341 DiagnosticsEngine &diags,
342 CoverageSourceInfo *CoverageInfo)
343 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
344 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
345 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
346 VMContext(M.getContext()), VTables(*this),
347 SanitizerMD(new SanitizerMetadata(*this)) {
349 // Initialize the type cache.
350 Types.reset(new CodeGenTypes(*this));
351 llvm::LLVMContext &LLVMContext = M.getContext();
352 VoidTy = llvm::Type::getVoidTy(LLVMContext);
353 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
354 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
355 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
356 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
357 HalfTy = llvm::Type::getHalfTy(LLVMContext);
358 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
359 FloatTy = llvm::Type::getFloatTy(LLVMContext);
360 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
361 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
362 PointerAlignInBytes =
363 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
364 .getQuantity();
365 SizeSizeInBytes =
366 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
367 IntAlignInBytes =
368 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
369 CharTy =
370 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
371 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
372 IntPtrTy = llvm::IntegerType::get(LLVMContext,
373 C.getTargetInfo().getMaxPointerWidth());
374 Int8PtrTy = llvm::PointerType::get(LLVMContext,
375 C.getTargetAddressSpace(LangAS::Default));
376 const llvm::DataLayout &DL = M.getDataLayout();
377 AllocaInt8PtrTy =
378 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
379 GlobalsInt8PtrTy =
380 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
381 ConstGlobalsPtrTy = llvm::PointerType::get(
382 LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
383 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
385 // Build C++20 Module initializers.
386 // TODO: Add Microsoft here once we know the mangling required for the
387 // initializers.
388 CXX20ModuleInits =
389 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
390 ItaniumMangleContext::MK_Itanium;
392 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
394 if (LangOpts.ObjC)
395 createObjCRuntime();
396 if (LangOpts.OpenCL)
397 createOpenCLRuntime();
398 if (LangOpts.OpenMP)
399 createOpenMPRuntime();
400 if (LangOpts.CUDA)
401 createCUDARuntime();
402 if (LangOpts.HLSL)
403 createHLSLRuntime();
405 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
406 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
407 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
408 TBAA.reset(new CodeGenTBAA(Context, getTypes(), TheModule, CodeGenOpts,
409 getLangOpts()));
411 // If debug info or coverage generation is enabled, create the CGDebugInfo
412 // object.
413 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
414 CodeGenOpts.CoverageNotesFile.size() ||
415 CodeGenOpts.CoverageDataFile.size())
416 DebugInfo.reset(new CGDebugInfo(*this));
418 Block.GlobalUniqueCount = 0;
420 if (C.getLangOpts().ObjC)
421 ObjCData.reset(new ObjCEntrypoints());
423 if (CodeGenOpts.hasProfileClangUse()) {
424 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
425 CodeGenOpts.ProfileInstrumentUsePath, *FS,
426 CodeGenOpts.ProfileRemappingFile);
427 // We're checking for profile read errors in CompilerInvocation, so if
428 // there was an error it should've already been caught. If it hasn't been
429 // somehow, trip an assertion.
430 assert(ReaderOrErr);
431 PGOReader = std::move(ReaderOrErr.get());
434 // If coverage mapping generation is enabled, create the
435 // CoverageMappingModuleGen object.
436 if (CodeGenOpts.CoverageMapping)
437 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
439 // Generate the module name hash here if needed.
440 if (CodeGenOpts.UniqueInternalLinkageNames &&
441 !getModule().getSourceFileName().empty()) {
442 std::string Path = getModule().getSourceFileName();
443 // Check if a path substitution is needed from the MacroPrefixMap.
444 for (const auto &Entry : LangOpts.MacroPrefixMap)
445 if (Path.rfind(Entry.first, 0) != std::string::npos) {
446 Path = Entry.second + Path.substr(Entry.first.size());
447 break;
449 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
452 // Record mregparm value now so it is visible through all of codegen.
453 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
454 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
455 CodeGenOpts.NumRegisterParameters);
458 CodeGenModule::~CodeGenModule() {}
460 void CodeGenModule::createObjCRuntime() {
461 // This is just isGNUFamily(), but we want to force implementors of
462 // new ABIs to decide how best to do this.
463 switch (LangOpts.ObjCRuntime.getKind()) {
464 case ObjCRuntime::GNUstep:
465 case ObjCRuntime::GCC:
466 case ObjCRuntime::ObjFW:
467 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
468 return;
470 case ObjCRuntime::FragileMacOSX:
471 case ObjCRuntime::MacOSX:
472 case ObjCRuntime::iOS:
473 case ObjCRuntime::WatchOS:
474 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
475 return;
477 llvm_unreachable("bad runtime kind");
480 void CodeGenModule::createOpenCLRuntime() {
481 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
484 void CodeGenModule::createOpenMPRuntime() {
485 // Select a specialized code generation class based on the target, if any.
486 // If it does not exist use the default implementation.
487 switch (getTriple().getArch()) {
488 case llvm::Triple::nvptx:
489 case llvm::Triple::nvptx64:
490 case llvm::Triple::amdgcn:
491 assert(getLangOpts().OpenMPIsTargetDevice &&
492 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
493 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
494 break;
495 default:
496 if (LangOpts.OpenMPSimd)
497 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
498 else
499 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
500 break;
504 void CodeGenModule::createCUDARuntime() {
505 CUDARuntime.reset(CreateNVCUDARuntime(*this));
508 void CodeGenModule::createHLSLRuntime() {
509 HLSLRuntime.reset(new CGHLSLRuntime(*this));
512 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
513 Replacements[Name] = C;
516 void CodeGenModule::applyReplacements() {
517 for (auto &I : Replacements) {
518 StringRef MangledName = I.first;
519 llvm::Constant *Replacement = I.second;
520 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
521 if (!Entry)
522 continue;
523 auto *OldF = cast<llvm::Function>(Entry);
524 auto *NewF = dyn_cast<llvm::Function>(Replacement);
525 if (!NewF) {
526 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
527 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
528 } else {
529 auto *CE = cast<llvm::ConstantExpr>(Replacement);
530 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
531 CE->getOpcode() == llvm::Instruction::GetElementPtr);
532 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
536 // Replace old with new, but keep the old order.
537 OldF->replaceAllUsesWith(Replacement);
538 if (NewF) {
539 NewF->removeFromParent();
540 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
541 NewF);
543 OldF->eraseFromParent();
547 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
548 GlobalValReplacements.push_back(std::make_pair(GV, C));
551 void CodeGenModule::applyGlobalValReplacements() {
552 for (auto &I : GlobalValReplacements) {
553 llvm::GlobalValue *GV = I.first;
554 llvm::Constant *C = I.second;
556 GV->replaceAllUsesWith(C);
557 GV->eraseFromParent();
561 // This is only used in aliases that we created and we know they have a
562 // linear structure.
563 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
564 const llvm::Constant *C;
565 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
566 C = GA->getAliasee();
567 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
568 C = GI->getResolver();
569 else
570 return GV;
572 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
573 if (!AliaseeGV)
574 return nullptr;
576 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
577 if (FinalGV == GV)
578 return nullptr;
580 return FinalGV;
583 static bool checkAliasedGlobal(
584 const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
585 bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
586 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
587 SourceRange AliasRange) {
588 GV = getAliasedGlobal(Alias);
589 if (!GV) {
590 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
591 return false;
594 if (GV->hasCommonLinkage()) {
595 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
596 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
597 Diags.Report(Location, diag::err_alias_to_common);
598 return false;
602 if (GV->isDeclaration()) {
603 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
604 Diags.Report(Location, diag::note_alias_requires_mangled_name)
605 << IsIFunc << IsIFunc;
606 // Provide a note if the given function is not found and exists as a
607 // mangled name.
608 for (const auto &[Decl, Name] : MangledDeclNames) {
609 if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
610 if (ND->getName() == GV->getName()) {
611 Diags.Report(Location, diag::note_alias_mangled_name_alternative)
612 << Name
613 << FixItHint::CreateReplacement(
614 AliasRange,
615 (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
616 .str());
620 return false;
623 if (IsIFunc) {
624 // Check resolver function type.
625 const auto *F = dyn_cast<llvm::Function>(GV);
626 if (!F) {
627 Diags.Report(Location, diag::err_alias_to_undefined)
628 << IsIFunc << IsIFunc;
629 return false;
632 llvm::FunctionType *FTy = F->getFunctionType();
633 if (!FTy->getReturnType()->isPointerTy()) {
634 Diags.Report(Location, diag::err_ifunc_resolver_return);
635 return false;
639 return true;
642 // Emit a warning if toc-data attribute is requested for global variables that
643 // have aliases and remove the toc-data attribute.
644 static void checkAliasForTocData(llvm::GlobalVariable *GVar,
645 const CodeGenOptions &CodeGenOpts,
646 DiagnosticsEngine &Diags,
647 SourceLocation Location) {
648 if (GVar->hasAttribute("toc-data")) {
649 auto GVId = GVar->getName();
650 // Is this a global variable specified by the user as local?
651 if ((llvm::binary_search(CodeGenOpts.TocDataVarsUserSpecified, GVId))) {
652 Diags.Report(Location, diag::warn_toc_unsupported_type)
653 << GVId << "the variable has an alias";
655 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
656 llvm::AttributeSet NewAttributes =
657 CurrAttributes.removeAttribute(GVar->getContext(), "toc-data");
658 GVar->setAttributes(NewAttributes);
662 void CodeGenModule::checkAliases() {
663 // Check if the constructed aliases are well formed. It is really unfortunate
664 // that we have to do this in CodeGen, but we only construct mangled names
665 // and aliases during codegen.
666 bool Error = false;
667 DiagnosticsEngine &Diags = getDiags();
668 for (const GlobalDecl &GD : Aliases) {
669 const auto *D = cast<ValueDecl>(GD.getDecl());
670 SourceLocation Location;
671 SourceRange Range;
672 bool IsIFunc = D->hasAttr<IFuncAttr>();
673 if (const Attr *A = D->getDefiningAttr()) {
674 Location = A->getLocation();
675 Range = A->getRange();
676 } else
677 llvm_unreachable("Not an alias or ifunc?");
679 StringRef MangledName = getMangledName(GD);
680 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
681 const llvm::GlobalValue *GV = nullptr;
682 if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
683 MangledDeclNames, Range)) {
684 Error = true;
685 continue;
688 if (getContext().getTargetInfo().getTriple().isOSAIX())
689 if (const llvm::GlobalVariable *GVar =
690 dyn_cast<const llvm::GlobalVariable>(GV))
691 checkAliasForTocData(const_cast<llvm::GlobalVariable *>(GVar),
692 getCodeGenOpts(), Diags, Location);
694 llvm::Constant *Aliasee =
695 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
696 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
698 llvm::GlobalValue *AliaseeGV;
699 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
700 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
701 else
702 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
704 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
705 StringRef AliasSection = SA->getName();
706 if (AliasSection != AliaseeGV->getSection())
707 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
708 << AliasSection << IsIFunc << IsIFunc;
711 // We have to handle alias to weak aliases in here. LLVM itself disallows
712 // this since the object semantics would not match the IL one. For
713 // compatibility with gcc we implement it by just pointing the alias
714 // to its aliasee's aliasee. We also warn, since the user is probably
715 // expecting the link to be weak.
716 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
717 if (GA->isInterposable()) {
718 Diags.Report(Location, diag::warn_alias_to_weak_alias)
719 << GV->getName() << GA->getName() << IsIFunc;
720 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
721 GA->getAliasee(), Alias->getType());
723 if (IsIFunc)
724 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
725 else
726 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
729 // ifunc resolvers are usually implemented to run before sanitizer
730 // initialization. Disable instrumentation to prevent the ordering issue.
731 if (IsIFunc)
732 cast<llvm::Function>(Aliasee)->addFnAttr(
733 llvm::Attribute::DisableSanitizerInstrumentation);
735 if (!Error)
736 return;
738 for (const GlobalDecl &GD : Aliases) {
739 StringRef MangledName = getMangledName(GD);
740 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
741 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
742 Alias->eraseFromParent();
746 void CodeGenModule::clear() {
747 DeferredDeclsToEmit.clear();
748 EmittedDeferredDecls.clear();
749 DeferredAnnotations.clear();
750 if (OpenMPRuntime)
751 OpenMPRuntime->clear();
754 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
755 StringRef MainFile) {
756 if (!hasDiagnostics())
757 return;
758 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
759 if (MainFile.empty())
760 MainFile = "<stdin>";
761 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
762 } else {
763 if (Mismatched > 0)
764 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
766 if (Missing > 0)
767 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
771 static std::optional<llvm::GlobalValue::VisibilityTypes>
772 getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) {
773 // Map to LLVM visibility.
774 switch (K) {
775 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep:
776 return std::nullopt;
777 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default:
778 return llvm::GlobalValue::DefaultVisibility;
779 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden:
780 return llvm::GlobalValue::HiddenVisibility;
781 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected:
782 return llvm::GlobalValue::ProtectedVisibility;
784 llvm_unreachable("unknown option value!");
787 void setLLVMVisibility(llvm::GlobalValue &GV,
788 std::optional<llvm::GlobalValue::VisibilityTypes> V) {
789 if (!V)
790 return;
792 // Reset DSO locality before setting the visibility. This removes
793 // any effects that visibility options and annotations may have
794 // had on the DSO locality. Setting the visibility will implicitly set
795 // appropriate globals to DSO Local; however, this will be pessimistic
796 // w.r.t. to the normal compiler IRGen.
797 GV.setDSOLocal(false);
798 GV.setVisibility(*V);
801 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
802 llvm::Module &M) {
803 if (!LO.VisibilityFromDLLStorageClass)
804 return;
806 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
807 getLLVMVisibility(LO.getDLLExportVisibility());
809 std::optional<llvm::GlobalValue::VisibilityTypes>
810 NoDLLStorageClassVisibility =
811 getLLVMVisibility(LO.getNoDLLStorageClassVisibility());
813 std::optional<llvm::GlobalValue::VisibilityTypes>
814 ExternDeclDLLImportVisibility =
815 getLLVMVisibility(LO.getExternDeclDLLImportVisibility());
817 std::optional<llvm::GlobalValue::VisibilityTypes>
818 ExternDeclNoDLLStorageClassVisibility =
819 getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility());
821 for (llvm::GlobalValue &GV : M.global_values()) {
822 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
823 continue;
825 if (GV.isDeclarationForLinker())
826 setLLVMVisibility(GV, GV.getDLLStorageClass() ==
827 llvm::GlobalValue::DLLImportStorageClass
828 ? ExternDeclDLLImportVisibility
829 : ExternDeclNoDLLStorageClassVisibility);
830 else
831 setLLVMVisibility(GV, GV.getDLLStorageClass() ==
832 llvm::GlobalValue::DLLExportStorageClass
833 ? DLLExportVisibility
834 : NoDLLStorageClassVisibility);
836 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
840 static bool isStackProtectorOn(const LangOptions &LangOpts,
841 const llvm::Triple &Triple,
842 clang::LangOptions::StackProtectorMode Mode) {
843 if (Triple.isAMDGPU() || Triple.isNVPTX())
844 return false;
845 return LangOpts.getStackProtector() == Mode;
848 void CodeGenModule::Release() {
849 Module *Primary = getContext().getCurrentNamedModule();
850 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
851 EmitModuleInitializers(Primary);
852 EmitDeferred();
853 DeferredDecls.insert(EmittedDeferredDecls.begin(),
854 EmittedDeferredDecls.end());
855 EmittedDeferredDecls.clear();
856 EmitVTablesOpportunistically();
857 applyGlobalValReplacements();
858 applyReplacements();
859 emitMultiVersionFunctions();
861 if (Context.getLangOpts().IncrementalExtensions &&
862 GlobalTopLevelStmtBlockInFlight.first) {
863 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
864 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
865 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
868 // Module implementations are initialized the same way as a regular TU that
869 // imports one or more modules.
870 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
871 EmitCXXModuleInitFunc(Primary);
872 else
873 EmitCXXGlobalInitFunc();
874 EmitCXXGlobalCleanUpFunc();
875 registerGlobalDtorsWithAtExit();
876 EmitCXXThreadLocalInitFunc();
877 if (ObjCRuntime)
878 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
879 AddGlobalCtor(ObjCInitFunction);
880 if (Context.getLangOpts().CUDA && CUDARuntime) {
881 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
882 AddGlobalCtor(CudaCtorFunction);
884 if (OpenMPRuntime) {
885 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
886 OpenMPRuntime->clear();
888 if (PGOReader) {
889 getModule().setProfileSummary(
890 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
891 llvm::ProfileSummary::PSK_Instr);
892 if (PGOStats.hasDiagnostics())
893 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
895 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
896 return L.LexOrder < R.LexOrder;
898 EmitCtorList(GlobalCtors, "llvm.global_ctors");
899 EmitCtorList(GlobalDtors, "llvm.global_dtors");
900 EmitGlobalAnnotations();
901 EmitStaticExternCAliases();
902 checkAliases();
903 EmitDeferredUnusedCoverageMappings();
904 CodeGenPGO(*this).setValueProfilingFlag(getModule());
905 CodeGenPGO(*this).setProfileVersion(getModule());
906 if (CoverageMapping)
907 CoverageMapping->emit();
908 if (CodeGenOpts.SanitizeCfiCrossDso) {
909 CodeGenFunction(*this).EmitCfiCheckFail();
910 CodeGenFunction(*this).EmitCfiCheckStub();
912 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
913 finalizeKCFITypes();
914 emitAtAvailableLinkGuard();
915 if (Context.getTargetInfo().getTriple().isWasm())
916 EmitMainVoidAlias();
918 if (getTriple().isAMDGPU() ||
919 (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD)) {
920 // Emit amdhsa_code_object_version module flag, which is code object version
921 // times 100.
922 if (getTarget().getTargetOpts().CodeObjectVersion !=
923 llvm::CodeObjectVersionKind::COV_None) {
924 getModule().addModuleFlag(llvm::Module::Error,
925 "amdhsa_code_object_version",
926 getTarget().getTargetOpts().CodeObjectVersion);
929 // Currently, "-mprintf-kind" option is only supported for HIP
930 if (LangOpts.HIP) {
931 auto *MDStr = llvm::MDString::get(
932 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
933 TargetOptions::AMDGPUPrintfKind::Hostcall)
934 ? "hostcall"
935 : "buffered");
936 getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
937 MDStr);
941 // Emit a global array containing all external kernels or device variables
942 // used by host functions and mark it as used for CUDA/HIP. This is necessary
943 // to get kernels or device variables in archives linked in even if these
944 // kernels or device variables are only used in host functions.
945 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
946 SmallVector<llvm::Constant *, 8> UsedArray;
947 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
948 GlobalDecl GD;
949 if (auto *FD = dyn_cast<FunctionDecl>(D))
950 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
951 else
952 GD = GlobalDecl(D);
953 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
954 GetAddrOfGlobal(GD), Int8PtrTy));
957 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
959 auto *GV = new llvm::GlobalVariable(
960 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
961 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
962 addCompilerUsedGlobal(GV);
964 if (LangOpts.HIP && !getLangOpts().OffloadingNewDriver) {
965 // Emit a unique ID so that host and device binaries from the same
966 // compilation unit can be associated.
967 auto *GV = new llvm::GlobalVariable(
968 getModule(), Int8Ty, false, llvm::GlobalValue::ExternalLinkage,
969 llvm::Constant::getNullValue(Int8Ty),
970 "__hip_cuid_" + getContext().getCUIDHash());
971 addCompilerUsedGlobal(GV);
973 emitLLVMUsed();
974 if (SanStats)
975 SanStats->finish();
977 if (CodeGenOpts.Autolink &&
978 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
979 EmitModuleLinkOptions();
982 // On ELF we pass the dependent library specifiers directly to the linker
983 // without manipulating them. This is in contrast to other platforms where
984 // they are mapped to a specific linker option by the compiler. This
985 // difference is a result of the greater variety of ELF linkers and the fact
986 // that ELF linkers tend to handle libraries in a more complicated fashion
987 // than on other platforms. This forces us to defer handling the dependent
988 // libs to the linker.
990 // CUDA/HIP device and host libraries are different. Currently there is no
991 // way to differentiate dependent libraries for host or device. Existing
992 // usage of #pragma comment(lib, *) is intended for host libraries on
993 // Windows. Therefore emit llvm.dependent-libraries only for host.
994 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
995 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
996 for (auto *MD : ELFDependentLibraries)
997 NMD->addOperand(MD);
1000 if (CodeGenOpts.DwarfVersion) {
1001 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
1002 CodeGenOpts.DwarfVersion);
1005 if (CodeGenOpts.Dwarf64)
1006 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
1008 if (Context.getLangOpts().SemanticInterposition)
1009 // Require various optimization to respect semantic interposition.
1010 getModule().setSemanticInterposition(true);
1012 if (CodeGenOpts.EmitCodeView) {
1013 // Indicate that we want CodeView in the metadata.
1014 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
1016 if (CodeGenOpts.CodeViewGHash) {
1017 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
1019 if (CodeGenOpts.ControlFlowGuard) {
1020 // Function ID tables and checks for Control Flow Guard (cfguard=2).
1021 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
1022 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1023 // Function ID tables for Control Flow Guard (cfguard=1).
1024 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
1026 if (CodeGenOpts.EHContGuard) {
1027 // Function ID tables for EH Continuation Guard.
1028 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
1030 if (Context.getLangOpts().Kernel) {
1031 // Note if we are compiling with /kernel.
1032 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
1034 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1035 // We don't support LTO with 2 with different StrictVTablePointers
1036 // FIXME: we could support it by stripping all the information introduced
1037 // by StrictVTablePointers.
1039 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
1041 llvm::Metadata *Ops[2] = {
1042 llvm::MDString::get(VMContext, "StrictVTablePointers"),
1043 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1044 llvm::Type::getInt32Ty(VMContext), 1))};
1046 getModule().addModuleFlag(llvm::Module::Require,
1047 "StrictVTablePointersRequirement",
1048 llvm::MDNode::get(VMContext, Ops));
1050 if (getModuleDebugInfo())
1051 // We support a single version in the linked module. The LLVM
1052 // parser will drop debug info with a different version number
1053 // (and warn about it, too).
1054 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
1055 llvm::DEBUG_METADATA_VERSION);
1057 // We need to record the widths of enums and wchar_t, so that we can generate
1058 // the correct build attributes in the ARM backend. wchar_size is also used by
1059 // TargetLibraryInfo.
1060 uint64_t WCharWidth =
1061 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1062 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
1064 if (getTriple().isOSzOS()) {
1065 getModule().addModuleFlag(llvm::Module::Warning,
1066 "zos_product_major_version",
1067 uint32_t(CLANG_VERSION_MAJOR));
1068 getModule().addModuleFlag(llvm::Module::Warning,
1069 "zos_product_minor_version",
1070 uint32_t(CLANG_VERSION_MINOR));
1071 getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel",
1072 uint32_t(CLANG_VERSION_PATCHLEVEL));
1073 std::string ProductId = getClangVendor() + "clang";
1074 getModule().addModuleFlag(llvm::Module::Error, "zos_product_id",
1075 llvm::MDString::get(VMContext, ProductId));
1077 // Record the language because we need it for the PPA2.
1078 StringRef lang_str = languageToString(
1079 LangStandard::getLangStandardForKind(LangOpts.LangStd).Language);
1080 getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language",
1081 llvm::MDString::get(VMContext, lang_str));
1083 time_t TT = PreprocessorOpts.SourceDateEpoch
1084 ? *PreprocessorOpts.SourceDateEpoch
1085 : std::time(nullptr);
1086 getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time",
1087 static_cast<uint64_t>(TT));
1089 // Multiple modes will be supported here.
1090 getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
1091 llvm::MDString::get(VMContext, "ascii"));
1094 llvm::Triple T = Context.getTargetInfo().getTriple();
1095 if (T.isARM() || T.isThumb()) {
1096 // The minimum width of an enum in bytes
1097 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1098 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
1101 if (T.isRISCV()) {
1102 StringRef ABIStr = Target.getABI();
1103 llvm::LLVMContext &Ctx = TheModule.getContext();
1104 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
1105 llvm::MDString::get(Ctx, ABIStr));
1107 // Add the canonical ISA string as metadata so the backend can set the ELF
1108 // attributes correctly. We use AppendUnique so LTO will keep all of the
1109 // unique ISA strings that were linked together.
1110 const std::vector<std::string> &Features =
1111 getTarget().getTargetOpts().Features;
1112 auto ParseResult =
1113 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1114 if (!errorToBool(ParseResult.takeError()))
1115 getModule().addModuleFlag(
1116 llvm::Module::AppendUnique, "riscv-isa",
1117 llvm::MDNode::get(
1118 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1121 if (CodeGenOpts.SanitizeCfiCrossDso) {
1122 // Indicate that we want cross-DSO control flow integrity checks.
1123 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
1126 if (CodeGenOpts.WholeProgramVTables) {
1127 // Indicate whether VFE was enabled for this module, so that the
1128 // vcall_visibility metadata added under whole program vtables is handled
1129 // appropriately in the optimizer.
1130 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
1131 CodeGenOpts.VirtualFunctionElimination);
1134 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1135 getModule().addModuleFlag(llvm::Module::Override,
1136 "CFI Canonical Jump Tables",
1137 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1140 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1141 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1142 // KCFI assumes patchable-function-prefix is the same for all indirectly
1143 // called functions. Store the expected offset for code generation.
1144 if (CodeGenOpts.PatchableFunctionEntryOffset)
1145 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1146 CodeGenOpts.PatchableFunctionEntryOffset);
1149 if (CodeGenOpts.CFProtectionReturn &&
1150 Target.checkCFProtectionReturnSupported(getDiags())) {
1151 // Indicate that we want to instrument return control flow protection.
1152 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
1156 if (CodeGenOpts.CFProtectionBranch &&
1157 Target.checkCFProtectionBranchSupported(getDiags())) {
1158 // Indicate that we want to instrument branch control flow protection.
1159 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
1163 if (CodeGenOpts.FunctionReturnThunks)
1164 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
1166 if (CodeGenOpts.IndirectBranchCSPrefix)
1167 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1169 // Add module metadata for return address signing (ignoring
1170 // non-leaf/all) and stack tagging. These are actually turned on by function
1171 // attributes, but we use module metadata to emit build attributes. This is
1172 // needed for LTO, where the function attributes are inside bitcode
1173 // serialised into a global variable by the time build attributes are
1174 // emitted, so we can't access them. LTO objects could be compiled with
1175 // different flags therefore module flags are set to "Min" behavior to achieve
1176 // the same end result of the normal build where e.g BTI is off if any object
1177 // doesn't support it.
1178 if (Context.getTargetInfo().hasFeature("ptrauth") &&
1179 LangOpts.getSignReturnAddressScope() !=
1180 LangOptions::SignReturnAddressScopeKind::None)
1181 getModule().addModuleFlag(llvm::Module::Override,
1182 "sign-return-address-buildattr", 1);
1183 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1184 getModule().addModuleFlag(llvm::Module::Override,
1185 "tag-stack-memory-buildattr", 1);
1187 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1188 if (LangOpts.BranchTargetEnforcement)
1189 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1191 if (LangOpts.BranchProtectionPAuthLR)
1192 getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr",
1194 if (LangOpts.GuardedControlStack)
1195 getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1);
1196 if (LangOpts.hasSignReturnAddress())
1197 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1198 if (LangOpts.isSignReturnAddressScopeAll())
1199 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1201 if (!LangOpts.isSignReturnAddressWithAKey())
1202 getModule().addModuleFlag(llvm::Module::Min,
1203 "sign-return-address-with-bkey", 1);
1205 if (getTriple().isOSLinux()) {
1206 assert(getTriple().isOSBinFormatELF());
1207 using namespace llvm::ELF;
1208 uint64_t PAuthABIVersion =
1209 (LangOpts.PointerAuthIntrinsics
1210 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1211 (LangOpts.PointerAuthCalls
1212 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1213 (LangOpts.PointerAuthReturns
1214 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1215 (LangOpts.PointerAuthAuthTraps
1216 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1217 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1218 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1219 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1220 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1221 (LangOpts.PointerAuthInitFini
1222 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI);
1223 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI ==
1224 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1225 "Update when new enum items are defined");
1226 if (PAuthABIVersion != 0) {
1227 getModule().addModuleFlag(llvm::Module::Error,
1228 "aarch64-elf-pauthabi-platform",
1229 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1230 getModule().addModuleFlag(llvm::Module::Error,
1231 "aarch64-elf-pauthabi-version",
1232 PAuthABIVersion);
1237 if (CodeGenOpts.StackClashProtector)
1238 getModule().addModuleFlag(
1239 llvm::Module::Override, "probe-stack",
1240 llvm::MDString::get(TheModule.getContext(), "inline-asm"));
1242 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1243 getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
1244 CodeGenOpts.StackProbeSize);
1246 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1247 llvm::LLVMContext &Ctx = TheModule.getContext();
1248 getModule().addModuleFlag(
1249 llvm::Module::Error, "MemProfProfileFilename",
1250 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1253 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
1254 // Indicate whether __nvvm_reflect should be configured to flush denormal
1255 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
1256 // property.)
1257 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
1258 CodeGenOpts.FP32DenormalMode.Output !=
1259 llvm::DenormalMode::IEEE);
1262 if (LangOpts.EHAsynch)
1263 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1265 // Indicate whether this Module was compiled with -fopenmp
1266 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1267 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
1268 if (getLangOpts().OpenMPIsTargetDevice)
1269 getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1270 LangOpts.OpenMP);
1272 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
1273 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
1274 EmitOpenCLMetadata();
1275 // Emit SPIR version.
1276 if (getTriple().isSPIR()) {
1277 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
1278 // opencl.spir.version named metadata.
1279 // C++ for OpenCL has a distinct mapping for version compatibility with
1280 // OpenCL.
1281 auto Version = LangOpts.getOpenCLCompatibleVersion();
1282 llvm::Metadata *SPIRVerElts[] = {
1283 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1284 Int32Ty, Version / 100)),
1285 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1286 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1287 llvm::NamedMDNode *SPIRVerMD =
1288 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
1289 llvm::LLVMContext &Ctx = TheModule.getContext();
1290 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1294 // HLSL related end of code gen work items.
1295 if (LangOpts.HLSL)
1296 getHLSLRuntime().finishCodeGen();
1298 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1299 assert(PLevel < 3 && "Invalid PIC Level");
1300 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
1301 if (Context.getLangOpts().PIE)
1302 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
1305 if (getCodeGenOpts().CodeModel.size() > 0) {
1306 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
1307 .Case("tiny", llvm::CodeModel::Tiny)
1308 .Case("small", llvm::CodeModel::Small)
1309 .Case("kernel", llvm::CodeModel::Kernel)
1310 .Case("medium", llvm::CodeModel::Medium)
1311 .Case("large", llvm::CodeModel::Large)
1312 .Default(~0u);
1313 if (CM != ~0u) {
1314 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
1315 getModule().setCodeModel(codeModel);
1317 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1318 Context.getTargetInfo().getTriple().getArch() ==
1319 llvm::Triple::x86_64) {
1320 getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold);
1325 if (CodeGenOpts.NoPLT)
1326 getModule().setRtLibUseGOT();
1327 if (getTriple().isOSBinFormatELF() &&
1328 CodeGenOpts.DirectAccessExternalData !=
1329 getModule().getDirectAccessExternalData()) {
1330 getModule().setDirectAccessExternalData(
1331 CodeGenOpts.DirectAccessExternalData);
1333 if (CodeGenOpts.UnwindTables)
1334 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1336 switch (CodeGenOpts.getFramePointer()) {
1337 case CodeGenOptions::FramePointerKind::None:
1338 // 0 ("none") is the default.
1339 break;
1340 case CodeGenOptions::FramePointerKind::Reserved:
1341 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1342 break;
1343 case CodeGenOptions::FramePointerKind::NonLeaf:
1344 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1345 break;
1346 case CodeGenOptions::FramePointerKind::All:
1347 getModule().setFramePointer(llvm::FramePointerKind::All);
1348 break;
1351 SimplifyPersonality();
1353 if (getCodeGenOpts().EmitDeclMetadata)
1354 EmitDeclMetadata();
1356 if (getCodeGenOpts().CoverageNotesFile.size() ||
1357 getCodeGenOpts().CoverageDataFile.size())
1358 EmitCoverageFile();
1360 if (CGDebugInfo *DI = getModuleDebugInfo())
1361 DI->finalize();
1363 if (getCodeGenOpts().EmitVersionIdentMetadata)
1364 EmitVersionIdentMetadata();
1366 if (!getCodeGenOpts().RecordCommandLine.empty())
1367 EmitCommandLineMetadata();
1369 if (!getCodeGenOpts().StackProtectorGuard.empty())
1370 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1371 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1372 getModule().setStackProtectorGuardReg(
1373 getCodeGenOpts().StackProtectorGuardReg);
1374 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1375 getModule().setStackProtectorGuardSymbol(
1376 getCodeGenOpts().StackProtectorGuardSymbol);
1377 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1378 getModule().setStackProtectorGuardOffset(
1379 getCodeGenOpts().StackProtectorGuardOffset);
1380 if (getCodeGenOpts().StackAlignment)
1381 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1382 if (getCodeGenOpts().SkipRaxSetup)
1383 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1384 if (getLangOpts().RegCall4)
1385 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1387 if (getContext().getTargetInfo().getMaxTLSAlign())
1388 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1389 getContext().getTargetInfo().getMaxTLSAlign());
1391 getTargetCodeGenInfo().emitTargetGlobals(*this);
1393 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
1395 EmitBackendOptionsMetadata(getCodeGenOpts());
1397 // If there is device offloading code embed it in the host now.
1398 EmbedObject(&getModule(), CodeGenOpts, getDiags());
1400 // Set visibility from DLL storage class
1401 // We do this at the end of LLVM IR generation; after any operation
1402 // that might affect the DLL storage class or the visibility, and
1403 // before anything that might act on these.
1404 setVisibilityFromDLLStorageClass(LangOpts, getModule());
1406 // Check the tail call symbols are truly undefined.
1407 if (getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1408 for (auto &I : MustTailCallUndefinedGlobals) {
1409 if (!I.first->isDefined())
1410 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1411 else {
1412 StringRef MangledName = getMangledName(GlobalDecl(I.first));
1413 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1414 if (!Entry || Entry->isWeakForLinker() ||
1415 Entry->isDeclarationForLinker())
1416 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1422 void CodeGenModule::EmitOpenCLMetadata() {
1423 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1424 // opencl.ocl.version named metadata node.
1425 // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL.
1426 auto CLVersion = LangOpts.getOpenCLCompatibleVersion();
1428 auto EmitVersion = [this](StringRef MDName, int Version) {
1429 llvm::Metadata *OCLVerElts[] = {
1430 llvm::ConstantAsMetadata::get(
1431 llvm::ConstantInt::get(Int32Ty, Version / 100)),
1432 llvm::ConstantAsMetadata::get(
1433 llvm::ConstantInt::get(Int32Ty, (Version % 100) / 10))};
1434 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1435 llvm::LLVMContext &Ctx = TheModule.getContext();
1436 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1439 EmitVersion("opencl.ocl.version", CLVersion);
1440 if (LangOpts.OpenCLCPlusPlus) {
1441 // In addition to the OpenCL compatible version, emit the C++ version.
1442 EmitVersion("opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1446 void CodeGenModule::EmitBackendOptionsMetadata(
1447 const CodeGenOptions &CodeGenOpts) {
1448 if (getTriple().isRISCV()) {
1449 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
1450 CodeGenOpts.SmallDataLimit);
1454 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
1455 // Make sure that this type is translated.
1456 getTypes().UpdateCompletedType(TD);
1459 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
1460 // Make sure that this type is translated.
1461 getTypes().RefreshTypeCacheForClass(RD);
1464 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
1465 if (!TBAA)
1466 return nullptr;
1467 return TBAA->getTypeInfo(QTy);
1470 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
1471 if (!TBAA)
1472 return TBAAAccessInfo();
1473 if (getLangOpts().CUDAIsDevice) {
1474 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1475 // access info.
1476 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1477 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1478 nullptr)
1479 return TBAAAccessInfo();
1480 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1481 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1482 nullptr)
1483 return TBAAAccessInfo();
1486 return TBAA->getAccessInfo(AccessType);
1489 TBAAAccessInfo
1490 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
1491 if (!TBAA)
1492 return TBAAAccessInfo();
1493 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1496 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
1497 if (!TBAA)
1498 return nullptr;
1499 return TBAA->getTBAAStructInfo(QTy);
1502 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
1503 if (!TBAA)
1504 return nullptr;
1505 return TBAA->getBaseTypeInfo(QTy);
1508 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
1509 if (!TBAA)
1510 return nullptr;
1511 return TBAA->getAccessTagInfo(Info);
1514 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
1515 TBAAAccessInfo TargetInfo) {
1516 if (!TBAA)
1517 return TBAAAccessInfo();
1518 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1521 TBAAAccessInfo
1522 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
1523 TBAAAccessInfo InfoB) {
1524 if (!TBAA)
1525 return TBAAAccessInfo();
1526 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1529 TBAAAccessInfo
1530 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
1531 TBAAAccessInfo SrcInfo) {
1532 if (!TBAA)
1533 return TBAAAccessInfo();
1534 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1537 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1538 TBAAAccessInfo TBAAInfo) {
1539 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1540 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1543 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1544 llvm::Instruction *I, const CXXRecordDecl *RD) {
1545 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1546 llvm::MDNode::get(getLLVMContext(), {}));
1549 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1550 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1551 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1554 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1555 /// specified stmt yet.
1556 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1557 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1558 "cannot compile this %0 yet");
1559 std::string Msg = Type;
1560 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1561 << Msg << S->getSourceRange();
1564 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1565 /// specified decl yet.
1566 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1567 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1568 "cannot compile this %0 yet");
1569 std::string Msg = Type;
1570 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1573 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1574 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1577 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1578 const NamedDecl *D) const {
1579 // Internal definitions always have default visibility.
1580 if (GV->hasLocalLinkage()) {
1581 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1582 return;
1584 if (!D)
1585 return;
1587 // Set visibility for definitions, and for declarations if requested globally
1588 // or set explicitly.
1589 LinkageInfo LV = D->getLinkageAndVisibility();
1591 // OpenMP declare target variables must be visible to the host so they can
1592 // be registered. We require protected visibility unless the variable has
1593 // the DT_nohost modifier and does not need to be registered.
1594 if (Context.getLangOpts().OpenMP &&
1595 Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1596 D->hasAttr<OMPDeclareTargetDeclAttr>() &&
1597 D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1598 OMPDeclareTargetDeclAttr::DT_NoHost &&
1599 LV.getVisibility() == HiddenVisibility) {
1600 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1601 return;
1604 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1605 // Reject incompatible dlllstorage and visibility annotations.
1606 if (!LV.isVisibilityExplicit())
1607 return;
1608 if (GV->hasDLLExportStorageClass()) {
1609 if (LV.getVisibility() == HiddenVisibility)
1610 getDiags().Report(D->getLocation(),
1611 diag::err_hidden_visibility_dllexport);
1612 } else if (LV.getVisibility() != DefaultVisibility) {
1613 getDiags().Report(D->getLocation(),
1614 diag::err_non_default_visibility_dllimport);
1616 return;
1619 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1620 !GV->isDeclarationForLinker())
1621 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1624 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
1625 llvm::GlobalValue *GV) {
1626 if (GV->hasLocalLinkage())
1627 return true;
1629 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1630 return true;
1632 // DLLImport explicitly marks the GV as external.
1633 if (GV->hasDLLImportStorageClass())
1634 return false;
1636 const llvm::Triple &TT = CGM.getTriple();
1637 const auto &CGOpts = CGM.getCodeGenOpts();
1638 if (TT.isWindowsGNUEnvironment()) {
1639 // In MinGW, variables without DLLImport can still be automatically
1640 // imported from a DLL by the linker; don't mark variables that
1641 // potentially could come from another DLL as DSO local.
1643 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1644 // (and this actually happens in the public interface of libstdc++), so
1645 // such variables can't be marked as DSO local. (Native TLS variables
1646 // can't be dllimported at all, though.)
1647 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1648 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
1649 CGOpts.AutoImport)
1650 return false;
1653 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1654 // remain unresolved in the link, they can be resolved to zero, which is
1655 // outside the current DSO.
1656 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1657 return false;
1659 // Every other GV is local on COFF.
1660 // Make an exception for windows OS in the triple: Some firmware builds use
1661 // *-win32-macho triples. This (accidentally?) produced windows relocations
1662 // without GOT tables in older clang versions; Keep this behaviour.
1663 // FIXME: even thread local variables?
1664 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1665 return true;
1667 // Only handle COFF and ELF for now.
1668 if (!TT.isOSBinFormatELF())
1669 return false;
1671 // If this is not an executable, don't assume anything is local.
1672 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1673 const auto &LOpts = CGM.getLangOpts();
1674 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1675 // On ELF, if -fno-semantic-interposition is specified and the target
1676 // supports local aliases, there will be neither CC1
1677 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1678 // dso_local on the function if using a local alias is preferable (can avoid
1679 // PLT indirection).
1680 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1681 return false;
1682 return !(CGM.getLangOpts().SemanticInterposition ||
1683 CGM.getLangOpts().HalfNoSemanticInterposition);
1686 // A definition cannot be preempted from an executable.
1687 if (!GV->isDeclarationForLinker())
1688 return true;
1690 // Most PIC code sequences that assume that a symbol is local cannot produce a
1691 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1692 // depended, it seems worth it to handle it here.
1693 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1694 return false;
1696 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1697 if (TT.isPPC64())
1698 return false;
1700 if (CGOpts.DirectAccessExternalData) {
1701 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1702 // for non-thread-local variables. If the symbol is not defined in the
1703 // executable, a copy relocation will be needed at link time. dso_local is
1704 // excluded for thread-local variables because they generally don't support
1705 // copy relocations.
1706 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1707 if (!Var->isThreadLocal())
1708 return true;
1710 // -fno-pic sets dso_local on a function declaration to allow direct
1711 // accesses when taking its address (similar to a data symbol). If the
1712 // function is not defined in the executable, a canonical PLT entry will be
1713 // needed at link time. -fno-direct-access-external-data can avoid the
1714 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1715 // it could just cause trouble without providing perceptible benefits.
1716 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1717 return true;
1720 // If we can use copy relocations we can assume it is local.
1722 // Otherwise don't assume it is local.
1723 return false;
1726 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1727 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1730 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1731 GlobalDecl GD) const {
1732 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1733 // C++ destructors have a few C++ ABI specific special cases.
1734 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1735 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1736 return;
1738 setDLLImportDLLExport(GV, D);
1741 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1742 const NamedDecl *D) const {
1743 if (D && D->isExternallyVisible()) {
1744 if (D->hasAttr<DLLImportAttr>())
1745 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1746 else if ((D->hasAttr<DLLExportAttr>() ||
1747 shouldMapVisibilityToDLLExport(D)) &&
1748 !GV->isDeclarationForLinker())
1749 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1753 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1754 GlobalDecl GD) const {
1755 setDLLImportDLLExport(GV, GD);
1756 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1759 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1760 const NamedDecl *D) const {
1761 setDLLImportDLLExport(GV, D);
1762 setGVPropertiesAux(GV, D);
1765 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1766 const NamedDecl *D) const {
1767 setGlobalVisibility(GV, D);
1768 setDSOLocal(GV);
1769 GV->setPartition(CodeGenOpts.SymbolPartition);
1772 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1773 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1774 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1775 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1776 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1777 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1780 llvm::GlobalVariable::ThreadLocalMode
1781 CodeGenModule::GetDefaultLLVMTLSModel() const {
1782 switch (CodeGenOpts.getDefaultTLSModel()) {
1783 case CodeGenOptions::GeneralDynamicTLSModel:
1784 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1785 case CodeGenOptions::LocalDynamicTLSModel:
1786 return llvm::GlobalVariable::LocalDynamicTLSModel;
1787 case CodeGenOptions::InitialExecTLSModel:
1788 return llvm::GlobalVariable::InitialExecTLSModel;
1789 case CodeGenOptions::LocalExecTLSModel:
1790 return llvm::GlobalVariable::LocalExecTLSModel;
1792 llvm_unreachable("Invalid TLS model!");
1795 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1796 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1798 llvm::GlobalValue::ThreadLocalMode TLM;
1799 TLM = GetDefaultLLVMTLSModel();
1801 // Override the TLS model if it is explicitly specified.
1802 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1803 TLM = GetLLVMTLSModel(Attr->getModel());
1806 GV->setThreadLocalMode(TLM);
1809 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1810 StringRef Name) {
1811 const TargetInfo &Target = CGM.getTarget();
1812 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1815 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1816 const CPUSpecificAttr *Attr,
1817 unsigned CPUIndex,
1818 raw_ostream &Out) {
1819 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1820 // supported.
1821 if (Attr)
1822 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1823 else if (CGM.getTarget().supportsIFunc())
1824 Out << ".resolver";
1827 // Returns true if GD is a function decl with internal linkage and
1828 // needs a unique suffix after the mangled name.
1829 static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1830 CodeGenModule &CGM) {
1831 const Decl *D = GD.getDecl();
1832 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1833 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1836 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1837 const NamedDecl *ND,
1838 bool OmitMultiVersionMangling = false) {
1839 SmallString<256> Buffer;
1840 llvm::raw_svector_ostream Out(Buffer);
1841 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1842 if (!CGM.getModuleNameHash().empty())
1843 MC.needsUniqueInternalLinkageNames();
1844 bool ShouldMangle = MC.shouldMangleDeclName(ND);
1845 if (ShouldMangle)
1846 MC.mangleName(GD.getWithDecl(ND), Out);
1847 else {
1848 IdentifierInfo *II = ND->getIdentifier();
1849 assert(II && "Attempt to mangle unnamed decl.");
1850 const auto *FD = dyn_cast<FunctionDecl>(ND);
1852 if (FD &&
1853 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1854 if (CGM.getLangOpts().RegCall4)
1855 Out << "__regcall4__" << II->getName();
1856 else
1857 Out << "__regcall3__" << II->getName();
1858 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1859 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1860 Out << "__device_stub__" << II->getName();
1861 } else {
1862 Out << II->getName();
1866 // Check if the module name hash should be appended for internal linkage
1867 // symbols. This should come before multi-version target suffixes are
1868 // appended. This is to keep the name and module hash suffix of the
1869 // internal linkage function together. The unique suffix should only be
1870 // added when name mangling is done to make sure that the final name can
1871 // be properly demangled. For example, for C functions without prototypes,
1872 // name mangling is not done and the unique suffix should not be appeneded
1873 // then.
1874 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1875 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1876 "Hash computed when not explicitly requested");
1877 Out << CGM.getModuleNameHash();
1880 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1881 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1882 switch (FD->getMultiVersionKind()) {
1883 case MultiVersionKind::CPUDispatch:
1884 case MultiVersionKind::CPUSpecific:
1885 AppendCPUSpecificCPUDispatchMangling(CGM,
1886 FD->getAttr<CPUSpecificAttr>(),
1887 GD.getMultiVersionIndex(), Out);
1888 break;
1889 case MultiVersionKind::Target: {
1890 auto *Attr = FD->getAttr<TargetAttr>();
1891 assert(Attr && "Expected TargetAttr to be present "
1892 "for attribute mangling");
1893 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1894 Info.appendAttributeMangling(Attr, Out);
1895 break;
1897 case MultiVersionKind::TargetVersion: {
1898 auto *Attr = FD->getAttr<TargetVersionAttr>();
1899 assert(Attr && "Expected TargetVersionAttr to be present "
1900 "for attribute mangling");
1901 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1902 Info.appendAttributeMangling(Attr, Out);
1903 break;
1905 case MultiVersionKind::TargetClones: {
1906 auto *Attr = FD->getAttr<TargetClonesAttr>();
1907 assert(Attr && "Expected TargetClonesAttr to be present "
1908 "for attribute mangling");
1909 unsigned Index = GD.getMultiVersionIndex();
1910 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1911 Info.appendAttributeMangling(Attr, Index, Out);
1912 break;
1914 case MultiVersionKind::None:
1915 llvm_unreachable("None multiversion type isn't valid here");
1919 // Make unique name for device side static file-scope variable for HIP.
1920 if (CGM.getContext().shouldExternalize(ND) &&
1921 CGM.getLangOpts().GPURelocatableDeviceCode &&
1922 CGM.getLangOpts().CUDAIsDevice)
1923 CGM.printPostfixForExternalizedDecl(Out, ND);
1925 return std::string(Out.str());
1928 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1929 const FunctionDecl *FD,
1930 StringRef &CurName) {
1931 if (!FD->isMultiVersion())
1932 return;
1934 // Get the name of what this would be without the 'target' attribute. This
1935 // allows us to lookup the version that was emitted when this wasn't a
1936 // multiversion function.
1937 std::string NonTargetName =
1938 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1939 GlobalDecl OtherGD;
1940 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1941 assert(OtherGD.getCanonicalDecl()
1942 .getDecl()
1943 ->getAsFunction()
1944 ->isMultiVersion() &&
1945 "Other GD should now be a multiversioned function");
1946 // OtherFD is the version of this function that was mangled BEFORE
1947 // becoming a MultiVersion function. It potentially needs to be updated.
1948 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1949 .getDecl()
1950 ->getAsFunction()
1951 ->getMostRecentDecl();
1952 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1953 // This is so that if the initial version was already the 'default'
1954 // version, we don't try to update it.
1955 if (OtherName != NonTargetName) {
1956 // Remove instead of erase, since others may have stored the StringRef
1957 // to this.
1958 const auto ExistingRecord = Manglings.find(NonTargetName);
1959 if (ExistingRecord != std::end(Manglings))
1960 Manglings.remove(&(*ExistingRecord));
1961 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1962 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1963 Result.first->first();
1964 // If this is the current decl is being created, make sure we update the name.
1965 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1966 CurName = OtherNameRef;
1967 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1968 Entry->setName(OtherName);
1973 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1974 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1976 // Some ABIs don't have constructor variants. Make sure that base and
1977 // complete constructors get mangled the same.
1978 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1979 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1980 CXXCtorType OrigCtorType = GD.getCtorType();
1981 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1982 if (OrigCtorType == Ctor_Base)
1983 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1987 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1988 // static device variable depends on whether the variable is referenced by
1989 // a host or device host function. Therefore the mangled name cannot be
1990 // cached.
1991 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
1992 auto FoundName = MangledDeclNames.find(CanonicalGD);
1993 if (FoundName != MangledDeclNames.end())
1994 return FoundName->second;
1997 // Keep the first result in the case of a mangling collision.
1998 const auto *ND = cast<NamedDecl>(GD.getDecl());
1999 std::string MangledName = getMangledNameImpl(*this, GD, ND);
2001 // Ensure either we have different ABIs between host and device compilations,
2002 // says host compilation following MSVC ABI but device compilation follows
2003 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
2004 // mangling should be the same after name stubbing. The later checking is
2005 // very important as the device kernel name being mangled in host-compilation
2006 // is used to resolve the device binaries to be executed. Inconsistent naming
2007 // result in undefined behavior. Even though we cannot check that naming
2008 // directly between host- and device-compilations, the host- and
2009 // device-mangling in host compilation could help catching certain ones.
2010 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2011 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
2012 (getContext().getAuxTargetInfo() &&
2013 (getContext().getAuxTargetInfo()->getCXXABI() !=
2014 getContext().getTargetInfo().getCXXABI())) ||
2015 getCUDARuntime().getDeviceSideName(ND) ==
2016 getMangledNameImpl(
2017 *this,
2018 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
2019 ND));
2021 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2022 return MangledDeclNames[CanonicalGD] = Result.first->first();
2025 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
2026 const BlockDecl *BD) {
2027 MangleContext &MangleCtx = getCXXABI().getMangleContext();
2028 const Decl *D = GD.getDecl();
2030 SmallString<256> Buffer;
2031 llvm::raw_svector_ostream Out(Buffer);
2032 if (!D)
2033 MangleCtx.mangleGlobalBlock(BD,
2034 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2035 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2036 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
2037 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2038 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
2039 else
2040 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
2042 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2043 return Result.first->first();
2046 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
2047 auto it = MangledDeclNames.begin();
2048 while (it != MangledDeclNames.end()) {
2049 if (it->second == Name)
2050 return it->first;
2051 it++;
2053 return GlobalDecl();
2056 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
2057 return getModule().getNamedValue(Name);
2060 /// AddGlobalCtor - Add a function to the list that will be called before
2061 /// main() runs.
2062 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2063 unsigned LexOrder,
2064 llvm::Constant *AssociatedData) {
2065 // FIXME: Type coercion of void()* types.
2066 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
2069 /// AddGlobalDtor - Add a function to the list that will be called
2070 /// when the module is unloaded.
2071 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2072 bool IsDtorAttrFunc) {
2073 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2074 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
2075 DtorsUsingAtExit[Priority].push_back(Dtor);
2076 return;
2079 // FIXME: Type coercion of void()* types.
2080 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
2083 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
2084 if (Fns.empty()) return;
2086 // Ctor function type is void()*.
2087 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
2088 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
2089 TheModule.getDataLayout().getProgramAddressSpace());
2091 // Get the type of a ctor entry, { i32, void ()*, i8* }.
2092 llvm::StructType *CtorStructTy = llvm::StructType::get(
2093 Int32Ty, CtorPFTy, VoidPtrTy);
2095 // Construct the constructor and destructor arrays.
2096 ConstantInitBuilder builder(*this);
2097 auto ctors = builder.beginArray(CtorStructTy);
2098 for (const auto &I : Fns) {
2099 auto ctor = ctors.beginStruct(CtorStructTy);
2100 ctor.addInt(Int32Ty, I.Priority);
2101 ctor.add(I.Initializer);
2102 if (I.AssociatedData)
2103 ctor.add(I.AssociatedData);
2104 else
2105 ctor.addNullPointer(VoidPtrTy);
2106 ctor.finishAndAddTo(ctors);
2109 auto list =
2110 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
2111 /*constant*/ false,
2112 llvm::GlobalValue::AppendingLinkage);
2114 // The LTO linker doesn't seem to like it when we set an alignment
2115 // on appending variables. Take it off as a workaround.
2116 list->setAlignment(std::nullopt);
2118 Fns.clear();
2121 llvm::GlobalValue::LinkageTypes
2122 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
2123 const auto *D = cast<FunctionDecl>(GD.getDecl());
2125 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
2127 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2128 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
2130 return getLLVMLinkageForDeclarator(D, Linkage);
2133 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
2134 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2135 if (!MDS) return nullptr;
2137 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
2140 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
2141 if (auto *FnType = T->getAs<FunctionProtoType>())
2142 T = getContext().getFunctionType(
2143 FnType->getReturnType(), FnType->getParamTypes(),
2144 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2146 std::string OutName;
2147 llvm::raw_string_ostream Out(OutName);
2148 getCXXABI().getMangleContext().mangleCanonicalTypeName(
2149 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2151 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2152 Out << ".normalized";
2154 return llvm::ConstantInt::get(Int32Ty,
2155 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2158 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
2159 const CGFunctionInfo &Info,
2160 llvm::Function *F, bool IsThunk) {
2161 unsigned CallingConv;
2162 llvm::AttributeList PAL;
2163 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2164 /*AttrOnCallSite=*/false, IsThunk);
2165 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
2166 getTarget().getTriple().isWindowsArm64EC()) {
2167 SourceLocation Loc;
2168 if (const Decl *D = GD.getDecl())
2169 Loc = D->getLocation();
2171 Error(Loc, "__vectorcall calling convention is not currently supported");
2173 F->setAttributes(PAL);
2174 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2177 static void removeImageAccessQualifier(std::string& TyName) {
2178 std::string ReadOnlyQual("__read_only");
2179 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2180 if (ReadOnlyPos != std::string::npos)
2181 // "+ 1" for the space after access qualifier.
2182 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2183 else {
2184 std::string WriteOnlyQual("__write_only");
2185 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2186 if (WriteOnlyPos != std::string::npos)
2187 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2188 else {
2189 std::string ReadWriteQual("__read_write");
2190 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2191 if (ReadWritePos != std::string::npos)
2192 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2197 // Returns the address space id that should be produced to the
2198 // kernel_arg_addr_space metadata. This is always fixed to the ids
2199 // as specified in the SPIR 2.0 specification in order to differentiate
2200 // for example in clGetKernelArgInfo() implementation between the address
2201 // spaces with targets without unique mapping to the OpenCL address spaces
2202 // (basically all single AS CPUs).
2203 static unsigned ArgInfoAddressSpace(LangAS AS) {
2204 switch (AS) {
2205 case LangAS::opencl_global:
2206 return 1;
2207 case LangAS::opencl_constant:
2208 return 2;
2209 case LangAS::opencl_local:
2210 return 3;
2211 case LangAS::opencl_generic:
2212 return 4; // Not in SPIR 2.0 specs.
2213 case LangAS::opencl_global_device:
2214 return 5;
2215 case LangAS::opencl_global_host:
2216 return 6;
2217 default:
2218 return 0; // Assume private.
2222 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
2223 const FunctionDecl *FD,
2224 CodeGenFunction *CGF) {
2225 assert(((FD && CGF) || (!FD && !CGF)) &&
2226 "Incorrect use - FD and CGF should either be both null or not!");
2227 // Create MDNodes that represent the kernel arg metadata.
2228 // Each MDNode is a list in the form of "key", N number of values which is
2229 // the same number of values as their are kernel arguments.
2231 const PrintingPolicy &Policy = Context.getPrintingPolicy();
2233 // MDNode for the kernel argument address space qualifiers.
2234 SmallVector<llvm::Metadata *, 8> addressQuals;
2236 // MDNode for the kernel argument access qualifiers (images only).
2237 SmallVector<llvm::Metadata *, 8> accessQuals;
2239 // MDNode for the kernel argument type names.
2240 SmallVector<llvm::Metadata *, 8> argTypeNames;
2242 // MDNode for the kernel argument base type names.
2243 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2245 // MDNode for the kernel argument type qualifiers.
2246 SmallVector<llvm::Metadata *, 8> argTypeQuals;
2248 // MDNode for the kernel argument names.
2249 SmallVector<llvm::Metadata *, 8> argNames;
2251 if (FD && CGF)
2252 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2253 const ParmVarDecl *parm = FD->getParamDecl(i);
2254 // Get argument name.
2255 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2257 if (!getLangOpts().OpenCL)
2258 continue;
2259 QualType ty = parm->getType();
2260 std::string typeQuals;
2262 // Get image and pipe access qualifier:
2263 if (ty->isImageType() || ty->isPipeType()) {
2264 const Decl *PDecl = parm;
2265 if (const auto *TD = ty->getAs<TypedefType>())
2266 PDecl = TD->getDecl();
2267 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2268 if (A && A->isWriteOnly())
2269 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2270 else if (A && A->isReadWrite())
2271 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2272 else
2273 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2274 } else
2275 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2277 auto getTypeSpelling = [&](QualType Ty) {
2278 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2280 if (Ty.isCanonical()) {
2281 StringRef typeNameRef = typeName;
2282 // Turn "unsigned type" to "utype"
2283 if (typeNameRef.consume_front("unsigned "))
2284 return std::string("u") + typeNameRef.str();
2285 if (typeNameRef.consume_front("signed "))
2286 return typeNameRef.str();
2289 return typeName;
2292 if (ty->isPointerType()) {
2293 QualType pointeeTy = ty->getPointeeType();
2295 // Get address qualifier.
2296 addressQuals.push_back(
2297 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2298 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2300 // Get argument type name.
2301 std::string typeName = getTypeSpelling(pointeeTy) + "*";
2302 std::string baseTypeName =
2303 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2304 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2305 argBaseTypeNames.push_back(
2306 llvm::MDString::get(VMContext, baseTypeName));
2308 // Get argument type qualifiers:
2309 if (ty.isRestrictQualified())
2310 typeQuals = "restrict";
2311 if (pointeeTy.isConstQualified() ||
2312 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
2313 typeQuals += typeQuals.empty() ? "const" : " const";
2314 if (pointeeTy.isVolatileQualified())
2315 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2316 } else {
2317 uint32_t AddrSpc = 0;
2318 bool isPipe = ty->isPipeType();
2319 if (ty->isImageType() || isPipe)
2320 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
2322 addressQuals.push_back(
2323 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2325 // Get argument type name.
2326 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2327 std::string typeName = getTypeSpelling(ty);
2328 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2330 // Remove access qualifiers on images
2331 // (as they are inseparable from type in clang implementation,
2332 // but OpenCL spec provides a special query to get access qualifier
2333 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2334 if (ty->isImageType()) {
2335 removeImageAccessQualifier(typeName);
2336 removeImageAccessQualifier(baseTypeName);
2339 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2340 argBaseTypeNames.push_back(
2341 llvm::MDString::get(VMContext, baseTypeName));
2343 if (isPipe)
2344 typeQuals = "pipe";
2346 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2349 if (getLangOpts().OpenCL) {
2350 Fn->setMetadata("kernel_arg_addr_space",
2351 llvm::MDNode::get(VMContext, addressQuals));
2352 Fn->setMetadata("kernel_arg_access_qual",
2353 llvm::MDNode::get(VMContext, accessQuals));
2354 Fn->setMetadata("kernel_arg_type",
2355 llvm::MDNode::get(VMContext, argTypeNames));
2356 Fn->setMetadata("kernel_arg_base_type",
2357 llvm::MDNode::get(VMContext, argBaseTypeNames));
2358 Fn->setMetadata("kernel_arg_type_qual",
2359 llvm::MDNode::get(VMContext, argTypeQuals));
2361 if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2362 getCodeGenOpts().HIPSaveKernelArgName)
2363 Fn->setMetadata("kernel_arg_name",
2364 llvm::MDNode::get(VMContext, argNames));
2367 /// Determines whether the language options require us to model
2368 /// unwind exceptions. We treat -fexceptions as mandating this
2369 /// except under the fragile ObjC ABI with only ObjC exceptions
2370 /// enabled. This means, for example, that C with -fexceptions
2371 /// enables this.
2372 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2373 // If exceptions are completely disabled, obviously this is false.
2374 if (!LangOpts.Exceptions) return false;
2376 // If C++ exceptions are enabled, this is true.
2377 if (LangOpts.CXXExceptions) return true;
2379 // If ObjC exceptions are enabled, this depends on the ABI.
2380 if (LangOpts.ObjCExceptions) {
2381 return LangOpts.ObjCRuntime.hasUnwindExceptions();
2384 return true;
2387 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
2388 const CXXMethodDecl *MD) {
2389 // Check that the type metadata can ever actually be used by a call.
2390 if (!CGM.getCodeGenOpts().LTOUnit ||
2391 !CGM.HasHiddenLTOVisibility(MD->getParent()))
2392 return false;
2394 // Only functions whose address can be taken with a member function pointer
2395 // need this sort of type metadata.
2396 return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2397 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2400 SmallVector<const CXXRecordDecl *, 0>
2401 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
2402 llvm::SetVector<const CXXRecordDecl *> MostBases;
2404 std::function<void (const CXXRecordDecl *)> CollectMostBases;
2405 CollectMostBases = [&](const CXXRecordDecl *RD) {
2406 if (RD->getNumBases() == 0)
2407 MostBases.insert(RD);
2408 for (const CXXBaseSpecifier &B : RD->bases())
2409 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2411 CollectMostBases(RD);
2412 return MostBases.takeVector();
2415 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2416 llvm::Function *F) {
2417 llvm::AttrBuilder B(F->getContext());
2419 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2420 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2422 if (CodeGenOpts.StackClashProtector)
2423 B.addAttribute("probe-stack", "inline-asm");
2425 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2426 B.addAttribute("stack-probe-size",
2427 std::to_string(CodeGenOpts.StackProbeSize));
2429 if (!hasUnwindExceptions(LangOpts))
2430 B.addAttribute(llvm::Attribute::NoUnwind);
2432 if (D && D->hasAttr<NoStackProtectorAttr>())
2433 ; // Do nothing.
2434 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2435 isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2436 B.addAttribute(llvm::Attribute::StackProtectStrong);
2437 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2438 B.addAttribute(llvm::Attribute::StackProtect);
2439 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong))
2440 B.addAttribute(llvm::Attribute::StackProtectStrong);
2441 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
2442 B.addAttribute(llvm::Attribute::StackProtectReq);
2444 if (!D) {
2445 // If we don't have a declaration to control inlining, the function isn't
2446 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2447 // disabled, mark the function as noinline.
2448 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2449 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2450 B.addAttribute(llvm::Attribute::NoInline);
2452 F->addFnAttrs(B);
2453 return;
2456 // Handle SME attributes that apply to function definitions,
2457 // rather than to function prototypes.
2458 if (D->hasAttr<ArmLocallyStreamingAttr>())
2459 B.addAttribute("aarch64_pstate_sm_body");
2461 if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2462 if (Attr->isNewZA())
2463 B.addAttribute("aarch64_new_za");
2464 if (Attr->isNewZT0())
2465 B.addAttribute("aarch64_new_zt0");
2468 // Track whether we need to add the optnone LLVM attribute,
2469 // starting with the default for this optimization level.
2470 bool ShouldAddOptNone =
2471 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2472 // We can't add optnone in the following cases, it won't pass the verifier.
2473 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2474 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2476 // Add optnone, but do so only if the function isn't always_inline.
2477 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2478 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2479 B.addAttribute(llvm::Attribute::OptimizeNone);
2481 // OptimizeNone implies noinline; we should not be inlining such functions.
2482 B.addAttribute(llvm::Attribute::NoInline);
2484 // We still need to handle naked functions even though optnone subsumes
2485 // much of their semantics.
2486 if (D->hasAttr<NakedAttr>())
2487 B.addAttribute(llvm::Attribute::Naked);
2489 // OptimizeNone wins over OptimizeForSize and MinSize.
2490 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2491 F->removeFnAttr(llvm::Attribute::MinSize);
2492 } else if (D->hasAttr<NakedAttr>()) {
2493 // Naked implies noinline: we should not be inlining such functions.
2494 B.addAttribute(llvm::Attribute::Naked);
2495 B.addAttribute(llvm::Attribute::NoInline);
2496 } else if (D->hasAttr<NoDuplicateAttr>()) {
2497 B.addAttribute(llvm::Attribute::NoDuplicate);
2498 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2499 // Add noinline if the function isn't always_inline.
2500 B.addAttribute(llvm::Attribute::NoInline);
2501 } else if (D->hasAttr<AlwaysInlineAttr>() &&
2502 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2503 // (noinline wins over always_inline, and we can't specify both in IR)
2504 B.addAttribute(llvm::Attribute::AlwaysInline);
2505 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2506 // If we're not inlining, then force everything that isn't always_inline to
2507 // carry an explicit noinline attribute.
2508 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2509 B.addAttribute(llvm::Attribute::NoInline);
2510 } else {
2511 // Otherwise, propagate the inline hint attribute and potentially use its
2512 // absence to mark things as noinline.
2513 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2514 // Search function and template pattern redeclarations for inline.
2515 auto CheckForInline = [](const FunctionDecl *FD) {
2516 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2517 return Redecl->isInlineSpecified();
2519 if (any_of(FD->redecls(), CheckRedeclForInline))
2520 return true;
2521 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2522 if (!Pattern)
2523 return false;
2524 return any_of(Pattern->redecls(), CheckRedeclForInline);
2526 if (CheckForInline(FD)) {
2527 B.addAttribute(llvm::Attribute::InlineHint);
2528 } else if (CodeGenOpts.getInlining() ==
2529 CodeGenOptions::OnlyHintInlining &&
2530 !FD->isInlined() &&
2531 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2532 B.addAttribute(llvm::Attribute::NoInline);
2537 // Add other optimization related attributes if we are optimizing this
2538 // function.
2539 if (!D->hasAttr<OptimizeNoneAttr>()) {
2540 if (D->hasAttr<ColdAttr>()) {
2541 if (!ShouldAddOptNone)
2542 B.addAttribute(llvm::Attribute::OptimizeForSize);
2543 B.addAttribute(llvm::Attribute::Cold);
2545 if (D->hasAttr<HotAttr>())
2546 B.addAttribute(llvm::Attribute::Hot);
2547 if (D->hasAttr<MinSizeAttr>())
2548 B.addAttribute(llvm::Attribute::MinSize);
2551 F->addFnAttrs(B);
2553 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2554 if (alignment)
2555 F->setAlignment(llvm::Align(alignment));
2557 if (!D->hasAttr<AlignedAttr>())
2558 if (LangOpts.FunctionAlignment)
2559 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2561 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2562 // reserve a bit for differentiating between virtual and non-virtual member
2563 // functions. If the current target's C++ ABI requires this and this is a
2564 // member function, set its alignment accordingly.
2565 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2566 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2567 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2570 // In the cross-dso CFI mode with canonical jump tables, we want !type
2571 // attributes on definitions only.
2572 if (CodeGenOpts.SanitizeCfiCrossDso &&
2573 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2574 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2575 // Skip available_externally functions. They won't be codegen'ed in the
2576 // current module anyway.
2577 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2578 CreateFunctionTypeMetadataForIcall(FD, F);
2582 // Emit type metadata on member functions for member function pointer checks.
2583 // These are only ever necessary on definitions; we're guaranteed that the
2584 // definition will be present in the LTO unit as a result of LTO visibility.
2585 auto *MD = dyn_cast<CXXMethodDecl>(D);
2586 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2587 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2588 llvm::Metadata *Id =
2589 CreateMetadataIdentifierForType(Context.getMemberPointerType(
2590 MD->getType(), Context.getRecordType(Base).getTypePtr()));
2591 F->addTypeMetadata(0, Id);
2596 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2597 const Decl *D = GD.getDecl();
2598 if (isa_and_nonnull<NamedDecl>(D))
2599 setGVProperties(GV, GD);
2600 else
2601 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2603 if (D && D->hasAttr<UsedAttr>())
2604 addUsedOrCompilerUsedGlobal(GV);
2606 if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2607 VD &&
2608 ((CodeGenOpts.KeepPersistentStorageVariables &&
2609 (VD->getStorageDuration() == SD_Static ||
2610 VD->getStorageDuration() == SD_Thread)) ||
2611 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2612 VD->getType().isConstQualified())))
2613 addUsedOrCompilerUsedGlobal(GV);
2616 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2617 llvm::AttrBuilder &Attrs,
2618 bool SetTargetFeatures) {
2619 // Add target-cpu and target-features attributes to functions. If
2620 // we have a decl for the function and it has a target attribute then
2621 // parse that and add it to the feature set.
2622 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2623 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2624 std::vector<std::string> Features;
2625 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2626 FD = FD ? FD->getMostRecentDecl() : FD;
2627 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2628 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2629 assert((!TD || !TV) && "both target_version and target specified");
2630 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2631 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2632 bool AddedAttr = false;
2633 if (TD || TV || SD || TC) {
2634 llvm::StringMap<bool> FeatureMap;
2635 getContext().getFunctionFeatureMap(FeatureMap, GD);
2637 // Produce the canonical string for this set of features.
2638 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2639 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2641 // Now add the target-cpu and target-features to the function.
2642 // While we populated the feature map above, we still need to
2643 // get and parse the target attribute so we can get the cpu for
2644 // the function.
2645 if (TD) {
2646 ParsedTargetAttr ParsedAttr =
2647 Target.parseTargetAttr(TD->getFeaturesStr());
2648 if (!ParsedAttr.CPU.empty() &&
2649 getTarget().isValidCPUName(ParsedAttr.CPU)) {
2650 TargetCPU = ParsedAttr.CPU;
2651 TuneCPU = ""; // Clear the tune CPU.
2653 if (!ParsedAttr.Tune.empty() &&
2654 getTarget().isValidCPUName(ParsedAttr.Tune))
2655 TuneCPU = ParsedAttr.Tune;
2658 if (SD) {
2659 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2660 // favor this processor.
2661 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2663 } else {
2664 // Otherwise just add the existing target cpu and target features to the
2665 // function.
2666 Features = getTarget().getTargetOpts().Features;
2669 if (!TargetCPU.empty()) {
2670 Attrs.addAttribute("target-cpu", TargetCPU);
2671 AddedAttr = true;
2673 if (!TuneCPU.empty()) {
2674 Attrs.addAttribute("tune-cpu", TuneCPU);
2675 AddedAttr = true;
2677 if (!Features.empty() && SetTargetFeatures) {
2678 llvm::erase_if(Features, [&](const std::string& F) {
2679 return getTarget().isReadOnlyFeature(F.substr(1));
2681 llvm::sort(Features);
2682 Attrs.addAttribute("target-features", llvm::join(Features, ","));
2683 AddedAttr = true;
2686 return AddedAttr;
2689 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2690 llvm::GlobalObject *GO) {
2691 const Decl *D = GD.getDecl();
2692 SetCommonAttributes(GD, GO);
2694 if (D) {
2695 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2696 if (D->hasAttr<RetainAttr>())
2697 addUsedGlobal(GV);
2698 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2699 GV->addAttribute("bss-section", SA->getName());
2700 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2701 GV->addAttribute("data-section", SA->getName());
2702 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2703 GV->addAttribute("rodata-section", SA->getName());
2704 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2705 GV->addAttribute("relro-section", SA->getName());
2708 if (auto *F = dyn_cast<llvm::Function>(GO)) {
2709 if (D->hasAttr<RetainAttr>())
2710 addUsedGlobal(F);
2711 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2712 if (!D->getAttr<SectionAttr>())
2713 F->setSection(SA->getName());
2715 llvm::AttrBuilder Attrs(F->getContext());
2716 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2717 // We know that GetCPUAndFeaturesAttributes will always have the
2718 // newest set, since it has the newest possible FunctionDecl, so the
2719 // new ones should replace the old.
2720 llvm::AttributeMask RemoveAttrs;
2721 RemoveAttrs.addAttribute("target-cpu");
2722 RemoveAttrs.addAttribute("target-features");
2723 RemoveAttrs.addAttribute("tune-cpu");
2724 F->removeFnAttrs(RemoveAttrs);
2725 F->addFnAttrs(Attrs);
2729 if (const auto *CSA = D->getAttr<CodeSegAttr>())
2730 GO->setSection(CSA->getName());
2731 else if (const auto *SA = D->getAttr<SectionAttr>())
2732 GO->setSection(SA->getName());
2735 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2738 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2739 llvm::Function *F,
2740 const CGFunctionInfo &FI) {
2741 const Decl *D = GD.getDecl();
2742 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2743 SetLLVMFunctionAttributesForDefinition(D, F);
2745 F->setLinkage(llvm::Function::InternalLinkage);
2747 setNonAliasAttributes(GD, F);
2750 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2751 // Set linkage and visibility in case we never see a definition.
2752 LinkageInfo LV = ND->getLinkageAndVisibility();
2753 // Don't set internal linkage on declarations.
2754 // "extern_weak" is overloaded in LLVM; we probably should have
2755 // separate linkage types for this.
2756 if (isExternallyVisible(LV.getLinkage()) &&
2757 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2758 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2761 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2762 llvm::Function *F) {
2763 // Only if we are checking indirect calls.
2764 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2765 return;
2767 // Non-static class methods are handled via vtable or member function pointer
2768 // checks elsewhere.
2769 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2770 return;
2772 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2773 F->addTypeMetadata(0, MD);
2774 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2776 // Emit a hash-based bit set entry for cross-DSO calls.
2777 if (CodeGenOpts.SanitizeCfiCrossDso)
2778 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2779 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2782 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2783 llvm::LLVMContext &Ctx = F->getContext();
2784 llvm::MDBuilder MDB(Ctx);
2785 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2786 llvm::MDNode::get(
2787 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2790 static bool allowKCFIIdentifier(StringRef Name) {
2791 // KCFI type identifier constants are only necessary for external assembly
2792 // functions, which means it's safe to skip unusual names. Subset of
2793 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2794 return llvm::all_of(Name, [](const char &C) {
2795 return llvm::isAlnum(C) || C == '_' || C == '.';
2799 void CodeGenModule::finalizeKCFITypes() {
2800 llvm::Module &M = getModule();
2801 for (auto &F : M.functions()) {
2802 // Remove KCFI type metadata from non-address-taken local functions.
2803 bool AddressTaken = F.hasAddressTaken();
2804 if (!AddressTaken && F.hasLocalLinkage())
2805 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2807 // Generate a constant with the expected KCFI type identifier for all
2808 // address-taken function declarations to support annotating indirectly
2809 // called assembly functions.
2810 if (!AddressTaken || !F.isDeclaration())
2811 continue;
2813 const llvm::ConstantInt *Type;
2814 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2815 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2816 else
2817 continue;
2819 StringRef Name = F.getName();
2820 if (!allowKCFIIdentifier(Name))
2821 continue;
2823 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2824 Name + ", " + Twine(Type->getZExtValue()) + "\n")
2825 .str();
2826 M.appendModuleInlineAsm(Asm);
2830 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2831 bool IsIncompleteFunction,
2832 bool IsThunk) {
2834 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2835 // If this is an intrinsic function, set the function's attributes
2836 // to the intrinsic's attributes.
2837 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2838 return;
2841 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2843 if (!IsIncompleteFunction)
2844 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2845 IsThunk);
2847 // Add the Returned attribute for "this", except for iOS 5 and earlier
2848 // where substantial code, including the libstdc++ dylib, was compiled with
2849 // GCC and does not actually return "this".
2850 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2851 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2852 assert(!F->arg_empty() &&
2853 F->arg_begin()->getType()
2854 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2855 "unexpected this return");
2856 F->addParamAttr(0, llvm::Attribute::Returned);
2859 // Only a few attributes are set on declarations; these may later be
2860 // overridden by a definition.
2862 setLinkageForGV(F, FD);
2863 setGVProperties(F, FD);
2865 // Setup target-specific attributes.
2866 if (!IsIncompleteFunction && F->isDeclaration())
2867 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2869 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2870 F->setSection(CSA->getName());
2871 else if (const auto *SA = FD->getAttr<SectionAttr>())
2872 F->setSection(SA->getName());
2874 if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2875 if (EA->isError())
2876 F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2877 else if (EA->isWarning())
2878 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2881 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2882 if (FD->isInlineBuiltinDeclaration()) {
2883 const FunctionDecl *FDBody;
2884 bool HasBody = FD->hasBody(FDBody);
2885 (void)HasBody;
2886 assert(HasBody && "Inline builtin declarations should always have an "
2887 "available body!");
2888 if (shouldEmitFunction(FDBody))
2889 F->addFnAttr(llvm::Attribute::NoBuiltin);
2892 if (FD->isReplaceableGlobalAllocationFunction()) {
2893 // A replaceable global allocation function does not act like a builtin by
2894 // default, only if it is invoked by a new-expression or delete-expression.
2895 F->addFnAttr(llvm::Attribute::NoBuiltin);
2898 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2899 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2900 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2901 if (MD->isVirtual())
2902 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2904 // Don't emit entries for function declarations in the cross-DSO mode. This
2905 // is handled with better precision by the receiving DSO. But if jump tables
2906 // are non-canonical then we need type metadata in order to produce the local
2907 // jump table.
2908 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2909 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2910 CreateFunctionTypeMetadataForIcall(FD, F);
2912 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2913 setKCFIType(FD, F);
2915 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2916 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2918 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2919 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2921 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2922 // Annotate the callback behavior as metadata:
2923 // - The callback callee (as argument number).
2924 // - The callback payloads (as argument numbers).
2925 llvm::LLVMContext &Ctx = F->getContext();
2926 llvm::MDBuilder MDB(Ctx);
2928 // The payload indices are all but the first one in the encoding. The first
2929 // identifies the callback callee.
2930 int CalleeIdx = *CB->encoding_begin();
2931 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2932 F->addMetadata(llvm::LLVMContext::MD_callback,
2933 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2934 CalleeIdx, PayloadIndices,
2935 /* VarArgsArePassed */ false)}));
2939 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2940 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2941 "Only globals with definition can force usage.");
2942 LLVMUsed.emplace_back(GV);
2945 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2946 assert(!GV->isDeclaration() &&
2947 "Only globals with definition can force usage.");
2948 LLVMCompilerUsed.emplace_back(GV);
2951 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2952 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2953 "Only globals with definition can force usage.");
2954 if (getTriple().isOSBinFormatELF())
2955 LLVMCompilerUsed.emplace_back(GV);
2956 else
2957 LLVMUsed.emplace_back(GV);
2960 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2961 std::vector<llvm::WeakTrackingVH> &List) {
2962 // Don't create llvm.used if there is no need.
2963 if (List.empty())
2964 return;
2966 // Convert List to what ConstantArray needs.
2967 SmallVector<llvm::Constant*, 8> UsedArray;
2968 UsedArray.resize(List.size());
2969 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2970 UsedArray[i] =
2971 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2972 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2975 if (UsedArray.empty())
2976 return;
2977 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2979 auto *GV = new llvm::GlobalVariable(
2980 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2981 llvm::ConstantArray::get(ATy, UsedArray), Name);
2983 GV->setSection("llvm.metadata");
2986 void CodeGenModule::emitLLVMUsed() {
2987 emitUsed(*this, "llvm.used", LLVMUsed);
2988 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2991 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2992 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2993 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2996 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2997 llvm::SmallString<32> Opt;
2998 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2999 if (Opt.empty())
3000 return;
3001 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3002 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3005 void CodeGenModule::AddDependentLib(StringRef Lib) {
3006 auto &C = getLLVMContext();
3007 if (getTarget().getTriple().isOSBinFormatELF()) {
3008 ELFDependentLibraries.push_back(
3009 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
3010 return;
3013 llvm::SmallString<24> Opt;
3014 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
3015 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3016 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
3019 /// Add link options implied by the given module, including modules
3020 /// it depends on, using a postorder walk.
3021 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
3022 SmallVectorImpl<llvm::MDNode *> &Metadata,
3023 llvm::SmallPtrSet<Module *, 16> &Visited) {
3024 // Import this module's parent.
3025 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
3026 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
3029 // Import this module's dependencies.
3030 for (Module *Import : llvm::reverse(Mod->Imports)) {
3031 if (Visited.insert(Import).second)
3032 addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
3035 // Add linker options to link against the libraries/frameworks
3036 // described by this module.
3037 llvm::LLVMContext &Context = CGM.getLLVMContext();
3038 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
3040 // For modules that use export_as for linking, use that module
3041 // name instead.
3042 if (Mod->UseExportAsModuleLinkName)
3043 return;
3045 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
3046 // Link against a framework. Frameworks are currently Darwin only, so we
3047 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3048 if (LL.IsFramework) {
3049 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3050 llvm::MDString::get(Context, LL.Library)};
3052 Metadata.push_back(llvm::MDNode::get(Context, Args));
3053 continue;
3056 // Link against a library.
3057 if (IsELF) {
3058 llvm::Metadata *Args[2] = {
3059 llvm::MDString::get(Context, "lib"),
3060 llvm::MDString::get(Context, LL.Library),
3062 Metadata.push_back(llvm::MDNode::get(Context, Args));
3063 } else {
3064 llvm::SmallString<24> Opt;
3065 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
3066 auto *OptString = llvm::MDString::get(Context, Opt);
3067 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3072 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3073 assert(Primary->isNamedModuleUnit() &&
3074 "We should only emit module initializers for named modules.");
3076 // Emit the initializers in the order that sub-modules appear in the
3077 // source, first Global Module Fragments, if present.
3078 if (auto GMF = Primary->getGlobalModuleFragment()) {
3079 for (Decl *D : getContext().getModuleInitializers(GMF)) {
3080 if (isa<ImportDecl>(D))
3081 continue;
3082 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3083 EmitTopLevelDecl(D);
3086 // Second any associated with the module, itself.
3087 for (Decl *D : getContext().getModuleInitializers(Primary)) {
3088 // Skip import decls, the inits for those are called explicitly.
3089 if (isa<ImportDecl>(D))
3090 continue;
3091 EmitTopLevelDecl(D);
3093 // Third any associated with the Privat eMOdule Fragment, if present.
3094 if (auto PMF = Primary->getPrivateModuleFragment()) {
3095 for (Decl *D : getContext().getModuleInitializers(PMF)) {
3096 // Skip import decls, the inits for those are called explicitly.
3097 if (isa<ImportDecl>(D))
3098 continue;
3099 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3100 EmitTopLevelDecl(D);
3105 void CodeGenModule::EmitModuleLinkOptions() {
3106 // Collect the set of all of the modules we want to visit to emit link
3107 // options, which is essentially the imported modules and all of their
3108 // non-explicit child modules.
3109 llvm::SetVector<clang::Module *> LinkModules;
3110 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3111 SmallVector<clang::Module *, 16> Stack;
3113 // Seed the stack with imported modules.
3114 for (Module *M : ImportedModules) {
3115 // Do not add any link flags when an implementation TU of a module imports
3116 // a header of that same module.
3117 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3118 !getLangOpts().isCompilingModule())
3119 continue;
3120 if (Visited.insert(M).second)
3121 Stack.push_back(M);
3124 // Find all of the modules to import, making a little effort to prune
3125 // non-leaf modules.
3126 while (!Stack.empty()) {
3127 clang::Module *Mod = Stack.pop_back_val();
3129 bool AnyChildren = false;
3131 // Visit the submodules of this module.
3132 for (const auto &SM : Mod->submodules()) {
3133 // Skip explicit children; they need to be explicitly imported to be
3134 // linked against.
3135 if (SM->IsExplicit)
3136 continue;
3138 if (Visited.insert(SM).second) {
3139 Stack.push_back(SM);
3140 AnyChildren = true;
3144 // We didn't find any children, so add this module to the list of
3145 // modules to link against.
3146 if (!AnyChildren) {
3147 LinkModules.insert(Mod);
3151 // Add link options for all of the imported modules in reverse topological
3152 // order. We don't do anything to try to order import link flags with respect
3153 // to linker options inserted by things like #pragma comment().
3154 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3155 Visited.clear();
3156 for (Module *M : LinkModules)
3157 if (Visited.insert(M).second)
3158 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
3159 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3160 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3162 // Add the linker options metadata flag.
3163 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
3164 for (auto *MD : LinkerOptionsMetadata)
3165 NMD->addOperand(MD);
3168 void CodeGenModule::EmitDeferred() {
3169 // Emit deferred declare target declarations.
3170 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3171 getOpenMPRuntime().emitDeferredTargetDecls();
3173 // Emit code for any potentially referenced deferred decls. Since a
3174 // previously unused static decl may become used during the generation of code
3175 // for a static function, iterate until no changes are made.
3177 if (!DeferredVTables.empty()) {
3178 EmitDeferredVTables();
3180 // Emitting a vtable doesn't directly cause more vtables to
3181 // become deferred, although it can cause functions to be
3182 // emitted that then need those vtables.
3183 assert(DeferredVTables.empty());
3186 // Emit CUDA/HIP static device variables referenced by host code only.
3187 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3188 // needed for further handling.
3189 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3190 llvm::append_range(DeferredDeclsToEmit,
3191 getContext().CUDADeviceVarODRUsedByHost);
3193 // Stop if we're out of both deferred vtables and deferred declarations.
3194 if (DeferredDeclsToEmit.empty())
3195 return;
3197 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3198 // work, it will not interfere with this.
3199 std::vector<GlobalDecl> CurDeclsToEmit;
3200 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3202 for (GlobalDecl &D : CurDeclsToEmit) {
3203 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3204 // to get GlobalValue with exactly the type we need, not something that
3205 // might had been created for another decl with the same mangled name but
3206 // different type.
3207 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3208 GetAddrOfGlobal(D, ForDefinition));
3210 // In case of different address spaces, we may still get a cast, even with
3211 // IsForDefinition equal to true. Query mangled names table to get
3212 // GlobalValue.
3213 if (!GV)
3214 GV = GetGlobalValue(getMangledName(D));
3216 // Make sure GetGlobalValue returned non-null.
3217 assert(GV);
3219 // Check to see if we've already emitted this. This is necessary
3220 // for a couple of reasons: first, decls can end up in the
3221 // deferred-decls queue multiple times, and second, decls can end
3222 // up with definitions in unusual ways (e.g. by an extern inline
3223 // function acquiring a strong function redefinition). Just
3224 // ignore these cases.
3225 if (!GV->isDeclaration())
3226 continue;
3228 // If this is OpenMP, check if it is legal to emit this global normally.
3229 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3230 continue;
3232 // Otherwise, emit the definition and move on to the next one.
3233 EmitGlobalDefinition(D, GV);
3235 // If we found out that we need to emit more decls, do that recursively.
3236 // This has the advantage that the decls are emitted in a DFS and related
3237 // ones are close together, which is convenient for testing.
3238 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3239 EmitDeferred();
3240 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3245 void CodeGenModule::EmitVTablesOpportunistically() {
3246 // Try to emit external vtables as available_externally if they have emitted
3247 // all inlined virtual functions. It runs after EmitDeferred() and therefore
3248 // is not allowed to create new references to things that need to be emitted
3249 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3251 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3252 && "Only emit opportunistic vtables with optimizations");
3254 for (const CXXRecordDecl *RD : OpportunisticVTables) {
3255 assert(getVTables().isVTableExternal(RD) &&
3256 "This queue should only contain external vtables");
3257 if (getCXXABI().canSpeculativelyEmitVTable(RD))
3258 VTables.GenerateClassData(RD);
3260 OpportunisticVTables.clear();
3263 void CodeGenModule::EmitGlobalAnnotations() {
3264 for (const auto& [MangledName, VD] : DeferredAnnotations) {
3265 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3266 if (GV)
3267 AddGlobalAnnotations(VD, GV);
3269 DeferredAnnotations.clear();
3271 if (Annotations.empty())
3272 return;
3274 // Create a new global variable for the ConstantStruct in the Module.
3275 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3276 Annotations[0]->getType(), Annotations.size()), Annotations);
3277 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3278 llvm::GlobalValue::AppendingLinkage,
3279 Array, "llvm.global.annotations");
3280 gv->setSection(AnnotationSection);
3283 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3284 llvm::Constant *&AStr = AnnotationStrings[Str];
3285 if (AStr)
3286 return AStr;
3288 // Not found yet, create a new global.
3289 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3290 auto *gv = new llvm::GlobalVariable(
3291 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3292 ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3293 ConstGlobalsPtrTy->getAddressSpace());
3294 gv->setSection(AnnotationSection);
3295 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3296 AStr = gv;
3297 return gv;
3300 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
3301 SourceManager &SM = getContext().getSourceManager();
3302 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3303 if (PLoc.isValid())
3304 return EmitAnnotationString(PLoc.getFilename());
3305 return EmitAnnotationString(SM.getBufferName(Loc));
3308 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
3309 SourceManager &SM = getContext().getSourceManager();
3310 PresumedLoc PLoc = SM.getPresumedLoc(L);
3311 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3312 SM.getExpansionLineNumber(L);
3313 return llvm::ConstantInt::get(Int32Ty, LineNo);
3316 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3317 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3318 if (Exprs.empty())
3319 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3321 llvm::FoldingSetNodeID ID;
3322 for (Expr *E : Exprs) {
3323 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3325 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3326 if (Lookup)
3327 return Lookup;
3329 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3330 LLVMArgs.reserve(Exprs.size());
3331 ConstantEmitter ConstEmiter(*this);
3332 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3333 const auto *CE = cast<clang::ConstantExpr>(E);
3334 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3335 CE->getType());
3337 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3338 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3339 llvm::GlobalValue::PrivateLinkage, Struct,
3340 ".args");
3341 GV->setSection(AnnotationSection);
3342 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3344 Lookup = GV;
3345 return GV;
3348 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3349 const AnnotateAttr *AA,
3350 SourceLocation L) {
3351 // Get the globals for file name, annotation, and the line number.
3352 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3353 *UnitGV = EmitAnnotationUnit(L),
3354 *LineNoCst = EmitAnnotationLineNo(L),
3355 *Args = EmitAnnotationArgs(AA);
3357 llvm::Constant *GVInGlobalsAS = GV;
3358 if (GV->getAddressSpace() !=
3359 getDataLayout().getDefaultGlobalsAddressSpace()) {
3360 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3362 llvm::PointerType::get(
3363 GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3366 // Create the ConstantStruct for the global annotation.
3367 llvm::Constant *Fields[] = {
3368 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3370 return llvm::ConstantStruct::getAnon(Fields);
3373 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
3374 llvm::GlobalValue *GV) {
3375 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3376 // Get the struct elements for these annotations.
3377 for (const auto *I : D->specific_attrs<AnnotateAttr>())
3378 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3381 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
3382 SourceLocation Loc) const {
3383 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3384 // NoSanitize by function name.
3385 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3386 return true;
3387 // NoSanitize by location. Check "mainfile" prefix.
3388 auto &SM = Context.getSourceManager();
3389 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3390 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3391 return true;
3393 // Check "src" prefix.
3394 if (Loc.isValid())
3395 return NoSanitizeL.containsLocation(Kind, Loc);
3396 // If location is unknown, this may be a compiler-generated function. Assume
3397 // it's located in the main file.
3398 return NoSanitizeL.containsFile(Kind, MainFile.getName());
3401 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
3402 llvm::GlobalVariable *GV,
3403 SourceLocation Loc, QualType Ty,
3404 StringRef Category) const {
3405 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3406 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3407 return true;
3408 auto &SM = Context.getSourceManager();
3409 if (NoSanitizeL.containsMainFile(
3410 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3411 Category))
3412 return true;
3413 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3414 return true;
3416 // Check global type.
3417 if (!Ty.isNull()) {
3418 // Drill down the array types: if global variable of a fixed type is
3419 // not sanitized, we also don't instrument arrays of them.
3420 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3421 Ty = AT->getElementType();
3422 Ty = Ty.getCanonicalType().getUnqualifiedType();
3423 // Only record types (classes, structs etc.) are ignored.
3424 if (Ty->isRecordType()) {
3425 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3426 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3427 return true;
3430 return false;
3433 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3434 StringRef Category) const {
3435 const auto &XRayFilter = getContext().getXRayFilter();
3436 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3437 auto Attr = ImbueAttr::NONE;
3438 if (Loc.isValid())
3439 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3440 if (Attr == ImbueAttr::NONE)
3441 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3442 switch (Attr) {
3443 case ImbueAttr::NONE:
3444 return false;
3445 case ImbueAttr::ALWAYS:
3446 Fn->addFnAttr("function-instrument", "xray-always");
3447 break;
3448 case ImbueAttr::ALWAYS_ARG1:
3449 Fn->addFnAttr("function-instrument", "xray-always");
3450 Fn->addFnAttr("xray-log-args", "1");
3451 break;
3452 case ImbueAttr::NEVER:
3453 Fn->addFnAttr("function-instrument", "xray-never");
3454 break;
3456 return true;
3459 ProfileList::ExclusionType
3460 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3461 SourceLocation Loc) const {
3462 const auto &ProfileList = getContext().getProfileList();
3463 // If the profile list is empty, then instrument everything.
3464 if (ProfileList.isEmpty())
3465 return ProfileList::Allow;
3466 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3467 // First, check the function name.
3468 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3469 return *V;
3470 // Next, check the source location.
3471 if (Loc.isValid())
3472 if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3473 return *V;
3474 // If location is unknown, this may be a compiler-generated function. Assume
3475 // it's located in the main file.
3476 auto &SM = Context.getSourceManager();
3477 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3478 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3479 return *V;
3480 return ProfileList.getDefault(Kind);
3483 ProfileList::ExclusionType
3484 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3485 SourceLocation Loc) const {
3486 auto V = isFunctionBlockedByProfileList(Fn, Loc);
3487 if (V != ProfileList::Allow)
3488 return V;
3490 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3491 if (NumGroups > 1) {
3492 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3493 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3494 return ProfileList::Skip;
3496 return ProfileList::Allow;
3499 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3500 // Never defer when EmitAllDecls is specified.
3501 if (LangOpts.EmitAllDecls)
3502 return true;
3504 const auto *VD = dyn_cast<VarDecl>(Global);
3505 if (VD &&
3506 ((CodeGenOpts.KeepPersistentStorageVariables &&
3507 (VD->getStorageDuration() == SD_Static ||
3508 VD->getStorageDuration() == SD_Thread)) ||
3509 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3510 VD->getType().isConstQualified())))
3511 return true;
3513 return getContext().DeclMustBeEmitted(Global);
3516 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3517 // In OpenMP 5.0 variables and function may be marked as
3518 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3519 // that they must be emitted on the host/device. To be sure we need to have
3520 // seen a declare target with an explicit mentioning of the function, we know
3521 // we have if the level of the declare target attribute is -1. Note that we
3522 // check somewhere else if we should emit this at all.
3523 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3524 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3525 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3526 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3527 return false;
3530 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3531 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3532 // Implicit template instantiations may change linkage if they are later
3533 // explicitly instantiated, so they should not be emitted eagerly.
3534 return false;
3535 // Defer until all versions have been semantically checked.
3536 if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion())
3537 return false;
3539 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3540 if (Context.getInlineVariableDefinitionKind(VD) ==
3541 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3542 // A definition of an inline constexpr static data member may change
3543 // linkage later if it's redeclared outside the class.
3544 return false;
3545 if (CXX20ModuleInits && VD->getOwningModule() &&
3546 !VD->getOwningModule()->isModuleMapModule()) {
3547 // For CXX20, module-owned initializers need to be deferred, since it is
3548 // not known at this point if they will be run for the current module or
3549 // as part of the initializer for an imported one.
3550 return false;
3553 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3554 // codegen for global variables, because they may be marked as threadprivate.
3555 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3556 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3557 !Global->getType().isConstantStorage(getContext(), false, false) &&
3558 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3559 return false;
3561 return true;
3564 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3565 StringRef Name = getMangledName(GD);
3567 // The UUID descriptor should be pointer aligned.
3568 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3570 // Look for an existing global.
3571 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3572 return ConstantAddress(GV, GV->getValueType(), Alignment);
3574 ConstantEmitter Emitter(*this);
3575 llvm::Constant *Init;
3577 APValue &V = GD->getAsAPValue();
3578 if (!V.isAbsent()) {
3579 // If possible, emit the APValue version of the initializer. In particular,
3580 // this gets the type of the constant right.
3581 Init = Emitter.emitForInitializer(
3582 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3583 } else {
3584 // As a fallback, directly construct the constant.
3585 // FIXME: This may get padding wrong under esoteric struct layout rules.
3586 // MSVC appears to create a complete type 'struct __s_GUID' that it
3587 // presumably uses to represent these constants.
3588 MSGuidDecl::Parts Parts = GD->getParts();
3589 llvm::Constant *Fields[4] = {
3590 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3591 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3592 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3593 llvm::ConstantDataArray::getRaw(
3594 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3595 Int8Ty)};
3596 Init = llvm::ConstantStruct::getAnon(Fields);
3599 auto *GV = new llvm::GlobalVariable(
3600 getModule(), Init->getType(),
3601 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3602 if (supportsCOMDAT())
3603 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3604 setDSOLocal(GV);
3606 if (!V.isAbsent()) {
3607 Emitter.finalize(GV);
3608 return ConstantAddress(GV, GV->getValueType(), Alignment);
3611 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3612 return ConstantAddress(GV, Ty, Alignment);
3615 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3616 const UnnamedGlobalConstantDecl *GCD) {
3617 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3619 llvm::GlobalVariable **Entry = nullptr;
3620 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3621 if (*Entry)
3622 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3624 ConstantEmitter Emitter(*this);
3625 llvm::Constant *Init;
3627 const APValue &V = GCD->getValue();
3629 assert(!V.isAbsent());
3630 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3631 GCD->getType());
3633 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3634 /*isConstant=*/true,
3635 llvm::GlobalValue::PrivateLinkage, Init,
3636 ".constant");
3637 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3638 GV->setAlignment(Alignment.getAsAlign());
3640 Emitter.finalize(GV);
3642 *Entry = GV;
3643 return ConstantAddress(GV, GV->getValueType(), Alignment);
3646 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3647 const TemplateParamObjectDecl *TPO) {
3648 StringRef Name = getMangledName(TPO);
3649 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3651 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3652 return ConstantAddress(GV, GV->getValueType(), Alignment);
3654 ConstantEmitter Emitter(*this);
3655 llvm::Constant *Init = Emitter.emitForInitializer(
3656 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3658 if (!Init) {
3659 ErrorUnsupported(TPO, "template parameter object");
3660 return ConstantAddress::invalid();
3663 llvm::GlobalValue::LinkageTypes Linkage =
3664 isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
3665 ? llvm::GlobalValue::LinkOnceODRLinkage
3666 : llvm::GlobalValue::InternalLinkage;
3667 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3668 /*isConstant=*/true, Linkage, Init, Name);
3669 setGVProperties(GV, TPO);
3670 if (supportsCOMDAT())
3671 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3672 Emitter.finalize(GV);
3674 return ConstantAddress(GV, GV->getValueType(), Alignment);
3677 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3678 const AliasAttr *AA = VD->getAttr<AliasAttr>();
3679 assert(AA && "No alias?");
3681 CharUnits Alignment = getContext().getDeclAlign(VD);
3682 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3684 // See if there is already something with the target's name in the module.
3685 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3686 if (Entry)
3687 return ConstantAddress(Entry, DeclTy, Alignment);
3689 llvm::Constant *Aliasee;
3690 if (isa<llvm::FunctionType>(DeclTy))
3691 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3692 GlobalDecl(cast<FunctionDecl>(VD)),
3693 /*ForVTable=*/false);
3694 else
3695 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3696 nullptr);
3698 auto *F = cast<llvm::GlobalValue>(Aliasee);
3699 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3700 WeakRefReferences.insert(F);
3702 return ConstantAddress(Aliasee, DeclTy, Alignment);
3705 template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
3706 if (!D)
3707 return false;
3708 if (auto *A = D->getAttr<AttrT>())
3709 return A->isImplicit();
3710 return D->isImplicit();
3713 bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl *Global) const {
3714 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
3715 // We need to emit host-side 'shadows' for all global
3716 // device-side variables because the CUDA runtime needs their
3717 // size and host-side address in order to provide access to
3718 // their device-side incarnations.
3719 return !LangOpts.CUDAIsDevice || Global->hasAttr<CUDADeviceAttr>() ||
3720 Global->hasAttr<CUDAConstantAttr>() ||
3721 Global->hasAttr<CUDASharedAttr>() ||
3722 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3723 Global->getType()->isCUDADeviceBuiltinTextureType();
3726 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3727 const auto *Global = cast<ValueDecl>(GD.getDecl());
3729 // Weak references don't produce any output by themselves.
3730 if (Global->hasAttr<WeakRefAttr>())
3731 return;
3733 // If this is an alias definition (which otherwise looks like a declaration)
3734 // emit it now.
3735 if (Global->hasAttr<AliasAttr>())
3736 return EmitAliasDefinition(GD);
3738 // IFunc like an alias whose value is resolved at runtime by calling resolver.
3739 if (Global->hasAttr<IFuncAttr>())
3740 return emitIFuncDefinition(GD);
3742 // If this is a cpu_dispatch multiversion function, emit the resolver.
3743 if (Global->hasAttr<CPUDispatchAttr>())
3744 return emitCPUDispatchDefinition(GD);
3746 // If this is CUDA, be selective about which declarations we emit.
3747 // Non-constexpr non-lambda implicit host device functions are not emitted
3748 // unless they are used on device side.
3749 if (LangOpts.CUDA) {
3750 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3751 "Expected Variable or Function");
3752 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3753 if (!shouldEmitCUDAGlobalVar(VD))
3754 return;
3755 } else if (LangOpts.CUDAIsDevice) {
3756 const auto *FD = dyn_cast<FunctionDecl>(Global);
3757 if ((!Global->hasAttr<CUDADeviceAttr>() ||
3758 (LangOpts.OffloadImplicitHostDeviceTemplates &&
3759 hasImplicitAttr<CUDAHostAttr>(FD) &&
3760 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
3761 !isLambdaCallOperator(FD) &&
3762 !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3763 !Global->hasAttr<CUDAGlobalAttr>() &&
3764 !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
3765 !Global->hasAttr<CUDAHostAttr>()))
3766 return;
3767 // Device-only functions are the only things we skip.
3768 } else if (!Global->hasAttr<CUDAHostAttr>() &&
3769 Global->hasAttr<CUDADeviceAttr>())
3770 return;
3773 if (LangOpts.OpenMP) {
3774 // If this is OpenMP, check if it is legal to emit this global normally.
3775 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3776 return;
3777 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3778 if (MustBeEmitted(Global))
3779 EmitOMPDeclareReduction(DRD);
3780 return;
3782 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3783 if (MustBeEmitted(Global))
3784 EmitOMPDeclareMapper(DMD);
3785 return;
3789 // Ignore declarations, they will be emitted on their first use.
3790 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3791 // Update deferred annotations with the latest declaration if the function
3792 // function was already used or defined.
3793 if (FD->hasAttr<AnnotateAttr>()) {
3794 StringRef MangledName = getMangledName(GD);
3795 if (GetGlobalValue(MangledName))
3796 DeferredAnnotations[MangledName] = FD;
3799 // Forward declarations are emitted lazily on first use.
3800 if (!FD->doesThisDeclarationHaveABody()) {
3801 if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
3802 (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64()))
3803 return;
3805 StringRef MangledName = getMangledName(GD);
3807 // Compute the function info and LLVM type.
3808 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3809 llvm::Type *Ty = getTypes().GetFunctionType(FI);
3811 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3812 /*DontDefer=*/false);
3813 return;
3815 } else {
3816 const auto *VD = cast<VarDecl>(Global);
3817 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3818 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3819 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3820 if (LangOpts.OpenMP) {
3821 // Emit declaration of the must-be-emitted declare target variable.
3822 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3823 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3825 // If this variable has external storage and doesn't require special
3826 // link handling we defer to its canonical definition.
3827 if (VD->hasExternalStorage() &&
3828 Res != OMPDeclareTargetDeclAttr::MT_Link)
3829 return;
3831 bool UnifiedMemoryEnabled =
3832 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3833 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3834 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3835 !UnifiedMemoryEnabled) {
3836 (void)GetAddrOfGlobalVar(VD);
3837 } else {
3838 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3839 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3840 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3841 UnifiedMemoryEnabled)) &&
3842 "Link clause or to clause with unified memory expected.");
3843 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3846 return;
3849 // If this declaration may have caused an inline variable definition to
3850 // change linkage, make sure that it's emitted.
3851 if (Context.getInlineVariableDefinitionKind(VD) ==
3852 ASTContext::InlineVariableDefinitionKind::Strong)
3853 GetAddrOfGlobalVar(VD);
3854 return;
3858 // Defer code generation to first use when possible, e.g. if this is an inline
3859 // function. If the global must always be emitted, do it eagerly if possible
3860 // to benefit from cache locality.
3861 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3862 // Emit the definition if it can't be deferred.
3863 EmitGlobalDefinition(GD);
3864 addEmittedDeferredDecl(GD);
3865 return;
3868 // If we're deferring emission of a C++ variable with an
3869 // initializer, remember the order in which it appeared in the file.
3870 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3871 cast<VarDecl>(Global)->hasInit()) {
3872 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3873 CXXGlobalInits.push_back(nullptr);
3876 StringRef MangledName = getMangledName(GD);
3877 if (GetGlobalValue(MangledName) != nullptr) {
3878 // The value has already been used and should therefore be emitted.
3879 addDeferredDeclToEmit(GD);
3880 } else if (MustBeEmitted(Global)) {
3881 // The value must be emitted, but cannot be emitted eagerly.
3882 assert(!MayBeEmittedEagerly(Global));
3883 addDeferredDeclToEmit(GD);
3884 } else {
3885 // Otherwise, remember that we saw a deferred decl with this name. The
3886 // first use of the mangled name will cause it to move into
3887 // DeferredDeclsToEmit.
3888 DeferredDecls[MangledName] = GD;
3892 // Check if T is a class type with a destructor that's not dllimport.
3893 static bool HasNonDllImportDtor(QualType T) {
3894 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3895 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3896 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3897 return true;
3899 return false;
3902 namespace {
3903 struct FunctionIsDirectlyRecursive
3904 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3905 const StringRef Name;
3906 const Builtin::Context &BI;
3907 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3908 : Name(N), BI(C) {}
3910 bool VisitCallExpr(const CallExpr *E) {
3911 const FunctionDecl *FD = E->getDirectCallee();
3912 if (!FD)
3913 return false;
3914 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3915 if (Attr && Name == Attr->getLabel())
3916 return true;
3917 unsigned BuiltinID = FD->getBuiltinID();
3918 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3919 return false;
3920 StringRef BuiltinName = BI.getName(BuiltinID);
3921 if (BuiltinName.starts_with("__builtin_") &&
3922 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3923 return true;
3925 return false;
3928 bool VisitStmt(const Stmt *S) {
3929 for (const Stmt *Child : S->children())
3930 if (Child && this->Visit(Child))
3931 return true;
3932 return false;
3936 // Make sure we're not referencing non-imported vars or functions.
3937 struct DLLImportFunctionVisitor
3938 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3939 bool SafeToInline = true;
3941 bool shouldVisitImplicitCode() const { return true; }
3943 bool VisitVarDecl(VarDecl *VD) {
3944 if (VD->getTLSKind()) {
3945 // A thread-local variable cannot be imported.
3946 SafeToInline = false;
3947 return SafeToInline;
3950 // A variable definition might imply a destructor call.
3951 if (VD->isThisDeclarationADefinition())
3952 SafeToInline = !HasNonDllImportDtor(VD->getType());
3954 return SafeToInline;
3957 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3958 if (const auto *D = E->getTemporary()->getDestructor())
3959 SafeToInline = D->hasAttr<DLLImportAttr>();
3960 return SafeToInline;
3963 bool VisitDeclRefExpr(DeclRefExpr *E) {
3964 ValueDecl *VD = E->getDecl();
3965 if (isa<FunctionDecl>(VD))
3966 SafeToInline = VD->hasAttr<DLLImportAttr>();
3967 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3968 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3969 return SafeToInline;
3972 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3973 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3974 return SafeToInline;
3977 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3978 CXXMethodDecl *M = E->getMethodDecl();
3979 if (!M) {
3980 // Call through a pointer to member function. This is safe to inline.
3981 SafeToInline = true;
3982 } else {
3983 SafeToInline = M->hasAttr<DLLImportAttr>();
3985 return SafeToInline;
3988 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3989 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3990 return SafeToInline;
3993 bool VisitCXXNewExpr(CXXNewExpr *E) {
3994 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3995 return SafeToInline;
4000 // isTriviallyRecursive - Check if this function calls another
4001 // decl that, because of the asm attribute or the other decl being a builtin,
4002 // ends up pointing to itself.
4003 bool
4004 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
4005 StringRef Name;
4006 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4007 // asm labels are a special kind of mangling we have to support.
4008 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
4009 if (!Attr)
4010 return false;
4011 Name = Attr->getLabel();
4012 } else {
4013 Name = FD->getName();
4016 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4017 const Stmt *Body = FD->getBody();
4018 return Body ? Walker.Visit(Body) : false;
4021 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4022 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
4023 return true;
4025 const auto *F = cast<FunctionDecl>(GD.getDecl());
4026 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4027 return false;
4029 // We don't import function bodies from other named module units since that
4030 // behavior may break ABI compatibility of the current unit.
4031 if (const Module *M = F->getOwningModule();
4032 M && M->getTopLevelModule()->isNamedModule() &&
4033 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4034 // There are practices to mark template member function as always-inline
4035 // and mark the template as extern explicit instantiation but not give
4036 // the definition for member function. So we have to emit the function
4037 // from explicitly instantiation with always-inline.
4039 // See https://github.com/llvm/llvm-project/issues/86893 for details.
4041 // TODO: Maybe it is better to give it a warning if we call a non-inline
4042 // function from other module units which is marked as always-inline.
4043 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4044 return false;
4048 if (F->hasAttr<NoInlineAttr>())
4049 return false;
4051 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4052 // Check whether it would be safe to inline this dllimport function.
4053 DLLImportFunctionVisitor Visitor;
4054 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
4055 if (!Visitor.SafeToInline)
4056 return false;
4058 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4059 // Implicit destructor invocations aren't captured in the AST, so the
4060 // check above can't see them. Check for them manually here.
4061 for (const Decl *Member : Dtor->getParent()->decls())
4062 if (isa<FieldDecl>(Member))
4063 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
4064 return false;
4065 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4066 if (HasNonDllImportDtor(B.getType()))
4067 return false;
4071 // Inline builtins declaration must be emitted. They often are fortified
4072 // functions.
4073 if (F->isInlineBuiltinDeclaration())
4074 return true;
4076 // PR9614. Avoid cases where the source code is lying to us. An available
4077 // externally function should have an equivalent function somewhere else,
4078 // but a function that calls itself through asm label/`__builtin_` trickery is
4079 // clearly not equivalent to the real implementation.
4080 // This happens in glibc's btowc and in some configure checks.
4081 return !isTriviallyRecursive(F);
4084 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4085 return CodeGenOpts.OptimizationLevel > 0;
4088 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4089 llvm::GlobalValue *GV) {
4090 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4092 if (FD->isCPUSpecificMultiVersion()) {
4093 auto *Spec = FD->getAttr<CPUSpecificAttr>();
4094 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
4095 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4096 } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) {
4097 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4098 // AArch64 favors the default target version over the clone if any.
4099 if ((!TC->isDefaultVersion(I) || !getTarget().getTriple().isAArch64()) &&
4100 TC->isFirstOfVersion(I))
4101 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4102 // Ensure that the resolver function is also emitted.
4103 GetOrCreateMultiVersionResolver(GD);
4104 } else
4105 EmitGlobalFunctionDefinition(GD, GV);
4107 // Defer the resolver emission until we can reason whether the TU
4108 // contains a default target version implementation.
4109 if (FD->isTargetVersionMultiVersion())
4110 AddDeferredMultiVersionResolverToEmit(GD);
4113 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4114 const auto *D = cast<ValueDecl>(GD.getDecl());
4116 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
4117 Context.getSourceManager(),
4118 "Generating code for declaration");
4120 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4121 // At -O0, don't generate IR for functions with available_externally
4122 // linkage.
4123 if (!shouldEmitFunction(GD))
4124 return;
4126 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
4127 std::string Name;
4128 llvm::raw_string_ostream OS(Name);
4129 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
4130 /*Qualified=*/true);
4131 return Name;
4134 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4135 // Make sure to emit the definition(s) before we emit the thunks.
4136 // This is necessary for the generation of certain thunks.
4137 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4138 ABI->emitCXXStructor(GD);
4139 else if (FD->isMultiVersion())
4140 EmitMultiVersionFunctionDefinition(GD, GV);
4141 else
4142 EmitGlobalFunctionDefinition(GD, GV);
4144 if (Method->isVirtual())
4145 getVTables().EmitThunks(GD);
4147 return;
4150 if (FD->isMultiVersion())
4151 return EmitMultiVersionFunctionDefinition(GD, GV);
4152 return EmitGlobalFunctionDefinition(GD, GV);
4155 if (const auto *VD = dyn_cast<VarDecl>(D))
4156 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4158 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4161 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4162 llvm::Function *NewFn);
4164 static unsigned
4165 TargetMVPriority(const TargetInfo &TI,
4166 const CodeGenFunction::MultiVersionResolverOption &RO) {
4167 unsigned Priority = 0;
4168 unsigned NumFeatures = 0;
4169 for (StringRef Feat : RO.Conditions.Features) {
4170 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
4171 NumFeatures++;
4174 if (!RO.Conditions.Architecture.empty())
4175 Priority = std::max(
4176 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
4178 Priority += TI.multiVersionFeatureCost() * NumFeatures;
4180 return Priority;
4183 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4184 // TU can forward declare the function without causing problems. Particularly
4185 // in the cases of CPUDispatch, this causes issues. This also makes sure we
4186 // work with internal linkage functions, so that the same function name can be
4187 // used with internal linkage in multiple TUs.
4188 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
4189 GlobalDecl GD) {
4190 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4191 if (FD->getFormalLinkage() == Linkage::Internal)
4192 return llvm::GlobalValue::InternalLinkage;
4193 return llvm::GlobalValue::WeakODRLinkage;
4196 void CodeGenModule::emitMultiVersionFunctions() {
4197 std::vector<GlobalDecl> MVFuncsToEmit;
4198 MultiVersionFuncs.swap(MVFuncsToEmit);
4199 for (GlobalDecl GD : MVFuncsToEmit) {
4200 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4201 assert(FD && "Expected a FunctionDecl");
4203 auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
4204 GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx};
4205 StringRef MangledName = getMangledName(CurGD);
4206 llvm::Constant *Func = GetGlobalValue(MangledName);
4207 if (!Func) {
4208 if (Decl->isDefined()) {
4209 EmitGlobalFunctionDefinition(CurGD, nullptr);
4210 Func = GetGlobalValue(MangledName);
4211 } else {
4212 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(CurGD);
4213 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4214 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4215 /*DontDefer=*/false, ForDefinition);
4217 assert(Func && "This should have just been created");
4219 return cast<llvm::Function>(Func);
4222 // For AArch64, a resolver is only emitted if a function marked with
4223 // target_version("default")) or target_clones() is present and defined
4224 // in this TU. For other architectures it is always emitted.
4225 bool ShouldEmitResolver = !getTarget().getTriple().isAArch64();
4226 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4228 getContext().forEachMultiversionedFunctionVersion(
4229 FD, [&](const FunctionDecl *CurFD) {
4230 llvm::SmallVector<StringRef, 8> Feats;
4231 bool IsDefined = CurFD->doesThisDeclarationHaveABody();
4233 if (const auto *TA = CurFD->getAttr<TargetAttr>()) {
4234 TA->getAddedFeatures(Feats);
4235 llvm::Function *Func = createFunction(CurFD);
4236 Options.emplace_back(Func, TA->getArchitecture(), Feats);
4237 } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) {
4238 if (TVA->isDefaultVersion() && IsDefined)
4239 ShouldEmitResolver = true;
4240 TVA->getFeatures(Feats);
4241 llvm::Function *Func = createFunction(CurFD);
4242 Options.emplace_back(Func, /*Architecture*/ "", Feats);
4243 } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) {
4244 if (IsDefined)
4245 ShouldEmitResolver = true;
4246 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4247 if (!TC->isFirstOfVersion(I))
4248 continue;
4250 llvm::Function *Func = createFunction(CurFD, I);
4251 StringRef Architecture;
4252 Feats.clear();
4253 if (getTarget().getTriple().isAArch64())
4254 TC->getFeatures(Feats, I);
4255 else {
4256 StringRef Version = TC->getFeatureStr(I);
4257 if (Version.starts_with("arch="))
4258 Architecture = Version.drop_front(sizeof("arch=") - 1);
4259 else if (Version != "default")
4260 Feats.push_back(Version);
4262 Options.emplace_back(Func, Architecture, Feats);
4264 } else
4265 llvm_unreachable("unexpected MultiVersionKind");
4268 if (!ShouldEmitResolver)
4269 continue;
4271 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4272 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4273 ResolverConstant = IFunc->getResolver();
4274 if (FD->isTargetClonesMultiVersion() &&
4275 !getTarget().getTriple().isAArch64()) {
4276 std::string MangledName = getMangledNameImpl(
4277 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4278 if (!GetGlobalValue(MangledName + ".ifunc")) {
4279 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4280 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4281 // In prior versions of Clang, the mangling for ifuncs incorrectly
4282 // included an .ifunc suffix. This alias is generated for backward
4283 // compatibility. It is deprecated, and may be removed in the future.
4284 auto *Alias = llvm::GlobalAlias::create(
4285 DeclTy, 0, getMultiversionLinkage(*this, GD),
4286 MangledName + ".ifunc", IFunc, &getModule());
4287 SetCommonAttributes(FD, Alias);
4291 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4293 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4295 if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
4296 ResolverFunc->setComdat(
4297 getModule().getOrInsertComdat(ResolverFunc->getName()));
4299 const TargetInfo &TI = getTarget();
4300 llvm::stable_sort(
4301 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
4302 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4303 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
4305 CodeGenFunction CGF(*this);
4306 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4309 // Ensure that any additions to the deferred decls list caused by emitting a
4310 // variant are emitted. This can happen when the variant itself is inline and
4311 // calls a function without linkage.
4312 if (!MVFuncsToEmit.empty())
4313 EmitDeferred();
4315 // Ensure that any additions to the multiversion funcs list from either the
4316 // deferred decls or the multiversion functions themselves are emitted.
4317 if (!MultiVersionFuncs.empty())
4318 emitMultiVersionFunctions();
4321 static void replaceDeclarationWith(llvm::GlobalValue *Old,
4322 llvm::Constant *New) {
4323 assert(cast<llvm::Function>(Old)->isDeclaration() && "Not a declaration");
4324 New->takeName(Old);
4325 Old->replaceAllUsesWith(New);
4326 Old->eraseFromParent();
4329 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4330 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4331 assert(FD && "Not a FunctionDecl?");
4332 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4333 const auto *DD = FD->getAttr<CPUDispatchAttr>();
4334 assert(DD && "Not a cpu_dispatch Function?");
4336 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4337 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4339 StringRef ResolverName = getMangledName(GD);
4340 UpdateMultiVersionNames(GD, FD, ResolverName);
4342 llvm::Type *ResolverType;
4343 GlobalDecl ResolverGD;
4344 if (getTarget().supportsIFunc()) {
4345 ResolverType = llvm::FunctionType::get(
4346 llvm::PointerType::get(DeclTy,
4347 getTypes().getTargetAddressSpace(FD->getType())),
4348 false);
4350 else {
4351 ResolverType = DeclTy;
4352 ResolverGD = GD;
4355 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4356 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4357 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4358 if (supportsCOMDAT())
4359 ResolverFunc->setComdat(
4360 getModule().getOrInsertComdat(ResolverFunc->getName()));
4362 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4363 const TargetInfo &Target = getTarget();
4364 unsigned Index = 0;
4365 for (const IdentifierInfo *II : DD->cpus()) {
4366 // Get the name of the target function so we can look it up/create it.
4367 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4368 getCPUSpecificMangling(*this, II->getName());
4370 llvm::Constant *Func = GetGlobalValue(MangledName);
4372 if (!Func) {
4373 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4374 if (ExistingDecl.getDecl() &&
4375 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4376 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4377 Func = GetGlobalValue(MangledName);
4378 } else {
4379 if (!ExistingDecl.getDecl())
4380 ExistingDecl = GD.getWithMultiVersionIndex(Index);
4382 Func = GetOrCreateLLVMFunction(
4383 MangledName, DeclTy, ExistingDecl,
4384 /*ForVTable=*/false, /*DontDefer=*/true,
4385 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4389 llvm::SmallVector<StringRef, 32> Features;
4390 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4391 llvm::transform(Features, Features.begin(),
4392 [](StringRef Str) { return Str.substr(1); });
4393 llvm::erase_if(Features, [&Target](StringRef Feat) {
4394 return !Target.validateCpuSupports(Feat);
4396 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
4397 ++Index;
4400 llvm::stable_sort(
4401 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
4402 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4403 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4404 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4407 // If the list contains multiple 'default' versions, such as when it contains
4408 // 'pentium' and 'generic', don't emit the call to the generic one (since we
4409 // always run on at least a 'pentium'). We do this by deleting the 'least
4410 // advanced' (read, lowest mangling letter).
4411 while (Options.size() > 1 &&
4412 llvm::all_of(llvm::X86::getCpuSupportsMask(
4413 (Options.end() - 2)->Conditions.Features),
4414 [](auto X) { return X == 0; })) {
4415 StringRef LHSName = (Options.end() - 2)->Function->getName();
4416 StringRef RHSName = (Options.end() - 1)->Function->getName();
4417 if (LHSName.compare(RHSName) < 0)
4418 Options.erase(Options.end() - 2);
4419 else
4420 Options.erase(Options.end() - 1);
4423 CodeGenFunction CGF(*this);
4424 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4426 if (getTarget().supportsIFunc()) {
4427 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4428 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4430 // Fix up function declarations that were created for cpu_specific before
4431 // cpu_dispatch was known
4432 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4433 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
4434 &getModule());
4435 replaceDeclarationWith(IFunc, GI);
4436 IFunc = GI;
4439 std::string AliasName = getMangledNameImpl(
4440 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4441 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4442 if (!AliasFunc) {
4443 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
4444 &getModule());
4445 SetCommonAttributes(GD, GA);
4450 /// Adds a declaration to the list of multi version functions if not present.
4451 void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4452 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4453 assert(FD && "Not a FunctionDecl?");
4455 if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) {
4456 std::string MangledName =
4457 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4458 if (!DeferredResolversToEmit.insert(MangledName).second)
4459 return;
4461 MultiVersionFuncs.push_back(GD);
4464 /// If a dispatcher for the specified mangled name is not in the module, create
4465 /// and return it. The dispatcher is either an llvm Function with the specified
4466 /// type, or a global ifunc.
4467 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4468 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4469 assert(FD && "Not a FunctionDecl?");
4471 std::string MangledName =
4472 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4474 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4475 // a separate resolver).
4476 std::string ResolverName = MangledName;
4477 if (getTarget().supportsIFunc()) {
4478 switch (FD->getMultiVersionKind()) {
4479 case MultiVersionKind::None:
4480 llvm_unreachable("unexpected MultiVersionKind::None for resolver");
4481 case MultiVersionKind::Target:
4482 case MultiVersionKind::CPUSpecific:
4483 case MultiVersionKind::CPUDispatch:
4484 ResolverName += ".ifunc";
4485 break;
4486 case MultiVersionKind::TargetClones:
4487 case MultiVersionKind::TargetVersion:
4488 break;
4490 } else if (FD->isTargetMultiVersion()) {
4491 ResolverName += ".resolver";
4494 // If the resolver has already been created, just return it. This lookup may
4495 // yield a function declaration instead of a resolver on AArch64. That is
4496 // because we didn't know whether a resolver will be generated when we first
4497 // encountered a use of the symbol named after this resolver. Therefore,
4498 // targets which support ifuncs should not return here unless we actually
4499 // found an ifunc.
4500 llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName);
4501 if (ResolverGV &&
4502 (isa<llvm::GlobalIFunc>(ResolverGV) || !getTarget().supportsIFunc()))
4503 return ResolverGV;
4505 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4506 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4508 // The resolver needs to be created. For target and target_clones, defer
4509 // creation until the end of the TU.
4510 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
4511 AddDeferredMultiVersionResolverToEmit(GD);
4513 // For cpu_specific, don't create an ifunc yet because we don't know if the
4514 // cpu_dispatch will be emitted in this translation unit.
4515 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
4516 llvm::Type *ResolverType = llvm::FunctionType::get(
4517 llvm::PointerType::get(DeclTy,
4518 getTypes().getTargetAddressSpace(FD->getType())),
4519 false);
4520 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4521 MangledName + ".resolver", ResolverType, GlobalDecl{},
4522 /*ForVTable=*/false);
4523 llvm::GlobalIFunc *GIF =
4524 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4525 "", Resolver, &getModule());
4526 GIF->setName(ResolverName);
4527 SetCommonAttributes(FD, GIF);
4528 if (ResolverGV)
4529 replaceDeclarationWith(ResolverGV, GIF);
4530 return GIF;
4533 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4534 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
4535 assert(isa<llvm::GlobalValue>(Resolver) &&
4536 "Resolver should be created for the first time");
4537 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
4538 if (ResolverGV)
4539 replaceDeclarationWith(ResolverGV, Resolver);
4540 return Resolver;
4543 bool CodeGenModule::shouldDropDLLAttribute(const Decl *D,
4544 const llvm::GlobalValue *GV) const {
4545 auto SC = GV->getDLLStorageClass();
4546 if (SC == llvm::GlobalValue::DefaultStorageClass)
4547 return false;
4548 const Decl *MRD = D->getMostRecentDecl();
4549 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4550 !MRD->hasAttr<DLLImportAttr>()) ||
4551 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4552 !MRD->hasAttr<DLLExportAttr>())) &&
4553 !shouldMapVisibilityToDLLExport(cast<NamedDecl>(MRD)));
4556 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
4557 /// module, create and return an llvm Function with the specified type. If there
4558 /// is something in the module with the specified name, return it potentially
4559 /// bitcasted to the right type.
4561 /// If D is non-null, it specifies a decl that correspond to this. This is used
4562 /// to set the attributes on the function when it is first created.
4563 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4564 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
4565 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
4566 ForDefinition_t IsForDefinition) {
4567 const Decl *D = GD.getDecl();
4569 std::string NameWithoutMultiVersionMangling;
4570 // Any attempts to use a MultiVersion function should result in retrieving
4571 // the iFunc instead. Name Mangling will handle the rest of the changes.
4572 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4573 // For the device mark the function as one that should be emitted.
4574 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4575 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
4576 !DontDefer && !IsForDefinition) {
4577 if (const FunctionDecl *FDDef = FD->getDefinition()) {
4578 GlobalDecl GDDef;
4579 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4580 GDDef = GlobalDecl(CD, GD.getCtorType());
4581 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4582 GDDef = GlobalDecl(DD, GD.getDtorType());
4583 else
4584 GDDef = GlobalDecl(FDDef);
4585 EmitGlobal(GDDef);
4589 if (FD->isMultiVersion()) {
4590 UpdateMultiVersionNames(GD, FD, MangledName);
4591 if (!IsForDefinition) {
4592 // On AArch64 we do not immediatelly emit an ifunc resolver when a
4593 // function is used. Instead we defer the emission until we see a
4594 // default definition. In the meantime we just reference the symbol
4595 // without FMV mangling (it may or may not be replaced later).
4596 if (getTarget().getTriple().isAArch64()) {
4597 AddDeferredMultiVersionResolverToEmit(GD);
4598 NameWithoutMultiVersionMangling = getMangledNameImpl(
4599 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4600 } else
4601 return GetOrCreateMultiVersionResolver(GD);
4606 if (!NameWithoutMultiVersionMangling.empty())
4607 MangledName = NameWithoutMultiVersionMangling;
4609 // Lookup the entry, lazily creating it if necessary.
4610 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4611 if (Entry) {
4612 if (WeakRefReferences.erase(Entry)) {
4613 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4614 if (FD && !FD->hasAttr<WeakAttr>())
4615 Entry->setLinkage(llvm::Function::ExternalLinkage);
4618 // Handle dropped DLL attributes.
4619 if (D && shouldDropDLLAttribute(D, Entry)) {
4620 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4621 setDSOLocal(Entry);
4624 // If there are two attempts to define the same mangled name, issue an
4625 // error.
4626 if (IsForDefinition && !Entry->isDeclaration()) {
4627 GlobalDecl OtherGD;
4628 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4629 // to make sure that we issue an error only once.
4630 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4631 (GD.getCanonicalDecl().getDecl() !=
4632 OtherGD.getCanonicalDecl().getDecl()) &&
4633 DiagnosedConflictingDefinitions.insert(GD).second) {
4634 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4635 << MangledName;
4636 getDiags().Report(OtherGD.getDecl()->getLocation(),
4637 diag::note_previous_definition);
4641 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4642 (Entry->getValueType() == Ty)) {
4643 return Entry;
4646 // Make sure the result is of the correct type.
4647 // (If function is requested for a definition, we always need to create a new
4648 // function, not just return a bitcast.)
4649 if (!IsForDefinition)
4650 return Entry;
4653 // This function doesn't have a complete type (for example, the return
4654 // type is an incomplete struct). Use a fake type instead, and make
4655 // sure not to try to set attributes.
4656 bool IsIncompleteFunction = false;
4658 llvm::FunctionType *FTy;
4659 if (isa<llvm::FunctionType>(Ty)) {
4660 FTy = cast<llvm::FunctionType>(Ty);
4661 } else {
4662 FTy = llvm::FunctionType::get(VoidTy, false);
4663 IsIncompleteFunction = true;
4666 llvm::Function *F =
4667 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4668 Entry ? StringRef() : MangledName, &getModule());
4670 // Store the declaration associated with this function so it is potentially
4671 // updated by further declarations or definitions and emitted at the end.
4672 if (D && D->hasAttr<AnnotateAttr>())
4673 DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
4675 // If we already created a function with the same mangled name (but different
4676 // type) before, take its name and add it to the list of functions to be
4677 // replaced with F at the end of CodeGen.
4679 // This happens if there is a prototype for a function (e.g. "int f()") and
4680 // then a definition of a different type (e.g. "int f(int x)").
4681 if (Entry) {
4682 F->takeName(Entry);
4684 // This might be an implementation of a function without a prototype, in
4685 // which case, try to do special replacement of calls which match the new
4686 // prototype. The really key thing here is that we also potentially drop
4687 // arguments from the call site so as to make a direct call, which makes the
4688 // inliner happier and suppresses a number of optimizer warnings (!) about
4689 // dropping arguments.
4690 if (!Entry->use_empty()) {
4691 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
4692 Entry->removeDeadConstantUsers();
4695 addGlobalValReplacement(Entry, F);
4698 assert(F->getName() == MangledName && "name was uniqued!");
4699 if (D)
4700 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4701 if (ExtraAttrs.hasFnAttrs()) {
4702 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4703 F->addFnAttrs(B);
4706 if (!DontDefer) {
4707 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4708 // each other bottoming out with the base dtor. Therefore we emit non-base
4709 // dtors on usage, even if there is no dtor definition in the TU.
4710 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4711 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4712 GD.getDtorType()))
4713 addDeferredDeclToEmit(GD);
4715 // This is the first use or definition of a mangled name. If there is a
4716 // deferred decl with this name, remember that we need to emit it at the end
4717 // of the file.
4718 auto DDI = DeferredDecls.find(MangledName);
4719 if (DDI != DeferredDecls.end()) {
4720 // Move the potentially referenced deferred decl to the
4721 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4722 // don't need it anymore).
4723 addDeferredDeclToEmit(DDI->second);
4724 DeferredDecls.erase(DDI);
4726 // Otherwise, there are cases we have to worry about where we're
4727 // using a declaration for which we must emit a definition but where
4728 // we might not find a top-level definition:
4729 // - member functions defined inline in their classes
4730 // - friend functions defined inline in some class
4731 // - special member functions with implicit definitions
4732 // If we ever change our AST traversal to walk into class methods,
4733 // this will be unnecessary.
4735 // We also don't emit a definition for a function if it's going to be an
4736 // entry in a vtable, unless it's already marked as used.
4737 } else if (getLangOpts().CPlusPlus && D) {
4738 // Look for a declaration that's lexically in a record.
4739 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4740 FD = FD->getPreviousDecl()) {
4741 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4742 if (FD->doesThisDeclarationHaveABody()) {
4743 addDeferredDeclToEmit(GD.getWithDecl(FD));
4744 break;
4751 // Make sure the result is of the requested type.
4752 if (!IsIncompleteFunction) {
4753 assert(F->getFunctionType() == Ty);
4754 return F;
4757 return F;
4760 /// GetAddrOfFunction - Return the address of the given function. If Ty is
4761 /// non-null, then this function will use the specified type if it has to
4762 /// create it (this occurs when we see a definition of the function).
4763 llvm::Constant *
4764 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
4765 bool DontDefer,
4766 ForDefinition_t IsForDefinition) {
4767 // If there was no specific requested type, just convert it now.
4768 if (!Ty) {
4769 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4770 Ty = getTypes().ConvertType(FD->getType());
4773 // Devirtualized destructor calls may come through here instead of via
4774 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4775 // of the complete destructor when necessary.
4776 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4777 if (getTarget().getCXXABI().isMicrosoft() &&
4778 GD.getDtorType() == Dtor_Complete &&
4779 DD->getParent()->getNumVBases() == 0)
4780 GD = GlobalDecl(DD, Dtor_Base);
4783 StringRef MangledName = getMangledName(GD);
4784 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4785 /*IsThunk=*/false, llvm::AttributeList(),
4786 IsForDefinition);
4787 // Returns kernel handle for HIP kernel stub function.
4788 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4789 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4790 auto *Handle = getCUDARuntime().getKernelHandle(
4791 cast<llvm::Function>(F->stripPointerCasts()), GD);
4792 if (IsForDefinition)
4793 return F;
4794 return Handle;
4796 return F;
4799 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4800 llvm::GlobalValue *F =
4801 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4803 return llvm::NoCFIValue::get(F);
4806 static const FunctionDecl *
4807 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4808 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4809 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4811 IdentifierInfo &CII = C.Idents.get(Name);
4812 for (const auto *Result : DC->lookup(&CII))
4813 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4814 return FD;
4816 if (!C.getLangOpts().CPlusPlus)
4817 return nullptr;
4819 // Demangle the premangled name from getTerminateFn()
4820 IdentifierInfo &CXXII =
4821 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4822 ? C.Idents.get("terminate")
4823 : C.Idents.get(Name);
4825 for (const auto &N : {"__cxxabiv1", "std"}) {
4826 IdentifierInfo &NS = C.Idents.get(N);
4827 for (const auto *Result : DC->lookup(&NS)) {
4828 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4829 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4830 for (const auto *Result : LSD->lookup(&NS))
4831 if ((ND = dyn_cast<NamespaceDecl>(Result)))
4832 break;
4834 if (ND)
4835 for (const auto *Result : ND->lookup(&CXXII))
4836 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4837 return FD;
4841 return nullptr;
4844 /// CreateRuntimeFunction - Create a new runtime function with the specified
4845 /// type and name.
4846 llvm::FunctionCallee
4847 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4848 llvm::AttributeList ExtraAttrs, bool Local,
4849 bool AssumeConvergent) {
4850 if (AssumeConvergent) {
4851 ExtraAttrs =
4852 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4855 llvm::Constant *C =
4856 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4857 /*DontDefer=*/false, /*IsThunk=*/false,
4858 ExtraAttrs);
4860 if (auto *F = dyn_cast<llvm::Function>(C)) {
4861 if (F->empty()) {
4862 F->setCallingConv(getRuntimeCC());
4864 // In Windows Itanium environments, try to mark runtime functions
4865 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4866 // will link their standard library statically or dynamically. Marking
4867 // functions imported when they are not imported can cause linker errors
4868 // and warnings.
4869 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4870 !getCodeGenOpts().LTOVisibilityPublicStd) {
4871 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4872 if (!FD || FD->hasAttr<DLLImportAttr>()) {
4873 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4874 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4877 setDSOLocal(F);
4878 // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
4879 // of trying to approximate the attributes using the LLVM function
4880 // signature. This requires revising the API of CreateRuntimeFunction().
4881 markRegisterParameterAttributes(F);
4885 return {FTy, C};
4888 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4889 /// create and return an llvm GlobalVariable with the specified type and address
4890 /// space. If there is something in the module with the specified name, return
4891 /// it potentially bitcasted to the right type.
4893 /// If D is non-null, it specifies a decl that correspond to this. This is used
4894 /// to set the attributes on the global when it is first created.
4896 /// If IsForDefinition is true, it is guaranteed that an actual global with
4897 /// type Ty will be returned, not conversion of a variable with the same
4898 /// mangled name but some other type.
4899 llvm::Constant *
4900 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4901 LangAS AddrSpace, const VarDecl *D,
4902 ForDefinition_t IsForDefinition) {
4903 // Lookup the entry, lazily creating it if necessary.
4904 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4905 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4906 if (Entry) {
4907 if (WeakRefReferences.erase(Entry)) {
4908 if (D && !D->hasAttr<WeakAttr>())
4909 Entry->setLinkage(llvm::Function::ExternalLinkage);
4912 // Handle dropped DLL attributes.
4913 if (D && shouldDropDLLAttribute(D, Entry))
4914 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4916 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4917 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4919 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4920 return Entry;
4922 // If there are two attempts to define the same mangled name, issue an
4923 // error.
4924 if (IsForDefinition && !Entry->isDeclaration()) {
4925 GlobalDecl OtherGD;
4926 const VarDecl *OtherD;
4928 // Check that D is not yet in DiagnosedConflictingDefinitions is required
4929 // to make sure that we issue an error only once.
4930 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4931 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4932 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4933 OtherD->hasInit() &&
4934 DiagnosedConflictingDefinitions.insert(D).second) {
4935 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4936 << MangledName;
4937 getDiags().Report(OtherGD.getDecl()->getLocation(),
4938 diag::note_previous_definition);
4942 // Make sure the result is of the correct type.
4943 if (Entry->getType()->getAddressSpace() != TargetAS)
4944 return llvm::ConstantExpr::getAddrSpaceCast(
4945 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
4947 // (If global is requested for a definition, we always need to create a new
4948 // global, not just return a bitcast.)
4949 if (!IsForDefinition)
4950 return Entry;
4953 auto DAddrSpace = GetGlobalVarAddressSpace(D);
4955 auto *GV = new llvm::GlobalVariable(
4956 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4957 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4958 getContext().getTargetAddressSpace(DAddrSpace));
4960 // If we already created a global with the same mangled name (but different
4961 // type) before, take its name and remove it from its parent.
4962 if (Entry) {
4963 GV->takeName(Entry);
4965 if (!Entry->use_empty()) {
4966 Entry->replaceAllUsesWith(GV);
4969 Entry->eraseFromParent();
4972 // This is the first use or definition of a mangled name. If there is a
4973 // deferred decl with this name, remember that we need to emit it at the end
4974 // of the file.
4975 auto DDI = DeferredDecls.find(MangledName);
4976 if (DDI != DeferredDecls.end()) {
4977 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4978 // list, and remove it from DeferredDecls (since we don't need it anymore).
4979 addDeferredDeclToEmit(DDI->second);
4980 DeferredDecls.erase(DDI);
4983 // Handle things which are present even on external declarations.
4984 if (D) {
4985 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4986 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4988 // FIXME: This code is overly simple and should be merged with other global
4989 // handling.
4990 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
4992 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4994 setLinkageForGV(GV, D);
4996 if (D->getTLSKind()) {
4997 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4998 CXXThreadLocals.push_back(D);
4999 setTLSMode(GV, *D);
5002 setGVProperties(GV, D);
5004 // If required by the ABI, treat declarations of static data members with
5005 // inline initializers as definitions.
5006 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
5007 EmitGlobalVarDefinition(D);
5010 // Emit section information for extern variables.
5011 if (D->hasExternalStorage()) {
5012 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5013 GV->setSection(SA->getName());
5016 // Handle XCore specific ABI requirements.
5017 if (getTriple().getArch() == llvm::Triple::xcore &&
5018 D->getLanguageLinkage() == CLanguageLinkage &&
5019 D->getType().isConstant(Context) &&
5020 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
5021 GV->setSection(".cp.rodata");
5023 // Handle code model attribute
5024 if (const auto *CMA = D->getAttr<CodeModelAttr>())
5025 GV->setCodeModel(CMA->getModel());
5027 // Check if we a have a const declaration with an initializer, we may be
5028 // able to emit it as available_externally to expose it's value to the
5029 // optimizer.
5030 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5031 D->getType().isConstQualified() && !GV->hasInitializer() &&
5032 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
5033 const auto *Record =
5034 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
5035 bool HasMutableFields = Record && Record->hasMutableFields();
5036 if (!HasMutableFields) {
5037 const VarDecl *InitDecl;
5038 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5039 if (InitExpr) {
5040 ConstantEmitter emitter(*this);
5041 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
5042 if (Init) {
5043 auto *InitType = Init->getType();
5044 if (GV->getValueType() != InitType) {
5045 // The type of the initializer does not match the definition.
5046 // This happens when an initializer has a different type from
5047 // the type of the global (because of padding at the end of a
5048 // structure for instance).
5049 GV->setName(StringRef());
5050 // Make a new global with the correct type, this is now guaranteed
5051 // to work.
5052 auto *NewGV = cast<llvm::GlobalVariable>(
5053 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
5054 ->stripPointerCasts());
5056 // Erase the old global, since it is no longer used.
5057 GV->eraseFromParent();
5058 GV = NewGV;
5059 } else {
5060 GV->setInitializer(Init);
5061 GV->setConstant(true);
5062 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5064 emitter.finalize(GV);
5071 if (D &&
5072 D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
5073 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
5074 // External HIP managed variables needed to be recorded for transformation
5075 // in both device and host compilations.
5076 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
5077 D->hasExternalStorage())
5078 getCUDARuntime().handleVarRegistration(D, *GV);
5081 if (D)
5082 SanitizerMD->reportGlobal(GV, *D);
5084 LangAS ExpectedAS =
5085 D ? D->getType().getAddressSpace()
5086 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
5087 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5088 if (DAddrSpace != ExpectedAS) {
5089 return getTargetCodeGenInfo().performAddrSpaceCast(
5090 *this, GV, DAddrSpace, ExpectedAS,
5091 llvm::PointerType::get(getLLVMContext(), TargetAS));
5094 return GV;
5097 llvm::Constant *
5098 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
5099 const Decl *D = GD.getDecl();
5101 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
5102 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
5103 /*DontDefer=*/false, IsForDefinition);
5105 if (isa<CXXMethodDecl>(D)) {
5106 auto FInfo =
5107 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
5108 auto Ty = getTypes().GetFunctionType(*FInfo);
5109 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5110 IsForDefinition);
5113 if (isa<FunctionDecl>(D)) {
5114 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5115 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5116 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5117 IsForDefinition);
5120 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
5123 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
5124 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
5125 llvm::Align Alignment) {
5126 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
5127 llvm::GlobalVariable *OldGV = nullptr;
5129 if (GV) {
5130 // Check if the variable has the right type.
5131 if (GV->getValueType() == Ty)
5132 return GV;
5134 // Because C++ name mangling, the only way we can end up with an already
5135 // existing global with the same name is if it has been declared extern "C".
5136 assert(GV->isDeclaration() && "Declaration has wrong type!");
5137 OldGV = GV;
5140 // Create a new variable.
5141 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
5142 Linkage, nullptr, Name);
5144 if (OldGV) {
5145 // Replace occurrences of the old variable if needed.
5146 GV->takeName(OldGV);
5148 if (!OldGV->use_empty()) {
5149 OldGV->replaceAllUsesWith(GV);
5152 OldGV->eraseFromParent();
5155 if (supportsCOMDAT() && GV->isWeakForLinker() &&
5156 !GV->hasAvailableExternallyLinkage())
5157 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5159 GV->setAlignment(Alignment);
5161 return GV;
5164 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
5165 /// given global variable. If Ty is non-null and if the global doesn't exist,
5166 /// then it will be created with the specified type instead of whatever the
5167 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
5168 /// that an actual global with type Ty will be returned, not conversion of a
5169 /// variable with the same mangled name but some other type.
5170 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
5171 llvm::Type *Ty,
5172 ForDefinition_t IsForDefinition) {
5173 assert(D->hasGlobalStorage() && "Not a global variable");
5174 QualType ASTTy = D->getType();
5175 if (!Ty)
5176 Ty = getTypes().ConvertTypeForMem(ASTTy);
5178 StringRef MangledName = getMangledName(D);
5179 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
5180 IsForDefinition);
5183 /// CreateRuntimeVariable - Create a new runtime global variable with the
5184 /// specified type and name.
5185 llvm::Constant *
5186 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
5187 StringRef Name) {
5188 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
5189 : LangAS::Default;
5190 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
5191 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5192 return Ret;
5195 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
5196 assert(!D->getInit() && "Cannot emit definite definitions here!");
5198 StringRef MangledName = getMangledName(D);
5199 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
5201 // We already have a definition, not declaration, with the same mangled name.
5202 // Emitting of declaration is not required (and actually overwrites emitted
5203 // definition).
5204 if (GV && !GV->isDeclaration())
5205 return;
5207 // If we have not seen a reference to this variable yet, place it into the
5208 // deferred declarations table to be emitted if needed later.
5209 if (!MustBeEmitted(D) && !GV) {
5210 DeferredDecls[MangledName] = D;
5211 return;
5214 // The tentative definition is the only definition.
5215 EmitGlobalVarDefinition(D);
5218 void CodeGenModule::EmitExternalDeclaration(const DeclaratorDecl *D) {
5219 if (auto const *V = dyn_cast<const VarDecl>(D))
5220 EmitExternalVarDeclaration(V);
5221 if (auto const *FD = dyn_cast<const FunctionDecl>(D))
5222 EmitExternalFunctionDeclaration(FD);
5225 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
5226 return Context.toCharUnitsFromBits(
5227 getDataLayout().getTypeStoreSizeInBits(Ty));
5230 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
5231 if (LangOpts.OpenCL) {
5232 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
5233 assert(AS == LangAS::opencl_global ||
5234 AS == LangAS::opencl_global_device ||
5235 AS == LangAS::opencl_global_host ||
5236 AS == LangAS::opencl_constant ||
5237 AS == LangAS::opencl_local ||
5238 AS >= LangAS::FirstTargetAddressSpace);
5239 return AS;
5242 if (LangOpts.SYCLIsDevice &&
5243 (!D || D->getType().getAddressSpace() == LangAS::Default))
5244 return LangAS::sycl_global;
5246 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5247 if (D) {
5248 if (D->hasAttr<CUDAConstantAttr>())
5249 return LangAS::cuda_constant;
5250 if (D->hasAttr<CUDASharedAttr>())
5251 return LangAS::cuda_shared;
5252 if (D->hasAttr<CUDADeviceAttr>())
5253 return LangAS::cuda_device;
5254 if (D->getType().isConstQualified())
5255 return LangAS::cuda_constant;
5257 return LangAS::cuda_device;
5260 if (LangOpts.OpenMP) {
5261 LangAS AS;
5262 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5263 return AS;
5265 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
5268 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
5269 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
5270 if (LangOpts.OpenCL)
5271 return LangAS::opencl_constant;
5272 if (LangOpts.SYCLIsDevice)
5273 return LangAS::sycl_global;
5274 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
5275 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5276 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5277 // with OpVariable instructions with Generic storage class which is not
5278 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5279 // UniformConstant storage class is not viable as pointers to it may not be
5280 // casted to Generic pointers which are used to model HIP's "flat" pointers.
5281 return LangAS::cuda_device;
5282 if (auto AS = getTarget().getConstantAddressSpace())
5283 return *AS;
5284 return LangAS::Default;
5287 // In address space agnostic languages, string literals are in default address
5288 // space in AST. However, certain targets (e.g. amdgcn) request them to be
5289 // emitted in constant address space in LLVM IR. To be consistent with other
5290 // parts of AST, string literal global variables in constant address space
5291 // need to be casted to default address space before being put into address
5292 // map and referenced by other part of CodeGen.
5293 // In OpenCL, string literals are in constant address space in AST, therefore
5294 // they should not be casted to default address space.
5295 static llvm::Constant *
5296 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
5297 llvm::GlobalVariable *GV) {
5298 llvm::Constant *Cast = GV;
5299 if (!CGM.getLangOpts().OpenCL) {
5300 auto AS = CGM.GetGlobalConstantAddressSpace();
5301 if (AS != LangAS::Default)
5302 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
5303 CGM, GV, AS, LangAS::Default,
5304 llvm::PointerType::get(
5305 CGM.getLLVMContext(),
5306 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
5308 return Cast;
5311 template<typename SomeDecl>
5312 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
5313 llvm::GlobalValue *GV) {
5314 if (!getLangOpts().CPlusPlus)
5315 return;
5317 // Must have 'used' attribute, or else inline assembly can't rely on
5318 // the name existing.
5319 if (!D->template hasAttr<UsedAttr>())
5320 return;
5322 // Must have internal linkage and an ordinary name.
5323 if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal)
5324 return;
5326 // Must be in an extern "C" context. Entities declared directly within
5327 // a record are not extern "C" even if the record is in such a context.
5328 const SomeDecl *First = D->getFirstDecl();
5329 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
5330 return;
5332 // OK, this is an internal linkage entity inside an extern "C" linkage
5333 // specification. Make a note of that so we can give it the "expected"
5334 // mangled name if nothing else is using that name.
5335 std::pair<StaticExternCMap::iterator, bool> R =
5336 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5338 // If we have multiple internal linkage entities with the same name
5339 // in extern "C" regions, none of them gets that name.
5340 if (!R.second)
5341 R.first->second = nullptr;
5344 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
5345 if (!CGM.supportsCOMDAT())
5346 return false;
5348 if (D.hasAttr<SelectAnyAttr>())
5349 return true;
5351 GVALinkage Linkage;
5352 if (auto *VD = dyn_cast<VarDecl>(&D))
5353 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
5354 else
5355 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
5357 switch (Linkage) {
5358 case GVA_Internal:
5359 case GVA_AvailableExternally:
5360 case GVA_StrongExternal:
5361 return false;
5362 case GVA_DiscardableODR:
5363 case GVA_StrongODR:
5364 return true;
5366 llvm_unreachable("No such linkage");
5369 bool CodeGenModule::supportsCOMDAT() const {
5370 return getTriple().supportsCOMDAT();
5373 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
5374 llvm::GlobalObject &GO) {
5375 if (!shouldBeInCOMDAT(*this, D))
5376 return;
5377 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5380 const ABIInfo &CodeGenModule::getABIInfo() {
5381 return getTargetCodeGenInfo().getABIInfo();
5384 /// Pass IsTentative as true if you want to create a tentative definition.
5385 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
5386 bool IsTentative) {
5387 // OpenCL global variables of sampler type are translated to function calls,
5388 // therefore no need to be translated.
5389 QualType ASTTy = D->getType();
5390 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
5391 return;
5393 // If this is OpenMP device, check if it is legal to emit this global
5394 // normally.
5395 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5396 OpenMPRuntime->emitTargetGlobalVariable(D))
5397 return;
5399 llvm::TrackingVH<llvm::Constant> Init;
5400 bool NeedsGlobalCtor = false;
5401 // Whether the definition of the variable is available externally.
5402 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5403 // since this is the job for its original source.
5404 bool IsDefinitionAvailableExternally =
5405 getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5406 bool NeedsGlobalDtor =
5407 !IsDefinitionAvailableExternally &&
5408 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
5410 // It is helpless to emit the definition for an available_externally variable
5411 // which can't be marked as const.
5412 // We don't need to check if it needs global ctor or dtor. See the above
5413 // comment for ideas.
5414 if (IsDefinitionAvailableExternally &&
5415 (!D->hasConstantInitialization() ||
5416 // TODO: Update this when we have interface to check constexpr
5417 // destructor.
5418 D->needsDestruction(getContext()) ||
5419 !D->getType().isConstantStorage(getContext(), true, true)))
5420 return;
5422 const VarDecl *InitDecl;
5423 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5425 std::optional<ConstantEmitter> emitter;
5427 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5428 // as part of their declaration." Sema has already checked for
5429 // error cases, so we just need to set Init to UndefValue.
5430 bool IsCUDASharedVar =
5431 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5432 // Shadows of initialized device-side global variables are also left
5433 // undefined.
5434 // Managed Variables should be initialized on both host side and device side.
5435 bool IsCUDAShadowVar =
5436 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5437 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
5438 D->hasAttr<CUDASharedAttr>());
5439 bool IsCUDADeviceShadowVar =
5440 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5441 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5442 D->getType()->isCUDADeviceBuiltinTextureType());
5443 if (getLangOpts().CUDA &&
5444 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5445 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5446 else if (D->hasAttr<LoaderUninitializedAttr>())
5447 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5448 else if (!InitExpr) {
5449 // This is a tentative definition; tentative definitions are
5450 // implicitly initialized with { 0 }.
5452 // Note that tentative definitions are only emitted at the end of
5453 // a translation unit, so they should never have incomplete
5454 // type. In addition, EmitTentativeDefinition makes sure that we
5455 // never attempt to emit a tentative definition if a real one
5456 // exists. A use may still exists, however, so we still may need
5457 // to do a RAUW.
5458 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
5459 Init = EmitNullConstant(D->getType());
5460 } else {
5461 initializedGlobalDecl = GlobalDecl(D);
5462 emitter.emplace(*this);
5463 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5464 if (!Initializer) {
5465 QualType T = InitExpr->getType();
5466 if (D->getType()->isReferenceType())
5467 T = D->getType();
5469 if (getLangOpts().CPlusPlus) {
5470 if (InitDecl->hasFlexibleArrayInit(getContext()))
5471 ErrorUnsupported(D, "flexible array initializer");
5472 Init = EmitNullConstant(T);
5474 if (!IsDefinitionAvailableExternally)
5475 NeedsGlobalCtor = true;
5476 } else {
5477 ErrorUnsupported(D, "static initializer");
5478 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
5480 } else {
5481 Init = Initializer;
5482 // We don't need an initializer, so remove the entry for the delayed
5483 // initializer position (just in case this entry was delayed) if we
5484 // also don't need to register a destructor.
5485 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
5486 DelayedCXXInitPosition.erase(D);
5488 #ifndef NDEBUG
5489 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
5490 InitDecl->getFlexibleArrayInitChars(getContext());
5491 CharUnits CstSize = CharUnits::fromQuantity(
5492 getDataLayout().getTypeAllocSize(Init->getType()));
5493 assert(VarSize == CstSize && "Emitted constant has unexpected size");
5494 #endif
5498 llvm::Type* InitType = Init->getType();
5499 llvm::Constant *Entry =
5500 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
5502 // Strip off pointer casts if we got them.
5503 Entry = Entry->stripPointerCasts();
5505 // Entry is now either a Function or GlobalVariable.
5506 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5508 // We have a definition after a declaration with the wrong type.
5509 // We must make a new GlobalVariable* and update everything that used OldGV
5510 // (a declaration or tentative definition) with the new GlobalVariable*
5511 // (which will be a definition).
5513 // This happens if there is a prototype for a global (e.g.
5514 // "extern int x[];") and then a definition of a different type (e.g.
5515 // "int x[10];"). This also happens when an initializer has a different type
5516 // from the type of the global (this happens with unions).
5517 if (!GV || GV->getValueType() != InitType ||
5518 GV->getType()->getAddressSpace() !=
5519 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
5521 // Move the old entry aside so that we'll create a new one.
5522 Entry->setName(StringRef());
5524 // Make a new global with the correct type, this is now guaranteed to work.
5525 GV = cast<llvm::GlobalVariable>(
5526 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5527 ->stripPointerCasts());
5529 // Replace all uses of the old global with the new global
5530 llvm::Constant *NewPtrForOldDecl =
5531 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5532 Entry->getType());
5533 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5535 // Erase the old global, since it is no longer used.
5536 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5539 MaybeHandleStaticInExternC(D, GV);
5541 if (D->hasAttr<AnnotateAttr>())
5542 AddGlobalAnnotations(D, GV);
5544 // Set the llvm linkage type as appropriate.
5545 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
5547 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
5548 // the device. [...]"
5549 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
5550 // __device__, declares a variable that: [...]
5551 // Is accessible from all the threads within the grid and from the host
5552 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
5553 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
5554 if (LangOpts.CUDA) {
5555 if (LangOpts.CUDAIsDevice) {
5556 if (Linkage != llvm::GlobalValue::InternalLinkage &&
5557 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5558 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5559 D->getType()->isCUDADeviceBuiltinTextureType()))
5560 GV->setExternallyInitialized(true);
5561 } else {
5562 getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
5564 getCUDARuntime().handleVarRegistration(D, *GV);
5567 GV->setInitializer(Init);
5568 if (emitter)
5569 emitter->finalize(GV);
5571 // If it is safe to mark the global 'constant', do so now.
5572 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5573 D->getType().isConstantStorage(getContext(), true, true));
5575 // If it is in a read-only section, mark it 'constant'.
5576 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
5577 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
5578 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
5579 GV->setConstant(true);
5582 CharUnits AlignVal = getContext().getDeclAlign(D);
5583 // Check for alignment specifed in an 'omp allocate' directive.
5584 if (std::optional<CharUnits> AlignValFromAllocate =
5585 getOMPAllocateAlignment(D))
5586 AlignVal = *AlignValFromAllocate;
5587 GV->setAlignment(AlignVal.getAsAlign());
5589 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5590 // function is only defined alongside the variable, not also alongside
5591 // callers. Normally, all accesses to a thread_local go through the
5592 // thread-wrapper in order to ensure initialization has occurred, underlying
5593 // variable will never be used other than the thread-wrapper, so it can be
5594 // converted to internal linkage.
5596 // However, if the variable has the 'constinit' attribute, it _can_ be
5597 // referenced directly, without calling the thread-wrapper, so the linkage
5598 // must not be changed.
5600 // Additionally, if the variable isn't plain external linkage, e.g. if it's
5601 // weak or linkonce, the de-duplication semantics are important to preserve,
5602 // so we don't change the linkage.
5603 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
5604 Linkage == llvm::GlobalValue::ExternalLinkage &&
5605 Context.getTargetInfo().getTriple().isOSDarwin() &&
5606 !D->hasAttr<ConstInitAttr>())
5607 Linkage = llvm::GlobalValue::InternalLinkage;
5609 GV->setLinkage(Linkage);
5610 if (D->hasAttr<DLLImportAttr>())
5611 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5612 else if (D->hasAttr<DLLExportAttr>())
5613 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5614 else
5615 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5617 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
5618 // common vars aren't constant even if declared const.
5619 GV->setConstant(false);
5620 // Tentative definition of global variables may be initialized with
5621 // non-zero null pointers. In this case they should have weak linkage
5622 // since common linkage must have zero initializer and must not have
5623 // explicit section therefore cannot have non-zero initial value.
5624 if (!GV->getInitializer()->isNullValue())
5625 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5628 setNonAliasAttributes(D, GV);
5630 if (D->getTLSKind() && !GV->isThreadLocal()) {
5631 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5632 CXXThreadLocals.push_back(D);
5633 setTLSMode(GV, *D);
5636 maybeSetTrivialComdat(*D, *GV);
5638 // Emit the initializer function if necessary.
5639 if (NeedsGlobalCtor || NeedsGlobalDtor)
5640 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5642 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5644 // Emit global variable debug information.
5645 if (CGDebugInfo *DI = getModuleDebugInfo())
5646 if (getCodeGenOpts().hasReducedDebugInfo())
5647 DI->EmitGlobalVariable(GV, D);
5650 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5651 if (CGDebugInfo *DI = getModuleDebugInfo())
5652 if (getCodeGenOpts().hasReducedDebugInfo()) {
5653 QualType ASTTy = D->getType();
5654 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5655 llvm::Constant *GV =
5656 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5657 DI->EmitExternalVariable(
5658 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5662 void CodeGenModule::EmitExternalFunctionDeclaration(const FunctionDecl *FD) {
5663 if (CGDebugInfo *DI = getModuleDebugInfo())
5664 if (getCodeGenOpts().hasReducedDebugInfo()) {
5665 auto *Ty = getTypes().ConvertType(FD->getType());
5666 StringRef MangledName = getMangledName(FD);
5667 auto *Fn = dyn_cast<llvm::Function>(
5668 GetOrCreateLLVMFunction(MangledName, Ty, FD, /* ForVTable */ false));
5669 if (!Fn->getSubprogram())
5670 DI->EmitFunctionDecl(FD, FD->getLocation(), FD->getType(), Fn);
5674 static bool isVarDeclStrongDefinition(const ASTContext &Context,
5675 CodeGenModule &CGM, const VarDecl *D,
5676 bool NoCommon) {
5677 // Don't give variables common linkage if -fno-common was specified unless it
5678 // was overridden by a NoCommon attribute.
5679 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
5680 return true;
5682 // C11 6.9.2/2:
5683 // A declaration of an identifier for an object that has file scope without
5684 // an initializer, and without a storage-class specifier or with the
5685 // storage-class specifier static, constitutes a tentative definition.
5686 if (D->getInit() || D->hasExternalStorage())
5687 return true;
5689 // A variable cannot be both common and exist in a section.
5690 if (D->hasAttr<SectionAttr>())
5691 return true;
5693 // A variable cannot be both common and exist in a section.
5694 // We don't try to determine which is the right section in the front-end.
5695 // If no specialized section name is applicable, it will resort to default.
5696 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
5697 D->hasAttr<PragmaClangDataSectionAttr>() ||
5698 D->hasAttr<PragmaClangRelroSectionAttr>() ||
5699 D->hasAttr<PragmaClangRodataSectionAttr>())
5700 return true;
5702 // Thread local vars aren't considered common linkage.
5703 if (D->getTLSKind())
5704 return true;
5706 // Tentative definitions marked with WeakImportAttr are true definitions.
5707 if (D->hasAttr<WeakImportAttr>())
5708 return true;
5710 // A variable cannot be both common and exist in a comdat.
5711 if (shouldBeInCOMDAT(CGM, *D))
5712 return true;
5714 // Declarations with a required alignment do not have common linkage in MSVC
5715 // mode.
5716 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5717 if (D->hasAttr<AlignedAttr>())
5718 return true;
5719 QualType VarType = D->getType();
5720 if (Context.isAlignmentRequired(VarType))
5721 return true;
5723 if (const auto *RT = VarType->getAs<RecordType>()) {
5724 const RecordDecl *RD = RT->getDecl();
5725 for (const FieldDecl *FD : RD->fields()) {
5726 if (FD->isBitField())
5727 continue;
5728 if (FD->hasAttr<AlignedAttr>())
5729 return true;
5730 if (Context.isAlignmentRequired(FD->getType()))
5731 return true;
5736 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5737 // common symbols, so symbols with greater alignment requirements cannot be
5738 // common.
5739 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5740 // alignments for common symbols via the aligncomm directive, so this
5741 // restriction only applies to MSVC environments.
5742 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5743 Context.getTypeAlignIfKnown(D->getType()) >
5744 Context.toBits(CharUnits::fromQuantity(32)))
5745 return true;
5747 return false;
5750 llvm::GlobalValue::LinkageTypes
5751 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
5752 GVALinkage Linkage) {
5753 if (Linkage == GVA_Internal)
5754 return llvm::Function::InternalLinkage;
5756 if (D->hasAttr<WeakAttr>())
5757 return llvm::GlobalVariable::WeakAnyLinkage;
5759 if (const auto *FD = D->getAsFunction())
5760 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
5761 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5763 // We are guaranteed to have a strong definition somewhere else,
5764 // so we can use available_externally linkage.
5765 if (Linkage == GVA_AvailableExternally)
5766 return llvm::GlobalValue::AvailableExternallyLinkage;
5768 // Note that Apple's kernel linker doesn't support symbol
5769 // coalescing, so we need to avoid linkonce and weak linkages there.
5770 // Normally, this means we just map to internal, but for explicit
5771 // instantiations we'll map to external.
5773 // In C++, the compiler has to emit a definition in every translation unit
5774 // that references the function. We should use linkonce_odr because
5775 // a) if all references in this translation unit are optimized away, we
5776 // don't need to codegen it. b) if the function persists, it needs to be
5777 // merged with other definitions. c) C++ has the ODR, so we know the
5778 // definition is dependable.
5779 if (Linkage == GVA_DiscardableODR)
5780 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5781 : llvm::Function::InternalLinkage;
5783 // An explicit instantiation of a template has weak linkage, since
5784 // explicit instantiations can occur in multiple translation units
5785 // and must all be equivalent. However, we are not allowed to
5786 // throw away these explicit instantiations.
5788 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5789 // so say that CUDA templates are either external (for kernels) or internal.
5790 // This lets llvm perform aggressive inter-procedural optimizations. For
5791 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5792 // therefore we need to follow the normal linkage paradigm.
5793 if (Linkage == GVA_StrongODR) {
5794 if (getLangOpts().AppleKext)
5795 return llvm::Function::ExternalLinkage;
5796 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5797 !getLangOpts().GPURelocatableDeviceCode)
5798 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5799 : llvm::Function::InternalLinkage;
5800 return llvm::Function::WeakODRLinkage;
5803 // C++ doesn't have tentative definitions and thus cannot have common
5804 // linkage.
5805 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5806 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
5807 CodeGenOpts.NoCommon))
5808 return llvm::GlobalVariable::CommonLinkage;
5810 // selectany symbols are externally visible, so use weak instead of
5811 // linkonce. MSVC optimizes away references to const selectany globals, so
5812 // all definitions should be the same and ODR linkage should be used.
5813 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5814 if (D->hasAttr<SelectAnyAttr>())
5815 return llvm::GlobalVariable::WeakODRLinkage;
5817 // Otherwise, we have strong external linkage.
5818 assert(Linkage == GVA_StrongExternal);
5819 return llvm::GlobalVariable::ExternalLinkage;
5822 llvm::GlobalValue::LinkageTypes
5823 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
5824 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5825 return getLLVMLinkageForDeclarator(VD, Linkage);
5828 /// Replace the uses of a function that was declared with a non-proto type.
5829 /// We want to silently drop extra arguments from call sites
5830 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5831 llvm::Function *newFn) {
5832 // Fast path.
5833 if (old->use_empty())
5834 return;
5836 llvm::Type *newRetTy = newFn->getReturnType();
5837 SmallVector<llvm::Value *, 4> newArgs;
5839 SmallVector<llvm::CallBase *> callSitesToBeRemovedFromParent;
5841 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5842 ui != ue; ui++) {
5843 llvm::User *user = ui->getUser();
5845 // Recognize and replace uses of bitcasts. Most calls to
5846 // unprototyped functions will use bitcasts.
5847 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5848 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5849 replaceUsesOfNonProtoConstant(bitcast, newFn);
5850 continue;
5853 // Recognize calls to the function.
5854 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5855 if (!callSite)
5856 continue;
5857 if (!callSite->isCallee(&*ui))
5858 continue;
5860 // If the return types don't match exactly, then we can't
5861 // transform this call unless it's dead.
5862 if (callSite->getType() != newRetTy && !callSite->use_empty())
5863 continue;
5865 // Get the call site's attribute list.
5866 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5867 llvm::AttributeList oldAttrs = callSite->getAttributes();
5869 // If the function was passed too few arguments, don't transform.
5870 unsigned newNumArgs = newFn->arg_size();
5871 if (callSite->arg_size() < newNumArgs)
5872 continue;
5874 // If extra arguments were passed, we silently drop them.
5875 // If any of the types mismatch, we don't transform.
5876 unsigned argNo = 0;
5877 bool dontTransform = false;
5878 for (llvm::Argument &A : newFn->args()) {
5879 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5880 dontTransform = true;
5881 break;
5884 // Add any parameter attributes.
5885 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5886 argNo++;
5888 if (dontTransform)
5889 continue;
5891 // Okay, we can transform this. Create the new call instruction and copy
5892 // over the required information.
5893 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5895 // Copy over any operand bundles.
5896 SmallVector<llvm::OperandBundleDef, 1> newBundles;
5897 callSite->getOperandBundlesAsDefs(newBundles);
5899 llvm::CallBase *newCall;
5900 if (isa<llvm::CallInst>(callSite)) {
5901 newCall =
5902 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5903 } else {
5904 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5905 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5906 oldInvoke->getUnwindDest(), newArgs,
5907 newBundles, "", callSite);
5909 newArgs.clear(); // for the next iteration
5911 if (!newCall->getType()->isVoidTy())
5912 newCall->takeName(callSite);
5913 newCall->setAttributes(
5914 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5915 oldAttrs.getRetAttrs(), newArgAttrs));
5916 newCall->setCallingConv(callSite->getCallingConv());
5918 // Finally, remove the old call, replacing any uses with the new one.
5919 if (!callSite->use_empty())
5920 callSite->replaceAllUsesWith(newCall);
5922 // Copy debug location attached to CI.
5923 if (callSite->getDebugLoc())
5924 newCall->setDebugLoc(callSite->getDebugLoc());
5926 callSitesToBeRemovedFromParent.push_back(callSite);
5929 for (auto *callSite : callSitesToBeRemovedFromParent) {
5930 callSite->eraseFromParent();
5934 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5935 /// implement a function with no prototype, e.g. "int foo() {}". If there are
5936 /// existing call uses of the old function in the module, this adjusts them to
5937 /// call the new function directly.
5939 /// This is not just a cleanup: the always_inline pass requires direct calls to
5940 /// functions to be able to inline them. If there is a bitcast in the way, it
5941 /// won't inline them. Instcombine normally deletes these calls, but it isn't
5942 /// run at -O0.
5943 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5944 llvm::Function *NewFn) {
5945 // If we're redefining a global as a function, don't transform it.
5946 if (!isa<llvm::Function>(Old)) return;
5948 replaceUsesOfNonProtoConstant(Old, NewFn);
5951 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5952 auto DK = VD->isThisDeclarationADefinition();
5953 if ((DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) ||
5954 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
5955 return;
5957 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5958 // If we have a definition, this might be a deferred decl. If the
5959 // instantiation is explicit, make sure we emit it at the end.
5960 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5961 GetAddrOfGlobalVar(VD);
5963 EmitTopLevelDecl(VD);
5966 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5967 llvm::GlobalValue *GV) {
5968 const auto *D = cast<FunctionDecl>(GD.getDecl());
5970 // Compute the function info and LLVM type.
5971 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5972 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5974 // Get or create the prototype for the function.
5975 if (!GV || (GV->getValueType() != Ty))
5976 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5977 /*DontDefer=*/true,
5978 ForDefinition));
5980 // Already emitted.
5981 if (!GV->isDeclaration())
5982 return;
5984 // We need to set linkage and visibility on the function before
5985 // generating code for it because various parts of IR generation
5986 // want to propagate this information down (e.g. to local static
5987 // declarations).
5988 auto *Fn = cast<llvm::Function>(GV);
5989 setFunctionLinkage(GD, Fn);
5991 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5992 setGVProperties(Fn, GD);
5994 MaybeHandleStaticInExternC(D, Fn);
5996 maybeSetTrivialComdat(*D, *Fn);
5998 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
6000 setNonAliasAttributes(GD, Fn);
6001 SetLLVMFunctionAttributesForDefinition(D, Fn);
6003 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
6004 AddGlobalCtor(Fn, CA->getPriority());
6005 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
6006 AddGlobalDtor(Fn, DA->getPriority(), true);
6007 if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
6008 getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
6011 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6012 const auto *D = cast<ValueDecl>(GD.getDecl());
6013 const AliasAttr *AA = D->getAttr<AliasAttr>();
6014 assert(AA && "Not an alias?");
6016 StringRef MangledName = getMangledName(GD);
6018 if (AA->getAliasee() == MangledName) {
6019 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6020 return;
6023 // If there is a definition in the module, then it wins over the alias.
6024 // This is dubious, but allow it to be safe. Just ignore the alias.
6025 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6026 if (Entry && !Entry->isDeclaration())
6027 return;
6029 Aliases.push_back(GD);
6031 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6033 // Create a reference to the named value. This ensures that it is emitted
6034 // if a deferred decl.
6035 llvm::Constant *Aliasee;
6036 llvm::GlobalValue::LinkageTypes LT;
6037 if (isa<llvm::FunctionType>(DeclTy)) {
6038 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6039 /*ForVTable=*/false);
6040 LT = getFunctionLinkage(GD);
6041 } else {
6042 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
6043 /*D=*/nullptr);
6044 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
6045 LT = getLLVMLinkageVarDefinition(VD);
6046 else
6047 LT = getFunctionLinkage(GD);
6050 // Create the new alias itself, but don't set a name yet.
6051 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6052 auto *GA =
6053 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
6055 if (Entry) {
6056 if (GA->getAliasee() == Entry) {
6057 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6058 return;
6061 assert(Entry->isDeclaration());
6063 // If there is a declaration in the module, then we had an extern followed
6064 // by the alias, as in:
6065 // extern int test6();
6066 // ...
6067 // int test6() __attribute__((alias("test7")));
6069 // Remove it and replace uses of it with the alias.
6070 GA->takeName(Entry);
6072 Entry->replaceAllUsesWith(GA);
6073 Entry->eraseFromParent();
6074 } else {
6075 GA->setName(MangledName);
6078 // Set attributes which are particular to an alias; this is a
6079 // specialization of the attributes which may be set on a global
6080 // variable/function.
6081 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
6082 D->isWeakImported()) {
6083 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6086 if (const auto *VD = dyn_cast<VarDecl>(D))
6087 if (VD->getTLSKind())
6088 setTLSMode(GA, *VD);
6090 SetCommonAttributes(GD, GA);
6092 // Emit global alias debug information.
6093 if (isa<VarDecl>(D))
6094 if (CGDebugInfo *DI = getModuleDebugInfo())
6095 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6098 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6099 const auto *D = cast<ValueDecl>(GD.getDecl());
6100 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
6101 assert(IFA && "Not an ifunc?");
6103 StringRef MangledName = getMangledName(GD);
6105 if (IFA->getResolver() == MangledName) {
6106 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6107 return;
6110 // Report an error if some definition overrides ifunc.
6111 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6112 if (Entry && !Entry->isDeclaration()) {
6113 GlobalDecl OtherGD;
6114 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
6115 DiagnosedConflictingDefinitions.insert(GD).second) {
6116 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
6117 << MangledName;
6118 Diags.Report(OtherGD.getDecl()->getLocation(),
6119 diag::note_previous_definition);
6121 return;
6124 Aliases.push_back(GD);
6126 // The resolver might not be visited yet. Specify a dummy non-function type to
6127 // indicate IsIncompleteFunction. Either the type is ignored (if the resolver
6128 // was emitted) or the whole function will be replaced (if the resolver has
6129 // not been emitted).
6130 llvm::Constant *Resolver =
6131 GetOrCreateLLVMFunction(IFA->getResolver(), VoidTy, {},
6132 /*ForVTable=*/false);
6133 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6134 llvm::GlobalIFunc *GIF =
6135 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
6136 "", Resolver, &getModule());
6137 if (Entry) {
6138 if (GIF->getResolver() == Entry) {
6139 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6140 return;
6142 assert(Entry->isDeclaration());
6144 // If there is a declaration in the module, then we had an extern followed
6145 // by the ifunc, as in:
6146 // extern int test();
6147 // ...
6148 // int test() __attribute__((ifunc("resolver")));
6150 // Remove it and replace uses of it with the ifunc.
6151 GIF->takeName(Entry);
6153 Entry->replaceAllUsesWith(GIF);
6154 Entry->eraseFromParent();
6155 } else
6156 GIF->setName(MangledName);
6157 SetCommonAttributes(GD, GIF);
6160 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
6161 ArrayRef<llvm::Type*> Tys) {
6162 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
6163 Tys);
6166 static llvm::StringMapEntry<llvm::GlobalVariable *> &
6167 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
6168 const StringLiteral *Literal, bool TargetIsLSB,
6169 bool &IsUTF16, unsigned &StringLength) {
6170 StringRef String = Literal->getString();
6171 unsigned NumBytes = String.size();
6173 // Check for simple case.
6174 if (!Literal->containsNonAsciiOrNull()) {
6175 StringLength = NumBytes;
6176 return *Map.insert(std::make_pair(String, nullptr)).first;
6179 // Otherwise, convert the UTF8 literals into a string of shorts.
6180 IsUTF16 = true;
6182 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
6183 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6184 llvm::UTF16 *ToPtr = &ToBuf[0];
6186 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6187 ToPtr + NumBytes, llvm::strictConversion);
6189 // ConvertUTF8toUTF16 returns the length in ToPtr.
6190 StringLength = ToPtr - &ToBuf[0];
6192 // Add an explicit null.
6193 *ToPtr = 0;
6194 return *Map.insert(std::make_pair(
6195 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
6196 (StringLength + 1) * 2),
6197 nullptr)).first;
6200 ConstantAddress
6201 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
6202 unsigned StringLength = 0;
6203 bool isUTF16 = false;
6204 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6205 GetConstantCFStringEntry(CFConstantStringMap, Literal,
6206 getDataLayout().isLittleEndian(), isUTF16,
6207 StringLength);
6209 if (auto *C = Entry.second)
6210 return ConstantAddress(
6211 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
6213 const ASTContext &Context = getContext();
6214 const llvm::Triple &Triple = getTriple();
6216 const auto CFRuntime = getLangOpts().CFRuntime;
6217 const bool IsSwiftABI =
6218 static_cast<unsigned>(CFRuntime) >=
6219 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
6220 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
6222 // If we don't already have it, get __CFConstantStringClassReference.
6223 if (!CFConstantStringClassRef) {
6224 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
6225 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
6226 Ty = llvm::ArrayType::get(Ty, 0);
6228 switch (CFRuntime) {
6229 default: break;
6230 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
6231 case LangOptions::CoreFoundationABI::Swift5_0:
6232 CFConstantStringClassName =
6233 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
6234 : "$s10Foundation19_NSCFConstantStringCN";
6235 Ty = IntPtrTy;
6236 break;
6237 case LangOptions::CoreFoundationABI::Swift4_2:
6238 CFConstantStringClassName =
6239 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
6240 : "$S10Foundation19_NSCFConstantStringCN";
6241 Ty = IntPtrTy;
6242 break;
6243 case LangOptions::CoreFoundationABI::Swift4_1:
6244 CFConstantStringClassName =
6245 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
6246 : "__T010Foundation19_NSCFConstantStringCN";
6247 Ty = IntPtrTy;
6248 break;
6251 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
6253 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6254 llvm::GlobalValue *GV = nullptr;
6256 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
6257 IdentifierInfo &II = Context.Idents.get(GV->getName());
6258 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
6259 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6261 const VarDecl *VD = nullptr;
6262 for (const auto *Result : DC->lookup(&II))
6263 if ((VD = dyn_cast<VarDecl>(Result)))
6264 break;
6266 if (Triple.isOSBinFormatELF()) {
6267 if (!VD)
6268 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6269 } else {
6270 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6271 if (!VD || !VD->hasAttr<DLLExportAttr>())
6272 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6273 else
6274 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6277 setDSOLocal(GV);
6281 // Decay array -> ptr
6282 CFConstantStringClassRef =
6283 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) : C;
6286 QualType CFTy = Context.getCFConstantStringType();
6288 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
6290 ConstantInitBuilder Builder(*this);
6291 auto Fields = Builder.beginStruct(STy);
6293 // Class pointer.
6294 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6296 // Flags.
6297 if (IsSwiftABI) {
6298 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6299 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6300 } else {
6301 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6304 // String pointer.
6305 llvm::Constant *C = nullptr;
6306 if (isUTF16) {
6307 auto Arr = llvm::ArrayRef(
6308 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
6309 Entry.first().size() / 2);
6310 C = llvm::ConstantDataArray::get(VMContext, Arr);
6311 } else {
6312 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6315 // Note: -fwritable-strings doesn't make the backing store strings of
6316 // CFStrings writable.
6317 auto *GV =
6318 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
6319 llvm::GlobalValue::PrivateLinkage, C, ".str");
6320 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6321 // Don't enforce the target's minimum global alignment, since the only use
6322 // of the string is via this class initializer.
6323 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6324 : Context.getTypeAlignInChars(Context.CharTy);
6325 GV->setAlignment(Align.getAsAlign());
6327 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
6328 // Without it LLVM can merge the string with a non unnamed_addr one during
6329 // LTO. Doing that changes the section it ends in, which surprises ld64.
6330 if (Triple.isOSBinFormatMachO())
6331 GV->setSection(isUTF16 ? "__TEXT,__ustring"
6332 : "__TEXT,__cstring,cstring_literals");
6333 // Make sure the literal ends up in .rodata to allow for safe ICF and for
6334 // the static linker to adjust permissions to read-only later on.
6335 else if (Triple.isOSBinFormatELF())
6336 GV->setSection(".rodata");
6338 // String.
6339 Fields.add(GV);
6341 // String length.
6342 llvm::IntegerType *LengthTy =
6343 llvm::IntegerType::get(getModule().getContext(),
6344 Context.getTargetInfo().getLongWidth());
6345 if (IsSwiftABI) {
6346 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6347 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6348 LengthTy = Int32Ty;
6349 else
6350 LengthTy = IntPtrTy;
6352 Fields.addInt(LengthTy, StringLength);
6354 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6355 // properly aligned on 32-bit platforms.
6356 CharUnits Alignment =
6357 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
6359 // The struct.
6360 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
6361 /*isConstant=*/false,
6362 llvm::GlobalVariable::PrivateLinkage);
6363 GV->addAttribute("objc_arc_inert");
6364 switch (Triple.getObjectFormat()) {
6365 case llvm::Triple::UnknownObjectFormat:
6366 llvm_unreachable("unknown file format");
6367 case llvm::Triple::DXContainer:
6368 case llvm::Triple::GOFF:
6369 case llvm::Triple::SPIRV:
6370 case llvm::Triple::XCOFF:
6371 llvm_unreachable("unimplemented");
6372 case llvm::Triple::COFF:
6373 case llvm::Triple::ELF:
6374 case llvm::Triple::Wasm:
6375 GV->setSection("cfstring");
6376 break;
6377 case llvm::Triple::MachO:
6378 GV->setSection("__DATA,__cfstring");
6379 break;
6381 Entry.second = GV;
6383 return ConstantAddress(GV, GV->getValueType(), Alignment);
6386 bool CodeGenModule::getExpressionLocationsEnabled() const {
6387 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6390 QualType CodeGenModule::getObjCFastEnumerationStateType() {
6391 if (ObjCFastEnumerationStateType.isNull()) {
6392 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
6393 D->startDefinition();
6395 QualType FieldTypes[] = {
6396 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
6397 Context.getPointerType(Context.UnsignedLongTy),
6398 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6399 nullptr, ArraySizeModifier::Normal, 0)};
6401 for (size_t i = 0; i < 4; ++i) {
6402 FieldDecl *Field = FieldDecl::Create(Context,
6404 SourceLocation(),
6405 SourceLocation(), nullptr,
6406 FieldTypes[i], /*TInfo=*/nullptr,
6407 /*BitWidth=*/nullptr,
6408 /*Mutable=*/false,
6409 ICIS_NoInit);
6410 Field->setAccess(AS_public);
6411 D->addDecl(Field);
6414 D->completeDefinition();
6415 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
6418 return ObjCFastEnumerationStateType;
6421 llvm::Constant *
6422 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
6423 assert(!E->getType()->isPointerType() && "Strings are always arrays");
6425 // Don't emit it as the address of the string, emit the string data itself
6426 // as an inline array.
6427 if (E->getCharByteWidth() == 1) {
6428 SmallString<64> Str(E->getString());
6430 // Resize the string to the right size, which is indicated by its type.
6431 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
6432 assert(CAT && "String literal not of constant array type!");
6433 Str.resize(CAT->getZExtSize());
6434 return llvm::ConstantDataArray::getString(VMContext, Str, false);
6437 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
6438 llvm::Type *ElemTy = AType->getElementType();
6439 unsigned NumElements = AType->getNumElements();
6441 // Wide strings have either 2-byte or 4-byte elements.
6442 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6443 SmallVector<uint16_t, 32> Elements;
6444 Elements.reserve(NumElements);
6446 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6447 Elements.push_back(E->getCodeUnit(i));
6448 Elements.resize(NumElements);
6449 return llvm::ConstantDataArray::get(VMContext, Elements);
6452 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6453 SmallVector<uint32_t, 32> Elements;
6454 Elements.reserve(NumElements);
6456 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6457 Elements.push_back(E->getCodeUnit(i));
6458 Elements.resize(NumElements);
6459 return llvm::ConstantDataArray::get(VMContext, Elements);
6462 static llvm::GlobalVariable *
6463 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
6464 CodeGenModule &CGM, StringRef GlobalName,
6465 CharUnits Alignment) {
6466 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6467 CGM.GetGlobalConstantAddressSpace());
6469 llvm::Module &M = CGM.getModule();
6470 // Create a global variable for this string
6471 auto *GV = new llvm::GlobalVariable(
6472 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
6473 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6474 GV->setAlignment(Alignment.getAsAlign());
6475 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6476 if (GV->isWeakForLinker()) {
6477 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
6478 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6480 CGM.setDSOLocal(GV);
6482 return GV;
6485 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
6486 /// constant array for the given string literal.
6487 ConstantAddress
6488 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
6489 StringRef Name) {
6490 CharUnits Alignment =
6491 getContext().getAlignOfGlobalVarInChars(S->getType(), /*VD=*/nullptr);
6493 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
6494 llvm::GlobalVariable **Entry = nullptr;
6495 if (!LangOpts.WritableStrings) {
6496 Entry = &ConstantStringMap[C];
6497 if (auto GV = *Entry) {
6498 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6499 GV->setAlignment(Alignment.getAsAlign());
6500 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6501 GV->getValueType(), Alignment);
6505 SmallString<256> MangledNameBuffer;
6506 StringRef GlobalVariableName;
6507 llvm::GlobalValue::LinkageTypes LT;
6509 // Mangle the string literal if that's how the ABI merges duplicate strings.
6510 // Don't do it if they are writable, since we don't want writes in one TU to
6511 // affect strings in another.
6512 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6513 !LangOpts.WritableStrings) {
6514 llvm::raw_svector_ostream Out(MangledNameBuffer);
6515 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
6516 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6517 GlobalVariableName = MangledNameBuffer;
6518 } else {
6519 LT = llvm::GlobalValue::PrivateLinkage;
6520 GlobalVariableName = Name;
6523 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
6525 CGDebugInfo *DI = getModuleDebugInfo();
6526 if (DI && getCodeGenOpts().hasReducedDebugInfo())
6527 DI->AddStringLiteralDebugInfo(GV, S);
6529 if (Entry)
6530 *Entry = GV;
6532 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
6534 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6535 GV->getValueType(), Alignment);
6538 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
6539 /// array for the given ObjCEncodeExpr node.
6540 ConstantAddress
6541 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
6542 std::string Str;
6543 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
6545 return GetAddrOfConstantCString(Str);
6548 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
6549 /// the literal and a terminating '\0' character.
6550 /// The result has pointer to array type.
6551 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
6552 const std::string &Str, const char *GlobalName) {
6553 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6554 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(
6555 getContext().CharTy, /*VD=*/nullptr);
6557 llvm::Constant *C =
6558 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
6560 // Don't share any string literals if strings aren't constant.
6561 llvm::GlobalVariable **Entry = nullptr;
6562 if (!LangOpts.WritableStrings) {
6563 Entry = &ConstantStringMap[C];
6564 if (auto GV = *Entry) {
6565 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6566 GV->setAlignment(Alignment.getAsAlign());
6567 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6568 GV->getValueType(), Alignment);
6572 // Get the default prefix if a name wasn't specified.
6573 if (!GlobalName)
6574 GlobalName = ".str";
6575 // Create a global variable for this.
6576 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
6577 GlobalName, Alignment);
6578 if (Entry)
6579 *Entry = GV;
6581 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6582 GV->getValueType(), Alignment);
6585 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6586 const MaterializeTemporaryExpr *E, const Expr *Init) {
6587 assert((E->getStorageDuration() == SD_Static ||
6588 E->getStorageDuration() == SD_Thread) && "not a global temporary");
6589 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6591 // If we're not materializing a subobject of the temporary, keep the
6592 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6593 QualType MaterializedType = Init->getType();
6594 if (Init == E->getSubExpr())
6595 MaterializedType = E->getType();
6597 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6599 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6600 if (!InsertResult.second) {
6601 // We've seen this before: either we already created it or we're in the
6602 // process of doing so.
6603 if (!InsertResult.first->second) {
6604 // We recursively re-entered this function, probably during emission of
6605 // the initializer. Create a placeholder. We'll clean this up in the
6606 // outer call, at the end of this function.
6607 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6608 InsertResult.first->second = new llvm::GlobalVariable(
6609 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6610 nullptr);
6612 return ConstantAddress(InsertResult.first->second,
6613 llvm::cast<llvm::GlobalVariable>(
6614 InsertResult.first->second->stripPointerCasts())
6615 ->getValueType(),
6616 Align);
6619 // FIXME: If an externally-visible declaration extends multiple temporaries,
6620 // we need to give each temporary the same name in every translation unit (and
6621 // we also need to make the temporaries externally-visible).
6622 SmallString<256> Name;
6623 llvm::raw_svector_ostream Out(Name);
6624 getCXXABI().getMangleContext().mangleReferenceTemporary(
6625 VD, E->getManglingNumber(), Out);
6627 APValue *Value = nullptr;
6628 if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
6629 // If the initializer of the extending declaration is a constant
6630 // initializer, we should have a cached constant initializer for this
6631 // temporary. Note that this might have a different value from the value
6632 // computed by evaluating the initializer if the surrounding constant
6633 // expression modifies the temporary.
6634 Value = E->getOrCreateValue(false);
6637 // Try evaluating it now, it might have a constant initializer.
6638 Expr::EvalResult EvalResult;
6639 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6640 !EvalResult.hasSideEffects())
6641 Value = &EvalResult.Val;
6643 LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
6645 std::optional<ConstantEmitter> emitter;
6646 llvm::Constant *InitialValue = nullptr;
6647 bool Constant = false;
6648 llvm::Type *Type;
6649 if (Value) {
6650 // The temporary has a constant initializer, use it.
6651 emitter.emplace(*this);
6652 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6653 MaterializedType);
6654 Constant =
6655 MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
6656 /*ExcludeDtor*/ false);
6657 Type = InitialValue->getType();
6658 } else {
6659 // No initializer, the initialization will be provided when we
6660 // initialize the declaration which performed lifetime extension.
6661 Type = getTypes().ConvertTypeForMem(MaterializedType);
6664 // Create a global variable for this lifetime-extended temporary.
6665 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
6666 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6667 const VarDecl *InitVD;
6668 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6669 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6670 // Temporaries defined inside a class get linkonce_odr linkage because the
6671 // class can be defined in multiple translation units.
6672 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6673 } else {
6674 // There is no need for this temporary to have external linkage if the
6675 // VarDecl has external linkage.
6676 Linkage = llvm::GlobalVariable::InternalLinkage;
6679 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6680 auto *GV = new llvm::GlobalVariable(
6681 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6682 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6683 if (emitter) emitter->finalize(GV);
6684 // Don't assign dllimport or dllexport to local linkage globals.
6685 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6686 setGVProperties(GV, VD);
6687 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6688 // The reference temporary should never be dllexport.
6689 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6691 GV->setAlignment(Align.getAsAlign());
6692 if (supportsCOMDAT() && GV->isWeakForLinker())
6693 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6694 if (VD->getTLSKind())
6695 setTLSMode(GV, *VD);
6696 llvm::Constant *CV = GV;
6697 if (AddrSpace != LangAS::Default)
6698 CV = getTargetCodeGenInfo().performAddrSpaceCast(
6699 *this, GV, AddrSpace, LangAS::Default,
6700 llvm::PointerType::get(
6701 getLLVMContext(),
6702 getContext().getTargetAddressSpace(LangAS::Default)));
6704 // Update the map with the new temporary. If we created a placeholder above,
6705 // replace it with the new global now.
6706 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6707 if (Entry) {
6708 Entry->replaceAllUsesWith(CV);
6709 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6711 Entry = CV;
6713 return ConstantAddress(CV, Type, Align);
6716 /// EmitObjCPropertyImplementations - Emit information for synthesized
6717 /// properties for an implementation.
6718 void CodeGenModule::EmitObjCPropertyImplementations(const
6719 ObjCImplementationDecl *D) {
6720 for (const auto *PID : D->property_impls()) {
6721 // Dynamic is just for type-checking.
6722 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6723 ObjCPropertyDecl *PD = PID->getPropertyDecl();
6725 // Determine which methods need to be implemented, some may have
6726 // been overridden. Note that ::isPropertyAccessor is not the method
6727 // we want, that just indicates if the decl came from a
6728 // property. What we want to know is if the method is defined in
6729 // this implementation.
6730 auto *Getter = PID->getGetterMethodDecl();
6731 if (!Getter || Getter->isSynthesizedAccessorStub())
6732 CodeGenFunction(*this).GenerateObjCGetter(
6733 const_cast<ObjCImplementationDecl *>(D), PID);
6734 auto *Setter = PID->getSetterMethodDecl();
6735 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6736 CodeGenFunction(*this).GenerateObjCSetter(
6737 const_cast<ObjCImplementationDecl *>(D), PID);
6742 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6743 const ObjCInterfaceDecl *iface = impl->getClassInterface();
6744 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6745 ivar; ivar = ivar->getNextIvar())
6746 if (ivar->getType().isDestructedType())
6747 return true;
6749 return false;
6752 static bool AllTrivialInitializers(CodeGenModule &CGM,
6753 ObjCImplementationDecl *D) {
6754 CodeGenFunction CGF(CGM);
6755 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6756 E = D->init_end(); B != E; ++B) {
6757 CXXCtorInitializer *CtorInitExp = *B;
6758 Expr *Init = CtorInitExp->getInit();
6759 if (!CGF.isTrivialInitializer(Init))
6760 return false;
6762 return true;
6765 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6766 /// for an implementation.
6767 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6768 // We might need a .cxx_destruct even if we don't have any ivar initializers.
6769 if (needsDestructMethod(D)) {
6770 const IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6771 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6772 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6773 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6774 getContext().VoidTy, nullptr, D,
6775 /*isInstance=*/true, /*isVariadic=*/false,
6776 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6777 /*isImplicitlyDeclared=*/true,
6778 /*isDefined=*/false, ObjCImplementationControl::Required);
6779 D->addInstanceMethod(DTORMethod);
6780 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6781 D->setHasDestructors(true);
6784 // If the implementation doesn't have any ivar initializers, we don't need
6785 // a .cxx_construct.
6786 if (D->getNumIvarInitializers() == 0 ||
6787 AllTrivialInitializers(*this, D))
6788 return;
6790 const IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6791 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6792 // The constructor returns 'self'.
6793 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6794 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6795 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6796 /*isVariadic=*/false,
6797 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6798 /*isImplicitlyDeclared=*/true,
6799 /*isDefined=*/false, ObjCImplementationControl::Required);
6800 D->addInstanceMethod(CTORMethod);
6801 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6802 D->setHasNonZeroConstructors(true);
6805 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6806 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6807 if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
6808 LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) {
6809 ErrorUnsupported(LSD, "linkage spec");
6810 return;
6813 EmitDeclContext(LSD);
6816 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6817 // Device code should not be at top level.
6818 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6819 return;
6821 std::unique_ptr<CodeGenFunction> &CurCGF =
6822 GlobalTopLevelStmtBlockInFlight.first;
6824 // We emitted a top-level stmt but after it there is initialization.
6825 // Stop squashing the top-level stmts into a single function.
6826 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6827 CurCGF->FinishFunction(D->getEndLoc());
6828 CurCGF = nullptr;
6831 if (!CurCGF) {
6832 // void __stmts__N(void)
6833 // FIXME: Ask the ABI name mangler to pick a name.
6834 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6835 FunctionArgList Args;
6836 QualType RetTy = getContext().VoidTy;
6837 const CGFunctionInfo &FnInfo =
6838 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6839 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6840 llvm::Function *Fn = llvm::Function::Create(
6841 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6843 CurCGF.reset(new CodeGenFunction(*this));
6844 GlobalTopLevelStmtBlockInFlight.second = D;
6845 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6846 D->getBeginLoc(), D->getBeginLoc());
6847 CXXGlobalInits.push_back(Fn);
6850 CurCGF->EmitStmt(D->getStmt());
6853 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6854 for (auto *I : DC->decls()) {
6855 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6856 // are themselves considered "top-level", so EmitTopLevelDecl on an
6857 // ObjCImplDecl does not recursively visit them. We need to do that in
6858 // case they're nested inside another construct (LinkageSpecDecl /
6859 // ExportDecl) that does stop them from being considered "top-level".
6860 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6861 for (auto *M : OID->methods())
6862 EmitTopLevelDecl(M);
6865 EmitTopLevelDecl(I);
6869 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6870 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6871 // Ignore dependent declarations.
6872 if (D->isTemplated())
6873 return;
6875 // Consteval function shouldn't be emitted.
6876 if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
6877 return;
6879 switch (D->getKind()) {
6880 case Decl::CXXConversion:
6881 case Decl::CXXMethod:
6882 case Decl::Function:
6883 EmitGlobal(cast<FunctionDecl>(D));
6884 // Always provide some coverage mapping
6885 // even for the functions that aren't emitted.
6886 AddDeferredUnusedCoverageMapping(D);
6887 break;
6889 case Decl::CXXDeductionGuide:
6890 // Function-like, but does not result in code emission.
6891 break;
6893 case Decl::Var:
6894 case Decl::Decomposition:
6895 case Decl::VarTemplateSpecialization:
6896 EmitGlobal(cast<VarDecl>(D));
6897 if (auto *DD = dyn_cast<DecompositionDecl>(D))
6898 for (auto *B : DD->bindings())
6899 if (auto *HD = B->getHoldingVar())
6900 EmitGlobal(HD);
6901 break;
6903 // Indirect fields from global anonymous structs and unions can be
6904 // ignored; only the actual variable requires IR gen support.
6905 case Decl::IndirectField:
6906 break;
6908 // C++ Decls
6909 case Decl::Namespace:
6910 EmitDeclContext(cast<NamespaceDecl>(D));
6911 break;
6912 case Decl::ClassTemplateSpecialization: {
6913 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6914 if (CGDebugInfo *DI = getModuleDebugInfo())
6915 if (Spec->getSpecializationKind() ==
6916 TSK_ExplicitInstantiationDefinition &&
6917 Spec->hasDefinition())
6918 DI->completeTemplateDefinition(*Spec);
6919 } [[fallthrough]];
6920 case Decl::CXXRecord: {
6921 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6922 if (CGDebugInfo *DI = getModuleDebugInfo()) {
6923 if (CRD->hasDefinition())
6924 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6925 if (auto *ES = D->getASTContext().getExternalSource())
6926 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6927 DI->completeUnusedClass(*CRD);
6929 // Emit any static data members, they may be definitions.
6930 for (auto *I : CRD->decls())
6931 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6932 EmitTopLevelDecl(I);
6933 break;
6935 // No code generation needed.
6936 case Decl::UsingShadow:
6937 case Decl::ClassTemplate:
6938 case Decl::VarTemplate:
6939 case Decl::Concept:
6940 case Decl::VarTemplatePartialSpecialization:
6941 case Decl::FunctionTemplate:
6942 case Decl::TypeAliasTemplate:
6943 case Decl::Block:
6944 case Decl::Empty:
6945 case Decl::Binding:
6946 break;
6947 case Decl::Using: // using X; [C++]
6948 if (CGDebugInfo *DI = getModuleDebugInfo())
6949 DI->EmitUsingDecl(cast<UsingDecl>(*D));
6950 break;
6951 case Decl::UsingEnum: // using enum X; [C++]
6952 if (CGDebugInfo *DI = getModuleDebugInfo())
6953 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6954 break;
6955 case Decl::NamespaceAlias:
6956 if (CGDebugInfo *DI = getModuleDebugInfo())
6957 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6958 break;
6959 case Decl::UsingDirective: // using namespace X; [C++]
6960 if (CGDebugInfo *DI = getModuleDebugInfo())
6961 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6962 break;
6963 case Decl::CXXConstructor:
6964 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6965 break;
6966 case Decl::CXXDestructor:
6967 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6968 break;
6970 case Decl::StaticAssert:
6971 // Nothing to do.
6972 break;
6974 // Objective-C Decls
6976 // Forward declarations, no (immediate) code generation.
6977 case Decl::ObjCInterface:
6978 case Decl::ObjCCategory:
6979 break;
6981 case Decl::ObjCProtocol: {
6982 auto *Proto = cast<ObjCProtocolDecl>(D);
6983 if (Proto->isThisDeclarationADefinition())
6984 ObjCRuntime->GenerateProtocol(Proto);
6985 break;
6988 case Decl::ObjCCategoryImpl:
6989 // Categories have properties but don't support synthesize so we
6990 // can ignore them here.
6991 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6992 break;
6994 case Decl::ObjCImplementation: {
6995 auto *OMD = cast<ObjCImplementationDecl>(D);
6996 EmitObjCPropertyImplementations(OMD);
6997 EmitObjCIvarInitializations(OMD);
6998 ObjCRuntime->GenerateClass(OMD);
6999 // Emit global variable debug information.
7000 if (CGDebugInfo *DI = getModuleDebugInfo())
7001 if (getCodeGenOpts().hasReducedDebugInfo())
7002 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
7003 OMD->getClassInterface()), OMD->getLocation());
7004 break;
7006 case Decl::ObjCMethod: {
7007 auto *OMD = cast<ObjCMethodDecl>(D);
7008 // If this is not a prototype, emit the body.
7009 if (OMD->getBody())
7010 CodeGenFunction(*this).GenerateObjCMethod(OMD);
7011 break;
7013 case Decl::ObjCCompatibleAlias:
7014 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
7015 break;
7017 case Decl::PragmaComment: {
7018 const auto *PCD = cast<PragmaCommentDecl>(D);
7019 switch (PCD->getCommentKind()) {
7020 case PCK_Unknown:
7021 llvm_unreachable("unexpected pragma comment kind");
7022 case PCK_Linker:
7023 AppendLinkerOptions(PCD->getArg());
7024 break;
7025 case PCK_Lib:
7026 AddDependentLib(PCD->getArg());
7027 break;
7028 case PCK_Compiler:
7029 case PCK_ExeStr:
7030 case PCK_User:
7031 break; // We ignore all of these.
7033 break;
7036 case Decl::PragmaDetectMismatch: {
7037 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
7038 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
7039 break;
7042 case Decl::LinkageSpec:
7043 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
7044 break;
7046 case Decl::FileScopeAsm: {
7047 // File-scope asm is ignored during device-side CUDA compilation.
7048 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7049 break;
7050 // File-scope asm is ignored during device-side OpenMP compilation.
7051 if (LangOpts.OpenMPIsTargetDevice)
7052 break;
7053 // File-scope asm is ignored during device-side SYCL compilation.
7054 if (LangOpts.SYCLIsDevice)
7055 break;
7056 auto *AD = cast<FileScopeAsmDecl>(D);
7057 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
7058 break;
7061 case Decl::TopLevelStmt:
7062 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
7063 break;
7065 case Decl::Import: {
7066 auto *Import = cast<ImportDecl>(D);
7068 // If we've already imported this module, we're done.
7069 if (!ImportedModules.insert(Import->getImportedModule()))
7070 break;
7072 // Emit debug information for direct imports.
7073 if (!Import->getImportedOwningModule()) {
7074 if (CGDebugInfo *DI = getModuleDebugInfo())
7075 DI->EmitImportDecl(*Import);
7078 // For C++ standard modules we are done - we will call the module
7079 // initializer for imported modules, and that will likewise call those for
7080 // any imports it has.
7081 if (CXX20ModuleInits && Import->getImportedOwningModule() &&
7082 !Import->getImportedOwningModule()->isModuleMapModule())
7083 break;
7085 // For clang C++ module map modules the initializers for sub-modules are
7086 // emitted here.
7088 // Find all of the submodules and emit the module initializers.
7089 llvm::SmallPtrSet<clang::Module *, 16> Visited;
7090 SmallVector<clang::Module *, 16> Stack;
7091 Visited.insert(Import->getImportedModule());
7092 Stack.push_back(Import->getImportedModule());
7094 while (!Stack.empty()) {
7095 clang::Module *Mod = Stack.pop_back_val();
7096 if (!EmittedModuleInitializers.insert(Mod).second)
7097 continue;
7099 for (auto *D : Context.getModuleInitializers(Mod))
7100 EmitTopLevelDecl(D);
7102 // Visit the submodules of this module.
7103 for (auto *Submodule : Mod->submodules()) {
7104 // Skip explicit children; they need to be explicitly imported to emit
7105 // the initializers.
7106 if (Submodule->IsExplicit)
7107 continue;
7109 if (Visited.insert(Submodule).second)
7110 Stack.push_back(Submodule);
7113 break;
7116 case Decl::Export:
7117 EmitDeclContext(cast<ExportDecl>(D));
7118 break;
7120 case Decl::OMPThreadPrivate:
7121 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
7122 break;
7124 case Decl::OMPAllocate:
7125 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
7126 break;
7128 case Decl::OMPDeclareReduction:
7129 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
7130 break;
7132 case Decl::OMPDeclareMapper:
7133 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
7134 break;
7136 case Decl::OMPRequires:
7137 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
7138 break;
7140 case Decl::Typedef:
7141 case Decl::TypeAlias: // using foo = bar; [C++11]
7142 if (CGDebugInfo *DI = getModuleDebugInfo())
7143 DI->EmitAndRetainType(
7144 getContext().getTypedefType(cast<TypedefNameDecl>(D)));
7145 break;
7147 case Decl::Record:
7148 if (CGDebugInfo *DI = getModuleDebugInfo())
7149 if (cast<RecordDecl>(D)->getDefinition())
7150 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
7151 break;
7153 case Decl::Enum:
7154 if (CGDebugInfo *DI = getModuleDebugInfo())
7155 if (cast<EnumDecl>(D)->getDefinition())
7156 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
7157 break;
7159 case Decl::HLSLBuffer:
7160 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
7161 break;
7163 default:
7164 // Make sure we handled everything we should, every other kind is a
7165 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
7166 // function. Need to recode Decl::Kind to do that easily.
7167 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
7168 break;
7172 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
7173 // Do we need to generate coverage mapping?
7174 if (!CodeGenOpts.CoverageMapping)
7175 return;
7176 switch (D->getKind()) {
7177 case Decl::CXXConversion:
7178 case Decl::CXXMethod:
7179 case Decl::Function:
7180 case Decl::ObjCMethod:
7181 case Decl::CXXConstructor:
7182 case Decl::CXXDestructor: {
7183 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
7184 break;
7185 SourceManager &SM = getContext().getSourceManager();
7186 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
7187 break;
7188 if (!llvm::coverage::SystemHeadersCoverage &&
7189 SM.isInSystemHeader(D->getBeginLoc()))
7190 break;
7191 DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
7192 break;
7194 default:
7195 break;
7199 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
7200 // Do we need to generate coverage mapping?
7201 if (!CodeGenOpts.CoverageMapping)
7202 return;
7203 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7204 if (Fn->isTemplateInstantiation())
7205 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
7207 DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
7210 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
7211 // We call takeVector() here to avoid use-after-free.
7212 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
7213 // we deserialize function bodies to emit coverage info for them, and that
7214 // deserializes more declarations. How should we handle that case?
7215 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7216 if (!Entry.second)
7217 continue;
7218 const Decl *D = Entry.first;
7219 switch (D->getKind()) {
7220 case Decl::CXXConversion:
7221 case Decl::CXXMethod:
7222 case Decl::Function:
7223 case Decl::ObjCMethod: {
7224 CodeGenPGO PGO(*this);
7225 GlobalDecl GD(cast<FunctionDecl>(D));
7226 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7227 getFunctionLinkage(GD));
7228 break;
7230 case Decl::CXXConstructor: {
7231 CodeGenPGO PGO(*this);
7232 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
7233 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7234 getFunctionLinkage(GD));
7235 break;
7237 case Decl::CXXDestructor: {
7238 CodeGenPGO PGO(*this);
7239 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
7240 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7241 getFunctionLinkage(GD));
7242 break;
7244 default:
7245 break;
7250 void CodeGenModule::EmitMainVoidAlias() {
7251 // In order to transition away from "__original_main" gracefully, emit an
7252 // alias for "main" in the no-argument case so that libc can detect when
7253 // new-style no-argument main is in used.
7254 if (llvm::Function *F = getModule().getFunction("main")) {
7255 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7256 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7257 auto *GA = llvm::GlobalAlias::create("__main_void", F);
7258 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7263 /// Turns the given pointer into a constant.
7264 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
7265 const void *Ptr) {
7266 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
7267 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7268 return llvm::ConstantInt::get(i64, PtrInt);
7271 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
7272 llvm::NamedMDNode *&GlobalMetadata,
7273 GlobalDecl D,
7274 llvm::GlobalValue *Addr) {
7275 if (!GlobalMetadata)
7276 GlobalMetadata =
7277 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
7279 // TODO: should we report variant information for ctors/dtors?
7280 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7281 llvm::ConstantAsMetadata::get(GetPointerConstant(
7282 CGM.getLLVMContext(), D.getDecl()))};
7283 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
7286 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7287 llvm::GlobalValue *CppFunc) {
7288 // Store the list of ifuncs we need to replace uses in.
7289 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7290 // List of ConstantExprs that we should be able to delete when we're done
7291 // here.
7292 llvm::SmallVector<llvm::ConstantExpr *> CEs;
7294 // It isn't valid to replace the extern-C ifuncs if all we find is itself!
7295 if (Elem == CppFunc)
7296 return false;
7298 // First make sure that all users of this are ifuncs (or ifuncs via a
7299 // bitcast), and collect the list of ifuncs and CEs so we can work on them
7300 // later.
7301 for (llvm::User *User : Elem->users()) {
7302 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
7303 // ifunc directly. In any other case, just give up, as we don't know what we
7304 // could break by changing those.
7305 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7306 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7307 return false;
7309 for (llvm::User *CEUser : ConstExpr->users()) {
7310 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7311 IFuncs.push_back(IFunc);
7312 } else {
7313 return false;
7316 CEs.push_back(ConstExpr);
7317 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7318 IFuncs.push_back(IFunc);
7319 } else {
7320 // This user is one we don't know how to handle, so fail redirection. This
7321 // will result in an ifunc retaining a resolver name that will ultimately
7322 // fail to be resolved to a defined function.
7323 return false;
7327 // Now we know this is a valid case where we can do this alias replacement, we
7328 // need to remove all of the references to Elem (and the bitcasts!) so we can
7329 // delete it.
7330 for (llvm::GlobalIFunc *IFunc : IFuncs)
7331 IFunc->setResolver(nullptr);
7332 for (llvm::ConstantExpr *ConstExpr : CEs)
7333 ConstExpr->destroyConstant();
7335 // We should now be out of uses for the 'old' version of this function, so we
7336 // can erase it as well.
7337 Elem->eraseFromParent();
7339 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7340 // The type of the resolver is always just a function-type that returns the
7341 // type of the IFunc, so create that here. If the type of the actual
7342 // resolver doesn't match, it just gets bitcast to the right thing.
7343 auto *ResolverTy =
7344 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7345 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7346 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7347 IFunc->setResolver(Resolver);
7349 return true;
7352 /// For each function which is declared within an extern "C" region and marked
7353 /// as 'used', but has internal linkage, create an alias from the unmangled
7354 /// name to the mangled name if possible. People expect to be able to refer
7355 /// to such functions with an unmangled name from inline assembly within the
7356 /// same translation unit.
7357 void CodeGenModule::EmitStaticExternCAliases() {
7358 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7359 return;
7360 for (auto &I : StaticExternCValues) {
7361 const IdentifierInfo *Name = I.first;
7362 llvm::GlobalValue *Val = I.second;
7364 // If Val is null, that implies there were multiple declarations that each
7365 // had a claim to the unmangled name. In this case, generation of the alias
7366 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7367 if (!Val)
7368 break;
7370 llvm::GlobalValue *ExistingElem =
7371 getModule().getNamedValue(Name->getName());
7373 // If there is either not something already by this name, or we were able to
7374 // replace all uses from IFuncs, create the alias.
7375 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7376 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7380 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
7381 GlobalDecl &Result) const {
7382 auto Res = Manglings.find(MangledName);
7383 if (Res == Manglings.end())
7384 return false;
7385 Result = Res->getValue();
7386 return true;
7389 /// Emits metadata nodes associating all the global values in the
7390 /// current module with the Decls they came from. This is useful for
7391 /// projects using IR gen as a subroutine.
7393 /// Since there's currently no way to associate an MDNode directly
7394 /// with an llvm::GlobalValue, we create a global named metadata
7395 /// with the name 'clang.global.decl.ptrs'.
7396 void CodeGenModule::EmitDeclMetadata() {
7397 llvm::NamedMDNode *GlobalMetadata = nullptr;
7399 for (auto &I : MangledDeclNames) {
7400 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7401 // Some mangled names don't necessarily have an associated GlobalValue
7402 // in this module, e.g. if we mangled it for DebugInfo.
7403 if (Addr)
7404 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7408 /// Emits metadata nodes for all the local variables in the current
7409 /// function.
7410 void CodeGenFunction::EmitDeclMetadata() {
7411 if (LocalDeclMap.empty()) return;
7413 llvm::LLVMContext &Context = getLLVMContext();
7415 // Find the unique metadata ID for this name.
7416 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
7418 llvm::NamedMDNode *GlobalMetadata = nullptr;
7420 for (auto &I : LocalDeclMap) {
7421 const Decl *D = I.first;
7422 llvm::Value *Addr = I.second.emitRawPointer(*this);
7423 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7424 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
7425 Alloca->setMetadata(
7426 DeclPtrKind, llvm::MDNode::get(
7427 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7428 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7429 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
7430 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
7435 void CodeGenModule::EmitVersionIdentMetadata() {
7436 llvm::NamedMDNode *IdentMetadata =
7437 TheModule.getOrInsertNamedMetadata("llvm.ident");
7438 std::string Version = getClangFullVersion();
7439 llvm::LLVMContext &Ctx = TheModule.getContext();
7441 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7442 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7445 void CodeGenModule::EmitCommandLineMetadata() {
7446 llvm::NamedMDNode *CommandLineMetadata =
7447 TheModule.getOrInsertNamedMetadata("llvm.commandline");
7448 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
7449 llvm::LLVMContext &Ctx = TheModule.getContext();
7451 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7452 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7455 void CodeGenModule::EmitCoverageFile() {
7456 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
7457 if (!CUNode)
7458 return;
7460 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
7461 llvm::LLVMContext &Ctx = TheModule.getContext();
7462 auto *CoverageDataFile =
7463 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
7464 auto *CoverageNotesFile =
7465 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
7466 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7467 llvm::MDNode *CU = CUNode->getOperand(i);
7468 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7469 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7473 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
7474 bool ForEH) {
7475 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
7476 // FIXME: should we even be calling this method if RTTI is disabled
7477 // and it's not for EH?
7478 if (!shouldEmitRTTI(ForEH))
7479 return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
7481 if (ForEH && Ty->isObjCObjectPointerType() &&
7482 LangOpts.ObjCRuntime.isGNUFamily())
7483 return ObjCRuntime->GetEHType(Ty);
7485 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
7488 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
7489 // Do not emit threadprivates in simd-only mode.
7490 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7491 return;
7492 for (auto RefExpr : D->varlists()) {
7493 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7494 bool PerformInit =
7495 VD->getAnyInitializer() &&
7496 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
7497 /*ForRef=*/false);
7499 Address Addr(GetAddrOfGlobalVar(VD),
7500 getTypes().ConvertTypeForMem(VD->getType()),
7501 getContext().getDeclAlign(VD));
7502 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
7503 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7504 CXXGlobalInits.push_back(InitFunction);
7508 llvm::Metadata *
7509 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
7510 StringRef Suffix) {
7511 if (auto *FnType = T->getAs<FunctionProtoType>())
7512 T = getContext().getFunctionType(
7513 FnType->getReturnType(), FnType->getParamTypes(),
7514 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
7516 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
7517 if (InternalId)
7518 return InternalId;
7520 if (isExternallyVisible(T->getLinkage())) {
7521 std::string OutName;
7522 llvm::raw_string_ostream Out(OutName);
7523 getCXXABI().getMangleContext().mangleCanonicalTypeName(
7524 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
7526 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
7527 Out << ".normalized";
7529 Out << Suffix;
7531 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
7532 } else {
7533 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
7534 llvm::ArrayRef<llvm::Metadata *>());
7537 return InternalId;
7540 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
7541 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
7544 llvm::Metadata *
7545 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
7546 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
7549 // Generalize pointer types to a void pointer with the qualifiers of the
7550 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
7551 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
7552 // 'void *'.
7553 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
7554 if (!Ty->isPointerType())
7555 return Ty;
7557 return Ctx.getPointerType(
7558 QualType(Ctx.VoidTy).withCVRQualifiers(
7559 Ty->getPointeeType().getCVRQualifiers()));
7562 // Apply type generalization to a FunctionType's return and argument types
7563 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
7564 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
7565 SmallVector<QualType, 8> GeneralizedParams;
7566 for (auto &Param : FnType->param_types())
7567 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
7569 return Ctx.getFunctionType(
7570 GeneralizeType(Ctx, FnType->getReturnType()),
7571 GeneralizedParams, FnType->getExtProtoInfo());
7574 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
7575 return Ctx.getFunctionNoProtoType(
7576 GeneralizeType(Ctx, FnType->getReturnType()));
7578 llvm_unreachable("Encountered unknown FunctionType");
7581 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7582 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7583 GeneralizedMetadataIdMap, ".generalized");
7586 /// Returns whether this module needs the "all-vtables" type identifier.
7587 bool CodeGenModule::NeedAllVtablesTypeId() const {
7588 // Returns true if at least one of vtable-based CFI checkers is enabled and
7589 // is not in the trapping mode.
7590 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7591 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7592 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7593 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7594 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7595 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7596 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7597 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7600 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7601 CharUnits Offset,
7602 const CXXRecordDecl *RD) {
7603 llvm::Metadata *MD =
7604 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7605 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7607 if (CodeGenOpts.SanitizeCfiCrossDso)
7608 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7609 VTable->addTypeMetadata(Offset.getQuantity(),
7610 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7612 if (NeedAllVtablesTypeId()) {
7613 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7614 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7618 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7619 if (!SanStats)
7620 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7622 return *SanStats;
7625 llvm::Value *
7626 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7627 CodeGenFunction &CGF) {
7628 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7629 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7630 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7631 auto *Call = CGF.EmitRuntimeCall(
7632 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7633 return Call;
7636 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7637 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7638 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7639 /* forPointeeType= */ true);
7642 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7643 LValueBaseInfo *BaseInfo,
7644 TBAAAccessInfo *TBAAInfo,
7645 bool forPointeeType) {
7646 if (TBAAInfo)
7647 *TBAAInfo = getTBAAAccessInfo(T);
7649 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7650 // that doesn't return the information we need to compute BaseInfo.
7652 // Honor alignment typedef attributes even on incomplete types.
7653 // We also honor them straight for C++ class types, even as pointees;
7654 // there's an expressivity gap here.
7655 if (auto TT = T->getAs<TypedefType>()) {
7656 if (auto Align = TT->getDecl()->getMaxAlignment()) {
7657 if (BaseInfo)
7658 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7659 return getContext().toCharUnitsFromBits(Align);
7663 bool AlignForArray = T->isArrayType();
7665 // Analyze the base element type, so we don't get confused by incomplete
7666 // array types.
7667 T = getContext().getBaseElementType(T);
7669 if (T->isIncompleteType()) {
7670 // We could try to replicate the logic from
7671 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7672 // type is incomplete, so it's impossible to test. We could try to reuse
7673 // getTypeAlignIfKnown, but that doesn't return the information we need
7674 // to set BaseInfo. So just ignore the possibility that the alignment is
7675 // greater than one.
7676 if (BaseInfo)
7677 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7678 return CharUnits::One();
7681 if (BaseInfo)
7682 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7684 CharUnits Alignment;
7685 const CXXRecordDecl *RD;
7686 if (T.getQualifiers().hasUnaligned()) {
7687 Alignment = CharUnits::One();
7688 } else if (forPointeeType && !AlignForArray &&
7689 (RD = T->getAsCXXRecordDecl())) {
7690 // For C++ class pointees, we don't know whether we're pointing at a
7691 // base or a complete object, so we generally need to use the
7692 // non-virtual alignment.
7693 Alignment = getClassPointerAlignment(RD);
7694 } else {
7695 Alignment = getContext().getTypeAlignInChars(T);
7698 // Cap to the global maximum type alignment unless the alignment
7699 // was somehow explicit on the type.
7700 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7701 if (Alignment.getQuantity() > MaxAlign &&
7702 !getContext().isAlignmentRequired(T))
7703 Alignment = CharUnits::fromQuantity(MaxAlign);
7705 return Alignment;
7708 bool CodeGenModule::stopAutoInit() {
7709 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7710 if (StopAfter) {
7711 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7712 // used
7713 if (NumAutoVarInit >= StopAfter) {
7714 return true;
7716 if (!NumAutoVarInit) {
7717 unsigned DiagID = getDiags().getCustomDiagID(
7718 DiagnosticsEngine::Warning,
7719 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7720 "number of times ftrivial-auto-var-init=%1 gets applied.");
7721 getDiags().Report(DiagID)
7722 << StopAfter
7723 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7724 LangOptions::TrivialAutoVarInitKind::Zero
7725 ? "zero"
7726 : "pattern");
7728 ++NumAutoVarInit;
7730 return false;
7733 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7734 const Decl *D) const {
7735 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7736 // postfix beginning with '.' since the symbol name can be demangled.
7737 if (LangOpts.HIP)
7738 OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7739 else
7740 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7742 // If the CUID is not specified we try to generate a unique postfix.
7743 if (getLangOpts().CUID.empty()) {
7744 SourceManager &SM = getContext().getSourceManager();
7745 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7746 assert(PLoc.isValid() && "Source location is expected to be valid.");
7748 // Get the hash of the user defined macros.
7749 llvm::MD5 Hash;
7750 llvm::MD5::MD5Result Result;
7751 for (const auto &Arg : PreprocessorOpts.Macros)
7752 Hash.update(Arg.first);
7753 Hash.final(Result);
7755 // Get the UniqueID for the file containing the decl.
7756 llvm::sys::fs::UniqueID ID;
7757 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7758 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7759 assert(PLoc.isValid() && "Source location is expected to be valid.");
7760 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7761 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7762 << PLoc.getFilename() << EC.message();
7764 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7765 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7766 } else {
7767 OS << getContext().getCUIDHash();
7771 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7772 assert(DeferredDeclsToEmit.empty() &&
7773 "Should have emitted all decls deferred to emit.");
7774 assert(NewBuilder->DeferredDecls.empty() &&
7775 "Newly created module should not have deferred decls");
7776 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7777 assert(EmittedDeferredDecls.empty() &&
7778 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7780 assert(NewBuilder->DeferredVTables.empty() &&
7781 "Newly created module should not have deferred vtables");
7782 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7784 assert(NewBuilder->MangledDeclNames.empty() &&
7785 "Newly created module should not have mangled decl names");
7786 assert(NewBuilder->Manglings.empty() &&
7787 "Newly created module should not have manglings");
7788 NewBuilder->Manglings = std::move(Manglings);
7790 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7792 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);