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