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