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