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