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