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