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