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