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