[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / CodeGen / CodeGenModule.cpp
blobb1e5c9fc96faa50d78521a2c00569fb703169d8c
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/CharUnits.h"
32 #include "clang/AST/DeclCXX.h"
33 #include "clang/AST/DeclObjC.h"
34 #include "clang/AST/DeclTemplate.h"
35 #include "clang/AST/Mangle.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/AST/StmtVisitor.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/CodeGenOptions.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/FileManager.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "clang/Basic/Version.h"
47 #include "clang/CodeGen/BackendUtil.h"
48 #include "clang/CodeGen/ConstantInitBuilder.h"
49 #include "clang/Frontend/FrontendDiagnostic.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/Analysis/TargetLibraryInfo.h"
54 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
55 #include "llvm/IR/AttributeMask.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/ProfileSummary.h"
62 #include "llvm/ProfileData/InstrProfReader.h"
63 #include "llvm/ProfileData/SampleProf.h"
64 #include "llvm/Support/CRC.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/ConvertUTF.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/TimeProfiler.h"
70 #include "llvm/Support/xxhash.h"
71 #include "llvm/TargetParser/Triple.h"
72 #include "llvm/TargetParser/X86TargetParser.h"
73 #include <optional>
75 using namespace clang;
76 using namespace CodeGen;
78 static llvm::cl::opt<bool> LimitedCoverage(
79 "limited-coverage-experimental", llvm::cl::Hidden,
80 llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
82 static const char AnnotationSection[] = "llvm.metadata";
84 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
85 switch (CGM.getContext().getCXXABIKind()) {
86 case TargetCXXABI::AppleARM64:
87 case TargetCXXABI::Fuchsia:
88 case TargetCXXABI::GenericAArch64:
89 case TargetCXXABI::GenericARM:
90 case TargetCXXABI::iOS:
91 case TargetCXXABI::WatchOS:
92 case TargetCXXABI::GenericMIPS:
93 case TargetCXXABI::GenericItanium:
94 case TargetCXXABI::WebAssembly:
95 case TargetCXXABI::XL:
96 return CreateItaniumCXXABI(CGM);
97 case TargetCXXABI::Microsoft:
98 return CreateMicrosoftCXXABI(CGM);
101 llvm_unreachable("invalid C++ ABI kind");
104 static std::unique_ptr<TargetCodeGenInfo>
105 createTargetCodeGenInfo(CodeGenModule &CGM) {
106 const TargetInfo &Target = CGM.getTarget();
107 const llvm::Triple &Triple = Target.getTriple();
108 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
110 switch (Triple.getArch()) {
111 default:
112 return createDefaultTargetCodeGenInfo(CGM);
114 case llvm::Triple::le32:
115 return createPNaClTargetCodeGenInfo(CGM);
116 case llvm::Triple::m68k:
117 return createM68kTargetCodeGenInfo(CGM);
118 case llvm::Triple::mips:
119 case llvm::Triple::mipsel:
120 if (Triple.getOS() == llvm::Triple::NaCl)
121 return createPNaClTargetCodeGenInfo(CGM);
122 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
124 case llvm::Triple::mips64:
125 case llvm::Triple::mips64el:
126 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
128 case llvm::Triple::avr: {
129 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
130 // on avrtiny. For passing return value, R18~R25 are used on avr, and
131 // R22~R25 are used on avrtiny.
132 unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
133 unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
134 return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
137 case llvm::Triple::aarch64:
138 case llvm::Triple::aarch64_32:
139 case llvm::Triple::aarch64_be: {
140 AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
141 if (Target.getABI() == "darwinpcs")
142 Kind = AArch64ABIKind::DarwinPCS;
143 else if (Triple.isOSWindows())
144 return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
146 return createAArch64TargetCodeGenInfo(CGM, Kind);
149 case llvm::Triple::wasm32:
150 case llvm::Triple::wasm64: {
151 WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
152 if (Target.getABI() == "experimental-mv")
153 Kind = WebAssemblyABIKind::ExperimentalMV;
154 return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
157 case llvm::Triple::arm:
158 case llvm::Triple::armeb:
159 case llvm::Triple::thumb:
160 case llvm::Triple::thumbeb: {
161 if (Triple.getOS() == llvm::Triple::Win32)
162 return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
164 ARMABIKind Kind = ARMABIKind::AAPCS;
165 StringRef ABIStr = Target.getABI();
166 if (ABIStr == "apcs-gnu")
167 Kind = ARMABIKind::APCS;
168 else if (ABIStr == "aapcs16")
169 Kind = ARMABIKind::AAPCS16_VFP;
170 else if (CodeGenOpts.FloatABI == "hard" ||
171 (CodeGenOpts.FloatABI != "soft" &&
172 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
173 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
174 Triple.getEnvironment() == llvm::Triple::EABIHF)))
175 Kind = ARMABIKind::AAPCS_VFP;
177 return createARMTargetCodeGenInfo(CGM, Kind);
180 case llvm::Triple::ppc: {
181 if (Triple.isOSAIX())
182 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
184 bool IsSoftFloat =
185 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
186 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
188 case llvm::Triple::ppcle: {
189 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
190 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
192 case llvm::Triple::ppc64:
193 if (Triple.isOSAIX())
194 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
196 if (Triple.isOSBinFormatELF()) {
197 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
198 if (Target.getABI() == "elfv2")
199 Kind = PPC64_SVR4_ABIKind::ELFv2;
200 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
202 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
204 return createPPC64TargetCodeGenInfo(CGM);
205 case llvm::Triple::ppc64le: {
206 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
207 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
208 if (Target.getABI() == "elfv1")
209 Kind = PPC64_SVR4_ABIKind::ELFv1;
210 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
212 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
215 case llvm::Triple::nvptx:
216 case llvm::Triple::nvptx64:
217 return createNVPTXTargetCodeGenInfo(CGM);
219 case llvm::Triple::msp430:
220 return createMSP430TargetCodeGenInfo(CGM);
222 case llvm::Triple::riscv32:
223 case llvm::Triple::riscv64: {
224 StringRef ABIStr = Target.getABI();
225 unsigned XLen = Target.getPointerWidth(LangAS::Default);
226 unsigned ABIFLen = 0;
227 if (ABIStr.endswith("f"))
228 ABIFLen = 32;
229 else if (ABIStr.endswith("d"))
230 ABIFLen = 64;
231 return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen);
234 case llvm::Triple::systemz: {
235 bool SoftFloat = CodeGenOpts.FloatABI == "soft";
236 bool HasVector = !SoftFloat && Target.getABI() == "vector";
237 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
240 case llvm::Triple::tce:
241 case llvm::Triple::tcele:
242 return createTCETargetCodeGenInfo(CGM);
244 case llvm::Triple::x86: {
245 bool IsDarwinVectorABI = Triple.isOSDarwin();
246 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
248 if (Triple.getOS() == llvm::Triple::Win32) {
249 return createWinX86_32TargetCodeGenInfo(
250 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
251 CodeGenOpts.NumRegisterParameters);
253 return createX86_32TargetCodeGenInfo(
254 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
255 CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
258 case llvm::Triple::x86_64: {
259 StringRef ABI = Target.getABI();
260 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
261 : ABI == "avx" ? X86AVXABILevel::AVX
262 : X86AVXABILevel::None);
264 switch (Triple.getOS()) {
265 case llvm::Triple::Win32:
266 return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
267 default:
268 return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
271 case llvm::Triple::hexagon:
272 return createHexagonTargetCodeGenInfo(CGM);
273 case llvm::Triple::lanai:
274 return createLanaiTargetCodeGenInfo(CGM);
275 case llvm::Triple::r600:
276 return createAMDGPUTargetCodeGenInfo(CGM);
277 case llvm::Triple::amdgcn:
278 return createAMDGPUTargetCodeGenInfo(CGM);
279 case llvm::Triple::sparc:
280 return createSparcV8TargetCodeGenInfo(CGM);
281 case llvm::Triple::sparcv9:
282 return createSparcV9TargetCodeGenInfo(CGM);
283 case llvm::Triple::xcore:
284 return createXCoreTargetCodeGenInfo(CGM);
285 case llvm::Triple::arc:
286 return createARCTargetCodeGenInfo(CGM);
287 case llvm::Triple::spir:
288 case llvm::Triple::spir64:
289 return createCommonSPIRTargetCodeGenInfo(CGM);
290 case llvm::Triple::spirv32:
291 case llvm::Triple::spirv64:
292 return createSPIRVTargetCodeGenInfo(CGM);
293 case llvm::Triple::ve:
294 return createVETargetCodeGenInfo(CGM);
295 case llvm::Triple::csky: {
296 bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
297 bool hasFP64 =
298 Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
299 return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
300 : hasFP64 ? 64
301 : 32);
303 case llvm::Triple::bpfeb:
304 case llvm::Triple::bpfel:
305 return createBPFTargetCodeGenInfo(CGM);
306 case llvm::Triple::loongarch32:
307 case llvm::Triple::loongarch64: {
308 StringRef ABIStr = Target.getABI();
309 unsigned ABIFRLen = 0;
310 if (ABIStr.endswith("f"))
311 ABIFRLen = 32;
312 else if (ABIStr.endswith("d"))
313 ABIFRLen = 64;
314 return createLoongArchTargetCodeGenInfo(
315 CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
320 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
321 if (!TheTargetCodeGenInfo)
322 TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
323 return *TheTargetCodeGenInfo;
326 CodeGenModule::CodeGenModule(ASTContext &C,
327 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
328 const HeaderSearchOptions &HSO,
329 const PreprocessorOptions &PPO,
330 const CodeGenOptions &CGO, llvm::Module &M,
331 DiagnosticsEngine &diags,
332 CoverageSourceInfo *CoverageInfo)
333 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
334 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
335 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
336 VMContext(M.getContext()), Types(*this), VTables(*this),
337 SanitizerMD(new SanitizerMetadata(*this)) {
339 // Initialize the type cache.
340 llvm::LLVMContext &LLVMContext = M.getContext();
341 VoidTy = llvm::Type::getVoidTy(LLVMContext);
342 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
343 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
344 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
345 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
346 HalfTy = llvm::Type::getHalfTy(LLVMContext);
347 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
348 FloatTy = llvm::Type::getFloatTy(LLVMContext);
349 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
350 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
351 PointerAlignInBytes =
352 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
353 .getQuantity();
354 SizeSizeInBytes =
355 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
356 IntAlignInBytes =
357 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
358 CharTy =
359 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
360 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
361 IntPtrTy = llvm::IntegerType::get(LLVMContext,
362 C.getTargetInfo().getMaxPointerWidth());
363 Int8PtrTy = Int8Ty->getPointerTo(0);
364 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
365 const llvm::DataLayout &DL = M.getDataLayout();
366 AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
367 GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
368 ConstGlobalsPtrTy = Int8Ty->getPointerTo(
369 C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
370 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
372 // Build C++20 Module initializers.
373 // TODO: Add Microsoft here once we know the mangling required for the
374 // initializers.
375 CXX20ModuleInits =
376 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
377 ItaniumMangleContext::MK_Itanium;
379 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
381 if (LangOpts.ObjC)
382 createObjCRuntime();
383 if (LangOpts.OpenCL)
384 createOpenCLRuntime();
385 if (LangOpts.OpenMP)
386 createOpenMPRuntime();
387 if (LangOpts.CUDA)
388 createCUDARuntime();
389 if (LangOpts.HLSL)
390 createHLSLRuntime();
392 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
393 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
394 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
395 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
396 getCXXABI().getMangleContext()));
398 // If debug info or coverage generation is enabled, create the CGDebugInfo
399 // object.
400 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
401 CodeGenOpts.CoverageNotesFile.size() ||
402 CodeGenOpts.CoverageDataFile.size())
403 DebugInfo.reset(new CGDebugInfo(*this));
405 Block.GlobalUniqueCount = 0;
407 if (C.getLangOpts().ObjC)
408 ObjCData.reset(new ObjCEntrypoints());
410 if (CodeGenOpts.hasProfileClangUse()) {
411 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
412 CodeGenOpts.ProfileInstrumentUsePath, *FS,
413 CodeGenOpts.ProfileRemappingFile);
414 // We're checking for profile read errors in CompilerInvocation, so if
415 // there was an error it should've already been caught. If it hasn't been
416 // somehow, trip an assertion.
417 assert(ReaderOrErr);
418 PGOReader = std::move(ReaderOrErr.get());
421 // If coverage mapping generation is enabled, create the
422 // CoverageMappingModuleGen object.
423 if (CodeGenOpts.CoverageMapping)
424 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
426 // Generate the module name hash here if needed.
427 if (CodeGenOpts.UniqueInternalLinkageNames &&
428 !getModule().getSourceFileName().empty()) {
429 std::string Path = getModule().getSourceFileName();
430 // Check if a path substitution is needed from the MacroPrefixMap.
431 for (const auto &Entry : LangOpts.MacroPrefixMap)
432 if (Path.rfind(Entry.first, 0) != std::string::npos) {
433 Path = Entry.second + Path.substr(Entry.first.size());
434 break;
436 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
440 CodeGenModule::~CodeGenModule() {}
442 void CodeGenModule::createObjCRuntime() {
443 // This is just isGNUFamily(), but we want to force implementors of
444 // new ABIs to decide how best to do this.
445 switch (LangOpts.ObjCRuntime.getKind()) {
446 case ObjCRuntime::GNUstep:
447 case ObjCRuntime::GCC:
448 case ObjCRuntime::ObjFW:
449 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
450 return;
452 case ObjCRuntime::FragileMacOSX:
453 case ObjCRuntime::MacOSX:
454 case ObjCRuntime::iOS:
455 case ObjCRuntime::WatchOS:
456 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
457 return;
459 llvm_unreachable("bad runtime kind");
462 void CodeGenModule::createOpenCLRuntime() {
463 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
466 void CodeGenModule::createOpenMPRuntime() {
467 // Select a specialized code generation class based on the target, if any.
468 // If it does not exist use the default implementation.
469 switch (getTriple().getArch()) {
470 case llvm::Triple::nvptx:
471 case llvm::Triple::nvptx64:
472 case llvm::Triple::amdgcn:
473 assert(getLangOpts().OpenMPIsTargetDevice &&
474 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
475 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
476 break;
477 default:
478 if (LangOpts.OpenMPSimd)
479 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
480 else
481 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
482 break;
486 void CodeGenModule::createCUDARuntime() {
487 CUDARuntime.reset(CreateNVCUDARuntime(*this));
490 void CodeGenModule::createHLSLRuntime() {
491 HLSLRuntime.reset(new CGHLSLRuntime(*this));
494 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
495 Replacements[Name] = C;
498 void CodeGenModule::applyReplacements() {
499 for (auto &I : Replacements) {
500 StringRef MangledName = I.first;
501 llvm::Constant *Replacement = I.second;
502 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
503 if (!Entry)
504 continue;
505 auto *OldF = cast<llvm::Function>(Entry);
506 auto *NewF = dyn_cast<llvm::Function>(Replacement);
507 if (!NewF) {
508 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
509 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
510 } else {
511 auto *CE = cast<llvm::ConstantExpr>(Replacement);
512 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
513 CE->getOpcode() == llvm::Instruction::GetElementPtr);
514 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
518 // Replace old with new, but keep the old order.
519 OldF->replaceAllUsesWith(Replacement);
520 if (NewF) {
521 NewF->removeFromParent();
522 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
523 NewF);
525 OldF->eraseFromParent();
529 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
530 GlobalValReplacements.push_back(std::make_pair(GV, C));
533 void CodeGenModule::applyGlobalValReplacements() {
534 for (auto &I : GlobalValReplacements) {
535 llvm::GlobalValue *GV = I.first;
536 llvm::Constant *C = I.second;
538 GV->replaceAllUsesWith(C);
539 GV->eraseFromParent();
543 // This is only used in aliases that we created and we know they have a
544 // linear structure.
545 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
546 const llvm::Constant *C;
547 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
548 C = GA->getAliasee();
549 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
550 C = GI->getResolver();
551 else
552 return GV;
554 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
555 if (!AliaseeGV)
556 return nullptr;
558 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
559 if (FinalGV == GV)
560 return nullptr;
562 return FinalGV;
565 static bool checkAliasedGlobal(
566 DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc,
567 const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
568 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
569 SourceRange AliasRange) {
570 GV = getAliasedGlobal(Alias);
571 if (!GV) {
572 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
573 return false;
576 if (GV->isDeclaration()) {
577 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
578 Diags.Report(Location, diag::note_alias_requires_mangled_name)
579 << IsIFunc << IsIFunc;
580 // Provide a note if the given function is not found and exists as a
581 // mangled name.
582 for (const auto &[Decl, Name] : MangledDeclNames) {
583 if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
584 if (ND->getName() == GV->getName()) {
585 Diags.Report(Location, diag::note_alias_mangled_name_alternative)
586 << Name
587 << FixItHint::CreateReplacement(
588 AliasRange,
589 (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
590 .str());
594 return false;
597 if (IsIFunc) {
598 // Check resolver function type.
599 const auto *F = dyn_cast<llvm::Function>(GV);
600 if (!F) {
601 Diags.Report(Location, diag::err_alias_to_undefined)
602 << IsIFunc << IsIFunc;
603 return false;
606 llvm::FunctionType *FTy = F->getFunctionType();
607 if (!FTy->getReturnType()->isPointerTy()) {
608 Diags.Report(Location, diag::err_ifunc_resolver_return);
609 return false;
613 return true;
616 void CodeGenModule::checkAliases() {
617 // Check if the constructed aliases are well formed. It is really unfortunate
618 // that we have to do this in CodeGen, but we only construct mangled names
619 // and aliases during codegen.
620 bool Error = false;
621 DiagnosticsEngine &Diags = getDiags();
622 for (const GlobalDecl &GD : Aliases) {
623 const auto *D = cast<ValueDecl>(GD.getDecl());
624 SourceLocation Location;
625 SourceRange Range;
626 bool IsIFunc = D->hasAttr<IFuncAttr>();
627 if (const Attr *A = D->getDefiningAttr()) {
628 Location = A->getLocation();
629 Range = A->getRange();
630 } else
631 llvm_unreachable("Not an alias or ifunc?");
633 StringRef MangledName = getMangledName(GD);
634 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
635 const llvm::GlobalValue *GV = nullptr;
636 if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV,
637 MangledDeclNames, Range)) {
638 Error = true;
639 continue;
642 llvm::Constant *Aliasee =
643 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
644 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
646 llvm::GlobalValue *AliaseeGV;
647 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
648 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
649 else
650 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
652 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
653 StringRef AliasSection = SA->getName();
654 if (AliasSection != AliaseeGV->getSection())
655 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
656 << AliasSection << IsIFunc << IsIFunc;
659 // We have to handle alias to weak aliases in here. LLVM itself disallows
660 // this since the object semantics would not match the IL one. For
661 // compatibility with gcc we implement it by just pointing the alias
662 // to its aliasee's aliasee. We also warn, since the user is probably
663 // expecting the link to be weak.
664 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
665 if (GA->isInterposable()) {
666 Diags.Report(Location, diag::warn_alias_to_weak_alias)
667 << GV->getName() << GA->getName() << IsIFunc;
668 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
669 GA->getAliasee(), Alias->getType());
671 if (IsIFunc)
672 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
673 else
674 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
678 if (!Error)
679 return;
681 for (const GlobalDecl &GD : Aliases) {
682 StringRef MangledName = getMangledName(GD);
683 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
684 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
685 Alias->eraseFromParent();
689 void CodeGenModule::clear() {
690 DeferredDeclsToEmit.clear();
691 EmittedDeferredDecls.clear();
692 if (OpenMPRuntime)
693 OpenMPRuntime->clear();
696 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
697 StringRef MainFile) {
698 if (!hasDiagnostics())
699 return;
700 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
701 if (MainFile.empty())
702 MainFile = "<stdin>";
703 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
704 } else {
705 if (Mismatched > 0)
706 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
708 if (Missing > 0)
709 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
713 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
714 llvm::Module &M) {
715 if (!LO.VisibilityFromDLLStorageClass)
716 return;
718 llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
719 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
720 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
721 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
722 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
723 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
724 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
725 CodeGenModule::GetLLVMVisibility(
726 LO.getExternDeclNoDLLStorageClassVisibility());
728 for (llvm::GlobalValue &GV : M.global_values()) {
729 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
730 continue;
732 // Reset DSO locality before setting the visibility. This removes
733 // any effects that visibility options and annotations may have
734 // had on the DSO locality. Setting the visibility will implicitly set
735 // appropriate globals to DSO Local; however, this will be pessimistic
736 // w.r.t. to the normal compiler IRGen.
737 GV.setDSOLocal(false);
739 if (GV.isDeclarationForLinker()) {
740 GV.setVisibility(GV.getDLLStorageClass() ==
741 llvm::GlobalValue::DLLImportStorageClass
742 ? ExternDeclDLLImportVisibility
743 : ExternDeclNoDLLStorageClassVisibility);
744 } else {
745 GV.setVisibility(GV.getDLLStorageClass() ==
746 llvm::GlobalValue::DLLExportStorageClass
747 ? DLLExportVisibility
748 : NoDLLStorageClassVisibility);
751 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
755 void CodeGenModule::Release() {
756 Module *Primary = getContext().getCurrentNamedModule();
757 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
758 EmitModuleInitializers(Primary);
759 EmitDeferred();
760 DeferredDecls.insert(EmittedDeferredDecls.begin(),
761 EmittedDeferredDecls.end());
762 EmittedDeferredDecls.clear();
763 EmitVTablesOpportunistically();
764 applyGlobalValReplacements();
765 applyReplacements();
766 emitMultiVersionFunctions();
768 if (Context.getLangOpts().IncrementalExtensions &&
769 GlobalTopLevelStmtBlockInFlight.first) {
770 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
771 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
772 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
775 // Module implementations are initialized the same way as a regular TU that
776 // imports one or more modules.
777 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
778 EmitCXXModuleInitFunc(Primary);
779 else
780 EmitCXXGlobalInitFunc();
781 EmitCXXGlobalCleanUpFunc();
782 registerGlobalDtorsWithAtExit();
783 EmitCXXThreadLocalInitFunc();
784 if (ObjCRuntime)
785 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
786 AddGlobalCtor(ObjCInitFunction);
787 if (Context.getLangOpts().CUDA && CUDARuntime) {
788 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
789 AddGlobalCtor(CudaCtorFunction);
791 if (OpenMPRuntime) {
792 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
793 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
794 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
796 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
797 OpenMPRuntime->clear();
799 if (PGOReader) {
800 getModule().setProfileSummary(
801 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
802 llvm::ProfileSummary::PSK_Instr);
803 if (PGOStats.hasDiagnostics())
804 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
806 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
807 return L.LexOrder < R.LexOrder;
809 EmitCtorList(GlobalCtors, "llvm.global_ctors");
810 EmitCtorList(GlobalDtors, "llvm.global_dtors");
811 EmitGlobalAnnotations();
812 EmitStaticExternCAliases();
813 checkAliases();
814 EmitDeferredUnusedCoverageMappings();
815 CodeGenPGO(*this).setValueProfilingFlag(getModule());
816 if (CoverageMapping)
817 CoverageMapping->emit();
818 if (CodeGenOpts.SanitizeCfiCrossDso) {
819 CodeGenFunction(*this).EmitCfiCheckFail();
820 CodeGenFunction(*this).EmitCfiCheckStub();
822 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
823 finalizeKCFITypes();
824 emitAtAvailableLinkGuard();
825 if (Context.getTargetInfo().getTriple().isWasm())
826 EmitMainVoidAlias();
828 if (getTriple().isAMDGPU()) {
829 // Emit amdgpu_code_object_version module flag, which is code object version
830 // times 100.
831 if (getTarget().getTargetOpts().CodeObjectVersion !=
832 TargetOptions::COV_None) {
833 getModule().addModuleFlag(llvm::Module::Error,
834 "amdgpu_code_object_version",
835 getTarget().getTargetOpts().CodeObjectVersion);
838 // Currently, "-mprintf-kind" option is only supported for HIP
839 if (LangOpts.HIP) {
840 auto *MDStr = llvm::MDString::get(
841 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
842 TargetOptions::AMDGPUPrintfKind::Hostcall)
843 ? "hostcall"
844 : "buffered");
845 getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
846 MDStr);
850 // Emit a global array containing all external kernels or device variables
851 // used by host functions and mark it as used for CUDA/HIP. This is necessary
852 // to get kernels or device variables in archives linked in even if these
853 // kernels or device variables are only used in host functions.
854 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
855 SmallVector<llvm::Constant *, 8> UsedArray;
856 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
857 GlobalDecl GD;
858 if (auto *FD = dyn_cast<FunctionDecl>(D))
859 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
860 else
861 GD = GlobalDecl(D);
862 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
863 GetAddrOfGlobal(GD), Int8PtrTy));
866 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
868 auto *GV = new llvm::GlobalVariable(
869 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
870 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
871 addCompilerUsedGlobal(GV);
874 emitLLVMUsed();
875 if (SanStats)
876 SanStats->finish();
878 if (CodeGenOpts.Autolink &&
879 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
880 EmitModuleLinkOptions();
883 // On ELF we pass the dependent library specifiers directly to the linker
884 // without manipulating them. This is in contrast to other platforms where
885 // they are mapped to a specific linker option by the compiler. This
886 // difference is a result of the greater variety of ELF linkers and the fact
887 // that ELF linkers tend to handle libraries in a more complicated fashion
888 // than on other platforms. This forces us to defer handling the dependent
889 // libs to the linker.
891 // CUDA/HIP device and host libraries are different. Currently there is no
892 // way to differentiate dependent libraries for host or device. Existing
893 // usage of #pragma comment(lib, *) is intended for host libraries on
894 // Windows. Therefore emit llvm.dependent-libraries only for host.
895 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
896 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
897 for (auto *MD : ELFDependentLibraries)
898 NMD->addOperand(MD);
901 // Record mregparm value now so it is visible through rest of codegen.
902 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
903 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
904 CodeGenOpts.NumRegisterParameters);
906 if (CodeGenOpts.DwarfVersion) {
907 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
908 CodeGenOpts.DwarfVersion);
911 if (CodeGenOpts.Dwarf64)
912 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
914 if (Context.getLangOpts().SemanticInterposition)
915 // Require various optimization to respect semantic interposition.
916 getModule().setSemanticInterposition(true);
918 if (CodeGenOpts.EmitCodeView) {
919 // Indicate that we want CodeView in the metadata.
920 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
922 if (CodeGenOpts.CodeViewGHash) {
923 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
925 if (CodeGenOpts.ControlFlowGuard) {
926 // Function ID tables and checks for Control Flow Guard (cfguard=2).
927 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
928 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
929 // Function ID tables for Control Flow Guard (cfguard=1).
930 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
932 if (CodeGenOpts.EHContGuard) {
933 // Function ID tables for EH Continuation Guard.
934 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
936 if (Context.getLangOpts().Kernel) {
937 // Note if we are compiling with /kernel.
938 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
940 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
941 // We don't support LTO with 2 with different StrictVTablePointers
942 // FIXME: we could support it by stripping all the information introduced
943 // by StrictVTablePointers.
945 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
947 llvm::Metadata *Ops[2] = {
948 llvm::MDString::get(VMContext, "StrictVTablePointers"),
949 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
950 llvm::Type::getInt32Ty(VMContext), 1))};
952 getModule().addModuleFlag(llvm::Module::Require,
953 "StrictVTablePointersRequirement",
954 llvm::MDNode::get(VMContext, Ops));
956 if (getModuleDebugInfo())
957 // We support a single version in the linked module. The LLVM
958 // parser will drop debug info with a different version number
959 // (and warn about it, too).
960 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
961 llvm::DEBUG_METADATA_VERSION);
963 // We need to record the widths of enums and wchar_t, so that we can generate
964 // the correct build attributes in the ARM backend. wchar_size is also used by
965 // TargetLibraryInfo.
966 uint64_t WCharWidth =
967 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
968 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
970 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
971 if ( Arch == llvm::Triple::arm
972 || Arch == llvm::Triple::armeb
973 || Arch == llvm::Triple::thumb
974 || Arch == llvm::Triple::thumbeb) {
975 // The minimum width of an enum in bytes
976 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
977 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
980 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
981 StringRef ABIStr = Target.getABI();
982 llvm::LLVMContext &Ctx = TheModule.getContext();
983 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
984 llvm::MDString::get(Ctx, ABIStr));
987 if (CodeGenOpts.SanitizeCfiCrossDso) {
988 // Indicate that we want cross-DSO control flow integrity checks.
989 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
992 if (CodeGenOpts.WholeProgramVTables) {
993 // Indicate whether VFE was enabled for this module, so that the
994 // vcall_visibility metadata added under whole program vtables is handled
995 // appropriately in the optimizer.
996 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
997 CodeGenOpts.VirtualFunctionElimination);
1000 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1001 getModule().addModuleFlag(llvm::Module::Override,
1002 "CFI Canonical Jump Tables",
1003 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1006 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1007 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1008 // KCFI assumes patchable-function-prefix is the same for all indirectly
1009 // called functions. Store the expected offset for code generation.
1010 if (CodeGenOpts.PatchableFunctionEntryOffset)
1011 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1012 CodeGenOpts.PatchableFunctionEntryOffset);
1015 if (CodeGenOpts.CFProtectionReturn &&
1016 Target.checkCFProtectionReturnSupported(getDiags())) {
1017 // Indicate that we want to instrument return control flow protection.
1018 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
1022 if (CodeGenOpts.CFProtectionBranch &&
1023 Target.checkCFProtectionBranchSupported(getDiags())) {
1024 // Indicate that we want to instrument branch control flow protection.
1025 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
1029 if (CodeGenOpts.FunctionReturnThunks)
1030 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
1032 if (CodeGenOpts.IndirectBranchCSPrefix)
1033 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1035 // Add module metadata for return address signing (ignoring
1036 // non-leaf/all) and stack tagging. These are actually turned on by function
1037 // attributes, but we use module metadata to emit build attributes. This is
1038 // needed for LTO, where the function attributes are inside bitcode
1039 // serialised into a global variable by the time build attributes are
1040 // emitted, so we can't access them. LTO objects could be compiled with
1041 // different flags therefore module flags are set to "Min" behavior to achieve
1042 // the same end result of the normal build where e.g BTI is off if any object
1043 // doesn't support it.
1044 if (Context.getTargetInfo().hasFeature("ptrauth") &&
1045 LangOpts.getSignReturnAddressScope() !=
1046 LangOptions::SignReturnAddressScopeKind::None)
1047 getModule().addModuleFlag(llvm::Module::Override,
1048 "sign-return-address-buildattr", 1);
1049 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1050 getModule().addModuleFlag(llvm::Module::Override,
1051 "tag-stack-memory-buildattr", 1);
1053 if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
1054 Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
1055 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
1056 Arch == llvm::Triple::aarch64_be) {
1057 if (LangOpts.BranchTargetEnforcement)
1058 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1060 if (LangOpts.hasSignReturnAddress())
1061 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1062 if (LangOpts.isSignReturnAddressScopeAll())
1063 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1065 if (!LangOpts.isSignReturnAddressWithAKey())
1066 getModule().addModuleFlag(llvm::Module::Min,
1067 "sign-return-address-with-bkey", 1);
1070 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1071 llvm::LLVMContext &Ctx = TheModule.getContext();
1072 getModule().addModuleFlag(
1073 llvm::Module::Error, "MemProfProfileFilename",
1074 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1077 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
1078 // Indicate whether __nvvm_reflect should be configured to flush denormal
1079 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
1080 // property.)
1081 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
1082 CodeGenOpts.FP32DenormalMode.Output !=
1083 llvm::DenormalMode::IEEE);
1086 if (LangOpts.EHAsynch)
1087 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1089 // Indicate whether this Module was compiled with -fopenmp
1090 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1091 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
1092 if (getLangOpts().OpenMPIsTargetDevice)
1093 getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1094 LangOpts.OpenMP);
1096 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
1097 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
1098 EmitOpenCLMetadata();
1099 // Emit SPIR version.
1100 if (getTriple().isSPIR()) {
1101 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
1102 // opencl.spir.version named metadata.
1103 // C++ for OpenCL has a distinct mapping for version compatibility with
1104 // OpenCL.
1105 auto Version = LangOpts.getOpenCLCompatibleVersion();
1106 llvm::Metadata *SPIRVerElts[] = {
1107 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1108 Int32Ty, Version / 100)),
1109 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1110 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1111 llvm::NamedMDNode *SPIRVerMD =
1112 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
1113 llvm::LLVMContext &Ctx = TheModule.getContext();
1114 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1118 // HLSL related end of code gen work items.
1119 if (LangOpts.HLSL)
1120 getHLSLRuntime().finishCodeGen();
1122 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1123 assert(PLevel < 3 && "Invalid PIC Level");
1124 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
1125 if (Context.getLangOpts().PIE)
1126 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
1129 if (getCodeGenOpts().CodeModel.size() > 0) {
1130 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
1131 .Case("tiny", llvm::CodeModel::Tiny)
1132 .Case("small", llvm::CodeModel::Small)
1133 .Case("kernel", llvm::CodeModel::Kernel)
1134 .Case("medium", llvm::CodeModel::Medium)
1135 .Case("large", llvm::CodeModel::Large)
1136 .Default(~0u);
1137 if (CM != ~0u) {
1138 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
1139 getModule().setCodeModel(codeModel);
1143 if (CodeGenOpts.NoPLT)
1144 getModule().setRtLibUseGOT();
1145 if (getTriple().isOSBinFormatELF() &&
1146 CodeGenOpts.DirectAccessExternalData !=
1147 getModule().getDirectAccessExternalData()) {
1148 getModule().setDirectAccessExternalData(
1149 CodeGenOpts.DirectAccessExternalData);
1151 if (CodeGenOpts.UnwindTables)
1152 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1154 switch (CodeGenOpts.getFramePointer()) {
1155 case CodeGenOptions::FramePointerKind::None:
1156 // 0 ("none") is the default.
1157 break;
1158 case CodeGenOptions::FramePointerKind::NonLeaf:
1159 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1160 break;
1161 case CodeGenOptions::FramePointerKind::All:
1162 getModule().setFramePointer(llvm::FramePointerKind::All);
1163 break;
1166 SimplifyPersonality();
1168 if (getCodeGenOpts().EmitDeclMetadata)
1169 EmitDeclMetadata();
1171 if (getCodeGenOpts().CoverageNotesFile.size() ||
1172 getCodeGenOpts().CoverageDataFile.size())
1173 EmitCoverageFile();
1175 if (CGDebugInfo *DI = getModuleDebugInfo())
1176 DI->finalize();
1178 if (getCodeGenOpts().EmitVersionIdentMetadata)
1179 EmitVersionIdentMetadata();
1181 if (!getCodeGenOpts().RecordCommandLine.empty())
1182 EmitCommandLineMetadata();
1184 if (!getCodeGenOpts().StackProtectorGuard.empty())
1185 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1186 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1187 getModule().setStackProtectorGuardReg(
1188 getCodeGenOpts().StackProtectorGuardReg);
1189 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1190 getModule().setStackProtectorGuardSymbol(
1191 getCodeGenOpts().StackProtectorGuardSymbol);
1192 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1193 getModule().setStackProtectorGuardOffset(
1194 getCodeGenOpts().StackProtectorGuardOffset);
1195 if (getCodeGenOpts().StackAlignment)
1196 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1197 if (getCodeGenOpts().SkipRaxSetup)
1198 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1199 if (getLangOpts().RegCall4)
1200 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1202 if (getContext().getTargetInfo().getMaxTLSAlign())
1203 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1204 getContext().getTargetInfo().getMaxTLSAlign());
1206 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
1208 EmitBackendOptionsMetadata(getCodeGenOpts());
1210 // If there is device offloading code embed it in the host now.
1211 EmbedObject(&getModule(), CodeGenOpts, getDiags());
1213 // Set visibility from DLL storage class
1214 // We do this at the end of LLVM IR generation; after any operation
1215 // that might affect the DLL storage class or the visibility, and
1216 // before anything that might act on these.
1217 setVisibilityFromDLLStorageClass(LangOpts, getModule());
1220 void CodeGenModule::EmitOpenCLMetadata() {
1221 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1222 // opencl.ocl.version named metadata node.
1223 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
1224 auto Version = LangOpts.getOpenCLCompatibleVersion();
1225 llvm::Metadata *OCLVerElts[] = {
1226 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1227 Int32Ty, Version / 100)),
1228 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1229 Int32Ty, (Version % 100) / 10))};
1230 llvm::NamedMDNode *OCLVerMD =
1231 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
1232 llvm::LLVMContext &Ctx = TheModule.getContext();
1233 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1236 void CodeGenModule::EmitBackendOptionsMetadata(
1237 const CodeGenOptions &CodeGenOpts) {
1238 if (getTriple().isRISCV()) {
1239 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
1240 CodeGenOpts.SmallDataLimit);
1244 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
1245 // Make sure that this type is translated.
1246 Types.UpdateCompletedType(TD);
1249 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
1250 // Make sure that this type is translated.
1251 Types.RefreshTypeCacheForClass(RD);
1254 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
1255 if (!TBAA)
1256 return nullptr;
1257 return TBAA->getTypeInfo(QTy);
1260 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
1261 if (!TBAA)
1262 return TBAAAccessInfo();
1263 if (getLangOpts().CUDAIsDevice) {
1264 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1265 // access info.
1266 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1267 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1268 nullptr)
1269 return TBAAAccessInfo();
1270 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1271 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1272 nullptr)
1273 return TBAAAccessInfo();
1276 return TBAA->getAccessInfo(AccessType);
1279 TBAAAccessInfo
1280 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
1281 if (!TBAA)
1282 return TBAAAccessInfo();
1283 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1286 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
1287 if (!TBAA)
1288 return nullptr;
1289 return TBAA->getTBAAStructInfo(QTy);
1292 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
1293 if (!TBAA)
1294 return nullptr;
1295 return TBAA->getBaseTypeInfo(QTy);
1298 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
1299 if (!TBAA)
1300 return nullptr;
1301 return TBAA->getAccessTagInfo(Info);
1304 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
1305 TBAAAccessInfo TargetInfo) {
1306 if (!TBAA)
1307 return TBAAAccessInfo();
1308 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1311 TBAAAccessInfo
1312 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
1313 TBAAAccessInfo InfoB) {
1314 if (!TBAA)
1315 return TBAAAccessInfo();
1316 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1319 TBAAAccessInfo
1320 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
1321 TBAAAccessInfo SrcInfo) {
1322 if (!TBAA)
1323 return TBAAAccessInfo();
1324 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1327 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1328 TBAAAccessInfo TBAAInfo) {
1329 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1330 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1333 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1334 llvm::Instruction *I, const CXXRecordDecl *RD) {
1335 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1336 llvm::MDNode::get(getLLVMContext(), {}));
1339 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1340 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1341 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1344 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1345 /// specified stmt yet.
1346 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1347 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1348 "cannot compile this %0 yet");
1349 std::string Msg = Type;
1350 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1351 << Msg << S->getSourceRange();
1354 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1355 /// specified decl yet.
1356 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1357 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1358 "cannot compile this %0 yet");
1359 std::string Msg = Type;
1360 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1363 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1364 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1367 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1368 const NamedDecl *D) const {
1369 // Internal definitions always have default visibility.
1370 if (GV->hasLocalLinkage()) {
1371 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1372 return;
1374 if (!D)
1375 return;
1376 // Set visibility for definitions, and for declarations if requested globally
1377 // or set explicitly.
1378 LinkageInfo LV = D->getLinkageAndVisibility();
1379 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1380 // Reject incompatible dlllstorage and visibility annotations.
1381 if (!LV.isVisibilityExplicit())
1382 return;
1383 if (GV->hasDLLExportStorageClass()) {
1384 if (LV.getVisibility() == HiddenVisibility)
1385 getDiags().Report(D->getLocation(),
1386 diag::err_hidden_visibility_dllexport);
1387 } else if (LV.getVisibility() != DefaultVisibility) {
1388 getDiags().Report(D->getLocation(),
1389 diag::err_non_default_visibility_dllimport);
1391 return;
1394 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1395 !GV->isDeclarationForLinker())
1396 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1399 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
1400 llvm::GlobalValue *GV) {
1401 if (GV->hasLocalLinkage())
1402 return true;
1404 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1405 return true;
1407 // DLLImport explicitly marks the GV as external.
1408 if (GV->hasDLLImportStorageClass())
1409 return false;
1411 const llvm::Triple &TT = CGM.getTriple();
1412 if (TT.isWindowsGNUEnvironment()) {
1413 // In MinGW, variables without DLLImport can still be automatically
1414 // imported from a DLL by the linker; don't mark variables that
1415 // potentially could come from another DLL as DSO local.
1417 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1418 // (and this actually happens in the public interface of libstdc++), so
1419 // such variables can't be marked as DSO local. (Native TLS variables
1420 // can't be dllimported at all, though.)
1421 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1422 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
1423 return false;
1426 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1427 // remain unresolved in the link, they can be resolved to zero, which is
1428 // outside the current DSO.
1429 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1430 return false;
1432 // Every other GV is local on COFF.
1433 // Make an exception for windows OS in the triple: Some firmware builds use
1434 // *-win32-macho triples. This (accidentally?) produced windows relocations
1435 // without GOT tables in older clang versions; Keep this behaviour.
1436 // FIXME: even thread local variables?
1437 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1438 return true;
1440 // Only handle COFF and ELF for now.
1441 if (!TT.isOSBinFormatELF())
1442 return false;
1444 // If this is not an executable, don't assume anything is local.
1445 const auto &CGOpts = CGM.getCodeGenOpts();
1446 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1447 const auto &LOpts = CGM.getLangOpts();
1448 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1449 // On ELF, if -fno-semantic-interposition is specified and the target
1450 // supports local aliases, there will be neither CC1
1451 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1452 // dso_local on the function if using a local alias is preferable (can avoid
1453 // PLT indirection).
1454 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1455 return false;
1456 return !(CGM.getLangOpts().SemanticInterposition ||
1457 CGM.getLangOpts().HalfNoSemanticInterposition);
1460 // A definition cannot be preempted from an executable.
1461 if (!GV->isDeclarationForLinker())
1462 return true;
1464 // Most PIC code sequences that assume that a symbol is local cannot produce a
1465 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1466 // depended, it seems worth it to handle it here.
1467 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1468 return false;
1470 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1471 if (TT.isPPC64())
1472 return false;
1474 if (CGOpts.DirectAccessExternalData) {
1475 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1476 // for non-thread-local variables. If the symbol is not defined in the
1477 // executable, a copy relocation will be needed at link time. dso_local is
1478 // excluded for thread-local variables because they generally don't support
1479 // copy relocations.
1480 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1481 if (!Var->isThreadLocal())
1482 return true;
1484 // -fno-pic sets dso_local on a function declaration to allow direct
1485 // accesses when taking its address (similar to a data symbol). If the
1486 // function is not defined in the executable, a canonical PLT entry will be
1487 // needed at link time. -fno-direct-access-external-data can avoid the
1488 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1489 // it could just cause trouble without providing perceptible benefits.
1490 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1491 return true;
1494 // If we can use copy relocations we can assume it is local.
1496 // Otherwise don't assume it is local.
1497 return false;
1500 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1501 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1504 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1505 GlobalDecl GD) const {
1506 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1507 // C++ destructors have a few C++ ABI specific special cases.
1508 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1509 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1510 return;
1512 setDLLImportDLLExport(GV, D);
1515 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1516 const NamedDecl *D) const {
1517 if (D && D->isExternallyVisible()) {
1518 if (D->hasAttr<DLLImportAttr>())
1519 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1520 else if ((D->hasAttr<DLLExportAttr>() ||
1521 shouldMapVisibilityToDLLExport(D)) &&
1522 !GV->isDeclarationForLinker())
1523 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1527 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1528 GlobalDecl GD) const {
1529 setDLLImportDLLExport(GV, GD);
1530 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1533 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1534 const NamedDecl *D) const {
1535 setDLLImportDLLExport(GV, D);
1536 setGVPropertiesAux(GV, D);
1539 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1540 const NamedDecl *D) const {
1541 setGlobalVisibility(GV, D);
1542 setDSOLocal(GV);
1543 GV->setPartition(CodeGenOpts.SymbolPartition);
1546 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1547 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1548 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1549 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1550 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1551 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1554 llvm::GlobalVariable::ThreadLocalMode
1555 CodeGenModule::GetDefaultLLVMTLSModel() const {
1556 switch (CodeGenOpts.getDefaultTLSModel()) {
1557 case CodeGenOptions::GeneralDynamicTLSModel:
1558 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1559 case CodeGenOptions::LocalDynamicTLSModel:
1560 return llvm::GlobalVariable::LocalDynamicTLSModel;
1561 case CodeGenOptions::InitialExecTLSModel:
1562 return llvm::GlobalVariable::InitialExecTLSModel;
1563 case CodeGenOptions::LocalExecTLSModel:
1564 return llvm::GlobalVariable::LocalExecTLSModel;
1566 llvm_unreachable("Invalid TLS model!");
1569 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1570 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1572 llvm::GlobalValue::ThreadLocalMode TLM;
1573 TLM = GetDefaultLLVMTLSModel();
1575 // Override the TLS model if it is explicitly specified.
1576 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1577 TLM = GetLLVMTLSModel(Attr->getModel());
1580 GV->setThreadLocalMode(TLM);
1583 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1584 StringRef Name) {
1585 const TargetInfo &Target = CGM.getTarget();
1586 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1589 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1590 const CPUSpecificAttr *Attr,
1591 unsigned CPUIndex,
1592 raw_ostream &Out) {
1593 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1594 // supported.
1595 if (Attr)
1596 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1597 else if (CGM.getTarget().supportsIFunc())
1598 Out << ".resolver";
1601 static void AppendTargetVersionMangling(const CodeGenModule &CGM,
1602 const TargetVersionAttr *Attr,
1603 raw_ostream &Out) {
1604 if (Attr->isDefaultVersion())
1605 return;
1606 Out << "._";
1607 const TargetInfo &TI = CGM.getTarget();
1608 llvm::SmallVector<StringRef, 8> Feats;
1609 Attr->getFeatures(Feats);
1610 llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) {
1611 return TI.multiVersionSortPriority(FeatL) <
1612 TI.multiVersionSortPriority(FeatR);
1614 for (const auto &Feat : Feats) {
1615 Out << 'M';
1616 Out << Feat;
1620 static void AppendTargetMangling(const CodeGenModule &CGM,
1621 const TargetAttr *Attr, raw_ostream &Out) {
1622 if (Attr->isDefaultVersion())
1623 return;
1625 Out << '.';
1626 const TargetInfo &Target = CGM.getTarget();
1627 ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr());
1628 llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) {
1629 // Multiversioning doesn't allow "no-${feature}", so we can
1630 // only have "+" prefixes here.
1631 assert(LHS.startswith("+") && RHS.startswith("+") &&
1632 "Features should always have a prefix.");
1633 return Target.multiVersionSortPriority(LHS.substr(1)) >
1634 Target.multiVersionSortPriority(RHS.substr(1));
1637 bool IsFirst = true;
1639 if (!Info.CPU.empty()) {
1640 IsFirst = false;
1641 Out << "arch_" << Info.CPU;
1644 for (StringRef Feat : Info.Features) {
1645 if (!IsFirst)
1646 Out << '_';
1647 IsFirst = false;
1648 Out << Feat.substr(1);
1652 // Returns true if GD is a function decl with internal linkage and
1653 // needs a unique suffix after the mangled name.
1654 static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1655 CodeGenModule &CGM) {
1656 const Decl *D = GD.getDecl();
1657 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1658 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1661 static void AppendTargetClonesMangling(const CodeGenModule &CGM,
1662 const TargetClonesAttr *Attr,
1663 unsigned VersionIndex,
1664 raw_ostream &Out) {
1665 const TargetInfo &TI = CGM.getTarget();
1666 if (TI.getTriple().isAArch64()) {
1667 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1668 if (FeatureStr == "default")
1669 return;
1670 Out << "._";
1671 SmallVector<StringRef, 8> Features;
1672 FeatureStr.split(Features, "+");
1673 llvm::stable_sort(Features,
1674 [&TI](const StringRef FeatL, const StringRef FeatR) {
1675 return TI.multiVersionSortPriority(FeatL) <
1676 TI.multiVersionSortPriority(FeatR);
1678 for (auto &Feat : Features) {
1679 Out << 'M';
1680 Out << Feat;
1682 } else {
1683 Out << '.';
1684 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1685 if (FeatureStr.startswith("arch="))
1686 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
1687 else
1688 Out << FeatureStr;
1690 Out << '.' << Attr->getMangledIndex(VersionIndex);
1694 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1695 const NamedDecl *ND,
1696 bool OmitMultiVersionMangling = false) {
1697 SmallString<256> Buffer;
1698 llvm::raw_svector_ostream Out(Buffer);
1699 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1700 if (!CGM.getModuleNameHash().empty())
1701 MC.needsUniqueInternalLinkageNames();
1702 bool ShouldMangle = MC.shouldMangleDeclName(ND);
1703 if (ShouldMangle)
1704 MC.mangleName(GD.getWithDecl(ND), Out);
1705 else {
1706 IdentifierInfo *II = ND->getIdentifier();
1707 assert(II && "Attempt to mangle unnamed decl.");
1708 const auto *FD = dyn_cast<FunctionDecl>(ND);
1710 if (FD &&
1711 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1712 if (CGM.getLangOpts().RegCall4)
1713 Out << "__regcall4__" << II->getName();
1714 else
1715 Out << "__regcall3__" << II->getName();
1716 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1717 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1718 Out << "__device_stub__" << II->getName();
1719 } else {
1720 Out << II->getName();
1724 // Check if the module name hash should be appended for internal linkage
1725 // symbols. This should come before multi-version target suffixes are
1726 // appended. This is to keep the name and module hash suffix of the
1727 // internal linkage function together. The unique suffix should only be
1728 // added when name mangling is done to make sure that the final name can
1729 // be properly demangled. For example, for C functions without prototypes,
1730 // name mangling is not done and the unique suffix should not be appeneded
1731 // then.
1732 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1733 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1734 "Hash computed when not explicitly requested");
1735 Out << CGM.getModuleNameHash();
1738 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1739 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1740 switch (FD->getMultiVersionKind()) {
1741 case MultiVersionKind::CPUDispatch:
1742 case MultiVersionKind::CPUSpecific:
1743 AppendCPUSpecificCPUDispatchMangling(CGM,
1744 FD->getAttr<CPUSpecificAttr>(),
1745 GD.getMultiVersionIndex(), Out);
1746 break;
1747 case MultiVersionKind::Target:
1748 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1749 break;
1750 case MultiVersionKind::TargetVersion:
1751 AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out);
1752 break;
1753 case MultiVersionKind::TargetClones:
1754 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
1755 GD.getMultiVersionIndex(), Out);
1756 break;
1757 case MultiVersionKind::None:
1758 llvm_unreachable("None multiversion type isn't valid here");
1762 // Make unique name for device side static file-scope variable for HIP.
1763 if (CGM.getContext().shouldExternalize(ND) &&
1764 CGM.getLangOpts().GPURelocatableDeviceCode &&
1765 CGM.getLangOpts().CUDAIsDevice)
1766 CGM.printPostfixForExternalizedDecl(Out, ND);
1768 return std::string(Out.str());
1771 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1772 const FunctionDecl *FD,
1773 StringRef &CurName) {
1774 if (!FD->isMultiVersion())
1775 return;
1777 // Get the name of what this would be without the 'target' attribute. This
1778 // allows us to lookup the version that was emitted when this wasn't a
1779 // multiversion function.
1780 std::string NonTargetName =
1781 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1782 GlobalDecl OtherGD;
1783 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1784 assert(OtherGD.getCanonicalDecl()
1785 .getDecl()
1786 ->getAsFunction()
1787 ->isMultiVersion() &&
1788 "Other GD should now be a multiversioned function");
1789 // OtherFD is the version of this function that was mangled BEFORE
1790 // becoming a MultiVersion function. It potentially needs to be updated.
1791 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1792 .getDecl()
1793 ->getAsFunction()
1794 ->getMostRecentDecl();
1795 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1796 // This is so that if the initial version was already the 'default'
1797 // version, we don't try to update it.
1798 if (OtherName != NonTargetName) {
1799 // Remove instead of erase, since others may have stored the StringRef
1800 // to this.
1801 const auto ExistingRecord = Manglings.find(NonTargetName);
1802 if (ExistingRecord != std::end(Manglings))
1803 Manglings.remove(&(*ExistingRecord));
1804 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1805 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1806 Result.first->first();
1807 // If this is the current decl is being created, make sure we update the name.
1808 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1809 CurName = OtherNameRef;
1810 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1811 Entry->setName(OtherName);
1816 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1817 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1819 // Some ABIs don't have constructor variants. Make sure that base and
1820 // complete constructors get mangled the same.
1821 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1822 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1823 CXXCtorType OrigCtorType = GD.getCtorType();
1824 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1825 if (OrigCtorType == Ctor_Base)
1826 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1830 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1831 // static device variable depends on whether the variable is referenced by
1832 // a host or device host function. Therefore the mangled name cannot be
1833 // cached.
1834 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
1835 auto FoundName = MangledDeclNames.find(CanonicalGD);
1836 if (FoundName != MangledDeclNames.end())
1837 return FoundName->second;
1840 // Keep the first result in the case of a mangling collision.
1841 const auto *ND = cast<NamedDecl>(GD.getDecl());
1842 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1844 // Ensure either we have different ABIs between host and device compilations,
1845 // says host compilation following MSVC ABI but device compilation follows
1846 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1847 // mangling should be the same after name stubbing. The later checking is
1848 // very important as the device kernel name being mangled in host-compilation
1849 // is used to resolve the device binaries to be executed. Inconsistent naming
1850 // result in undefined behavior. Even though we cannot check that naming
1851 // directly between host- and device-compilations, the host- and
1852 // device-mangling in host compilation could help catching certain ones.
1853 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1854 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
1855 (getContext().getAuxTargetInfo() &&
1856 (getContext().getAuxTargetInfo()->getCXXABI() !=
1857 getContext().getTargetInfo().getCXXABI())) ||
1858 getCUDARuntime().getDeviceSideName(ND) ==
1859 getMangledNameImpl(
1860 *this,
1861 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1862 ND));
1864 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1865 return MangledDeclNames[CanonicalGD] = Result.first->first();
1868 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1869 const BlockDecl *BD) {
1870 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1871 const Decl *D = GD.getDecl();
1873 SmallString<256> Buffer;
1874 llvm::raw_svector_ostream Out(Buffer);
1875 if (!D)
1876 MangleCtx.mangleGlobalBlock(BD,
1877 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1878 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1879 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1880 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1881 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1882 else
1883 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1885 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1886 return Result.first->first();
1889 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
1890 auto it = MangledDeclNames.begin();
1891 while (it != MangledDeclNames.end()) {
1892 if (it->second == Name)
1893 return it->first;
1894 it++;
1896 return GlobalDecl();
1899 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1900 return getModule().getNamedValue(Name);
1903 /// AddGlobalCtor - Add a function to the list that will be called before
1904 /// main() runs.
1905 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1906 unsigned LexOrder,
1907 llvm::Constant *AssociatedData) {
1908 // FIXME: Type coercion of void()* types.
1909 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
1912 /// AddGlobalDtor - Add a function to the list that will be called
1913 /// when the module is unloaded.
1914 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1915 bool IsDtorAttrFunc) {
1916 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1917 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
1918 DtorsUsingAtExit[Priority].push_back(Dtor);
1919 return;
1922 // FIXME: Type coercion of void()* types.
1923 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
1926 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1927 if (Fns.empty()) return;
1929 // Ctor function type is void()*.
1930 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1931 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1932 TheModule.getDataLayout().getProgramAddressSpace());
1934 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1935 llvm::StructType *CtorStructTy = llvm::StructType::get(
1936 Int32Ty, CtorPFTy, VoidPtrTy);
1938 // Construct the constructor and destructor arrays.
1939 ConstantInitBuilder builder(*this);
1940 auto ctors = builder.beginArray(CtorStructTy);
1941 for (const auto &I : Fns) {
1942 auto ctor = ctors.beginStruct(CtorStructTy);
1943 ctor.addInt(Int32Ty, I.Priority);
1944 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1945 if (I.AssociatedData)
1946 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1947 else
1948 ctor.addNullPointer(VoidPtrTy);
1949 ctor.finishAndAddTo(ctors);
1952 auto list =
1953 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1954 /*constant*/ false,
1955 llvm::GlobalValue::AppendingLinkage);
1957 // The LTO linker doesn't seem to like it when we set an alignment
1958 // on appending variables. Take it off as a workaround.
1959 list->setAlignment(std::nullopt);
1961 Fns.clear();
1964 llvm::GlobalValue::LinkageTypes
1965 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1966 const auto *D = cast<FunctionDecl>(GD.getDecl());
1968 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1970 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1971 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1973 if (isa<CXXConstructorDecl>(D) &&
1974 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1975 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1976 // Our approach to inheriting constructors is fundamentally different from
1977 // that used by the MS ABI, so keep our inheriting constructor thunks
1978 // internal rather than trying to pick an unambiguous mangling for them.
1979 return llvm::GlobalValue::InternalLinkage;
1982 return getLLVMLinkageForDeclarator(D, Linkage);
1985 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1986 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1987 if (!MDS) return nullptr;
1989 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1992 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
1993 if (auto *FnType = T->getAs<FunctionProtoType>())
1994 T = getContext().getFunctionType(
1995 FnType->getReturnType(), FnType->getParamTypes(),
1996 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
1998 std::string OutName;
1999 llvm::raw_string_ostream Out(OutName);
2000 getCXXABI().getMangleContext().mangleTypeName(
2001 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2003 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2004 Out << ".normalized";
2006 return llvm::ConstantInt::get(Int32Ty,
2007 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2010 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
2011 const CGFunctionInfo &Info,
2012 llvm::Function *F, bool IsThunk) {
2013 unsigned CallingConv;
2014 llvm::AttributeList PAL;
2015 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2016 /*AttrOnCallSite=*/false, IsThunk);
2017 F->setAttributes(PAL);
2018 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2021 static void removeImageAccessQualifier(std::string& TyName) {
2022 std::string ReadOnlyQual("__read_only");
2023 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2024 if (ReadOnlyPos != std::string::npos)
2025 // "+ 1" for the space after access qualifier.
2026 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2027 else {
2028 std::string WriteOnlyQual("__write_only");
2029 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2030 if (WriteOnlyPos != std::string::npos)
2031 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2032 else {
2033 std::string ReadWriteQual("__read_write");
2034 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2035 if (ReadWritePos != std::string::npos)
2036 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2041 // Returns the address space id that should be produced to the
2042 // kernel_arg_addr_space metadata. This is always fixed to the ids
2043 // as specified in the SPIR 2.0 specification in order to differentiate
2044 // for example in clGetKernelArgInfo() implementation between the address
2045 // spaces with targets without unique mapping to the OpenCL address spaces
2046 // (basically all single AS CPUs).
2047 static unsigned ArgInfoAddressSpace(LangAS AS) {
2048 switch (AS) {
2049 case LangAS::opencl_global:
2050 return 1;
2051 case LangAS::opencl_constant:
2052 return 2;
2053 case LangAS::opencl_local:
2054 return 3;
2055 case LangAS::opencl_generic:
2056 return 4; // Not in SPIR 2.0 specs.
2057 case LangAS::opencl_global_device:
2058 return 5;
2059 case LangAS::opencl_global_host:
2060 return 6;
2061 default:
2062 return 0; // Assume private.
2066 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
2067 const FunctionDecl *FD,
2068 CodeGenFunction *CGF) {
2069 assert(((FD && CGF) || (!FD && !CGF)) &&
2070 "Incorrect use - FD and CGF should either be both null or not!");
2071 // Create MDNodes that represent the kernel arg metadata.
2072 // Each MDNode is a list in the form of "key", N number of values which is
2073 // the same number of values as their are kernel arguments.
2075 const PrintingPolicy &Policy = Context.getPrintingPolicy();
2077 // MDNode for the kernel argument address space qualifiers.
2078 SmallVector<llvm::Metadata *, 8> addressQuals;
2080 // MDNode for the kernel argument access qualifiers (images only).
2081 SmallVector<llvm::Metadata *, 8> accessQuals;
2083 // MDNode for the kernel argument type names.
2084 SmallVector<llvm::Metadata *, 8> argTypeNames;
2086 // MDNode for the kernel argument base type names.
2087 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2089 // MDNode for the kernel argument type qualifiers.
2090 SmallVector<llvm::Metadata *, 8> argTypeQuals;
2092 // MDNode for the kernel argument names.
2093 SmallVector<llvm::Metadata *, 8> argNames;
2095 if (FD && CGF)
2096 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2097 const ParmVarDecl *parm = FD->getParamDecl(i);
2098 // Get argument name.
2099 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2101 if (!getLangOpts().OpenCL)
2102 continue;
2103 QualType ty = parm->getType();
2104 std::string typeQuals;
2106 // Get image and pipe access qualifier:
2107 if (ty->isImageType() || ty->isPipeType()) {
2108 const Decl *PDecl = parm;
2109 if (const auto *TD = ty->getAs<TypedefType>())
2110 PDecl = TD->getDecl();
2111 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2112 if (A && A->isWriteOnly())
2113 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2114 else if (A && A->isReadWrite())
2115 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2116 else
2117 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2118 } else
2119 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2121 auto getTypeSpelling = [&](QualType Ty) {
2122 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2124 if (Ty.isCanonical()) {
2125 StringRef typeNameRef = typeName;
2126 // Turn "unsigned type" to "utype"
2127 if (typeNameRef.consume_front("unsigned "))
2128 return std::string("u") + typeNameRef.str();
2129 if (typeNameRef.consume_front("signed "))
2130 return typeNameRef.str();
2133 return typeName;
2136 if (ty->isPointerType()) {
2137 QualType pointeeTy = ty->getPointeeType();
2139 // Get address qualifier.
2140 addressQuals.push_back(
2141 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2142 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2144 // Get argument type name.
2145 std::string typeName = getTypeSpelling(pointeeTy) + "*";
2146 std::string baseTypeName =
2147 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2148 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2149 argBaseTypeNames.push_back(
2150 llvm::MDString::get(VMContext, baseTypeName));
2152 // Get argument type qualifiers:
2153 if (ty.isRestrictQualified())
2154 typeQuals = "restrict";
2155 if (pointeeTy.isConstQualified() ||
2156 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
2157 typeQuals += typeQuals.empty() ? "const" : " const";
2158 if (pointeeTy.isVolatileQualified())
2159 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2160 } else {
2161 uint32_t AddrSpc = 0;
2162 bool isPipe = ty->isPipeType();
2163 if (ty->isImageType() || isPipe)
2164 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
2166 addressQuals.push_back(
2167 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2169 // Get argument type name.
2170 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2171 std::string typeName = getTypeSpelling(ty);
2172 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2174 // Remove access qualifiers on images
2175 // (as they are inseparable from type in clang implementation,
2176 // but OpenCL spec provides a special query to get access qualifier
2177 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2178 if (ty->isImageType()) {
2179 removeImageAccessQualifier(typeName);
2180 removeImageAccessQualifier(baseTypeName);
2183 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2184 argBaseTypeNames.push_back(
2185 llvm::MDString::get(VMContext, baseTypeName));
2187 if (isPipe)
2188 typeQuals = "pipe";
2190 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2193 if (getLangOpts().OpenCL) {
2194 Fn->setMetadata("kernel_arg_addr_space",
2195 llvm::MDNode::get(VMContext, addressQuals));
2196 Fn->setMetadata("kernel_arg_access_qual",
2197 llvm::MDNode::get(VMContext, accessQuals));
2198 Fn->setMetadata("kernel_arg_type",
2199 llvm::MDNode::get(VMContext, argTypeNames));
2200 Fn->setMetadata("kernel_arg_base_type",
2201 llvm::MDNode::get(VMContext, argBaseTypeNames));
2202 Fn->setMetadata("kernel_arg_type_qual",
2203 llvm::MDNode::get(VMContext, argTypeQuals));
2205 if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2206 getCodeGenOpts().HIPSaveKernelArgName)
2207 Fn->setMetadata("kernel_arg_name",
2208 llvm::MDNode::get(VMContext, argNames));
2211 /// Determines whether the language options require us to model
2212 /// unwind exceptions. We treat -fexceptions as mandating this
2213 /// except under the fragile ObjC ABI with only ObjC exceptions
2214 /// enabled. This means, for example, that C with -fexceptions
2215 /// enables this.
2216 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2217 // If exceptions are completely disabled, obviously this is false.
2218 if (!LangOpts.Exceptions) return false;
2220 // If C++ exceptions are enabled, this is true.
2221 if (LangOpts.CXXExceptions) return true;
2223 // If ObjC exceptions are enabled, this depends on the ABI.
2224 if (LangOpts.ObjCExceptions) {
2225 return LangOpts.ObjCRuntime.hasUnwindExceptions();
2228 return true;
2231 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
2232 const CXXMethodDecl *MD) {
2233 // Check that the type metadata can ever actually be used by a call.
2234 if (!CGM.getCodeGenOpts().LTOUnit ||
2235 !CGM.HasHiddenLTOVisibility(MD->getParent()))
2236 return false;
2238 // Only functions whose address can be taken with a member function pointer
2239 // need this sort of type metadata.
2240 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
2241 !isa<CXXDestructorDecl>(MD);
2244 SmallVector<const CXXRecordDecl *, 0>
2245 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
2246 llvm::SetVector<const CXXRecordDecl *> MostBases;
2248 std::function<void (const CXXRecordDecl *)> CollectMostBases;
2249 CollectMostBases = [&](const CXXRecordDecl *RD) {
2250 if (RD->getNumBases() == 0)
2251 MostBases.insert(RD);
2252 for (const CXXBaseSpecifier &B : RD->bases())
2253 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2255 CollectMostBases(RD);
2256 return MostBases.takeVector();
2259 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2260 llvm::Function *F) {
2261 llvm::AttrBuilder B(F->getContext());
2263 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2264 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2266 if (CodeGenOpts.StackClashProtector)
2267 B.addAttribute("probe-stack", "inline-asm");
2269 if (!hasUnwindExceptions(LangOpts))
2270 B.addAttribute(llvm::Attribute::NoUnwind);
2272 if (D && D->hasAttr<NoStackProtectorAttr>())
2273 ; // Do nothing.
2274 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2275 LangOpts.getStackProtector() == LangOptions::SSPOn)
2276 B.addAttribute(llvm::Attribute::StackProtectStrong);
2277 else if (LangOpts.getStackProtector() == LangOptions::SSPOn)
2278 B.addAttribute(llvm::Attribute::StackProtect);
2279 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
2280 B.addAttribute(llvm::Attribute::StackProtectStrong);
2281 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
2282 B.addAttribute(llvm::Attribute::StackProtectReq);
2284 if (!D) {
2285 // If we don't have a declaration to control inlining, the function isn't
2286 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2287 // disabled, mark the function as noinline.
2288 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2289 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2290 B.addAttribute(llvm::Attribute::NoInline);
2292 F->addFnAttrs(B);
2293 return;
2296 // Handle SME attributes that apply to function definitions,
2297 // rather than to function prototypes.
2298 if (D->hasAttr<ArmLocallyStreamingAttr>())
2299 B.addAttribute("aarch64_pstate_sm_body");
2301 if (D->hasAttr<ArmNewZAAttr>())
2302 B.addAttribute("aarch64_pstate_za_new");
2304 // Track whether we need to add the optnone LLVM attribute,
2305 // starting with the default for this optimization level.
2306 bool ShouldAddOptNone =
2307 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2308 // We can't add optnone in the following cases, it won't pass the verifier.
2309 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2310 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2312 // Add optnone, but do so only if the function isn't always_inline.
2313 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2314 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2315 B.addAttribute(llvm::Attribute::OptimizeNone);
2317 // OptimizeNone implies noinline; we should not be inlining such functions.
2318 B.addAttribute(llvm::Attribute::NoInline);
2320 // We still need to handle naked functions even though optnone subsumes
2321 // much of their semantics.
2322 if (D->hasAttr<NakedAttr>())
2323 B.addAttribute(llvm::Attribute::Naked);
2325 // OptimizeNone wins over OptimizeForSize and MinSize.
2326 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2327 F->removeFnAttr(llvm::Attribute::MinSize);
2328 } else if (D->hasAttr<NakedAttr>()) {
2329 // Naked implies noinline: we should not be inlining such functions.
2330 B.addAttribute(llvm::Attribute::Naked);
2331 B.addAttribute(llvm::Attribute::NoInline);
2332 } else if (D->hasAttr<NoDuplicateAttr>()) {
2333 B.addAttribute(llvm::Attribute::NoDuplicate);
2334 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2335 // Add noinline if the function isn't always_inline.
2336 B.addAttribute(llvm::Attribute::NoInline);
2337 } else if (D->hasAttr<AlwaysInlineAttr>() &&
2338 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2339 // (noinline wins over always_inline, and we can't specify both in IR)
2340 B.addAttribute(llvm::Attribute::AlwaysInline);
2341 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2342 // If we're not inlining, then force everything that isn't always_inline to
2343 // carry an explicit noinline attribute.
2344 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2345 B.addAttribute(llvm::Attribute::NoInline);
2346 } else {
2347 // Otherwise, propagate the inline hint attribute and potentially use its
2348 // absence to mark things as noinline.
2349 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2350 // Search function and template pattern redeclarations for inline.
2351 auto CheckForInline = [](const FunctionDecl *FD) {
2352 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2353 return Redecl->isInlineSpecified();
2355 if (any_of(FD->redecls(), CheckRedeclForInline))
2356 return true;
2357 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2358 if (!Pattern)
2359 return false;
2360 return any_of(Pattern->redecls(), CheckRedeclForInline);
2362 if (CheckForInline(FD)) {
2363 B.addAttribute(llvm::Attribute::InlineHint);
2364 } else if (CodeGenOpts.getInlining() ==
2365 CodeGenOptions::OnlyHintInlining &&
2366 !FD->isInlined() &&
2367 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2368 B.addAttribute(llvm::Attribute::NoInline);
2373 // Add other optimization related attributes if we are optimizing this
2374 // function.
2375 if (!D->hasAttr<OptimizeNoneAttr>()) {
2376 if (D->hasAttr<ColdAttr>()) {
2377 if (!ShouldAddOptNone)
2378 B.addAttribute(llvm::Attribute::OptimizeForSize);
2379 B.addAttribute(llvm::Attribute::Cold);
2381 if (D->hasAttr<HotAttr>())
2382 B.addAttribute(llvm::Attribute::Hot);
2383 if (D->hasAttr<MinSizeAttr>())
2384 B.addAttribute(llvm::Attribute::MinSize);
2387 F->addFnAttrs(B);
2389 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2390 if (alignment)
2391 F->setAlignment(llvm::Align(alignment));
2393 if (!D->hasAttr<AlignedAttr>())
2394 if (LangOpts.FunctionAlignment)
2395 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2397 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2398 // reserve a bit for differentiating between virtual and non-virtual member
2399 // functions. If the current target's C++ ABI requires this and this is a
2400 // member function, set its alignment accordingly.
2401 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2402 if (F->getPointerAlignment(getDataLayout()) < 2 && isa<CXXMethodDecl>(D))
2403 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2406 // In the cross-dso CFI mode with canonical jump tables, we want !type
2407 // attributes on definitions only.
2408 if (CodeGenOpts.SanitizeCfiCrossDso &&
2409 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2410 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2411 // Skip available_externally functions. They won't be codegen'ed in the
2412 // current module anyway.
2413 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2414 CreateFunctionTypeMetadataForIcall(FD, F);
2418 // Emit type metadata on member functions for member function pointer checks.
2419 // These are only ever necessary on definitions; we're guaranteed that the
2420 // definition will be present in the LTO unit as a result of LTO visibility.
2421 auto *MD = dyn_cast<CXXMethodDecl>(D);
2422 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2423 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2424 llvm::Metadata *Id =
2425 CreateMetadataIdentifierForType(Context.getMemberPointerType(
2426 MD->getType(), Context.getRecordType(Base).getTypePtr()));
2427 F->addTypeMetadata(0, Id);
2432 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2433 const Decl *D = GD.getDecl();
2434 if (isa_and_nonnull<NamedDecl>(D))
2435 setGVProperties(GV, GD);
2436 else
2437 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2439 if (D && D->hasAttr<UsedAttr>())
2440 addUsedOrCompilerUsedGlobal(GV);
2442 if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2443 VD &&
2444 ((CodeGenOpts.KeepPersistentStorageVariables &&
2445 (VD->getStorageDuration() == SD_Static ||
2446 VD->getStorageDuration() == SD_Thread)) ||
2447 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2448 VD->getType().isConstQualified())))
2449 addUsedOrCompilerUsedGlobal(GV);
2452 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2453 llvm::AttrBuilder &Attrs,
2454 bool SetTargetFeatures) {
2455 // Add target-cpu and target-features attributes to functions. If
2456 // we have a decl for the function and it has a target attribute then
2457 // parse that and add it to the feature set.
2458 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2459 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2460 std::vector<std::string> Features;
2461 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2462 FD = FD ? FD->getMostRecentDecl() : FD;
2463 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2464 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2465 assert((!TD || !TV) && "both target_version and target specified");
2466 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2467 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2468 bool AddedAttr = false;
2469 if (TD || TV || SD || TC) {
2470 llvm::StringMap<bool> FeatureMap;
2471 getContext().getFunctionFeatureMap(FeatureMap, GD);
2473 // Produce the canonical string for this set of features.
2474 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2475 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2477 // Now add the target-cpu and target-features to the function.
2478 // While we populated the feature map above, we still need to
2479 // get and parse the target attribute so we can get the cpu for
2480 // the function.
2481 if (TD) {
2482 ParsedTargetAttr ParsedAttr =
2483 Target.parseTargetAttr(TD->getFeaturesStr());
2484 if (!ParsedAttr.CPU.empty() &&
2485 getTarget().isValidCPUName(ParsedAttr.CPU)) {
2486 TargetCPU = ParsedAttr.CPU;
2487 TuneCPU = ""; // Clear the tune CPU.
2489 if (!ParsedAttr.Tune.empty() &&
2490 getTarget().isValidCPUName(ParsedAttr.Tune))
2491 TuneCPU = ParsedAttr.Tune;
2494 if (SD) {
2495 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2496 // favor this processor.
2497 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2499 } else {
2500 // Otherwise just add the existing target cpu and target features to the
2501 // function.
2502 Features = getTarget().getTargetOpts().Features;
2505 if (!TargetCPU.empty()) {
2506 Attrs.addAttribute("target-cpu", TargetCPU);
2507 AddedAttr = true;
2509 if (!TuneCPU.empty()) {
2510 Attrs.addAttribute("tune-cpu", TuneCPU);
2511 AddedAttr = true;
2513 if (!Features.empty() && SetTargetFeatures) {
2514 llvm::erase_if(Features, [&](const std::string& F) {
2515 return getTarget().isReadOnlyFeature(F.substr(1));
2517 llvm::sort(Features);
2518 Attrs.addAttribute("target-features", llvm::join(Features, ","));
2519 AddedAttr = true;
2522 return AddedAttr;
2525 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2526 llvm::GlobalObject *GO) {
2527 const Decl *D = GD.getDecl();
2528 SetCommonAttributes(GD, GO);
2530 if (D) {
2531 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2532 if (D->hasAttr<RetainAttr>())
2533 addUsedGlobal(GV);
2534 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2535 GV->addAttribute("bss-section", SA->getName());
2536 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2537 GV->addAttribute("data-section", SA->getName());
2538 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2539 GV->addAttribute("rodata-section", SA->getName());
2540 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2541 GV->addAttribute("relro-section", SA->getName());
2544 if (auto *F = dyn_cast<llvm::Function>(GO)) {
2545 if (D->hasAttr<RetainAttr>())
2546 addUsedGlobal(F);
2547 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2548 if (!D->getAttr<SectionAttr>())
2549 F->addFnAttr("implicit-section-name", SA->getName());
2551 llvm::AttrBuilder Attrs(F->getContext());
2552 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2553 // We know that GetCPUAndFeaturesAttributes will always have the
2554 // newest set, since it has the newest possible FunctionDecl, so the
2555 // new ones should replace the old.
2556 llvm::AttributeMask RemoveAttrs;
2557 RemoveAttrs.addAttribute("target-cpu");
2558 RemoveAttrs.addAttribute("target-features");
2559 RemoveAttrs.addAttribute("tune-cpu");
2560 F->removeFnAttrs(RemoveAttrs);
2561 F->addFnAttrs(Attrs);
2565 if (const auto *CSA = D->getAttr<CodeSegAttr>())
2566 GO->setSection(CSA->getName());
2567 else if (const auto *SA = D->getAttr<SectionAttr>())
2568 GO->setSection(SA->getName());
2571 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2574 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2575 llvm::Function *F,
2576 const CGFunctionInfo &FI) {
2577 const Decl *D = GD.getDecl();
2578 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2579 SetLLVMFunctionAttributesForDefinition(D, F);
2581 F->setLinkage(llvm::Function::InternalLinkage);
2583 setNonAliasAttributes(GD, F);
2586 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2587 // Set linkage and visibility in case we never see a definition.
2588 LinkageInfo LV = ND->getLinkageAndVisibility();
2589 // Don't set internal linkage on declarations.
2590 // "extern_weak" is overloaded in LLVM; we probably should have
2591 // separate linkage types for this.
2592 if (isExternallyVisible(LV.getLinkage()) &&
2593 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2594 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2597 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2598 llvm::Function *F) {
2599 // Only if we are checking indirect calls.
2600 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2601 return;
2603 // Non-static class methods are handled via vtable or member function pointer
2604 // checks elsewhere.
2605 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2606 return;
2608 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2609 F->addTypeMetadata(0, MD);
2610 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2612 // Emit a hash-based bit set entry for cross-DSO calls.
2613 if (CodeGenOpts.SanitizeCfiCrossDso)
2614 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2615 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2618 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2619 llvm::LLVMContext &Ctx = F->getContext();
2620 llvm::MDBuilder MDB(Ctx);
2621 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2622 llvm::MDNode::get(
2623 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2626 static bool allowKCFIIdentifier(StringRef Name) {
2627 // KCFI type identifier constants are only necessary for external assembly
2628 // functions, which means it's safe to skip unusual names. Subset of
2629 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2630 return llvm::all_of(Name, [](const char &C) {
2631 return llvm::isAlnum(C) || C == '_' || C == '.';
2635 void CodeGenModule::finalizeKCFITypes() {
2636 llvm::Module &M = getModule();
2637 for (auto &F : M.functions()) {
2638 // Remove KCFI type metadata from non-address-taken local functions.
2639 bool AddressTaken = F.hasAddressTaken();
2640 if (!AddressTaken && F.hasLocalLinkage())
2641 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2643 // Generate a constant with the expected KCFI type identifier for all
2644 // address-taken function declarations to support annotating indirectly
2645 // called assembly functions.
2646 if (!AddressTaken || !F.isDeclaration())
2647 continue;
2649 const llvm::ConstantInt *Type;
2650 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2651 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2652 else
2653 continue;
2655 StringRef Name = F.getName();
2656 if (!allowKCFIIdentifier(Name))
2657 continue;
2659 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2660 Name + ", " + Twine(Type->getZExtValue()) + "\n")
2661 .str();
2662 M.appendModuleInlineAsm(Asm);
2666 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2667 bool IsIncompleteFunction,
2668 bool IsThunk) {
2670 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2671 // If this is an intrinsic function, set the function's attributes
2672 // to the intrinsic's attributes.
2673 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2674 return;
2677 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2679 if (!IsIncompleteFunction)
2680 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2681 IsThunk);
2683 // Add the Returned attribute for "this", except for iOS 5 and earlier
2684 // where substantial code, including the libstdc++ dylib, was compiled with
2685 // GCC and does not actually return "this".
2686 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2687 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2688 assert(!F->arg_empty() &&
2689 F->arg_begin()->getType()
2690 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2691 "unexpected this return");
2692 F->addParamAttr(0, llvm::Attribute::Returned);
2695 // Only a few attributes are set on declarations; these may later be
2696 // overridden by a definition.
2698 setLinkageForGV(F, FD);
2699 setGVProperties(F, FD);
2701 // Setup target-specific attributes.
2702 if (!IsIncompleteFunction && F->isDeclaration())
2703 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2705 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2706 F->setSection(CSA->getName());
2707 else if (const auto *SA = FD->getAttr<SectionAttr>())
2708 F->setSection(SA->getName());
2710 if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2711 if (EA->isError())
2712 F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2713 else if (EA->isWarning())
2714 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2717 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2718 if (FD->isInlineBuiltinDeclaration()) {
2719 const FunctionDecl *FDBody;
2720 bool HasBody = FD->hasBody(FDBody);
2721 (void)HasBody;
2722 assert(HasBody && "Inline builtin declarations should always have an "
2723 "available body!");
2724 if (shouldEmitFunction(FDBody))
2725 F->addFnAttr(llvm::Attribute::NoBuiltin);
2728 if (FD->isReplaceableGlobalAllocationFunction()) {
2729 // A replaceable global allocation function does not act like a builtin by
2730 // default, only if it is invoked by a new-expression or delete-expression.
2731 F->addFnAttr(llvm::Attribute::NoBuiltin);
2734 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2735 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2736 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2737 if (MD->isVirtual())
2738 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2740 // Don't emit entries for function declarations in the cross-DSO mode. This
2741 // is handled with better precision by the receiving DSO. But if jump tables
2742 // are non-canonical then we need type metadata in order to produce the local
2743 // jump table.
2744 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2745 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2746 CreateFunctionTypeMetadataForIcall(FD, F);
2748 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2749 setKCFIType(FD, F);
2751 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2752 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2754 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2755 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2757 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2758 // Annotate the callback behavior as metadata:
2759 // - The callback callee (as argument number).
2760 // - The callback payloads (as argument numbers).
2761 llvm::LLVMContext &Ctx = F->getContext();
2762 llvm::MDBuilder MDB(Ctx);
2764 // The payload indices are all but the first one in the encoding. The first
2765 // identifies the callback callee.
2766 int CalleeIdx = *CB->encoding_begin();
2767 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2768 F->addMetadata(llvm::LLVMContext::MD_callback,
2769 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2770 CalleeIdx, PayloadIndices,
2771 /* VarArgsArePassed */ false)}));
2775 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2776 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2777 "Only globals with definition can force usage.");
2778 LLVMUsed.emplace_back(GV);
2781 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2782 assert(!GV->isDeclaration() &&
2783 "Only globals with definition can force usage.");
2784 LLVMCompilerUsed.emplace_back(GV);
2787 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2788 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2789 "Only globals with definition can force usage.");
2790 if (getTriple().isOSBinFormatELF())
2791 LLVMCompilerUsed.emplace_back(GV);
2792 else
2793 LLVMUsed.emplace_back(GV);
2796 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2797 std::vector<llvm::WeakTrackingVH> &List) {
2798 // Don't create llvm.used if there is no need.
2799 if (List.empty())
2800 return;
2802 // Convert List to what ConstantArray needs.
2803 SmallVector<llvm::Constant*, 8> UsedArray;
2804 UsedArray.resize(List.size());
2805 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2806 UsedArray[i] =
2807 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2808 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2811 if (UsedArray.empty())
2812 return;
2813 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2815 auto *GV = new llvm::GlobalVariable(
2816 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2817 llvm::ConstantArray::get(ATy, UsedArray), Name);
2819 GV->setSection("llvm.metadata");
2822 void CodeGenModule::emitLLVMUsed() {
2823 emitUsed(*this, "llvm.used", LLVMUsed);
2824 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2827 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2828 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2829 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2832 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2833 llvm::SmallString<32> Opt;
2834 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2835 if (Opt.empty())
2836 return;
2837 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2838 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2841 void CodeGenModule::AddDependentLib(StringRef Lib) {
2842 auto &C = getLLVMContext();
2843 if (getTarget().getTriple().isOSBinFormatELF()) {
2844 ELFDependentLibraries.push_back(
2845 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2846 return;
2849 llvm::SmallString<24> Opt;
2850 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2851 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2852 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2855 /// Add link options implied by the given module, including modules
2856 /// it depends on, using a postorder walk.
2857 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2858 SmallVectorImpl<llvm::MDNode *> &Metadata,
2859 llvm::SmallPtrSet<Module *, 16> &Visited) {
2860 // Import this module's parent.
2861 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2862 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2865 // Import this module's dependencies.
2866 for (Module *Import : llvm::reverse(Mod->Imports)) {
2867 if (Visited.insert(Import).second)
2868 addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2871 // Add linker options to link against the libraries/frameworks
2872 // described by this module.
2873 llvm::LLVMContext &Context = CGM.getLLVMContext();
2874 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2876 // For modules that use export_as for linking, use that module
2877 // name instead.
2878 if (Mod->UseExportAsModuleLinkName)
2879 return;
2881 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
2882 // Link against a framework. Frameworks are currently Darwin only, so we
2883 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2884 if (LL.IsFramework) {
2885 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2886 llvm::MDString::get(Context, LL.Library)};
2888 Metadata.push_back(llvm::MDNode::get(Context, Args));
2889 continue;
2892 // Link against a library.
2893 if (IsELF) {
2894 llvm::Metadata *Args[2] = {
2895 llvm::MDString::get(Context, "lib"),
2896 llvm::MDString::get(Context, LL.Library),
2898 Metadata.push_back(llvm::MDNode::get(Context, Args));
2899 } else {
2900 llvm::SmallString<24> Opt;
2901 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
2902 auto *OptString = llvm::MDString::get(Context, Opt);
2903 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2908 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
2909 // Emit the initializers in the order that sub-modules appear in the
2910 // source, first Global Module Fragments, if present.
2911 if (auto GMF = Primary->getGlobalModuleFragment()) {
2912 for (Decl *D : getContext().getModuleInitializers(GMF)) {
2913 if (isa<ImportDecl>(D))
2914 continue;
2915 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
2916 EmitTopLevelDecl(D);
2919 // Second any associated with the module, itself.
2920 for (Decl *D : getContext().getModuleInitializers(Primary)) {
2921 // Skip import decls, the inits for those are called explicitly.
2922 if (isa<ImportDecl>(D))
2923 continue;
2924 EmitTopLevelDecl(D);
2926 // Third any associated with the Privat eMOdule Fragment, if present.
2927 if (auto PMF = Primary->getPrivateModuleFragment()) {
2928 for (Decl *D : getContext().getModuleInitializers(PMF)) {
2929 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
2930 EmitTopLevelDecl(D);
2935 void CodeGenModule::EmitModuleLinkOptions() {
2936 // Collect the set of all of the modules we want to visit to emit link
2937 // options, which is essentially the imported modules and all of their
2938 // non-explicit child modules.
2939 llvm::SetVector<clang::Module *> LinkModules;
2940 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2941 SmallVector<clang::Module *, 16> Stack;
2943 // Seed the stack with imported modules.
2944 for (Module *M : ImportedModules) {
2945 // Do not add any link flags when an implementation TU of a module imports
2946 // a header of that same module.
2947 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2948 !getLangOpts().isCompilingModule())
2949 continue;
2950 if (Visited.insert(M).second)
2951 Stack.push_back(M);
2954 // Find all of the modules to import, making a little effort to prune
2955 // non-leaf modules.
2956 while (!Stack.empty()) {
2957 clang::Module *Mod = Stack.pop_back_val();
2959 bool AnyChildren = false;
2961 // Visit the submodules of this module.
2962 for (const auto &SM : Mod->submodules()) {
2963 // Skip explicit children; they need to be explicitly imported to be
2964 // linked against.
2965 if (SM->IsExplicit)
2966 continue;
2968 if (Visited.insert(SM).second) {
2969 Stack.push_back(SM);
2970 AnyChildren = true;
2974 // We didn't find any children, so add this module to the list of
2975 // modules to link against.
2976 if (!AnyChildren) {
2977 LinkModules.insert(Mod);
2981 // Add link options for all of the imported modules in reverse topological
2982 // order. We don't do anything to try to order import link flags with respect
2983 // to linker options inserted by things like #pragma comment().
2984 SmallVector<llvm::MDNode *, 16> MetadataArgs;
2985 Visited.clear();
2986 for (Module *M : LinkModules)
2987 if (Visited.insert(M).second)
2988 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2989 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2990 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2992 // Add the linker options metadata flag.
2993 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2994 for (auto *MD : LinkerOptionsMetadata)
2995 NMD->addOperand(MD);
2998 void CodeGenModule::EmitDeferred() {
2999 // Emit deferred declare target declarations.
3000 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3001 getOpenMPRuntime().emitDeferredTargetDecls();
3003 // Emit code for any potentially referenced deferred decls. Since a
3004 // previously unused static decl may become used during the generation of code
3005 // for a static function, iterate until no changes are made.
3007 if (!DeferredVTables.empty()) {
3008 EmitDeferredVTables();
3010 // Emitting a vtable doesn't directly cause more vtables to
3011 // become deferred, although it can cause functions to be
3012 // emitted that then need those vtables.
3013 assert(DeferredVTables.empty());
3016 // Emit CUDA/HIP static device variables referenced by host code only.
3017 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3018 // needed for further handling.
3019 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3020 llvm::append_range(DeferredDeclsToEmit,
3021 getContext().CUDADeviceVarODRUsedByHost);
3023 // Stop if we're out of both deferred vtables and deferred declarations.
3024 if (DeferredDeclsToEmit.empty())
3025 return;
3027 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3028 // work, it will not interfere with this.
3029 std::vector<GlobalDecl> CurDeclsToEmit;
3030 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3032 for (GlobalDecl &D : CurDeclsToEmit) {
3033 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3034 // to get GlobalValue with exactly the type we need, not something that
3035 // might had been created for another decl with the same mangled name but
3036 // different type.
3037 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3038 GetAddrOfGlobal(D, ForDefinition));
3040 // In case of different address spaces, we may still get a cast, even with
3041 // IsForDefinition equal to true. Query mangled names table to get
3042 // GlobalValue.
3043 if (!GV)
3044 GV = GetGlobalValue(getMangledName(D));
3046 // Make sure GetGlobalValue returned non-null.
3047 assert(GV);
3049 // Check to see if we've already emitted this. This is necessary
3050 // for a couple of reasons: first, decls can end up in the
3051 // deferred-decls queue multiple times, and second, decls can end
3052 // up with definitions in unusual ways (e.g. by an extern inline
3053 // function acquiring a strong function redefinition). Just
3054 // ignore these cases.
3055 if (!GV->isDeclaration())
3056 continue;
3058 // If this is OpenMP, check if it is legal to emit this global normally.
3059 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3060 continue;
3062 // Otherwise, emit the definition and move on to the next one.
3063 EmitGlobalDefinition(D, GV);
3065 // If we found out that we need to emit more decls, do that recursively.
3066 // This has the advantage that the decls are emitted in a DFS and related
3067 // ones are close together, which is convenient for testing.
3068 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3069 EmitDeferred();
3070 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3075 void CodeGenModule::EmitVTablesOpportunistically() {
3076 // Try to emit external vtables as available_externally if they have emitted
3077 // all inlined virtual functions. It runs after EmitDeferred() and therefore
3078 // is not allowed to create new references to things that need to be emitted
3079 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3081 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3082 && "Only emit opportunistic vtables with optimizations");
3084 for (const CXXRecordDecl *RD : OpportunisticVTables) {
3085 assert(getVTables().isVTableExternal(RD) &&
3086 "This queue should only contain external vtables");
3087 if (getCXXABI().canSpeculativelyEmitVTable(RD))
3088 VTables.GenerateClassData(RD);
3090 OpportunisticVTables.clear();
3093 void CodeGenModule::EmitGlobalAnnotations() {
3094 if (Annotations.empty())
3095 return;
3097 // Create a new global variable for the ConstantStruct in the Module.
3098 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3099 Annotations[0]->getType(), Annotations.size()), Annotations);
3100 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3101 llvm::GlobalValue::AppendingLinkage,
3102 Array, "llvm.global.annotations");
3103 gv->setSection(AnnotationSection);
3106 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3107 llvm::Constant *&AStr = AnnotationStrings[Str];
3108 if (AStr)
3109 return AStr;
3111 // Not found yet, create a new global.
3112 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3113 auto *gv = new llvm::GlobalVariable(
3114 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3115 ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3116 ConstGlobalsPtrTy->getAddressSpace());
3117 gv->setSection(AnnotationSection);
3118 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3119 AStr = gv;
3120 return gv;
3123 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
3124 SourceManager &SM = getContext().getSourceManager();
3125 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3126 if (PLoc.isValid())
3127 return EmitAnnotationString(PLoc.getFilename());
3128 return EmitAnnotationString(SM.getBufferName(Loc));
3131 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
3132 SourceManager &SM = getContext().getSourceManager();
3133 PresumedLoc PLoc = SM.getPresumedLoc(L);
3134 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3135 SM.getExpansionLineNumber(L);
3136 return llvm::ConstantInt::get(Int32Ty, LineNo);
3139 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3140 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3141 if (Exprs.empty())
3142 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3144 llvm::FoldingSetNodeID ID;
3145 for (Expr *E : Exprs) {
3146 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3148 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3149 if (Lookup)
3150 return Lookup;
3152 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3153 LLVMArgs.reserve(Exprs.size());
3154 ConstantEmitter ConstEmiter(*this);
3155 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3156 const auto *CE = cast<clang::ConstantExpr>(E);
3157 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3158 CE->getType());
3160 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3161 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3162 llvm::GlobalValue::PrivateLinkage, Struct,
3163 ".args");
3164 GV->setSection(AnnotationSection);
3165 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3166 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
3168 Lookup = Bitcasted;
3169 return Bitcasted;
3172 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3173 const AnnotateAttr *AA,
3174 SourceLocation L) {
3175 // Get the globals for file name, annotation, and the line number.
3176 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3177 *UnitGV = EmitAnnotationUnit(L),
3178 *LineNoCst = EmitAnnotationLineNo(L),
3179 *Args = EmitAnnotationArgs(AA);
3181 llvm::Constant *GVInGlobalsAS = GV;
3182 if (GV->getAddressSpace() !=
3183 getDataLayout().getDefaultGlobalsAddressSpace()) {
3184 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3185 GV, GV->getValueType()->getPointerTo(
3186 getDataLayout().getDefaultGlobalsAddressSpace()));
3189 // Create the ConstantStruct for the global annotation.
3190 llvm::Constant *Fields[] = {
3191 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
3192 llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy),
3193 llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy),
3194 LineNoCst,
3195 Args,
3197 return llvm::ConstantStruct::getAnon(Fields);
3200 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
3201 llvm::GlobalValue *GV) {
3202 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3203 // Get the struct elements for these annotations.
3204 for (const auto *I : D->specific_attrs<AnnotateAttr>())
3205 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3208 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
3209 SourceLocation Loc) const {
3210 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3211 // NoSanitize by function name.
3212 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3213 return true;
3214 // NoSanitize by location. Check "mainfile" prefix.
3215 auto &SM = Context.getSourceManager();
3216 const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID());
3217 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3218 return true;
3220 // Check "src" prefix.
3221 if (Loc.isValid())
3222 return NoSanitizeL.containsLocation(Kind, Loc);
3223 // If location is unknown, this may be a compiler-generated function. Assume
3224 // it's located in the main file.
3225 return NoSanitizeL.containsFile(Kind, MainFile.getName());
3228 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
3229 llvm::GlobalVariable *GV,
3230 SourceLocation Loc, QualType Ty,
3231 StringRef Category) const {
3232 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3233 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3234 return true;
3235 auto &SM = Context.getSourceManager();
3236 if (NoSanitizeL.containsMainFile(
3237 Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
3238 return true;
3239 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3240 return true;
3242 // Check global type.
3243 if (!Ty.isNull()) {
3244 // Drill down the array types: if global variable of a fixed type is
3245 // not sanitized, we also don't instrument arrays of them.
3246 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3247 Ty = AT->getElementType();
3248 Ty = Ty.getCanonicalType().getUnqualifiedType();
3249 // Only record types (classes, structs etc.) are ignored.
3250 if (Ty->isRecordType()) {
3251 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3252 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3253 return true;
3256 return false;
3259 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3260 StringRef Category) const {
3261 const auto &XRayFilter = getContext().getXRayFilter();
3262 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3263 auto Attr = ImbueAttr::NONE;
3264 if (Loc.isValid())
3265 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3266 if (Attr == ImbueAttr::NONE)
3267 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3268 switch (Attr) {
3269 case ImbueAttr::NONE:
3270 return false;
3271 case ImbueAttr::ALWAYS:
3272 Fn->addFnAttr("function-instrument", "xray-always");
3273 break;
3274 case ImbueAttr::ALWAYS_ARG1:
3275 Fn->addFnAttr("function-instrument", "xray-always");
3276 Fn->addFnAttr("xray-log-args", "1");
3277 break;
3278 case ImbueAttr::NEVER:
3279 Fn->addFnAttr("function-instrument", "xray-never");
3280 break;
3282 return true;
3285 ProfileList::ExclusionType
3286 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3287 SourceLocation Loc) const {
3288 const auto &ProfileList = getContext().getProfileList();
3289 // If the profile list is empty, then instrument everything.
3290 if (ProfileList.isEmpty())
3291 return ProfileList::Allow;
3292 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3293 // First, check the function name.
3294 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3295 return *V;
3296 // Next, check the source location.
3297 if (Loc.isValid())
3298 if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3299 return *V;
3300 // If location is unknown, this may be a compiler-generated function. Assume
3301 // it's located in the main file.
3302 auto &SM = Context.getSourceManager();
3303 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
3304 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3305 return *V;
3306 return ProfileList.getDefault(Kind);
3309 ProfileList::ExclusionType
3310 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3311 SourceLocation Loc) const {
3312 auto V = isFunctionBlockedByProfileList(Fn, Loc);
3313 if (V != ProfileList::Allow)
3314 return V;
3316 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3317 if (NumGroups > 1) {
3318 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3319 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3320 return ProfileList::Skip;
3322 return ProfileList::Allow;
3325 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3326 // Never defer when EmitAllDecls is specified.
3327 if (LangOpts.EmitAllDecls)
3328 return true;
3330 const auto *VD = dyn_cast<VarDecl>(Global);
3331 if (VD &&
3332 ((CodeGenOpts.KeepPersistentStorageVariables &&
3333 (VD->getStorageDuration() == SD_Static ||
3334 VD->getStorageDuration() == SD_Thread)) ||
3335 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3336 VD->getType().isConstQualified())))
3337 return true;
3339 return getContext().DeclMustBeEmitted(Global);
3342 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3343 // In OpenMP 5.0 variables and function may be marked as
3344 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3345 // that they must be emitted on the host/device. To be sure we need to have
3346 // seen a declare target with an explicit mentioning of the function, we know
3347 // we have if the level of the declare target attribute is -1. Note that we
3348 // check somewhere else if we should emit this at all.
3349 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3350 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3351 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3352 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3353 return false;
3356 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3357 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3358 // Implicit template instantiations may change linkage if they are later
3359 // explicitly instantiated, so they should not be emitted eagerly.
3360 return false;
3362 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3363 if (Context.getInlineVariableDefinitionKind(VD) ==
3364 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3365 // A definition of an inline constexpr static data member may change
3366 // linkage later if it's redeclared outside the class.
3367 return false;
3368 if (CXX20ModuleInits && VD->getOwningModule() &&
3369 !VD->getOwningModule()->isModuleMapModule()) {
3370 // For CXX20, module-owned initializers need to be deferred, since it is
3371 // not known at this point if they will be run for the current module or
3372 // as part of the initializer for an imported one.
3373 return false;
3376 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3377 // codegen for global variables, because they may be marked as threadprivate.
3378 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3379 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3380 !Global->getType().isConstantStorage(getContext(), false, false) &&
3381 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3382 return false;
3384 return true;
3387 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3388 StringRef Name = getMangledName(GD);
3390 // The UUID descriptor should be pointer aligned.
3391 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3393 // Look for an existing global.
3394 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3395 return ConstantAddress(GV, GV->getValueType(), Alignment);
3397 ConstantEmitter Emitter(*this);
3398 llvm::Constant *Init;
3400 APValue &V = GD->getAsAPValue();
3401 if (!V.isAbsent()) {
3402 // If possible, emit the APValue version of the initializer. In particular,
3403 // this gets the type of the constant right.
3404 Init = Emitter.emitForInitializer(
3405 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3406 } else {
3407 // As a fallback, directly construct the constant.
3408 // FIXME: This may get padding wrong under esoteric struct layout rules.
3409 // MSVC appears to create a complete type 'struct __s_GUID' that it
3410 // presumably uses to represent these constants.
3411 MSGuidDecl::Parts Parts = GD->getParts();
3412 llvm::Constant *Fields[4] = {
3413 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3414 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3415 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3416 llvm::ConstantDataArray::getRaw(
3417 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3418 Int8Ty)};
3419 Init = llvm::ConstantStruct::getAnon(Fields);
3422 auto *GV = new llvm::GlobalVariable(
3423 getModule(), Init->getType(),
3424 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3425 if (supportsCOMDAT())
3426 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3427 setDSOLocal(GV);
3429 if (!V.isAbsent()) {
3430 Emitter.finalize(GV);
3431 return ConstantAddress(GV, GV->getValueType(), Alignment);
3434 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3435 llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
3436 GV, Ty->getPointerTo(GV->getAddressSpace()));
3437 return ConstantAddress(Addr, Ty, Alignment);
3440 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3441 const UnnamedGlobalConstantDecl *GCD) {
3442 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3444 llvm::GlobalVariable **Entry = nullptr;
3445 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3446 if (*Entry)
3447 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3449 ConstantEmitter Emitter(*this);
3450 llvm::Constant *Init;
3452 const APValue &V = GCD->getValue();
3454 assert(!V.isAbsent());
3455 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3456 GCD->getType());
3458 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3459 /*isConstant=*/true,
3460 llvm::GlobalValue::PrivateLinkage, Init,
3461 ".constant");
3462 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3463 GV->setAlignment(Alignment.getAsAlign());
3465 Emitter.finalize(GV);
3467 *Entry = GV;
3468 return ConstantAddress(GV, GV->getValueType(), Alignment);
3471 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3472 const TemplateParamObjectDecl *TPO) {
3473 StringRef Name = getMangledName(TPO);
3474 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3476 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3477 return ConstantAddress(GV, GV->getValueType(), Alignment);
3479 ConstantEmitter Emitter(*this);
3480 llvm::Constant *Init = Emitter.emitForInitializer(
3481 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3483 if (!Init) {
3484 ErrorUnsupported(TPO, "template parameter object");
3485 return ConstantAddress::invalid();
3488 llvm::GlobalValue::LinkageTypes Linkage =
3489 isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
3490 ? llvm::GlobalValue::LinkOnceODRLinkage
3491 : llvm::GlobalValue::InternalLinkage;
3492 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3493 /*isConstant=*/true, Linkage, Init, Name);
3494 setGVProperties(GV, TPO);
3495 if (supportsCOMDAT())
3496 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3497 Emitter.finalize(GV);
3499 return ConstantAddress(GV, GV->getValueType(), Alignment);
3502 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3503 const AliasAttr *AA = VD->getAttr<AliasAttr>();
3504 assert(AA && "No alias?");
3506 CharUnits Alignment = getContext().getDeclAlign(VD);
3507 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3509 // See if there is already something with the target's name in the module.
3510 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3511 if (Entry) {
3512 unsigned AS = getTypes().getTargetAddressSpace(VD->getType());
3513 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
3514 return ConstantAddress(Ptr, DeclTy, Alignment);
3517 llvm::Constant *Aliasee;
3518 if (isa<llvm::FunctionType>(DeclTy))
3519 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3520 GlobalDecl(cast<FunctionDecl>(VD)),
3521 /*ForVTable=*/false);
3522 else
3523 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3524 nullptr);
3526 auto *F = cast<llvm::GlobalValue>(Aliasee);
3527 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3528 WeakRefReferences.insert(F);
3530 return ConstantAddress(Aliasee, DeclTy, Alignment);
3533 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3534 const auto *Global = cast<ValueDecl>(GD.getDecl());
3536 // Weak references don't produce any output by themselves.
3537 if (Global->hasAttr<WeakRefAttr>())
3538 return;
3540 // If this is an alias definition (which otherwise looks like a declaration)
3541 // emit it now.
3542 if (Global->hasAttr<AliasAttr>())
3543 return EmitAliasDefinition(GD);
3545 // IFunc like an alias whose value is resolved at runtime by calling resolver.
3546 if (Global->hasAttr<IFuncAttr>())
3547 return emitIFuncDefinition(GD);
3549 // If this is a cpu_dispatch multiversion function, emit the resolver.
3550 if (Global->hasAttr<CPUDispatchAttr>())
3551 return emitCPUDispatchDefinition(GD);
3553 // If this is CUDA, be selective about which declarations we emit.
3554 if (LangOpts.CUDA) {
3555 if (LangOpts.CUDAIsDevice) {
3556 if (!Global->hasAttr<CUDADeviceAttr>() &&
3557 !Global->hasAttr<CUDAGlobalAttr>() &&
3558 !Global->hasAttr<CUDAConstantAttr>() &&
3559 !Global->hasAttr<CUDASharedAttr>() &&
3560 !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3561 !Global->getType()->isCUDADeviceBuiltinTextureType())
3562 return;
3563 } else {
3564 // We need to emit host-side 'shadows' for all global
3565 // device-side variables because the CUDA runtime needs their
3566 // size and host-side address in order to provide access to
3567 // their device-side incarnations.
3569 // So device-only functions are the only things we skip.
3570 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3571 Global->hasAttr<CUDADeviceAttr>())
3572 return;
3574 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3575 "Expected Variable or Function");
3579 if (LangOpts.OpenMP) {
3580 // If this is OpenMP, check if it is legal to emit this global normally.
3581 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3582 return;
3583 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3584 if (MustBeEmitted(Global))
3585 EmitOMPDeclareReduction(DRD);
3586 return;
3588 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3589 if (MustBeEmitted(Global))
3590 EmitOMPDeclareMapper(DMD);
3591 return;
3595 // Ignore declarations, they will be emitted on their first use.
3596 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3597 // Forward declarations are emitted lazily on first use.
3598 if (!FD->doesThisDeclarationHaveABody()) {
3599 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3600 return;
3602 StringRef MangledName = getMangledName(GD);
3604 // Compute the function info and LLVM type.
3605 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3606 llvm::Type *Ty = getTypes().GetFunctionType(FI);
3608 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3609 /*DontDefer=*/false);
3610 return;
3612 } else {
3613 const auto *VD = cast<VarDecl>(Global);
3614 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3615 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3616 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3617 if (LangOpts.OpenMP) {
3618 // Emit declaration of the must-be-emitted declare target variable.
3619 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3620 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3622 // If this variable has external storage and doesn't require special
3623 // link handling we defer to its canonical definition.
3624 if (VD->hasExternalStorage() &&
3625 Res != OMPDeclareTargetDeclAttr::MT_Link)
3626 return;
3628 bool UnifiedMemoryEnabled =
3629 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3630 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3631 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3632 !UnifiedMemoryEnabled) {
3633 (void)GetAddrOfGlobalVar(VD);
3634 } else {
3635 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3636 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3637 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3638 UnifiedMemoryEnabled)) &&
3639 "Link clause or to clause with unified memory expected.");
3640 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3643 return;
3646 // If this declaration may have caused an inline variable definition to
3647 // change linkage, make sure that it's emitted.
3648 if (Context.getInlineVariableDefinitionKind(VD) ==
3649 ASTContext::InlineVariableDefinitionKind::Strong)
3650 GetAddrOfGlobalVar(VD);
3651 return;
3655 // Defer code generation to first use when possible, e.g. if this is an inline
3656 // function. If the global must always be emitted, do it eagerly if possible
3657 // to benefit from cache locality.
3658 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3659 // Emit the definition if it can't be deferred.
3660 EmitGlobalDefinition(GD);
3661 addEmittedDeferredDecl(GD);
3662 return;
3665 // If we're deferring emission of a C++ variable with an
3666 // initializer, remember the order in which it appeared in the file.
3667 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3668 cast<VarDecl>(Global)->hasInit()) {
3669 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3670 CXXGlobalInits.push_back(nullptr);
3673 StringRef MangledName = getMangledName(GD);
3674 if (GetGlobalValue(MangledName) != nullptr) {
3675 // The value has already been used and should therefore be emitted.
3676 addDeferredDeclToEmit(GD);
3677 } else if (MustBeEmitted(Global)) {
3678 // The value must be emitted, but cannot be emitted eagerly.
3679 assert(!MayBeEmittedEagerly(Global));
3680 addDeferredDeclToEmit(GD);
3681 } else {
3682 // Otherwise, remember that we saw a deferred decl with this name. The
3683 // first use of the mangled name will cause it to move into
3684 // DeferredDeclsToEmit.
3685 DeferredDecls[MangledName] = GD;
3689 // Check if T is a class type with a destructor that's not dllimport.
3690 static bool HasNonDllImportDtor(QualType T) {
3691 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3692 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3693 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3694 return true;
3696 return false;
3699 namespace {
3700 struct FunctionIsDirectlyRecursive
3701 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3702 const StringRef Name;
3703 const Builtin::Context &BI;
3704 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3705 : Name(N), BI(C) {}
3707 bool VisitCallExpr(const CallExpr *E) {
3708 const FunctionDecl *FD = E->getDirectCallee();
3709 if (!FD)
3710 return false;
3711 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3712 if (Attr && Name == Attr->getLabel())
3713 return true;
3714 unsigned BuiltinID = FD->getBuiltinID();
3715 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3716 return false;
3717 StringRef BuiltinName = BI.getName(BuiltinID);
3718 if (BuiltinName.startswith("__builtin_") &&
3719 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3720 return true;
3722 return false;
3725 bool VisitStmt(const Stmt *S) {
3726 for (const Stmt *Child : S->children())
3727 if (Child && this->Visit(Child))
3728 return true;
3729 return false;
3733 // Make sure we're not referencing non-imported vars or functions.
3734 struct DLLImportFunctionVisitor
3735 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3736 bool SafeToInline = true;
3738 bool shouldVisitImplicitCode() const { return true; }
3740 bool VisitVarDecl(VarDecl *VD) {
3741 if (VD->getTLSKind()) {
3742 // A thread-local variable cannot be imported.
3743 SafeToInline = false;
3744 return SafeToInline;
3747 // A variable definition might imply a destructor call.
3748 if (VD->isThisDeclarationADefinition())
3749 SafeToInline = !HasNonDllImportDtor(VD->getType());
3751 return SafeToInline;
3754 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3755 if (const auto *D = E->getTemporary()->getDestructor())
3756 SafeToInline = D->hasAttr<DLLImportAttr>();
3757 return SafeToInline;
3760 bool VisitDeclRefExpr(DeclRefExpr *E) {
3761 ValueDecl *VD = E->getDecl();
3762 if (isa<FunctionDecl>(VD))
3763 SafeToInline = VD->hasAttr<DLLImportAttr>();
3764 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3765 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3766 return SafeToInline;
3769 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3770 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3771 return SafeToInline;
3774 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3775 CXXMethodDecl *M = E->getMethodDecl();
3776 if (!M) {
3777 // Call through a pointer to member function. This is safe to inline.
3778 SafeToInline = true;
3779 } else {
3780 SafeToInline = M->hasAttr<DLLImportAttr>();
3782 return SafeToInline;
3785 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3786 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3787 return SafeToInline;
3790 bool VisitCXXNewExpr(CXXNewExpr *E) {
3791 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3792 return SafeToInline;
3797 // isTriviallyRecursive - Check if this function calls another
3798 // decl that, because of the asm attribute or the other decl being a builtin,
3799 // ends up pointing to itself.
3800 bool
3801 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3802 StringRef Name;
3803 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3804 // asm labels are a special kind of mangling we have to support.
3805 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3806 if (!Attr)
3807 return false;
3808 Name = Attr->getLabel();
3809 } else {
3810 Name = FD->getName();
3813 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3814 const Stmt *Body = FD->getBody();
3815 return Body ? Walker.Visit(Body) : false;
3818 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3819 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3820 return true;
3821 const auto *F = cast<FunctionDecl>(GD.getDecl());
3822 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3823 return false;
3825 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3826 // Check whether it would be safe to inline this dllimport function.
3827 DLLImportFunctionVisitor Visitor;
3828 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3829 if (!Visitor.SafeToInline)
3830 return false;
3832 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3833 // Implicit destructor invocations aren't captured in the AST, so the
3834 // check above can't see them. Check for them manually here.
3835 for (const Decl *Member : Dtor->getParent()->decls())
3836 if (isa<FieldDecl>(Member))
3837 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3838 return false;
3839 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3840 if (HasNonDllImportDtor(B.getType()))
3841 return false;
3845 // Inline builtins declaration must be emitted. They often are fortified
3846 // functions.
3847 if (F->isInlineBuiltinDeclaration())
3848 return true;
3850 // PR9614. Avoid cases where the source code is lying to us. An available
3851 // externally function should have an equivalent function somewhere else,
3852 // but a function that calls itself through asm label/`__builtin_` trickery is
3853 // clearly not equivalent to the real implementation.
3854 // This happens in glibc's btowc and in some configure checks.
3855 return !isTriviallyRecursive(F);
3858 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3859 return CodeGenOpts.OptimizationLevel > 0;
3862 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3863 llvm::GlobalValue *GV) {
3864 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3866 if (FD->isCPUSpecificMultiVersion()) {
3867 auto *Spec = FD->getAttr<CPUSpecificAttr>();
3868 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3869 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3870 } else if (FD->isTargetClonesMultiVersion()) {
3871 auto *Clone = FD->getAttr<TargetClonesAttr>();
3872 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
3873 if (Clone->isFirstOfVersion(I))
3874 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3875 // Ensure that the resolver function is also emitted.
3876 GetOrCreateMultiVersionResolver(GD);
3877 } else
3878 EmitGlobalFunctionDefinition(GD, GV);
3881 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3882 const auto *D = cast<ValueDecl>(GD.getDecl());
3884 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3885 Context.getSourceManager(),
3886 "Generating code for declaration");
3888 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3889 // At -O0, don't generate IR for functions with available_externally
3890 // linkage.
3891 if (!shouldEmitFunction(GD))
3892 return;
3894 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3895 std::string Name;
3896 llvm::raw_string_ostream OS(Name);
3897 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3898 /*Qualified=*/true);
3899 return Name;
3902 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3903 // Make sure to emit the definition(s) before we emit the thunks.
3904 // This is necessary for the generation of certain thunks.
3905 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3906 ABI->emitCXXStructor(GD);
3907 else if (FD->isMultiVersion())
3908 EmitMultiVersionFunctionDefinition(GD, GV);
3909 else
3910 EmitGlobalFunctionDefinition(GD, GV);
3912 if (Method->isVirtual())
3913 getVTables().EmitThunks(GD);
3915 return;
3918 if (FD->isMultiVersion())
3919 return EmitMultiVersionFunctionDefinition(GD, GV);
3920 return EmitGlobalFunctionDefinition(GD, GV);
3923 if (const auto *VD = dyn_cast<VarDecl>(D))
3924 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3926 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3929 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3930 llvm::Function *NewFn);
3932 static unsigned
3933 TargetMVPriority(const TargetInfo &TI,
3934 const CodeGenFunction::MultiVersionResolverOption &RO) {
3935 unsigned Priority = 0;
3936 unsigned NumFeatures = 0;
3937 for (StringRef Feat : RO.Conditions.Features) {
3938 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3939 NumFeatures++;
3942 if (!RO.Conditions.Architecture.empty())
3943 Priority = std::max(
3944 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3946 Priority += TI.multiVersionFeatureCost() * NumFeatures;
3948 return Priority;
3951 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3952 // TU can forward declare the function without causing problems. Particularly
3953 // in the cases of CPUDispatch, this causes issues. This also makes sure we
3954 // work with internal linkage functions, so that the same function name can be
3955 // used with internal linkage in multiple TUs.
3956 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3957 GlobalDecl GD) {
3958 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3959 if (FD->getFormalLinkage() == InternalLinkage)
3960 return llvm::GlobalValue::InternalLinkage;
3961 return llvm::GlobalValue::WeakODRLinkage;
3964 void CodeGenModule::emitMultiVersionFunctions() {
3965 std::vector<GlobalDecl> MVFuncsToEmit;
3966 MultiVersionFuncs.swap(MVFuncsToEmit);
3967 for (GlobalDecl GD : MVFuncsToEmit) {
3968 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3969 assert(FD && "Expected a FunctionDecl");
3971 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3972 if (FD->isTargetMultiVersion()) {
3973 getContext().forEachMultiversionedFunctionVersion(
3974 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3975 GlobalDecl CurGD{
3976 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3977 StringRef MangledName = getMangledName(CurGD);
3978 llvm::Constant *Func = GetGlobalValue(MangledName);
3979 if (!Func) {
3980 if (CurFD->isDefined()) {
3981 EmitGlobalFunctionDefinition(CurGD, nullptr);
3982 Func = GetGlobalValue(MangledName);
3983 } else {
3984 const CGFunctionInfo &FI =
3985 getTypes().arrangeGlobalDeclaration(GD);
3986 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3987 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3988 /*DontDefer=*/false, ForDefinition);
3990 assert(Func && "This should have just been created");
3992 if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
3993 const auto *TA = CurFD->getAttr<TargetAttr>();
3994 llvm::SmallVector<StringRef, 8> Feats;
3995 TA->getAddedFeatures(Feats);
3996 Options.emplace_back(cast<llvm::Function>(Func),
3997 TA->getArchitecture(), Feats);
3998 } else {
3999 const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
4000 llvm::SmallVector<StringRef, 8> Feats;
4001 TVA->getFeatures(Feats);
4002 Options.emplace_back(cast<llvm::Function>(Func),
4003 /*Architecture*/ "", Feats);
4006 } else if (FD->isTargetClonesMultiVersion()) {
4007 const auto *TC = FD->getAttr<TargetClonesAttr>();
4008 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
4009 ++VersionIndex) {
4010 if (!TC->isFirstOfVersion(VersionIndex))
4011 continue;
4012 GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
4013 VersionIndex};
4014 StringRef Version = TC->getFeatureStr(VersionIndex);
4015 StringRef MangledName = getMangledName(CurGD);
4016 llvm::Constant *Func = GetGlobalValue(MangledName);
4017 if (!Func) {
4018 if (FD->isDefined()) {
4019 EmitGlobalFunctionDefinition(CurGD, nullptr);
4020 Func = GetGlobalValue(MangledName);
4021 } else {
4022 const CGFunctionInfo &FI =
4023 getTypes().arrangeGlobalDeclaration(CurGD);
4024 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4025 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4026 /*DontDefer=*/false, ForDefinition);
4028 assert(Func && "This should have just been created");
4031 StringRef Architecture;
4032 llvm::SmallVector<StringRef, 1> Feature;
4034 if (getTarget().getTriple().isAArch64()) {
4035 if (Version != "default") {
4036 llvm::SmallVector<StringRef, 8> VerFeats;
4037 Version.split(VerFeats, "+");
4038 for (auto &CurFeat : VerFeats)
4039 Feature.push_back(CurFeat.trim());
4041 } else {
4042 if (Version.startswith("arch="))
4043 Architecture = Version.drop_front(sizeof("arch=") - 1);
4044 else if (Version != "default")
4045 Feature.push_back(Version);
4048 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
4050 } else {
4051 assert(0 && "Expected a target or target_clones multiversion function");
4052 continue;
4055 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4056 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
4057 ResolverConstant = IFunc->getResolver();
4058 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4060 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4062 if (supportsCOMDAT())
4063 ResolverFunc->setComdat(
4064 getModule().getOrInsertComdat(ResolverFunc->getName()));
4066 const TargetInfo &TI = getTarget();
4067 llvm::stable_sort(
4068 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
4069 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4070 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
4072 CodeGenFunction CGF(*this);
4073 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4076 // Ensure that any additions to the deferred decls list caused by emitting a
4077 // variant are emitted. This can happen when the variant itself is inline and
4078 // calls a function without linkage.
4079 if (!MVFuncsToEmit.empty())
4080 EmitDeferred();
4082 // Ensure that any additions to the multiversion funcs list from either the
4083 // deferred decls or the multiversion functions themselves are emitted.
4084 if (!MultiVersionFuncs.empty())
4085 emitMultiVersionFunctions();
4088 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4089 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4090 assert(FD && "Not a FunctionDecl?");
4091 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4092 const auto *DD = FD->getAttr<CPUDispatchAttr>();
4093 assert(DD && "Not a cpu_dispatch Function?");
4095 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4096 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4098 StringRef ResolverName = getMangledName(GD);
4099 UpdateMultiVersionNames(GD, FD, ResolverName);
4101 llvm::Type *ResolverType;
4102 GlobalDecl ResolverGD;
4103 if (getTarget().supportsIFunc()) {
4104 ResolverType = llvm::FunctionType::get(
4105 llvm::PointerType::get(DeclTy,
4106 getTypes().getTargetAddressSpace(FD->getType())),
4107 false);
4109 else {
4110 ResolverType = DeclTy;
4111 ResolverGD = GD;
4114 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4115 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4116 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4117 if (supportsCOMDAT())
4118 ResolverFunc->setComdat(
4119 getModule().getOrInsertComdat(ResolverFunc->getName()));
4121 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4122 const TargetInfo &Target = getTarget();
4123 unsigned Index = 0;
4124 for (const IdentifierInfo *II : DD->cpus()) {
4125 // Get the name of the target function so we can look it up/create it.
4126 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4127 getCPUSpecificMangling(*this, II->getName());
4129 llvm::Constant *Func = GetGlobalValue(MangledName);
4131 if (!Func) {
4132 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4133 if (ExistingDecl.getDecl() &&
4134 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4135 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4136 Func = GetGlobalValue(MangledName);
4137 } else {
4138 if (!ExistingDecl.getDecl())
4139 ExistingDecl = GD.getWithMultiVersionIndex(Index);
4141 Func = GetOrCreateLLVMFunction(
4142 MangledName, DeclTy, ExistingDecl,
4143 /*ForVTable=*/false, /*DontDefer=*/true,
4144 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4148 llvm::SmallVector<StringRef, 32> Features;
4149 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4150 llvm::transform(Features, Features.begin(),
4151 [](StringRef Str) { return Str.substr(1); });
4152 llvm::erase_if(Features, [&Target](StringRef Feat) {
4153 return !Target.validateCpuSupports(Feat);
4155 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
4156 ++Index;
4159 llvm::stable_sort(
4160 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
4161 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4162 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4163 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4166 // If the list contains multiple 'default' versions, such as when it contains
4167 // 'pentium' and 'generic', don't emit the call to the generic one (since we
4168 // always run on at least a 'pentium'). We do this by deleting the 'least
4169 // advanced' (read, lowest mangling letter).
4170 while (Options.size() > 1 &&
4171 llvm::X86::getCpuSupportsMask(
4172 (Options.end() - 2)->Conditions.Features) == 0) {
4173 StringRef LHSName = (Options.end() - 2)->Function->getName();
4174 StringRef RHSName = (Options.end() - 1)->Function->getName();
4175 if (LHSName.compare(RHSName) < 0)
4176 Options.erase(Options.end() - 2);
4177 else
4178 Options.erase(Options.end() - 1);
4181 CodeGenFunction CGF(*this);
4182 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4184 if (getTarget().supportsIFunc()) {
4185 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4186 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4188 // Fix up function declarations that were created for cpu_specific before
4189 // cpu_dispatch was known
4190 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4191 assert(cast<llvm::Function>(IFunc)->isDeclaration());
4192 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
4193 &getModule());
4194 GI->takeName(IFunc);
4195 IFunc->replaceAllUsesWith(GI);
4196 IFunc->eraseFromParent();
4197 IFunc = GI;
4200 std::string AliasName = getMangledNameImpl(
4201 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4202 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4203 if (!AliasFunc) {
4204 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
4205 &getModule());
4206 SetCommonAttributes(GD, GA);
4211 /// If a dispatcher for the specified mangled name is not in the module, create
4212 /// and return an llvm Function with the specified type.
4213 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4214 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4215 assert(FD && "Not a FunctionDecl?");
4217 std::string MangledName =
4218 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4220 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4221 // a separate resolver).
4222 std::string ResolverName = MangledName;
4223 if (getTarget().supportsIFunc())
4224 ResolverName += ".ifunc";
4225 else if (FD->isTargetMultiVersion())
4226 ResolverName += ".resolver";
4228 // If the resolver has already been created, just return it.
4229 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
4230 return ResolverGV;
4232 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4233 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4235 // The resolver needs to be created. For target and target_clones, defer
4236 // creation until the end of the TU.
4237 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
4238 MultiVersionFuncs.push_back(GD);
4240 // For cpu_specific, don't create an ifunc yet because we don't know if the
4241 // cpu_dispatch will be emitted in this translation unit.
4242 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
4243 llvm::Type *ResolverType = llvm::FunctionType::get(
4244 llvm::PointerType::get(DeclTy,
4245 getTypes().getTargetAddressSpace(FD->getType())),
4246 false);
4247 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4248 MangledName + ".resolver", ResolverType, GlobalDecl{},
4249 /*ForVTable=*/false);
4250 llvm::GlobalIFunc *GIF =
4251 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4252 "", Resolver, &getModule());
4253 GIF->setName(ResolverName);
4254 SetCommonAttributes(FD, GIF);
4256 return GIF;
4259 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4260 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
4261 assert(isa<llvm::GlobalValue>(Resolver) &&
4262 "Resolver should be created for the first time");
4263 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
4264 return Resolver;
4267 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
4268 /// module, create and return an llvm Function with the specified type. If there
4269 /// is something in the module with the specified name, return it potentially
4270 /// bitcasted to the right type.
4272 /// If D is non-null, it specifies a decl that correspond to this. This is used
4273 /// to set the attributes on the function when it is first created.
4274 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4275 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
4276 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
4277 ForDefinition_t IsForDefinition) {
4278 const Decl *D = GD.getDecl();
4280 // Any attempts to use a MultiVersion function should result in retrieving
4281 // the iFunc instead. Name Mangling will handle the rest of the changes.
4282 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4283 // For the device mark the function as one that should be emitted.
4284 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4285 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
4286 !DontDefer && !IsForDefinition) {
4287 if (const FunctionDecl *FDDef = FD->getDefinition()) {
4288 GlobalDecl GDDef;
4289 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4290 GDDef = GlobalDecl(CD, GD.getCtorType());
4291 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4292 GDDef = GlobalDecl(DD, GD.getDtorType());
4293 else
4294 GDDef = GlobalDecl(FDDef);
4295 EmitGlobal(GDDef);
4299 if (FD->isMultiVersion()) {
4300 UpdateMultiVersionNames(GD, FD, MangledName);
4301 if (!IsForDefinition)
4302 return GetOrCreateMultiVersionResolver(GD);
4306 // Lookup the entry, lazily creating it if necessary.
4307 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4308 if (Entry) {
4309 if (WeakRefReferences.erase(Entry)) {
4310 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4311 if (FD && !FD->hasAttr<WeakAttr>())
4312 Entry->setLinkage(llvm::Function::ExternalLinkage);
4315 // Handle dropped DLL attributes.
4316 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4317 !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
4318 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4319 setDSOLocal(Entry);
4322 // If there are two attempts to define the same mangled name, issue an
4323 // error.
4324 if (IsForDefinition && !Entry->isDeclaration()) {
4325 GlobalDecl OtherGD;
4326 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4327 // to make sure that we issue an error only once.
4328 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4329 (GD.getCanonicalDecl().getDecl() !=
4330 OtherGD.getCanonicalDecl().getDecl()) &&
4331 DiagnosedConflictingDefinitions.insert(GD).second) {
4332 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4333 << MangledName;
4334 getDiags().Report(OtherGD.getDecl()->getLocation(),
4335 diag::note_previous_definition);
4339 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4340 (Entry->getValueType() == Ty)) {
4341 return Entry;
4344 // Make sure the result is of the correct type.
4345 // (If function is requested for a definition, we always need to create a new
4346 // function, not just return a bitcast.)
4347 if (!IsForDefinition)
4348 return llvm::ConstantExpr::getBitCast(
4349 Entry, Ty->getPointerTo(Entry->getAddressSpace()));
4352 // This function doesn't have a complete type (for example, the return
4353 // type is an incomplete struct). Use a fake type instead, and make
4354 // sure not to try to set attributes.
4355 bool IsIncompleteFunction = false;
4357 llvm::FunctionType *FTy;
4358 if (isa<llvm::FunctionType>(Ty)) {
4359 FTy = cast<llvm::FunctionType>(Ty);
4360 } else {
4361 FTy = llvm::FunctionType::get(VoidTy, false);
4362 IsIncompleteFunction = true;
4365 llvm::Function *F =
4366 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4367 Entry ? StringRef() : MangledName, &getModule());
4369 // If we already created a function with the same mangled name (but different
4370 // type) before, take its name and add it to the list of functions to be
4371 // replaced with F at the end of CodeGen.
4373 // This happens if there is a prototype for a function (e.g. "int f()") and
4374 // then a definition of a different type (e.g. "int f(int x)").
4375 if (Entry) {
4376 F->takeName(Entry);
4378 // This might be an implementation of a function without a prototype, in
4379 // which case, try to do special replacement of calls which match the new
4380 // prototype. The really key thing here is that we also potentially drop
4381 // arguments from the call site so as to make a direct call, which makes the
4382 // inliner happier and suppresses a number of optimizer warnings (!) about
4383 // dropping arguments.
4384 if (!Entry->use_empty()) {
4385 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
4386 Entry->removeDeadConstantUsers();
4389 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
4390 F, Entry->getValueType()->getPointerTo(Entry->getAddressSpace()));
4391 addGlobalValReplacement(Entry, BC);
4394 assert(F->getName() == MangledName && "name was uniqued!");
4395 if (D)
4396 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4397 if (ExtraAttrs.hasFnAttrs()) {
4398 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4399 F->addFnAttrs(B);
4402 if (!DontDefer) {
4403 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4404 // each other bottoming out with the base dtor. Therefore we emit non-base
4405 // dtors on usage, even if there is no dtor definition in the TU.
4406 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4407 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4408 GD.getDtorType()))
4409 addDeferredDeclToEmit(GD);
4411 // This is the first use or definition of a mangled name. If there is a
4412 // deferred decl with this name, remember that we need to emit it at the end
4413 // of the file.
4414 auto DDI = DeferredDecls.find(MangledName);
4415 if (DDI != DeferredDecls.end()) {
4416 // Move the potentially referenced deferred decl to the
4417 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4418 // don't need it anymore).
4419 addDeferredDeclToEmit(DDI->second);
4420 DeferredDecls.erase(DDI);
4422 // Otherwise, there are cases we have to worry about where we're
4423 // using a declaration for which we must emit a definition but where
4424 // we might not find a top-level definition:
4425 // - member functions defined inline in their classes
4426 // - friend functions defined inline in some class
4427 // - special member functions with implicit definitions
4428 // If we ever change our AST traversal to walk into class methods,
4429 // this will be unnecessary.
4431 // We also don't emit a definition for a function if it's going to be an
4432 // entry in a vtable, unless it's already marked as used.
4433 } else if (getLangOpts().CPlusPlus && D) {
4434 // Look for a declaration that's lexically in a record.
4435 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4436 FD = FD->getPreviousDecl()) {
4437 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4438 if (FD->doesThisDeclarationHaveABody()) {
4439 addDeferredDeclToEmit(GD.getWithDecl(FD));
4440 break;
4447 // Make sure the result is of the requested type.
4448 if (!IsIncompleteFunction) {
4449 assert(F->getFunctionType() == Ty);
4450 return F;
4453 return llvm::ConstantExpr::getBitCast(F,
4454 Ty->getPointerTo(F->getAddressSpace()));
4457 /// GetAddrOfFunction - Return the address of the given function. If Ty is
4458 /// non-null, then this function will use the specified type if it has to
4459 /// create it (this occurs when we see a definition of the function).
4460 llvm::Constant *
4461 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
4462 bool DontDefer,
4463 ForDefinition_t IsForDefinition) {
4464 // If there was no specific requested type, just convert it now.
4465 if (!Ty) {
4466 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4467 Ty = getTypes().ConvertType(FD->getType());
4470 // Devirtualized destructor calls may come through here instead of via
4471 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4472 // of the complete destructor when necessary.
4473 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4474 if (getTarget().getCXXABI().isMicrosoft() &&
4475 GD.getDtorType() == Dtor_Complete &&
4476 DD->getParent()->getNumVBases() == 0)
4477 GD = GlobalDecl(DD, Dtor_Base);
4480 StringRef MangledName = getMangledName(GD);
4481 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4482 /*IsThunk=*/false, llvm::AttributeList(),
4483 IsForDefinition);
4484 // Returns kernel handle for HIP kernel stub function.
4485 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4486 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4487 auto *Handle = getCUDARuntime().getKernelHandle(
4488 cast<llvm::Function>(F->stripPointerCasts()), GD);
4489 if (IsForDefinition)
4490 return F;
4491 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
4493 return F;
4496 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4497 llvm::GlobalValue *F =
4498 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4500 return llvm::ConstantExpr::getBitCast(
4501 llvm::NoCFIValue::get(F),
4502 llvm::PointerType::get(VMContext, F->getAddressSpace()));
4505 static const FunctionDecl *
4506 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4507 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4508 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4510 IdentifierInfo &CII = C.Idents.get(Name);
4511 for (const auto *Result : DC->lookup(&CII))
4512 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4513 return FD;
4515 if (!C.getLangOpts().CPlusPlus)
4516 return nullptr;
4518 // Demangle the premangled name from getTerminateFn()
4519 IdentifierInfo &CXXII =
4520 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4521 ? C.Idents.get("terminate")
4522 : C.Idents.get(Name);
4524 for (const auto &N : {"__cxxabiv1", "std"}) {
4525 IdentifierInfo &NS = C.Idents.get(N);
4526 for (const auto *Result : DC->lookup(&NS)) {
4527 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4528 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4529 for (const auto *Result : LSD->lookup(&NS))
4530 if ((ND = dyn_cast<NamespaceDecl>(Result)))
4531 break;
4533 if (ND)
4534 for (const auto *Result : ND->lookup(&CXXII))
4535 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4536 return FD;
4540 return nullptr;
4543 /// CreateRuntimeFunction - Create a new runtime function with the specified
4544 /// type and name.
4545 llvm::FunctionCallee
4546 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4547 llvm::AttributeList ExtraAttrs, bool Local,
4548 bool AssumeConvergent) {
4549 if (AssumeConvergent) {
4550 ExtraAttrs =
4551 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4554 llvm::Constant *C =
4555 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4556 /*DontDefer=*/false, /*IsThunk=*/false,
4557 ExtraAttrs);
4559 if (auto *F = dyn_cast<llvm::Function>(C)) {
4560 if (F->empty()) {
4561 F->setCallingConv(getRuntimeCC());
4563 // In Windows Itanium environments, try to mark runtime functions
4564 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4565 // will link their standard library statically or dynamically. Marking
4566 // functions imported when they are not imported can cause linker errors
4567 // and warnings.
4568 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4569 !getCodeGenOpts().LTOVisibilityPublicStd) {
4570 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4571 if (!FD || FD->hasAttr<DLLImportAttr>()) {
4572 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4573 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4576 setDSOLocal(F);
4580 return {FTy, C};
4583 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4584 /// create and return an llvm GlobalVariable with the specified type and address
4585 /// space. If there is something in the module with the specified name, return
4586 /// it potentially bitcasted to the right type.
4588 /// If D is non-null, it specifies a decl that correspond to this. This is used
4589 /// to set the attributes on the global when it is first created.
4591 /// If IsForDefinition is true, it is guaranteed that an actual global with
4592 /// type Ty will be returned, not conversion of a variable with the same
4593 /// mangled name but some other type.
4594 llvm::Constant *
4595 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4596 LangAS AddrSpace, const VarDecl *D,
4597 ForDefinition_t IsForDefinition) {
4598 // Lookup the entry, lazily creating it if necessary.
4599 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4600 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4601 if (Entry) {
4602 if (WeakRefReferences.erase(Entry)) {
4603 if (D && !D->hasAttr<WeakAttr>())
4604 Entry->setLinkage(llvm::Function::ExternalLinkage);
4607 // Handle dropped DLL attributes.
4608 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4609 !shouldMapVisibilityToDLLExport(D))
4610 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4612 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4613 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4615 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4616 return Entry;
4618 // If there are two attempts to define the same mangled name, issue an
4619 // error.
4620 if (IsForDefinition && !Entry->isDeclaration()) {
4621 GlobalDecl OtherGD;
4622 const VarDecl *OtherD;
4624 // Check that D is not yet in DiagnosedConflictingDefinitions is required
4625 // to make sure that we issue an error only once.
4626 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4627 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4628 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4629 OtherD->hasInit() &&
4630 DiagnosedConflictingDefinitions.insert(D).second) {
4631 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4632 << MangledName;
4633 getDiags().Report(OtherGD.getDecl()->getLocation(),
4634 diag::note_previous_definition);
4638 // Make sure the result is of the correct type.
4639 if (Entry->getType()->getAddressSpace() != TargetAS) {
4640 return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4641 Ty->getPointerTo(TargetAS));
4644 // (If global is requested for a definition, we always need to create a new
4645 // global, not just return a bitcast.)
4646 if (!IsForDefinition)
4647 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
4650 auto DAddrSpace = GetGlobalVarAddressSpace(D);
4652 auto *GV = new llvm::GlobalVariable(
4653 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4654 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4655 getContext().getTargetAddressSpace(DAddrSpace));
4657 // If we already created a global with the same mangled name (but different
4658 // type) before, take its name and remove it from its parent.
4659 if (Entry) {
4660 GV->takeName(Entry);
4662 if (!Entry->use_empty()) {
4663 llvm::Constant *NewPtrForOldDecl =
4664 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4665 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4668 Entry->eraseFromParent();
4671 // This is the first use or definition of a mangled name. If there is a
4672 // deferred decl with this name, remember that we need to emit it at the end
4673 // of the file.
4674 auto DDI = DeferredDecls.find(MangledName);
4675 if (DDI != DeferredDecls.end()) {
4676 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4677 // list, and remove it from DeferredDecls (since we don't need it anymore).
4678 addDeferredDeclToEmit(DDI->second);
4679 DeferredDecls.erase(DDI);
4682 // Handle things which are present even on external declarations.
4683 if (D) {
4684 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4685 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4687 // FIXME: This code is overly simple and should be merged with other global
4688 // handling.
4689 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
4691 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4693 setLinkageForGV(GV, D);
4695 if (D->getTLSKind()) {
4696 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4697 CXXThreadLocals.push_back(D);
4698 setTLSMode(GV, *D);
4701 setGVProperties(GV, D);
4703 // If required by the ABI, treat declarations of static data members with
4704 // inline initializers as definitions.
4705 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4706 EmitGlobalVarDefinition(D);
4709 // Emit section information for extern variables.
4710 if (D->hasExternalStorage()) {
4711 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4712 GV->setSection(SA->getName());
4715 // Handle XCore specific ABI requirements.
4716 if (getTriple().getArch() == llvm::Triple::xcore &&
4717 D->getLanguageLinkage() == CLanguageLinkage &&
4718 D->getType().isConstant(Context) &&
4719 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4720 GV->setSection(".cp.rodata");
4722 // Check if we a have a const declaration with an initializer, we may be
4723 // able to emit it as available_externally to expose it's value to the
4724 // optimizer.
4725 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4726 D->getType().isConstQualified() && !GV->hasInitializer() &&
4727 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4728 const auto *Record =
4729 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4730 bool HasMutableFields = Record && Record->hasMutableFields();
4731 if (!HasMutableFields) {
4732 const VarDecl *InitDecl;
4733 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4734 if (InitExpr) {
4735 ConstantEmitter emitter(*this);
4736 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4737 if (Init) {
4738 auto *InitType = Init->getType();
4739 if (GV->getValueType() != InitType) {
4740 // The type of the initializer does not match the definition.
4741 // This happens when an initializer has a different type from
4742 // the type of the global (because of padding at the end of a
4743 // structure for instance).
4744 GV->setName(StringRef());
4745 // Make a new global with the correct type, this is now guaranteed
4746 // to work.
4747 auto *NewGV = cast<llvm::GlobalVariable>(
4748 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4749 ->stripPointerCasts());
4751 // Erase the old global, since it is no longer used.
4752 GV->eraseFromParent();
4753 GV = NewGV;
4754 } else {
4755 GV->setInitializer(Init);
4756 GV->setConstant(true);
4757 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4759 emitter.finalize(GV);
4766 if (D &&
4767 D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
4768 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4769 // External HIP managed variables needed to be recorded for transformation
4770 // in both device and host compilations.
4771 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4772 D->hasExternalStorage())
4773 getCUDARuntime().handleVarRegistration(D, *GV);
4776 if (D)
4777 SanitizerMD->reportGlobal(GV, *D);
4779 LangAS ExpectedAS =
4780 D ? D->getType().getAddressSpace()
4781 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4782 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4783 if (DAddrSpace != ExpectedAS) {
4784 return getTargetCodeGenInfo().performAddrSpaceCast(
4785 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4788 return GV;
4791 llvm::Constant *
4792 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4793 const Decl *D = GD.getDecl();
4795 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4796 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4797 /*DontDefer=*/false, IsForDefinition);
4799 if (isa<CXXMethodDecl>(D)) {
4800 auto FInfo =
4801 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4802 auto Ty = getTypes().GetFunctionType(*FInfo);
4803 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4804 IsForDefinition);
4807 if (isa<FunctionDecl>(D)) {
4808 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4809 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4810 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4811 IsForDefinition);
4814 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4817 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4818 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4819 llvm::Align Alignment) {
4820 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4821 llvm::GlobalVariable *OldGV = nullptr;
4823 if (GV) {
4824 // Check if the variable has the right type.
4825 if (GV->getValueType() == Ty)
4826 return GV;
4828 // Because C++ name mangling, the only way we can end up with an already
4829 // existing global with the same name is if it has been declared extern "C".
4830 assert(GV->isDeclaration() && "Declaration has wrong type!");
4831 OldGV = GV;
4834 // Create a new variable.
4835 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4836 Linkage, nullptr, Name);
4838 if (OldGV) {
4839 // Replace occurrences of the old variable if needed.
4840 GV->takeName(OldGV);
4842 if (!OldGV->use_empty()) {
4843 llvm::Constant *NewPtrForOldDecl =
4844 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4845 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4848 OldGV->eraseFromParent();
4851 if (supportsCOMDAT() && GV->isWeakForLinker() &&
4852 !GV->hasAvailableExternallyLinkage())
4853 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4855 GV->setAlignment(Alignment);
4857 return GV;
4860 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4861 /// given global variable. If Ty is non-null and if the global doesn't exist,
4862 /// then it will be created with the specified type instead of whatever the
4863 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4864 /// that an actual global with type Ty will be returned, not conversion of a
4865 /// variable with the same mangled name but some other type.
4866 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4867 llvm::Type *Ty,
4868 ForDefinition_t IsForDefinition) {
4869 assert(D->hasGlobalStorage() && "Not a global variable");
4870 QualType ASTTy = D->getType();
4871 if (!Ty)
4872 Ty = getTypes().ConvertTypeForMem(ASTTy);
4874 StringRef MangledName = getMangledName(D);
4875 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4876 IsForDefinition);
4879 /// CreateRuntimeVariable - Create a new runtime global variable with the
4880 /// specified type and name.
4881 llvm::Constant *
4882 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4883 StringRef Name) {
4884 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4885 : LangAS::Default;
4886 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4887 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4888 return Ret;
4891 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4892 assert(!D->getInit() && "Cannot emit definite definitions here!");
4894 StringRef MangledName = getMangledName(D);
4895 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4897 // We already have a definition, not declaration, with the same mangled name.
4898 // Emitting of declaration is not required (and actually overwrites emitted
4899 // definition).
4900 if (GV && !GV->isDeclaration())
4901 return;
4903 // If we have not seen a reference to this variable yet, place it into the
4904 // deferred declarations table to be emitted if needed later.
4905 if (!MustBeEmitted(D) && !GV) {
4906 DeferredDecls[MangledName] = D;
4907 return;
4910 // The tentative definition is the only definition.
4911 EmitGlobalVarDefinition(D);
4914 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4915 EmitExternalVarDeclaration(D);
4918 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4919 return Context.toCharUnitsFromBits(
4920 getDataLayout().getTypeStoreSizeInBits(Ty));
4923 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4924 if (LangOpts.OpenCL) {
4925 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4926 assert(AS == LangAS::opencl_global ||
4927 AS == LangAS::opencl_global_device ||
4928 AS == LangAS::opencl_global_host ||
4929 AS == LangAS::opencl_constant ||
4930 AS == LangAS::opencl_local ||
4931 AS >= LangAS::FirstTargetAddressSpace);
4932 return AS;
4935 if (LangOpts.SYCLIsDevice &&
4936 (!D || D->getType().getAddressSpace() == LangAS::Default))
4937 return LangAS::sycl_global;
4939 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4940 if (D) {
4941 if (D->hasAttr<CUDAConstantAttr>())
4942 return LangAS::cuda_constant;
4943 if (D->hasAttr<CUDASharedAttr>())
4944 return LangAS::cuda_shared;
4945 if (D->hasAttr<CUDADeviceAttr>())
4946 return LangAS::cuda_device;
4947 if (D->getType().isConstQualified())
4948 return LangAS::cuda_constant;
4950 return LangAS::cuda_device;
4953 if (LangOpts.OpenMP) {
4954 LangAS AS;
4955 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4956 return AS;
4958 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4961 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4962 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4963 if (LangOpts.OpenCL)
4964 return LangAS::opencl_constant;
4965 if (LangOpts.SYCLIsDevice)
4966 return LangAS::sycl_global;
4967 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4968 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4969 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4970 // with OpVariable instructions with Generic storage class which is not
4971 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4972 // UniformConstant storage class is not viable as pointers to it may not be
4973 // casted to Generic pointers which are used to model HIP's "flat" pointers.
4974 return LangAS::cuda_device;
4975 if (auto AS = getTarget().getConstantAddressSpace())
4976 return *AS;
4977 return LangAS::Default;
4980 // In address space agnostic languages, string literals are in default address
4981 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4982 // emitted in constant address space in LLVM IR. To be consistent with other
4983 // parts of AST, string literal global variables in constant address space
4984 // need to be casted to default address space before being put into address
4985 // map and referenced by other part of CodeGen.
4986 // In OpenCL, string literals are in constant address space in AST, therefore
4987 // they should not be casted to default address space.
4988 static llvm::Constant *
4989 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4990 llvm::GlobalVariable *GV) {
4991 llvm::Constant *Cast = GV;
4992 if (!CGM.getLangOpts().OpenCL) {
4993 auto AS = CGM.GetGlobalConstantAddressSpace();
4994 if (AS != LangAS::Default)
4995 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4996 CGM, GV, AS, LangAS::Default,
4997 GV->getValueType()->getPointerTo(
4998 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
5000 return Cast;
5003 template<typename SomeDecl>
5004 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
5005 llvm::GlobalValue *GV) {
5006 if (!getLangOpts().CPlusPlus)
5007 return;
5009 // Must have 'used' attribute, or else inline assembly can't rely on
5010 // the name existing.
5011 if (!D->template hasAttr<UsedAttr>())
5012 return;
5014 // Must have internal linkage and an ordinary name.
5015 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
5016 return;
5018 // Must be in an extern "C" context. Entities declared directly within
5019 // a record are not extern "C" even if the record is in such a context.
5020 const SomeDecl *First = D->getFirstDecl();
5021 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
5022 return;
5024 // OK, this is an internal linkage entity inside an extern "C" linkage
5025 // specification. Make a note of that so we can give it the "expected"
5026 // mangled name if nothing else is using that name.
5027 std::pair<StaticExternCMap::iterator, bool> R =
5028 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5030 // If we have multiple internal linkage entities with the same name
5031 // in extern "C" regions, none of them gets that name.
5032 if (!R.second)
5033 R.first->second = nullptr;
5036 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
5037 if (!CGM.supportsCOMDAT())
5038 return false;
5040 if (D.hasAttr<SelectAnyAttr>())
5041 return true;
5043 GVALinkage Linkage;
5044 if (auto *VD = dyn_cast<VarDecl>(&D))
5045 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
5046 else
5047 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
5049 switch (Linkage) {
5050 case GVA_Internal:
5051 case GVA_AvailableExternally:
5052 case GVA_StrongExternal:
5053 return false;
5054 case GVA_DiscardableODR:
5055 case GVA_StrongODR:
5056 return true;
5058 llvm_unreachable("No such linkage");
5061 bool CodeGenModule::supportsCOMDAT() const {
5062 return getTriple().supportsCOMDAT();
5065 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
5066 llvm::GlobalObject &GO) {
5067 if (!shouldBeInCOMDAT(*this, D))
5068 return;
5069 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5072 /// Pass IsTentative as true if you want to create a tentative definition.
5073 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
5074 bool IsTentative) {
5075 // OpenCL global variables of sampler type are translated to function calls,
5076 // therefore no need to be translated.
5077 QualType ASTTy = D->getType();
5078 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
5079 return;
5081 // If this is OpenMP device, check if it is legal to emit this global
5082 // normally.
5083 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5084 OpenMPRuntime->emitTargetGlobalVariable(D))
5085 return;
5087 llvm::TrackingVH<llvm::Constant> Init;
5088 bool NeedsGlobalCtor = false;
5089 // Whether the definition of the variable is available externally.
5090 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5091 // since this is the job for its original source.
5092 bool IsDefinitionAvailableExternally =
5093 getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5094 bool NeedsGlobalDtor =
5095 !IsDefinitionAvailableExternally &&
5096 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
5098 const VarDecl *InitDecl;
5099 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5101 std::optional<ConstantEmitter> emitter;
5103 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5104 // as part of their declaration." Sema has already checked for
5105 // error cases, so we just need to set Init to UndefValue.
5106 bool IsCUDASharedVar =
5107 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5108 // Shadows of initialized device-side global variables are also left
5109 // undefined.
5110 // Managed Variables should be initialized on both host side and device side.
5111 bool IsCUDAShadowVar =
5112 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5113 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
5114 D->hasAttr<CUDASharedAttr>());
5115 bool IsCUDADeviceShadowVar =
5116 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5117 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5118 D->getType()->isCUDADeviceBuiltinTextureType());
5119 if (getLangOpts().CUDA &&
5120 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5121 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5122 else if (D->hasAttr<LoaderUninitializedAttr>())
5123 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5124 else if (!InitExpr) {
5125 // This is a tentative definition; tentative definitions are
5126 // implicitly initialized with { 0 }.
5128 // Note that tentative definitions are only emitted at the end of
5129 // a translation unit, so they should never have incomplete
5130 // type. In addition, EmitTentativeDefinition makes sure that we
5131 // never attempt to emit a tentative definition if a real one
5132 // exists. A use may still exists, however, so we still may need
5133 // to do a RAUW.
5134 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
5135 Init = EmitNullConstant(D->getType());
5136 } else {
5137 initializedGlobalDecl = GlobalDecl(D);
5138 emitter.emplace(*this);
5139 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5140 if (!Initializer) {
5141 QualType T = InitExpr->getType();
5142 if (D->getType()->isReferenceType())
5143 T = D->getType();
5145 if (getLangOpts().CPlusPlus) {
5146 if (InitDecl->hasFlexibleArrayInit(getContext()))
5147 ErrorUnsupported(D, "flexible array initializer");
5148 Init = EmitNullConstant(T);
5150 if (!IsDefinitionAvailableExternally)
5151 NeedsGlobalCtor = true;
5152 } else {
5153 ErrorUnsupported(D, "static initializer");
5154 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
5156 } else {
5157 Init = Initializer;
5158 // We don't need an initializer, so remove the entry for the delayed
5159 // initializer position (just in case this entry was delayed) if we
5160 // also don't need to register a destructor.
5161 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
5162 DelayedCXXInitPosition.erase(D);
5164 #ifndef NDEBUG
5165 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
5166 InitDecl->getFlexibleArrayInitChars(getContext());
5167 CharUnits CstSize = CharUnits::fromQuantity(
5168 getDataLayout().getTypeAllocSize(Init->getType()));
5169 assert(VarSize == CstSize && "Emitted constant has unexpected size");
5170 #endif
5174 llvm::Type* InitType = Init->getType();
5175 llvm::Constant *Entry =
5176 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
5178 // Strip off pointer casts if we got them.
5179 Entry = Entry->stripPointerCasts();
5181 // Entry is now either a Function or GlobalVariable.
5182 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5184 // We have a definition after a declaration with the wrong type.
5185 // We must make a new GlobalVariable* and update everything that used OldGV
5186 // (a declaration or tentative definition) with the new GlobalVariable*
5187 // (which will be a definition).
5189 // This happens if there is a prototype for a global (e.g.
5190 // "extern int x[];") and then a definition of a different type (e.g.
5191 // "int x[10];"). This also happens when an initializer has a different type
5192 // from the type of the global (this happens with unions).
5193 if (!GV || GV->getValueType() != InitType ||
5194 GV->getType()->getAddressSpace() !=
5195 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
5197 // Move the old entry aside so that we'll create a new one.
5198 Entry->setName(StringRef());
5200 // Make a new global with the correct type, this is now guaranteed to work.
5201 GV = cast<llvm::GlobalVariable>(
5202 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5203 ->stripPointerCasts());
5205 // Replace all uses of the old global with the new global
5206 llvm::Constant *NewPtrForOldDecl =
5207 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5208 Entry->getType());
5209 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5211 // Erase the old global, since it is no longer used.
5212 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5215 MaybeHandleStaticInExternC(D, GV);
5217 if (D->hasAttr<AnnotateAttr>())
5218 AddGlobalAnnotations(D, GV);
5220 // Set the llvm linkage type as appropriate.
5221 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
5223 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
5224 // the device. [...]"
5225 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
5226 // __device__, declares a variable that: [...]
5227 // Is accessible from all the threads within the grid and from the host
5228 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
5229 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
5230 if (LangOpts.CUDA) {
5231 if (LangOpts.CUDAIsDevice) {
5232 if (Linkage != llvm::GlobalValue::InternalLinkage &&
5233 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5234 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5235 D->getType()->isCUDADeviceBuiltinTextureType()))
5236 GV->setExternallyInitialized(true);
5237 } else {
5238 getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
5240 getCUDARuntime().handleVarRegistration(D, *GV);
5243 GV->setInitializer(Init);
5244 if (emitter)
5245 emitter->finalize(GV);
5247 // If it is safe to mark the global 'constant', do so now.
5248 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5249 D->getType().isConstantStorage(getContext(), true, true));
5251 // If it is in a read-only section, mark it 'constant'.
5252 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
5253 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
5254 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
5255 GV->setConstant(true);
5258 CharUnits AlignVal = getContext().getDeclAlign(D);
5259 // Check for alignment specifed in an 'omp allocate' directive.
5260 if (std::optional<CharUnits> AlignValFromAllocate =
5261 getOMPAllocateAlignment(D))
5262 AlignVal = *AlignValFromAllocate;
5263 GV->setAlignment(AlignVal.getAsAlign());
5265 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5266 // function is only defined alongside the variable, not also alongside
5267 // callers. Normally, all accesses to a thread_local go through the
5268 // thread-wrapper in order to ensure initialization has occurred, underlying
5269 // variable will never be used other than the thread-wrapper, so it can be
5270 // converted to internal linkage.
5272 // However, if the variable has the 'constinit' attribute, it _can_ be
5273 // referenced directly, without calling the thread-wrapper, so the linkage
5274 // must not be changed.
5276 // Additionally, if the variable isn't plain external linkage, e.g. if it's
5277 // weak or linkonce, the de-duplication semantics are important to preserve,
5278 // so we don't change the linkage.
5279 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
5280 Linkage == llvm::GlobalValue::ExternalLinkage &&
5281 Context.getTargetInfo().getTriple().isOSDarwin() &&
5282 !D->hasAttr<ConstInitAttr>())
5283 Linkage = llvm::GlobalValue::InternalLinkage;
5285 GV->setLinkage(Linkage);
5286 if (D->hasAttr<DLLImportAttr>())
5287 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5288 else if (D->hasAttr<DLLExportAttr>())
5289 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5290 else
5291 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5293 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
5294 // common vars aren't constant even if declared const.
5295 GV->setConstant(false);
5296 // Tentative definition of global variables may be initialized with
5297 // non-zero null pointers. In this case they should have weak linkage
5298 // since common linkage must have zero initializer and must not have
5299 // explicit section therefore cannot have non-zero initial value.
5300 if (!GV->getInitializer()->isNullValue())
5301 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5304 setNonAliasAttributes(D, GV);
5306 if (D->getTLSKind() && !GV->isThreadLocal()) {
5307 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5308 CXXThreadLocals.push_back(D);
5309 setTLSMode(GV, *D);
5312 maybeSetTrivialComdat(*D, *GV);
5314 // Emit the initializer function if necessary.
5315 if (NeedsGlobalCtor || NeedsGlobalDtor)
5316 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5318 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5320 // Emit global variable debug information.
5321 if (CGDebugInfo *DI = getModuleDebugInfo())
5322 if (getCodeGenOpts().hasReducedDebugInfo())
5323 DI->EmitGlobalVariable(GV, D);
5326 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5327 if (CGDebugInfo *DI = getModuleDebugInfo())
5328 if (getCodeGenOpts().hasReducedDebugInfo()) {
5329 QualType ASTTy = D->getType();
5330 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5331 llvm::Constant *GV =
5332 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5333 DI->EmitExternalVariable(
5334 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5338 static bool isVarDeclStrongDefinition(const ASTContext &Context,
5339 CodeGenModule &CGM, const VarDecl *D,
5340 bool NoCommon) {
5341 // Don't give variables common linkage if -fno-common was specified unless it
5342 // was overridden by a NoCommon attribute.
5343 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
5344 return true;
5346 // C11 6.9.2/2:
5347 // A declaration of an identifier for an object that has file scope without
5348 // an initializer, and without a storage-class specifier or with the
5349 // storage-class specifier static, constitutes a tentative definition.
5350 if (D->getInit() || D->hasExternalStorage())
5351 return true;
5353 // A variable cannot be both common and exist in a section.
5354 if (D->hasAttr<SectionAttr>())
5355 return true;
5357 // A variable cannot be both common and exist in a section.
5358 // We don't try to determine which is the right section in the front-end.
5359 // If no specialized section name is applicable, it will resort to default.
5360 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
5361 D->hasAttr<PragmaClangDataSectionAttr>() ||
5362 D->hasAttr<PragmaClangRelroSectionAttr>() ||
5363 D->hasAttr<PragmaClangRodataSectionAttr>())
5364 return true;
5366 // Thread local vars aren't considered common linkage.
5367 if (D->getTLSKind())
5368 return true;
5370 // Tentative definitions marked with WeakImportAttr are true definitions.
5371 if (D->hasAttr<WeakImportAttr>())
5372 return true;
5374 // A variable cannot be both common and exist in a comdat.
5375 if (shouldBeInCOMDAT(CGM, *D))
5376 return true;
5378 // Declarations with a required alignment do not have common linkage in MSVC
5379 // mode.
5380 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5381 if (D->hasAttr<AlignedAttr>())
5382 return true;
5383 QualType VarType = D->getType();
5384 if (Context.isAlignmentRequired(VarType))
5385 return true;
5387 if (const auto *RT = VarType->getAs<RecordType>()) {
5388 const RecordDecl *RD = RT->getDecl();
5389 for (const FieldDecl *FD : RD->fields()) {
5390 if (FD->isBitField())
5391 continue;
5392 if (FD->hasAttr<AlignedAttr>())
5393 return true;
5394 if (Context.isAlignmentRequired(FD->getType()))
5395 return true;
5400 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5401 // common symbols, so symbols with greater alignment requirements cannot be
5402 // common.
5403 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5404 // alignments for common symbols via the aligncomm directive, so this
5405 // restriction only applies to MSVC environments.
5406 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5407 Context.getTypeAlignIfKnown(D->getType()) >
5408 Context.toBits(CharUnits::fromQuantity(32)))
5409 return true;
5411 return false;
5414 llvm::GlobalValue::LinkageTypes
5415 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
5416 GVALinkage Linkage) {
5417 if (Linkage == GVA_Internal)
5418 return llvm::Function::InternalLinkage;
5420 if (D->hasAttr<WeakAttr>())
5421 return llvm::GlobalVariable::WeakAnyLinkage;
5423 if (const auto *FD = D->getAsFunction())
5424 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
5425 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5427 // We are guaranteed to have a strong definition somewhere else,
5428 // so we can use available_externally linkage.
5429 if (Linkage == GVA_AvailableExternally)
5430 return llvm::GlobalValue::AvailableExternallyLinkage;
5432 // Note that Apple's kernel linker doesn't support symbol
5433 // coalescing, so we need to avoid linkonce and weak linkages there.
5434 // Normally, this means we just map to internal, but for explicit
5435 // instantiations we'll map to external.
5437 // In C++, the compiler has to emit a definition in every translation unit
5438 // that references the function. We should use linkonce_odr because
5439 // a) if all references in this translation unit are optimized away, we
5440 // don't need to codegen it. b) if the function persists, it needs to be
5441 // merged with other definitions. c) C++ has the ODR, so we know the
5442 // definition is dependable.
5443 if (Linkage == GVA_DiscardableODR)
5444 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5445 : llvm::Function::InternalLinkage;
5447 // An explicit instantiation of a template has weak linkage, since
5448 // explicit instantiations can occur in multiple translation units
5449 // and must all be equivalent. However, we are not allowed to
5450 // throw away these explicit instantiations.
5452 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5453 // so say that CUDA templates are either external (for kernels) or internal.
5454 // This lets llvm perform aggressive inter-procedural optimizations. For
5455 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5456 // therefore we need to follow the normal linkage paradigm.
5457 if (Linkage == GVA_StrongODR) {
5458 if (getLangOpts().AppleKext)
5459 return llvm::Function::ExternalLinkage;
5460 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5461 !getLangOpts().GPURelocatableDeviceCode)
5462 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5463 : llvm::Function::InternalLinkage;
5464 return llvm::Function::WeakODRLinkage;
5467 // C++ doesn't have tentative definitions and thus cannot have common
5468 // linkage.
5469 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5470 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
5471 CodeGenOpts.NoCommon))
5472 return llvm::GlobalVariable::CommonLinkage;
5474 // selectany symbols are externally visible, so use weak instead of
5475 // linkonce. MSVC optimizes away references to const selectany globals, so
5476 // all definitions should be the same and ODR linkage should be used.
5477 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5478 if (D->hasAttr<SelectAnyAttr>())
5479 return llvm::GlobalVariable::WeakODRLinkage;
5481 // Otherwise, we have strong external linkage.
5482 assert(Linkage == GVA_StrongExternal);
5483 return llvm::GlobalVariable::ExternalLinkage;
5486 llvm::GlobalValue::LinkageTypes
5487 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
5488 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5489 return getLLVMLinkageForDeclarator(VD, Linkage);
5492 /// Replace the uses of a function that was declared with a non-proto type.
5493 /// We want to silently drop extra arguments from call sites
5494 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5495 llvm::Function *newFn) {
5496 // Fast path.
5497 if (old->use_empty()) return;
5499 llvm::Type *newRetTy = newFn->getReturnType();
5500 SmallVector<llvm::Value*, 4> newArgs;
5502 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5503 ui != ue; ) {
5504 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
5505 llvm::User *user = use->getUser();
5507 // Recognize and replace uses of bitcasts. Most calls to
5508 // unprototyped functions will use bitcasts.
5509 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5510 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5511 replaceUsesOfNonProtoConstant(bitcast, newFn);
5512 continue;
5515 // Recognize calls to the function.
5516 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5517 if (!callSite) continue;
5518 if (!callSite->isCallee(&*use))
5519 continue;
5521 // If the return types don't match exactly, then we can't
5522 // transform this call unless it's dead.
5523 if (callSite->getType() != newRetTy && !callSite->use_empty())
5524 continue;
5526 // Get the call site's attribute list.
5527 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5528 llvm::AttributeList oldAttrs = callSite->getAttributes();
5530 // If the function was passed too few arguments, don't transform.
5531 unsigned newNumArgs = newFn->arg_size();
5532 if (callSite->arg_size() < newNumArgs)
5533 continue;
5535 // If extra arguments were passed, we silently drop them.
5536 // If any of the types mismatch, we don't transform.
5537 unsigned argNo = 0;
5538 bool dontTransform = false;
5539 for (llvm::Argument &A : newFn->args()) {
5540 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5541 dontTransform = true;
5542 break;
5545 // Add any parameter attributes.
5546 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5547 argNo++;
5549 if (dontTransform)
5550 continue;
5552 // Okay, we can transform this. Create the new call instruction and copy
5553 // over the required information.
5554 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5556 // Copy over any operand bundles.
5557 SmallVector<llvm::OperandBundleDef, 1> newBundles;
5558 callSite->getOperandBundlesAsDefs(newBundles);
5560 llvm::CallBase *newCall;
5561 if (isa<llvm::CallInst>(callSite)) {
5562 newCall =
5563 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5564 } else {
5565 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5566 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5567 oldInvoke->getUnwindDest(), newArgs,
5568 newBundles, "", callSite);
5570 newArgs.clear(); // for the next iteration
5572 if (!newCall->getType()->isVoidTy())
5573 newCall->takeName(callSite);
5574 newCall->setAttributes(
5575 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5576 oldAttrs.getRetAttrs(), newArgAttrs));
5577 newCall->setCallingConv(callSite->getCallingConv());
5579 // Finally, remove the old call, replacing any uses with the new one.
5580 if (!callSite->use_empty())
5581 callSite->replaceAllUsesWith(newCall);
5583 // Copy debug location attached to CI.
5584 if (callSite->getDebugLoc())
5585 newCall->setDebugLoc(callSite->getDebugLoc());
5587 callSite->eraseFromParent();
5591 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5592 /// implement a function with no prototype, e.g. "int foo() {}". If there are
5593 /// existing call uses of the old function in the module, this adjusts them to
5594 /// call the new function directly.
5596 /// This is not just a cleanup: the always_inline pass requires direct calls to
5597 /// functions to be able to inline them. If there is a bitcast in the way, it
5598 /// won't inline them. Instcombine normally deletes these calls, but it isn't
5599 /// run at -O0.
5600 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5601 llvm::Function *NewFn) {
5602 // If we're redefining a global as a function, don't transform it.
5603 if (!isa<llvm::Function>(Old)) return;
5605 replaceUsesOfNonProtoConstant(Old, NewFn);
5608 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5609 auto DK = VD->isThisDeclarationADefinition();
5610 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5611 return;
5613 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5614 // If we have a definition, this might be a deferred decl. If the
5615 // instantiation is explicit, make sure we emit it at the end.
5616 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5617 GetAddrOfGlobalVar(VD);
5619 EmitTopLevelDecl(VD);
5622 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5623 llvm::GlobalValue *GV) {
5624 const auto *D = cast<FunctionDecl>(GD.getDecl());
5626 // Compute the function info and LLVM type.
5627 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5628 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5630 // Get or create the prototype for the function.
5631 if (!GV || (GV->getValueType() != Ty))
5632 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5633 /*DontDefer=*/true,
5634 ForDefinition));
5636 // Already emitted.
5637 if (!GV->isDeclaration())
5638 return;
5640 // We need to set linkage and visibility on the function before
5641 // generating code for it because various parts of IR generation
5642 // want to propagate this information down (e.g. to local static
5643 // declarations).
5644 auto *Fn = cast<llvm::Function>(GV);
5645 setFunctionLinkage(GD, Fn);
5647 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5648 setGVProperties(Fn, GD);
5650 MaybeHandleStaticInExternC(D, Fn);
5652 maybeSetTrivialComdat(*D, *Fn);
5654 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5656 setNonAliasAttributes(GD, Fn);
5657 SetLLVMFunctionAttributesForDefinition(D, Fn);
5659 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5660 AddGlobalCtor(Fn, CA->getPriority());
5661 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5662 AddGlobalDtor(Fn, DA->getPriority(), true);
5663 if (D->hasAttr<AnnotateAttr>())
5664 AddGlobalAnnotations(D, Fn);
5665 if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
5666 getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
5669 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5670 const auto *D = cast<ValueDecl>(GD.getDecl());
5671 const AliasAttr *AA = D->getAttr<AliasAttr>();
5672 assert(AA && "Not an alias?");
5674 StringRef MangledName = getMangledName(GD);
5676 if (AA->getAliasee() == MangledName) {
5677 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5678 return;
5681 // If there is a definition in the module, then it wins over the alias.
5682 // This is dubious, but allow it to be safe. Just ignore the alias.
5683 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5684 if (Entry && !Entry->isDeclaration())
5685 return;
5687 Aliases.push_back(GD);
5689 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5691 // Create a reference to the named value. This ensures that it is emitted
5692 // if a deferred decl.
5693 llvm::Constant *Aliasee;
5694 llvm::GlobalValue::LinkageTypes LT;
5695 if (isa<llvm::FunctionType>(DeclTy)) {
5696 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5697 /*ForVTable=*/false);
5698 LT = getFunctionLinkage(GD);
5699 } else {
5700 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5701 /*D=*/nullptr);
5702 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5703 LT = getLLVMLinkageVarDefinition(VD);
5704 else
5705 LT = getFunctionLinkage(GD);
5708 // Create the new alias itself, but don't set a name yet.
5709 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5710 auto *GA =
5711 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5713 if (Entry) {
5714 if (GA->getAliasee() == Entry) {
5715 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5716 return;
5719 assert(Entry->isDeclaration());
5721 // If there is a declaration in the module, then we had an extern followed
5722 // by the alias, as in:
5723 // extern int test6();
5724 // ...
5725 // int test6() __attribute__((alias("test7")));
5727 // Remove it and replace uses of it with the alias.
5728 GA->takeName(Entry);
5730 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
5731 Entry->getType()));
5732 Entry->eraseFromParent();
5733 } else {
5734 GA->setName(MangledName);
5737 // Set attributes which are particular to an alias; this is a
5738 // specialization of the attributes which may be set on a global
5739 // variable/function.
5740 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
5741 D->isWeakImported()) {
5742 GA->setLinkage(llvm::Function::WeakAnyLinkage);
5745 if (const auto *VD = dyn_cast<VarDecl>(D))
5746 if (VD->getTLSKind())
5747 setTLSMode(GA, *VD);
5749 SetCommonAttributes(GD, GA);
5751 // Emit global alias debug information.
5752 if (isa<VarDecl>(D))
5753 if (CGDebugInfo *DI = getModuleDebugInfo())
5754 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
5757 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
5758 const auto *D = cast<ValueDecl>(GD.getDecl());
5759 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
5760 assert(IFA && "Not an ifunc?");
5762 StringRef MangledName = getMangledName(GD);
5764 if (IFA->getResolver() == MangledName) {
5765 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5766 return;
5769 // Report an error if some definition overrides ifunc.
5770 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5771 if (Entry && !Entry->isDeclaration()) {
5772 GlobalDecl OtherGD;
5773 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5774 DiagnosedConflictingDefinitions.insert(GD).second) {
5775 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
5776 << MangledName;
5777 Diags.Report(OtherGD.getDecl()->getLocation(),
5778 diag::note_previous_definition);
5780 return;
5783 Aliases.push_back(GD);
5785 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5786 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5787 llvm::Constant *Resolver =
5788 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5789 /*ForVTable=*/false);
5790 llvm::GlobalIFunc *GIF =
5791 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5792 "", Resolver, &getModule());
5793 if (Entry) {
5794 if (GIF->getResolver() == Entry) {
5795 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5796 return;
5798 assert(Entry->isDeclaration());
5800 // If there is a declaration in the module, then we had an extern followed
5801 // by the ifunc, as in:
5802 // extern int test();
5803 // ...
5804 // int test() __attribute__((ifunc("resolver")));
5806 // Remove it and replace uses of it with the ifunc.
5807 GIF->takeName(Entry);
5809 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5810 Entry->getType()));
5811 Entry->eraseFromParent();
5812 } else
5813 GIF->setName(MangledName);
5814 if (auto *F = dyn_cast<llvm::Function>(Resolver)) {
5815 F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5817 SetCommonAttributes(GD, GIF);
5820 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5821 ArrayRef<llvm::Type*> Tys) {
5822 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5823 Tys);
5826 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5827 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5828 const StringLiteral *Literal, bool TargetIsLSB,
5829 bool &IsUTF16, unsigned &StringLength) {
5830 StringRef String = Literal->getString();
5831 unsigned NumBytes = String.size();
5833 // Check for simple case.
5834 if (!Literal->containsNonAsciiOrNull()) {
5835 StringLength = NumBytes;
5836 return *Map.insert(std::make_pair(String, nullptr)).first;
5839 // Otherwise, convert the UTF8 literals into a string of shorts.
5840 IsUTF16 = true;
5842 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5843 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5844 llvm::UTF16 *ToPtr = &ToBuf[0];
5846 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5847 ToPtr + NumBytes, llvm::strictConversion);
5849 // ConvertUTF8toUTF16 returns the length in ToPtr.
5850 StringLength = ToPtr - &ToBuf[0];
5852 // Add an explicit null.
5853 *ToPtr = 0;
5854 return *Map.insert(std::make_pair(
5855 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5856 (StringLength + 1) * 2),
5857 nullptr)).first;
5860 ConstantAddress
5861 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5862 unsigned StringLength = 0;
5863 bool isUTF16 = false;
5864 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5865 GetConstantCFStringEntry(CFConstantStringMap, Literal,
5866 getDataLayout().isLittleEndian(), isUTF16,
5867 StringLength);
5869 if (auto *C = Entry.second)
5870 return ConstantAddress(
5871 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
5873 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5874 llvm::Constant *Zeros[] = { Zero, Zero };
5876 const ASTContext &Context = getContext();
5877 const llvm::Triple &Triple = getTriple();
5879 const auto CFRuntime = getLangOpts().CFRuntime;
5880 const bool IsSwiftABI =
5881 static_cast<unsigned>(CFRuntime) >=
5882 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5883 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5885 // If we don't already have it, get __CFConstantStringClassReference.
5886 if (!CFConstantStringClassRef) {
5887 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5888 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5889 Ty = llvm::ArrayType::get(Ty, 0);
5891 switch (CFRuntime) {
5892 default: break;
5893 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
5894 case LangOptions::CoreFoundationABI::Swift5_0:
5895 CFConstantStringClassName =
5896 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5897 : "$s10Foundation19_NSCFConstantStringCN";
5898 Ty = IntPtrTy;
5899 break;
5900 case LangOptions::CoreFoundationABI::Swift4_2:
5901 CFConstantStringClassName =
5902 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5903 : "$S10Foundation19_NSCFConstantStringCN";
5904 Ty = IntPtrTy;
5905 break;
5906 case LangOptions::CoreFoundationABI::Swift4_1:
5907 CFConstantStringClassName =
5908 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5909 : "__T010Foundation19_NSCFConstantStringCN";
5910 Ty = IntPtrTy;
5911 break;
5914 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5916 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5917 llvm::GlobalValue *GV = nullptr;
5919 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5920 IdentifierInfo &II = Context.Idents.get(GV->getName());
5921 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5922 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5924 const VarDecl *VD = nullptr;
5925 for (const auto *Result : DC->lookup(&II))
5926 if ((VD = dyn_cast<VarDecl>(Result)))
5927 break;
5929 if (Triple.isOSBinFormatELF()) {
5930 if (!VD)
5931 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5932 } else {
5933 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5934 if (!VD || !VD->hasAttr<DLLExportAttr>())
5935 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5936 else
5937 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5940 setDSOLocal(GV);
5944 // Decay array -> ptr
5945 CFConstantStringClassRef =
5946 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5947 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5950 QualType CFTy = Context.getCFConstantStringType();
5952 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5954 ConstantInitBuilder Builder(*this);
5955 auto Fields = Builder.beginStruct(STy);
5957 // Class pointer.
5958 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
5960 // Flags.
5961 if (IsSwiftABI) {
5962 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5963 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5964 } else {
5965 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5968 // String pointer.
5969 llvm::Constant *C = nullptr;
5970 if (isUTF16) {
5971 auto Arr = llvm::ArrayRef(
5972 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5973 Entry.first().size() / 2);
5974 C = llvm::ConstantDataArray::get(VMContext, Arr);
5975 } else {
5976 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5979 // Note: -fwritable-strings doesn't make the backing store strings of
5980 // CFStrings writable.
5981 auto *GV =
5982 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5983 llvm::GlobalValue::PrivateLinkage, C, ".str");
5984 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5985 // Don't enforce the target's minimum global alignment, since the only use
5986 // of the string is via this class initializer.
5987 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5988 : Context.getTypeAlignInChars(Context.CharTy);
5989 GV->setAlignment(Align.getAsAlign());
5991 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5992 // Without it LLVM can merge the string with a non unnamed_addr one during
5993 // LTO. Doing that changes the section it ends in, which surprises ld64.
5994 if (Triple.isOSBinFormatMachO())
5995 GV->setSection(isUTF16 ? "__TEXT,__ustring"
5996 : "__TEXT,__cstring,cstring_literals");
5997 // Make sure the literal ends up in .rodata to allow for safe ICF and for
5998 // the static linker to adjust permissions to read-only later on.
5999 else if (Triple.isOSBinFormatELF())
6000 GV->setSection(".rodata");
6002 // String.
6003 llvm::Constant *Str =
6004 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
6006 if (isUTF16)
6007 // Cast the UTF16 string to the correct type.
6008 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
6009 Fields.add(Str);
6011 // String length.
6012 llvm::IntegerType *LengthTy =
6013 llvm::IntegerType::get(getModule().getContext(),
6014 Context.getTargetInfo().getLongWidth());
6015 if (IsSwiftABI) {
6016 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6017 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6018 LengthTy = Int32Ty;
6019 else
6020 LengthTy = IntPtrTy;
6022 Fields.addInt(LengthTy, StringLength);
6024 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6025 // properly aligned on 32-bit platforms.
6026 CharUnits Alignment =
6027 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
6029 // The struct.
6030 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
6031 /*isConstant=*/false,
6032 llvm::GlobalVariable::PrivateLinkage);
6033 GV->addAttribute("objc_arc_inert");
6034 switch (Triple.getObjectFormat()) {
6035 case llvm::Triple::UnknownObjectFormat:
6036 llvm_unreachable("unknown file format");
6037 case llvm::Triple::DXContainer:
6038 case llvm::Triple::GOFF:
6039 case llvm::Triple::SPIRV:
6040 case llvm::Triple::XCOFF:
6041 llvm_unreachable("unimplemented");
6042 case llvm::Triple::COFF:
6043 case llvm::Triple::ELF:
6044 case llvm::Triple::Wasm:
6045 GV->setSection("cfstring");
6046 break;
6047 case llvm::Triple::MachO:
6048 GV->setSection("__DATA,__cfstring");
6049 break;
6051 Entry.second = GV;
6053 return ConstantAddress(GV, GV->getValueType(), Alignment);
6056 bool CodeGenModule::getExpressionLocationsEnabled() const {
6057 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6060 QualType CodeGenModule::getObjCFastEnumerationStateType() {
6061 if (ObjCFastEnumerationStateType.isNull()) {
6062 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
6063 D->startDefinition();
6065 QualType FieldTypes[] = {
6066 Context.UnsignedLongTy,
6067 Context.getPointerType(Context.getObjCIdType()),
6068 Context.getPointerType(Context.UnsignedLongTy),
6069 Context.getConstantArrayType(Context.UnsignedLongTy,
6070 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
6073 for (size_t i = 0; i < 4; ++i) {
6074 FieldDecl *Field = FieldDecl::Create(Context,
6076 SourceLocation(),
6077 SourceLocation(), nullptr,
6078 FieldTypes[i], /*TInfo=*/nullptr,
6079 /*BitWidth=*/nullptr,
6080 /*Mutable=*/false,
6081 ICIS_NoInit);
6082 Field->setAccess(AS_public);
6083 D->addDecl(Field);
6086 D->completeDefinition();
6087 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
6090 return ObjCFastEnumerationStateType;
6093 llvm::Constant *
6094 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
6095 assert(!E->getType()->isPointerType() && "Strings are always arrays");
6097 // Don't emit it as the address of the string, emit the string data itself
6098 // as an inline array.
6099 if (E->getCharByteWidth() == 1) {
6100 SmallString<64> Str(E->getString());
6102 // Resize the string to the right size, which is indicated by its type.
6103 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
6104 assert(CAT && "String literal not of constant array type!");
6105 Str.resize(CAT->getSize().getZExtValue());
6106 return llvm::ConstantDataArray::getString(VMContext, Str, false);
6109 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
6110 llvm::Type *ElemTy = AType->getElementType();
6111 unsigned NumElements = AType->getNumElements();
6113 // Wide strings have either 2-byte or 4-byte elements.
6114 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6115 SmallVector<uint16_t, 32> Elements;
6116 Elements.reserve(NumElements);
6118 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6119 Elements.push_back(E->getCodeUnit(i));
6120 Elements.resize(NumElements);
6121 return llvm::ConstantDataArray::get(VMContext, Elements);
6124 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6125 SmallVector<uint32_t, 32> Elements;
6126 Elements.reserve(NumElements);
6128 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6129 Elements.push_back(E->getCodeUnit(i));
6130 Elements.resize(NumElements);
6131 return llvm::ConstantDataArray::get(VMContext, Elements);
6134 static llvm::GlobalVariable *
6135 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
6136 CodeGenModule &CGM, StringRef GlobalName,
6137 CharUnits Alignment) {
6138 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6139 CGM.GetGlobalConstantAddressSpace());
6141 llvm::Module &M = CGM.getModule();
6142 // Create a global variable for this string
6143 auto *GV = new llvm::GlobalVariable(
6144 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
6145 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6146 GV->setAlignment(Alignment.getAsAlign());
6147 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6148 if (GV->isWeakForLinker()) {
6149 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
6150 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6152 CGM.setDSOLocal(GV);
6154 return GV;
6157 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
6158 /// constant array for the given string literal.
6159 ConstantAddress
6160 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
6161 StringRef Name) {
6162 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
6164 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
6165 llvm::GlobalVariable **Entry = nullptr;
6166 if (!LangOpts.WritableStrings) {
6167 Entry = &ConstantStringMap[C];
6168 if (auto GV = *Entry) {
6169 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6170 GV->setAlignment(Alignment.getAsAlign());
6171 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6172 GV->getValueType(), Alignment);
6176 SmallString<256> MangledNameBuffer;
6177 StringRef GlobalVariableName;
6178 llvm::GlobalValue::LinkageTypes LT;
6180 // Mangle the string literal if that's how the ABI merges duplicate strings.
6181 // Don't do it if they are writable, since we don't want writes in one TU to
6182 // affect strings in another.
6183 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6184 !LangOpts.WritableStrings) {
6185 llvm::raw_svector_ostream Out(MangledNameBuffer);
6186 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
6187 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6188 GlobalVariableName = MangledNameBuffer;
6189 } else {
6190 LT = llvm::GlobalValue::PrivateLinkage;
6191 GlobalVariableName = Name;
6194 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
6196 CGDebugInfo *DI = getModuleDebugInfo();
6197 if (DI && getCodeGenOpts().hasReducedDebugInfo())
6198 DI->AddStringLiteralDebugInfo(GV, S);
6200 if (Entry)
6201 *Entry = GV;
6203 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
6205 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6206 GV->getValueType(), Alignment);
6209 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
6210 /// array for the given ObjCEncodeExpr node.
6211 ConstantAddress
6212 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
6213 std::string Str;
6214 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
6216 return GetAddrOfConstantCString(Str);
6219 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
6220 /// the literal and a terminating '\0' character.
6221 /// The result has pointer to array type.
6222 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
6223 const std::string &Str, const char *GlobalName) {
6224 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6225 CharUnits Alignment =
6226 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
6228 llvm::Constant *C =
6229 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
6231 // Don't share any string literals if strings aren't constant.
6232 llvm::GlobalVariable **Entry = nullptr;
6233 if (!LangOpts.WritableStrings) {
6234 Entry = &ConstantStringMap[C];
6235 if (auto GV = *Entry) {
6236 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6237 GV->setAlignment(Alignment.getAsAlign());
6238 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6239 GV->getValueType(), Alignment);
6243 // Get the default prefix if a name wasn't specified.
6244 if (!GlobalName)
6245 GlobalName = ".str";
6246 // Create a global variable for this.
6247 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
6248 GlobalName, Alignment);
6249 if (Entry)
6250 *Entry = GV;
6252 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6253 GV->getValueType(), Alignment);
6256 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6257 const MaterializeTemporaryExpr *E, const Expr *Init) {
6258 assert((E->getStorageDuration() == SD_Static ||
6259 E->getStorageDuration() == SD_Thread) && "not a global temporary");
6260 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6262 // If we're not materializing a subobject of the temporary, keep the
6263 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6264 QualType MaterializedType = Init->getType();
6265 if (Init == E->getSubExpr())
6266 MaterializedType = E->getType();
6268 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6270 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6271 if (!InsertResult.second) {
6272 // We've seen this before: either we already created it or we're in the
6273 // process of doing so.
6274 if (!InsertResult.first->second) {
6275 // We recursively re-entered this function, probably during emission of
6276 // the initializer. Create a placeholder. We'll clean this up in the
6277 // outer call, at the end of this function.
6278 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6279 InsertResult.first->second = new llvm::GlobalVariable(
6280 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6281 nullptr);
6283 return ConstantAddress(InsertResult.first->second,
6284 llvm::cast<llvm::GlobalVariable>(
6285 InsertResult.first->second->stripPointerCasts())
6286 ->getValueType(),
6287 Align);
6290 // FIXME: If an externally-visible declaration extends multiple temporaries,
6291 // we need to give each temporary the same name in every translation unit (and
6292 // we also need to make the temporaries externally-visible).
6293 SmallString<256> Name;
6294 llvm::raw_svector_ostream Out(Name);
6295 getCXXABI().getMangleContext().mangleReferenceTemporary(
6296 VD, E->getManglingNumber(), Out);
6298 APValue *Value = nullptr;
6299 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
6300 // If the initializer of the extending declaration is a constant
6301 // initializer, we should have a cached constant initializer for this
6302 // temporary. Note that this might have a different value from the value
6303 // computed by evaluating the initializer if the surrounding constant
6304 // expression modifies the temporary.
6305 Value = E->getOrCreateValue(false);
6308 // Try evaluating it now, it might have a constant initializer.
6309 Expr::EvalResult EvalResult;
6310 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6311 !EvalResult.hasSideEffects())
6312 Value = &EvalResult.Val;
6314 LangAS AddrSpace =
6315 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
6317 std::optional<ConstantEmitter> emitter;
6318 llvm::Constant *InitialValue = nullptr;
6319 bool Constant = false;
6320 llvm::Type *Type;
6321 if (Value) {
6322 // The temporary has a constant initializer, use it.
6323 emitter.emplace(*this);
6324 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6325 MaterializedType);
6326 Constant =
6327 MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
6328 /*ExcludeDtor*/ false);
6329 Type = InitialValue->getType();
6330 } else {
6331 // No initializer, the initialization will be provided when we
6332 // initialize the declaration which performed lifetime extension.
6333 Type = getTypes().ConvertTypeForMem(MaterializedType);
6336 // Create a global variable for this lifetime-extended temporary.
6337 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
6338 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6339 const VarDecl *InitVD;
6340 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6341 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6342 // Temporaries defined inside a class get linkonce_odr linkage because the
6343 // class can be defined in multiple translation units.
6344 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6345 } else {
6346 // There is no need for this temporary to have external linkage if the
6347 // VarDecl has external linkage.
6348 Linkage = llvm::GlobalVariable::InternalLinkage;
6351 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6352 auto *GV = new llvm::GlobalVariable(
6353 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6354 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6355 if (emitter) emitter->finalize(GV);
6356 // Don't assign dllimport or dllexport to local linkage globals.
6357 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6358 setGVProperties(GV, VD);
6359 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6360 // The reference temporary should never be dllexport.
6361 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6363 GV->setAlignment(Align.getAsAlign());
6364 if (supportsCOMDAT() && GV->isWeakForLinker())
6365 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6366 if (VD->getTLSKind())
6367 setTLSMode(GV, *VD);
6368 llvm::Constant *CV = GV;
6369 if (AddrSpace != LangAS::Default)
6370 CV = getTargetCodeGenInfo().performAddrSpaceCast(
6371 *this, GV, AddrSpace, LangAS::Default,
6372 Type->getPointerTo(
6373 getContext().getTargetAddressSpace(LangAS::Default)));
6375 // Update the map with the new temporary. If we created a placeholder above,
6376 // replace it with the new global now.
6377 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6378 if (Entry) {
6379 Entry->replaceAllUsesWith(
6380 llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
6381 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6383 Entry = CV;
6385 return ConstantAddress(CV, Type, Align);
6388 /// EmitObjCPropertyImplementations - Emit information for synthesized
6389 /// properties for an implementation.
6390 void CodeGenModule::EmitObjCPropertyImplementations(const
6391 ObjCImplementationDecl *D) {
6392 for (const auto *PID : D->property_impls()) {
6393 // Dynamic is just for type-checking.
6394 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6395 ObjCPropertyDecl *PD = PID->getPropertyDecl();
6397 // Determine which methods need to be implemented, some may have
6398 // been overridden. Note that ::isPropertyAccessor is not the method
6399 // we want, that just indicates if the decl came from a
6400 // property. What we want to know is if the method is defined in
6401 // this implementation.
6402 auto *Getter = PID->getGetterMethodDecl();
6403 if (!Getter || Getter->isSynthesizedAccessorStub())
6404 CodeGenFunction(*this).GenerateObjCGetter(
6405 const_cast<ObjCImplementationDecl *>(D), PID);
6406 auto *Setter = PID->getSetterMethodDecl();
6407 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6408 CodeGenFunction(*this).GenerateObjCSetter(
6409 const_cast<ObjCImplementationDecl *>(D), PID);
6414 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6415 const ObjCInterfaceDecl *iface = impl->getClassInterface();
6416 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6417 ivar; ivar = ivar->getNextIvar())
6418 if (ivar->getType().isDestructedType())
6419 return true;
6421 return false;
6424 static bool AllTrivialInitializers(CodeGenModule &CGM,
6425 ObjCImplementationDecl *D) {
6426 CodeGenFunction CGF(CGM);
6427 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6428 E = D->init_end(); B != E; ++B) {
6429 CXXCtorInitializer *CtorInitExp = *B;
6430 Expr *Init = CtorInitExp->getInit();
6431 if (!CGF.isTrivialInitializer(Init))
6432 return false;
6434 return true;
6437 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6438 /// for an implementation.
6439 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6440 // We might need a .cxx_destruct even if we don't have any ivar initializers.
6441 if (needsDestructMethod(D)) {
6442 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6443 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6444 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6445 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6446 getContext().VoidTy, nullptr, D,
6447 /*isInstance=*/true, /*isVariadic=*/false,
6448 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6449 /*isImplicitlyDeclared=*/true,
6450 /*isDefined=*/false, ObjCMethodDecl::Required);
6451 D->addInstanceMethod(DTORMethod);
6452 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6453 D->setHasDestructors(true);
6456 // If the implementation doesn't have any ivar initializers, we don't need
6457 // a .cxx_construct.
6458 if (D->getNumIvarInitializers() == 0 ||
6459 AllTrivialInitializers(*this, D))
6460 return;
6462 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6463 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6464 // The constructor returns 'self'.
6465 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6466 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6467 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6468 /*isVariadic=*/false,
6469 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6470 /*isImplicitlyDeclared=*/true,
6471 /*isDefined=*/false, ObjCMethodDecl::Required);
6472 D->addInstanceMethod(CTORMethod);
6473 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6474 D->setHasNonZeroConstructors(true);
6477 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6478 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6479 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
6480 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
6481 ErrorUnsupported(LSD, "linkage spec");
6482 return;
6485 EmitDeclContext(LSD);
6488 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6489 // Device code should not be at top level.
6490 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6491 return;
6493 std::unique_ptr<CodeGenFunction> &CurCGF =
6494 GlobalTopLevelStmtBlockInFlight.first;
6496 // We emitted a top-level stmt but after it there is initialization.
6497 // Stop squashing the top-level stmts into a single function.
6498 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6499 CurCGF->FinishFunction(D->getEndLoc());
6500 CurCGF = nullptr;
6503 if (!CurCGF) {
6504 // void __stmts__N(void)
6505 // FIXME: Ask the ABI name mangler to pick a name.
6506 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6507 FunctionArgList Args;
6508 QualType RetTy = getContext().VoidTy;
6509 const CGFunctionInfo &FnInfo =
6510 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6511 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6512 llvm::Function *Fn = llvm::Function::Create(
6513 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6515 CurCGF.reset(new CodeGenFunction(*this));
6516 GlobalTopLevelStmtBlockInFlight.second = D;
6517 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6518 D->getBeginLoc(), D->getBeginLoc());
6519 CXXGlobalInits.push_back(Fn);
6522 CurCGF->EmitStmt(D->getStmt());
6525 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6526 for (auto *I : DC->decls()) {
6527 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6528 // are themselves considered "top-level", so EmitTopLevelDecl on an
6529 // ObjCImplDecl does not recursively visit them. We need to do that in
6530 // case they're nested inside another construct (LinkageSpecDecl /
6531 // ExportDecl) that does stop them from being considered "top-level".
6532 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6533 for (auto *M : OID->methods())
6534 EmitTopLevelDecl(M);
6537 EmitTopLevelDecl(I);
6541 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6542 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6543 // Ignore dependent declarations.
6544 if (D->isTemplated())
6545 return;
6547 // Consteval function shouldn't be emitted.
6548 if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
6549 return;
6551 switch (D->getKind()) {
6552 case Decl::CXXConversion:
6553 case Decl::CXXMethod:
6554 case Decl::Function:
6555 EmitGlobal(cast<FunctionDecl>(D));
6556 // Always provide some coverage mapping
6557 // even for the functions that aren't emitted.
6558 AddDeferredUnusedCoverageMapping(D);
6559 break;
6561 case Decl::CXXDeductionGuide:
6562 // Function-like, but does not result in code emission.
6563 break;
6565 case Decl::Var:
6566 case Decl::Decomposition:
6567 case Decl::VarTemplateSpecialization:
6568 EmitGlobal(cast<VarDecl>(D));
6569 if (auto *DD = dyn_cast<DecompositionDecl>(D))
6570 for (auto *B : DD->bindings())
6571 if (auto *HD = B->getHoldingVar())
6572 EmitGlobal(HD);
6573 break;
6575 // Indirect fields from global anonymous structs and unions can be
6576 // ignored; only the actual variable requires IR gen support.
6577 case Decl::IndirectField:
6578 break;
6580 // C++ Decls
6581 case Decl::Namespace:
6582 EmitDeclContext(cast<NamespaceDecl>(D));
6583 break;
6584 case Decl::ClassTemplateSpecialization: {
6585 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6586 if (CGDebugInfo *DI = getModuleDebugInfo())
6587 if (Spec->getSpecializationKind() ==
6588 TSK_ExplicitInstantiationDefinition &&
6589 Spec->hasDefinition())
6590 DI->completeTemplateDefinition(*Spec);
6591 } [[fallthrough]];
6592 case Decl::CXXRecord: {
6593 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6594 if (CGDebugInfo *DI = getModuleDebugInfo()) {
6595 if (CRD->hasDefinition())
6596 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6597 if (auto *ES = D->getASTContext().getExternalSource())
6598 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6599 DI->completeUnusedClass(*CRD);
6601 // Emit any static data members, they may be definitions.
6602 for (auto *I : CRD->decls())
6603 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6604 EmitTopLevelDecl(I);
6605 break;
6607 // No code generation needed.
6608 case Decl::UsingShadow:
6609 case Decl::ClassTemplate:
6610 case Decl::VarTemplate:
6611 case Decl::Concept:
6612 case Decl::VarTemplatePartialSpecialization:
6613 case Decl::FunctionTemplate:
6614 case Decl::TypeAliasTemplate:
6615 case Decl::Block:
6616 case Decl::Empty:
6617 case Decl::Binding:
6618 break;
6619 case Decl::Using: // using X; [C++]
6620 if (CGDebugInfo *DI = getModuleDebugInfo())
6621 DI->EmitUsingDecl(cast<UsingDecl>(*D));
6622 break;
6623 case Decl::UsingEnum: // using enum X; [C++]
6624 if (CGDebugInfo *DI = getModuleDebugInfo())
6625 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6626 break;
6627 case Decl::NamespaceAlias:
6628 if (CGDebugInfo *DI = getModuleDebugInfo())
6629 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6630 break;
6631 case Decl::UsingDirective: // using namespace X; [C++]
6632 if (CGDebugInfo *DI = getModuleDebugInfo())
6633 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6634 break;
6635 case Decl::CXXConstructor:
6636 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6637 break;
6638 case Decl::CXXDestructor:
6639 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6640 break;
6642 case Decl::StaticAssert:
6643 // Nothing to do.
6644 break;
6646 // Objective-C Decls
6648 // Forward declarations, no (immediate) code generation.
6649 case Decl::ObjCInterface:
6650 case Decl::ObjCCategory:
6651 break;
6653 case Decl::ObjCProtocol: {
6654 auto *Proto = cast<ObjCProtocolDecl>(D);
6655 if (Proto->isThisDeclarationADefinition())
6656 ObjCRuntime->GenerateProtocol(Proto);
6657 break;
6660 case Decl::ObjCCategoryImpl:
6661 // Categories have properties but don't support synthesize so we
6662 // can ignore them here.
6663 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6664 break;
6666 case Decl::ObjCImplementation: {
6667 auto *OMD = cast<ObjCImplementationDecl>(D);
6668 EmitObjCPropertyImplementations(OMD);
6669 EmitObjCIvarInitializations(OMD);
6670 ObjCRuntime->GenerateClass(OMD);
6671 // Emit global variable debug information.
6672 if (CGDebugInfo *DI = getModuleDebugInfo())
6673 if (getCodeGenOpts().hasReducedDebugInfo())
6674 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6675 OMD->getClassInterface()), OMD->getLocation());
6676 break;
6678 case Decl::ObjCMethod: {
6679 auto *OMD = cast<ObjCMethodDecl>(D);
6680 // If this is not a prototype, emit the body.
6681 if (OMD->getBody())
6682 CodeGenFunction(*this).GenerateObjCMethod(OMD);
6683 break;
6685 case Decl::ObjCCompatibleAlias:
6686 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6687 break;
6689 case Decl::PragmaComment: {
6690 const auto *PCD = cast<PragmaCommentDecl>(D);
6691 switch (PCD->getCommentKind()) {
6692 case PCK_Unknown:
6693 llvm_unreachable("unexpected pragma comment kind");
6694 case PCK_Linker:
6695 AppendLinkerOptions(PCD->getArg());
6696 break;
6697 case PCK_Lib:
6698 AddDependentLib(PCD->getArg());
6699 break;
6700 case PCK_Compiler:
6701 case PCK_ExeStr:
6702 case PCK_User:
6703 break; // We ignore all of these.
6705 break;
6708 case Decl::PragmaDetectMismatch: {
6709 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6710 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6711 break;
6714 case Decl::LinkageSpec:
6715 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6716 break;
6718 case Decl::FileScopeAsm: {
6719 // File-scope asm is ignored during device-side CUDA compilation.
6720 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6721 break;
6722 // File-scope asm is ignored during device-side OpenMP compilation.
6723 if (LangOpts.OpenMPIsTargetDevice)
6724 break;
6725 // File-scope asm is ignored during device-side SYCL compilation.
6726 if (LangOpts.SYCLIsDevice)
6727 break;
6728 auto *AD = cast<FileScopeAsmDecl>(D);
6729 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6730 break;
6733 case Decl::TopLevelStmt:
6734 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6735 break;
6737 case Decl::Import: {
6738 auto *Import = cast<ImportDecl>(D);
6740 // If we've already imported this module, we're done.
6741 if (!ImportedModules.insert(Import->getImportedModule()))
6742 break;
6744 // Emit debug information for direct imports.
6745 if (!Import->getImportedOwningModule()) {
6746 if (CGDebugInfo *DI = getModuleDebugInfo())
6747 DI->EmitImportDecl(*Import);
6750 // For C++ standard modules we are done - we will call the module
6751 // initializer for imported modules, and that will likewise call those for
6752 // any imports it has.
6753 if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6754 !Import->getImportedOwningModule()->isModuleMapModule())
6755 break;
6757 // For clang C++ module map modules the initializers for sub-modules are
6758 // emitted here.
6760 // Find all of the submodules and emit the module initializers.
6761 llvm::SmallPtrSet<clang::Module *, 16> Visited;
6762 SmallVector<clang::Module *, 16> Stack;
6763 Visited.insert(Import->getImportedModule());
6764 Stack.push_back(Import->getImportedModule());
6766 while (!Stack.empty()) {
6767 clang::Module *Mod = Stack.pop_back_val();
6768 if (!EmittedModuleInitializers.insert(Mod).second)
6769 continue;
6771 for (auto *D : Context.getModuleInitializers(Mod))
6772 EmitTopLevelDecl(D);
6774 // Visit the submodules of this module.
6775 for (auto *Submodule : Mod->submodules()) {
6776 // Skip explicit children; they need to be explicitly imported to emit
6777 // the initializers.
6778 if (Submodule->IsExplicit)
6779 continue;
6781 if (Visited.insert(Submodule).second)
6782 Stack.push_back(Submodule);
6785 break;
6788 case Decl::Export:
6789 EmitDeclContext(cast<ExportDecl>(D));
6790 break;
6792 case Decl::OMPThreadPrivate:
6793 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6794 break;
6796 case Decl::OMPAllocate:
6797 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6798 break;
6800 case Decl::OMPDeclareReduction:
6801 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6802 break;
6804 case Decl::OMPDeclareMapper:
6805 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6806 break;
6808 case Decl::OMPRequires:
6809 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6810 break;
6812 case Decl::Typedef:
6813 case Decl::TypeAlias: // using foo = bar; [C++11]
6814 if (CGDebugInfo *DI = getModuleDebugInfo())
6815 DI->EmitAndRetainType(
6816 getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6817 break;
6819 case Decl::Record:
6820 if (CGDebugInfo *DI = getModuleDebugInfo())
6821 if (cast<RecordDecl>(D)->getDefinition())
6822 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6823 break;
6825 case Decl::Enum:
6826 if (CGDebugInfo *DI = getModuleDebugInfo())
6827 if (cast<EnumDecl>(D)->getDefinition())
6828 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6829 break;
6831 case Decl::HLSLBuffer:
6832 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
6833 break;
6835 default:
6836 // Make sure we handled everything we should, every other kind is a
6837 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
6838 // function. Need to recode Decl::Kind to do that easily.
6839 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
6840 break;
6844 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
6845 // Do we need to generate coverage mapping?
6846 if (!CodeGenOpts.CoverageMapping)
6847 return;
6848 switch (D->getKind()) {
6849 case Decl::CXXConversion:
6850 case Decl::CXXMethod:
6851 case Decl::Function:
6852 case Decl::ObjCMethod:
6853 case Decl::CXXConstructor:
6854 case Decl::CXXDestructor: {
6855 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
6856 break;
6857 SourceManager &SM = getContext().getSourceManager();
6858 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
6859 break;
6860 auto I = DeferredEmptyCoverageMappingDecls.find(D);
6861 if (I == DeferredEmptyCoverageMappingDecls.end())
6862 DeferredEmptyCoverageMappingDecls[D] = true;
6863 break;
6865 default:
6866 break;
6870 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
6871 // Do we need to generate coverage mapping?
6872 if (!CodeGenOpts.CoverageMapping)
6873 return;
6874 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6875 if (Fn->isTemplateInstantiation())
6876 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6878 auto I = DeferredEmptyCoverageMappingDecls.find(D);
6879 if (I == DeferredEmptyCoverageMappingDecls.end())
6880 DeferredEmptyCoverageMappingDecls[D] = false;
6881 else
6882 I->second = false;
6885 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6886 // We call takeVector() here to avoid use-after-free.
6887 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6888 // we deserialize function bodies to emit coverage info for them, and that
6889 // deserializes more declarations. How should we handle that case?
6890 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6891 if (!Entry.second)
6892 continue;
6893 const Decl *D = Entry.first;
6894 switch (D->getKind()) {
6895 case Decl::CXXConversion:
6896 case Decl::CXXMethod:
6897 case Decl::Function:
6898 case Decl::ObjCMethod: {
6899 CodeGenPGO PGO(*this);
6900 GlobalDecl GD(cast<FunctionDecl>(D));
6901 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6902 getFunctionLinkage(GD));
6903 break;
6905 case Decl::CXXConstructor: {
6906 CodeGenPGO PGO(*this);
6907 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6908 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6909 getFunctionLinkage(GD));
6910 break;
6912 case Decl::CXXDestructor: {
6913 CodeGenPGO PGO(*this);
6914 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6915 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6916 getFunctionLinkage(GD));
6917 break;
6919 default:
6920 break;
6925 void CodeGenModule::EmitMainVoidAlias() {
6926 // In order to transition away from "__original_main" gracefully, emit an
6927 // alias for "main" in the no-argument case so that libc can detect when
6928 // new-style no-argument main is in used.
6929 if (llvm::Function *F = getModule().getFunction("main")) {
6930 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6931 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
6932 auto *GA = llvm::GlobalAlias::create("__main_void", F);
6933 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
6938 /// Turns the given pointer into a constant.
6939 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6940 const void *Ptr) {
6941 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6942 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6943 return llvm::ConstantInt::get(i64, PtrInt);
6946 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6947 llvm::NamedMDNode *&GlobalMetadata,
6948 GlobalDecl D,
6949 llvm::GlobalValue *Addr) {
6950 if (!GlobalMetadata)
6951 GlobalMetadata =
6952 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6954 // TODO: should we report variant information for ctors/dtors?
6955 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6956 llvm::ConstantAsMetadata::get(GetPointerConstant(
6957 CGM.getLLVMContext(), D.getDecl()))};
6958 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6961 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
6962 llvm::GlobalValue *CppFunc) {
6963 // Store the list of ifuncs we need to replace uses in.
6964 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
6965 // List of ConstantExprs that we should be able to delete when we're done
6966 // here.
6967 llvm::SmallVector<llvm::ConstantExpr *> CEs;
6969 // It isn't valid to replace the extern-C ifuncs if all we find is itself!
6970 if (Elem == CppFunc)
6971 return false;
6973 // First make sure that all users of this are ifuncs (or ifuncs via a
6974 // bitcast), and collect the list of ifuncs and CEs so we can work on them
6975 // later.
6976 for (llvm::User *User : Elem->users()) {
6977 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
6978 // ifunc directly. In any other case, just give up, as we don't know what we
6979 // could break by changing those.
6980 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
6981 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
6982 return false;
6984 for (llvm::User *CEUser : ConstExpr->users()) {
6985 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
6986 IFuncs.push_back(IFunc);
6987 } else {
6988 return false;
6991 CEs.push_back(ConstExpr);
6992 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
6993 IFuncs.push_back(IFunc);
6994 } else {
6995 // This user is one we don't know how to handle, so fail redirection. This
6996 // will result in an ifunc retaining a resolver name that will ultimately
6997 // fail to be resolved to a defined function.
6998 return false;
7002 // Now we know this is a valid case where we can do this alias replacement, we
7003 // need to remove all of the references to Elem (and the bitcasts!) so we can
7004 // delete it.
7005 for (llvm::GlobalIFunc *IFunc : IFuncs)
7006 IFunc->setResolver(nullptr);
7007 for (llvm::ConstantExpr *ConstExpr : CEs)
7008 ConstExpr->destroyConstant();
7010 // We should now be out of uses for the 'old' version of this function, so we
7011 // can erase it as well.
7012 Elem->eraseFromParent();
7014 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7015 // The type of the resolver is always just a function-type that returns the
7016 // type of the IFunc, so create that here. If the type of the actual
7017 // resolver doesn't match, it just gets bitcast to the right thing.
7018 auto *ResolverTy =
7019 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7020 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7021 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7022 IFunc->setResolver(Resolver);
7024 return true;
7027 /// For each function which is declared within an extern "C" region and marked
7028 /// as 'used', but has internal linkage, create an alias from the unmangled
7029 /// name to the mangled name if possible. People expect to be able to refer
7030 /// to such functions with an unmangled name from inline assembly within the
7031 /// same translation unit.
7032 void CodeGenModule::EmitStaticExternCAliases() {
7033 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7034 return;
7035 for (auto &I : StaticExternCValues) {
7036 IdentifierInfo *Name = I.first;
7037 llvm::GlobalValue *Val = I.second;
7039 // If Val is null, that implies there were multiple declarations that each
7040 // had a claim to the unmangled name. In this case, generation of the alias
7041 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7042 if (!Val)
7043 break;
7045 llvm::GlobalValue *ExistingElem =
7046 getModule().getNamedValue(Name->getName());
7048 // If there is either not something already by this name, or we were able to
7049 // replace all uses from IFuncs, create the alias.
7050 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7051 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7055 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
7056 GlobalDecl &Result) const {
7057 auto Res = Manglings.find(MangledName);
7058 if (Res == Manglings.end())
7059 return false;
7060 Result = Res->getValue();
7061 return true;
7064 /// Emits metadata nodes associating all the global values in the
7065 /// current module with the Decls they came from. This is useful for
7066 /// projects using IR gen as a subroutine.
7068 /// Since there's currently no way to associate an MDNode directly
7069 /// with an llvm::GlobalValue, we create a global named metadata
7070 /// with the name 'clang.global.decl.ptrs'.
7071 void CodeGenModule::EmitDeclMetadata() {
7072 llvm::NamedMDNode *GlobalMetadata = nullptr;
7074 for (auto &I : MangledDeclNames) {
7075 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7076 // Some mangled names don't necessarily have an associated GlobalValue
7077 // in this module, e.g. if we mangled it for DebugInfo.
7078 if (Addr)
7079 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7083 /// Emits metadata nodes for all the local variables in the current
7084 /// function.
7085 void CodeGenFunction::EmitDeclMetadata() {
7086 if (LocalDeclMap.empty()) return;
7088 llvm::LLVMContext &Context = getLLVMContext();
7090 // Find the unique metadata ID for this name.
7091 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
7093 llvm::NamedMDNode *GlobalMetadata = nullptr;
7095 for (auto &I : LocalDeclMap) {
7096 const Decl *D = I.first;
7097 llvm::Value *Addr = I.second.getPointer();
7098 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7099 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
7100 Alloca->setMetadata(
7101 DeclPtrKind, llvm::MDNode::get(
7102 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7103 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7104 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
7105 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
7110 void CodeGenModule::EmitVersionIdentMetadata() {
7111 llvm::NamedMDNode *IdentMetadata =
7112 TheModule.getOrInsertNamedMetadata("llvm.ident");
7113 std::string Version = getClangFullVersion();
7114 llvm::LLVMContext &Ctx = TheModule.getContext();
7116 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7117 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7120 void CodeGenModule::EmitCommandLineMetadata() {
7121 llvm::NamedMDNode *CommandLineMetadata =
7122 TheModule.getOrInsertNamedMetadata("llvm.commandline");
7123 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
7124 llvm::LLVMContext &Ctx = TheModule.getContext();
7126 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7127 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7130 void CodeGenModule::EmitCoverageFile() {
7131 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
7132 if (!CUNode)
7133 return;
7135 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
7136 llvm::LLVMContext &Ctx = TheModule.getContext();
7137 auto *CoverageDataFile =
7138 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
7139 auto *CoverageNotesFile =
7140 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
7141 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7142 llvm::MDNode *CU = CUNode->getOperand(i);
7143 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7144 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7148 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
7149 bool ForEH) {
7150 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
7151 // FIXME: should we even be calling this method if RTTI is disabled
7152 // and it's not for EH?
7153 if (!shouldEmitRTTI(ForEH))
7154 return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
7156 if (ForEH && Ty->isObjCObjectPointerType() &&
7157 LangOpts.ObjCRuntime.isGNUFamily())
7158 return ObjCRuntime->GetEHType(Ty);
7160 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
7163 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
7164 // Do not emit threadprivates in simd-only mode.
7165 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7166 return;
7167 for (auto RefExpr : D->varlists()) {
7168 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7169 bool PerformInit =
7170 VD->getAnyInitializer() &&
7171 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
7172 /*ForRef=*/false);
7174 Address Addr(GetAddrOfGlobalVar(VD),
7175 getTypes().ConvertTypeForMem(VD->getType()),
7176 getContext().getDeclAlign(VD));
7177 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
7178 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7179 CXXGlobalInits.push_back(InitFunction);
7183 llvm::Metadata *
7184 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
7185 StringRef Suffix) {
7186 if (auto *FnType = T->getAs<FunctionProtoType>())
7187 T = getContext().getFunctionType(
7188 FnType->getReturnType(), FnType->getParamTypes(),
7189 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
7191 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
7192 if (InternalId)
7193 return InternalId;
7195 if (isExternallyVisible(T->getLinkage())) {
7196 std::string OutName;
7197 llvm::raw_string_ostream Out(OutName);
7198 getCXXABI().getMangleContext().mangleTypeName(
7199 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
7201 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
7202 Out << ".normalized";
7204 Out << Suffix;
7206 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
7207 } else {
7208 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
7209 llvm::ArrayRef<llvm::Metadata *>());
7212 return InternalId;
7215 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
7216 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
7219 llvm::Metadata *
7220 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
7221 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
7224 // Generalize pointer types to a void pointer with the qualifiers of the
7225 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
7226 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
7227 // 'void *'.
7228 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
7229 if (!Ty->isPointerType())
7230 return Ty;
7232 return Ctx.getPointerType(
7233 QualType(Ctx.VoidTy).withCVRQualifiers(
7234 Ty->getPointeeType().getCVRQualifiers()));
7237 // Apply type generalization to a FunctionType's return and argument types
7238 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
7239 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
7240 SmallVector<QualType, 8> GeneralizedParams;
7241 for (auto &Param : FnType->param_types())
7242 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
7244 return Ctx.getFunctionType(
7245 GeneralizeType(Ctx, FnType->getReturnType()),
7246 GeneralizedParams, FnType->getExtProtoInfo());
7249 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
7250 return Ctx.getFunctionNoProtoType(
7251 GeneralizeType(Ctx, FnType->getReturnType()));
7253 llvm_unreachable("Encountered unknown FunctionType");
7256 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7257 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7258 GeneralizedMetadataIdMap, ".generalized");
7261 /// Returns whether this module needs the "all-vtables" type identifier.
7262 bool CodeGenModule::NeedAllVtablesTypeId() const {
7263 // Returns true if at least one of vtable-based CFI checkers is enabled and
7264 // is not in the trapping mode.
7265 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7266 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7267 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7268 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7269 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7270 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7271 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7272 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7275 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7276 CharUnits Offset,
7277 const CXXRecordDecl *RD) {
7278 llvm::Metadata *MD =
7279 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7280 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7282 if (CodeGenOpts.SanitizeCfiCrossDso)
7283 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7284 VTable->addTypeMetadata(Offset.getQuantity(),
7285 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7287 if (NeedAllVtablesTypeId()) {
7288 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7289 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7293 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7294 if (!SanStats)
7295 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7297 return *SanStats;
7300 llvm::Value *
7301 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7302 CodeGenFunction &CGF) {
7303 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7304 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7305 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7306 auto *Call = CGF.EmitRuntimeCall(
7307 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7308 return Call;
7311 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7312 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7313 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7314 /* forPointeeType= */ true);
7317 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7318 LValueBaseInfo *BaseInfo,
7319 TBAAAccessInfo *TBAAInfo,
7320 bool forPointeeType) {
7321 if (TBAAInfo)
7322 *TBAAInfo = getTBAAAccessInfo(T);
7324 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7325 // that doesn't return the information we need to compute BaseInfo.
7327 // Honor alignment typedef attributes even on incomplete types.
7328 // We also honor them straight for C++ class types, even as pointees;
7329 // there's an expressivity gap here.
7330 if (auto TT = T->getAs<TypedefType>()) {
7331 if (auto Align = TT->getDecl()->getMaxAlignment()) {
7332 if (BaseInfo)
7333 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7334 return getContext().toCharUnitsFromBits(Align);
7338 bool AlignForArray = T->isArrayType();
7340 // Analyze the base element type, so we don't get confused by incomplete
7341 // array types.
7342 T = getContext().getBaseElementType(T);
7344 if (T->isIncompleteType()) {
7345 // We could try to replicate the logic from
7346 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7347 // type is incomplete, so it's impossible to test. We could try to reuse
7348 // getTypeAlignIfKnown, but that doesn't return the information we need
7349 // to set BaseInfo. So just ignore the possibility that the alignment is
7350 // greater than one.
7351 if (BaseInfo)
7352 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7353 return CharUnits::One();
7356 if (BaseInfo)
7357 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7359 CharUnits Alignment;
7360 const CXXRecordDecl *RD;
7361 if (T.getQualifiers().hasUnaligned()) {
7362 Alignment = CharUnits::One();
7363 } else if (forPointeeType && !AlignForArray &&
7364 (RD = T->getAsCXXRecordDecl())) {
7365 // For C++ class pointees, we don't know whether we're pointing at a
7366 // base or a complete object, so we generally need to use the
7367 // non-virtual alignment.
7368 Alignment = getClassPointerAlignment(RD);
7369 } else {
7370 Alignment = getContext().getTypeAlignInChars(T);
7373 // Cap to the global maximum type alignment unless the alignment
7374 // was somehow explicit on the type.
7375 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7376 if (Alignment.getQuantity() > MaxAlign &&
7377 !getContext().isAlignmentRequired(T))
7378 Alignment = CharUnits::fromQuantity(MaxAlign);
7380 return Alignment;
7383 bool CodeGenModule::stopAutoInit() {
7384 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7385 if (StopAfter) {
7386 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7387 // used
7388 if (NumAutoVarInit >= StopAfter) {
7389 return true;
7391 if (!NumAutoVarInit) {
7392 unsigned DiagID = getDiags().getCustomDiagID(
7393 DiagnosticsEngine::Warning,
7394 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7395 "number of times ftrivial-auto-var-init=%1 gets applied.");
7396 getDiags().Report(DiagID)
7397 << StopAfter
7398 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7399 LangOptions::TrivialAutoVarInitKind::Zero
7400 ? "zero"
7401 : "pattern");
7403 ++NumAutoVarInit;
7405 return false;
7408 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7409 const Decl *D) const {
7410 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7411 // postfix beginning with '.' since the symbol name can be demangled.
7412 if (LangOpts.HIP)
7413 OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7414 else
7415 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7417 // If the CUID is not specified we try to generate a unique postfix.
7418 if (getLangOpts().CUID.empty()) {
7419 SourceManager &SM = getContext().getSourceManager();
7420 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7421 assert(PLoc.isValid() && "Source location is expected to be valid.");
7423 // Get the hash of the user defined macros.
7424 llvm::MD5 Hash;
7425 llvm::MD5::MD5Result Result;
7426 for (const auto &Arg : PreprocessorOpts.Macros)
7427 Hash.update(Arg.first);
7428 Hash.final(Result);
7430 // Get the UniqueID for the file containing the decl.
7431 llvm::sys::fs::UniqueID ID;
7432 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7433 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7434 assert(PLoc.isValid() && "Source location is expected to be valid.");
7435 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7436 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7437 << PLoc.getFilename() << EC.message();
7439 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7440 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7441 } else {
7442 OS << getContext().getCUIDHash();
7446 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7447 assert(DeferredDeclsToEmit.empty() &&
7448 "Should have emitted all decls deferred to emit.");
7449 assert(NewBuilder->DeferredDecls.empty() &&
7450 "Newly created module should not have deferred decls");
7451 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7452 assert(EmittedDeferredDecls.empty() &&
7453 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7455 assert(NewBuilder->DeferredVTables.empty() &&
7456 "Newly created module should not have deferred vtables");
7457 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7459 assert(NewBuilder->MangledDeclNames.empty() &&
7460 "Newly created module should not have mangled decl names");
7461 assert(NewBuilder->Manglings.empty() &&
7462 "Newly created module should not have manglings");
7463 NewBuilder->Manglings = std::move(Manglings);
7465 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7467 NewBuilder->TBAA = std::move(TBAA);
7469 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);