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