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