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