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