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