xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision b0f10a1dc34aa1b73faeeabdc2d348074a02c75d)
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         const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1857         Info.appendAttributeMangling(Attr, Out);
1858         break;
1859       }
1860       case MultiVersionKind::TargetVersion: {
1861         auto *Attr = FD->getAttr<TargetVersionAttr>();
1862         const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1863         Info.appendAttributeMangling(Attr, Out);
1864         break;
1865       }
1866       case MultiVersionKind::TargetClones: {
1867         auto *Attr = FD->getAttr<TargetClonesAttr>();
1868         unsigned Index = GD.getMultiVersionIndex();
1869         const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
1870         Info.appendAttributeMangling(Attr, Index, Out);
1871         break;
1872       }
1873       case MultiVersionKind::None:
1874         llvm_unreachable("None multiversion type isn't valid here");
1875       }
1876     }
1877 
1878   // Make unique name for device side static file-scope variable for HIP.
1879   if (CGM.getContext().shouldExternalize(ND) &&
1880       CGM.getLangOpts().GPURelocatableDeviceCode &&
1881       CGM.getLangOpts().CUDAIsDevice)
1882     CGM.printPostfixForExternalizedDecl(Out, ND);
1883 
1884   return std::string(Out.str());
1885 }
1886 
1887 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1888                                             const FunctionDecl *FD,
1889                                             StringRef &CurName) {
1890   if (!FD->isMultiVersion())
1891     return;
1892 
1893   // Get the name of what this would be without the 'target' attribute.  This
1894   // allows us to lookup the version that was emitted when this wasn't a
1895   // multiversion function.
1896   std::string NonTargetName =
1897       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1898   GlobalDecl OtherGD;
1899   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1900     assert(OtherGD.getCanonicalDecl()
1901                .getDecl()
1902                ->getAsFunction()
1903                ->isMultiVersion() &&
1904            "Other GD should now be a multiversioned function");
1905     // OtherFD is the version of this function that was mangled BEFORE
1906     // becoming a MultiVersion function.  It potentially needs to be updated.
1907     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1908                                       .getDecl()
1909                                       ->getAsFunction()
1910                                       ->getMostRecentDecl();
1911     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1912     // This is so that if the initial version was already the 'default'
1913     // version, we don't try to update it.
1914     if (OtherName != NonTargetName) {
1915       // Remove instead of erase, since others may have stored the StringRef
1916       // to this.
1917       const auto ExistingRecord = Manglings.find(NonTargetName);
1918       if (ExistingRecord != std::end(Manglings))
1919         Manglings.remove(&(*ExistingRecord));
1920       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1921       StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1922           Result.first->first();
1923       // If this is the current decl is being created, make sure we update the name.
1924       if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1925         CurName = OtherNameRef;
1926       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1927         Entry->setName(OtherName);
1928     }
1929   }
1930 }
1931 
1932 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1933   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1934 
1935   // Some ABIs don't have constructor variants.  Make sure that base and
1936   // complete constructors get mangled the same.
1937   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1938     if (!getTarget().getCXXABI().hasConstructorVariants()) {
1939       CXXCtorType OrigCtorType = GD.getCtorType();
1940       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1941       if (OrigCtorType == Ctor_Base)
1942         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1943     }
1944   }
1945 
1946   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1947   // static device variable depends on whether the variable is referenced by
1948   // a host or device host function. Therefore the mangled name cannot be
1949   // cached.
1950   if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
1951     auto FoundName = MangledDeclNames.find(CanonicalGD);
1952     if (FoundName != MangledDeclNames.end())
1953       return FoundName->second;
1954   }
1955 
1956   // Keep the first result in the case of a mangling collision.
1957   const auto *ND = cast<NamedDecl>(GD.getDecl());
1958   std::string MangledName = getMangledNameImpl(*this, GD, ND);
1959 
1960   // Ensure either we have different ABIs between host and device compilations,
1961   // says host compilation following MSVC ABI but device compilation follows
1962   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1963   // mangling should be the same after name stubbing. The later checking is
1964   // very important as the device kernel name being mangled in host-compilation
1965   // is used to resolve the device binaries to be executed. Inconsistent naming
1966   // result in undefined behavior. Even though we cannot check that naming
1967   // directly between host- and device-compilations, the host- and
1968   // device-mangling in host compilation could help catching certain ones.
1969   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1970          getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
1971          (getContext().getAuxTargetInfo() &&
1972           (getContext().getAuxTargetInfo()->getCXXABI() !=
1973            getContext().getTargetInfo().getCXXABI())) ||
1974          getCUDARuntime().getDeviceSideName(ND) ==
1975              getMangledNameImpl(
1976                  *this,
1977                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1978                  ND));
1979 
1980   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1981   return MangledDeclNames[CanonicalGD] = Result.first->first();
1982 }
1983 
1984 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1985                                              const BlockDecl *BD) {
1986   MangleContext &MangleCtx = getCXXABI().getMangleContext();
1987   const Decl *D = GD.getDecl();
1988 
1989   SmallString<256> Buffer;
1990   llvm::raw_svector_ostream Out(Buffer);
1991   if (!D)
1992     MangleCtx.mangleGlobalBlock(BD,
1993       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1994   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1995     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1996   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1997     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1998   else
1999     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
2000 
2001   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2002   return Result.first->first();
2003 }
2004 
2005 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
2006   auto it = MangledDeclNames.begin();
2007   while (it != MangledDeclNames.end()) {
2008     if (it->second == Name)
2009       return it->first;
2010     it++;
2011   }
2012   return GlobalDecl();
2013 }
2014 
2015 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
2016   return getModule().getNamedValue(Name);
2017 }
2018 
2019 /// AddGlobalCtor - Add a function to the list that will be called before
2020 /// main() runs.
2021 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2022                                   unsigned LexOrder,
2023                                   llvm::Constant *AssociatedData) {
2024   // FIXME: Type coercion of void()* types.
2025   GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
2026 }
2027 
2028 /// AddGlobalDtor - Add a function to the list that will be called
2029 /// when the module is unloaded.
2030 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2031                                   bool IsDtorAttrFunc) {
2032   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2033       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
2034     DtorsUsingAtExit[Priority].push_back(Dtor);
2035     return;
2036   }
2037 
2038   // FIXME: Type coercion of void()* types.
2039   GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
2040 }
2041 
2042 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
2043   if (Fns.empty()) return;
2044 
2045   // Ctor function type is void()*.
2046   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
2047   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
2048       TheModule.getDataLayout().getProgramAddressSpace());
2049 
2050   // Get the type of a ctor entry, { i32, void ()*, i8* }.
2051   llvm::StructType *CtorStructTy = llvm::StructType::get(
2052       Int32Ty, CtorPFTy, VoidPtrTy);
2053 
2054   // Construct the constructor and destructor arrays.
2055   ConstantInitBuilder builder(*this);
2056   auto ctors = builder.beginArray(CtorStructTy);
2057   for (const auto &I : Fns) {
2058     auto ctor = ctors.beginStruct(CtorStructTy);
2059     ctor.addInt(Int32Ty, I.Priority);
2060     ctor.add(I.Initializer);
2061     if (I.AssociatedData)
2062       ctor.add(I.AssociatedData);
2063     else
2064       ctor.addNullPointer(VoidPtrTy);
2065     ctor.finishAndAddTo(ctors);
2066   }
2067 
2068   auto list =
2069     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
2070                                 /*constant*/ false,
2071                                 llvm::GlobalValue::AppendingLinkage);
2072 
2073   // The LTO linker doesn't seem to like it when we set an alignment
2074   // on appending variables.  Take it off as a workaround.
2075   list->setAlignment(std::nullopt);
2076 
2077   Fns.clear();
2078 }
2079 
2080 llvm::GlobalValue::LinkageTypes
2081 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
2082   const auto *D = cast<FunctionDecl>(GD.getDecl());
2083 
2084   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
2085 
2086   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2087     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
2088 
2089   return getLLVMLinkageForDeclarator(D, Linkage);
2090 }
2091 
2092 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
2093   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2094   if (!MDS) return nullptr;
2095 
2096   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
2097 }
2098 
2099 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
2100   if (auto *FnType = T->getAs<FunctionProtoType>())
2101     T = getContext().getFunctionType(
2102         FnType->getReturnType(), FnType->getParamTypes(),
2103         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2104 
2105   std::string OutName;
2106   llvm::raw_string_ostream Out(OutName);
2107   getCXXABI().getMangleContext().mangleCanonicalTypeName(
2108       T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2109 
2110   if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2111     Out << ".normalized";
2112 
2113   return llvm::ConstantInt::get(Int32Ty,
2114                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2115 }
2116 
2117 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
2118                                               const CGFunctionInfo &Info,
2119                                               llvm::Function *F, bool IsThunk) {
2120   unsigned CallingConv;
2121   llvm::AttributeList PAL;
2122   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2123                          /*AttrOnCallSite=*/false, IsThunk);
2124   if (CallingConv == llvm::CallingConv::X86_VectorCall &&
2125       getTarget().getTriple().isWindowsArm64EC()) {
2126     SourceLocation Loc;
2127     if (const Decl *D = GD.getDecl())
2128       Loc = D->getLocation();
2129 
2130     Error(Loc, "__vectorcall calling convention is not currently supported");
2131   }
2132   F->setAttributes(PAL);
2133   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2134 }
2135 
2136 static void removeImageAccessQualifier(std::string& TyName) {
2137   std::string ReadOnlyQual("__read_only");
2138   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2139   if (ReadOnlyPos != std::string::npos)
2140     // "+ 1" for the space after access qualifier.
2141     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2142   else {
2143     std::string WriteOnlyQual("__write_only");
2144     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2145     if (WriteOnlyPos != std::string::npos)
2146       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2147     else {
2148       std::string ReadWriteQual("__read_write");
2149       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2150       if (ReadWritePos != std::string::npos)
2151         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2152     }
2153   }
2154 }
2155 
2156 // Returns the address space id that should be produced to the
2157 // kernel_arg_addr_space metadata. This is always fixed to the ids
2158 // as specified in the SPIR 2.0 specification in order to differentiate
2159 // for example in clGetKernelArgInfo() implementation between the address
2160 // spaces with targets without unique mapping to the OpenCL address spaces
2161 // (basically all single AS CPUs).
2162 static unsigned ArgInfoAddressSpace(LangAS AS) {
2163   switch (AS) {
2164   case LangAS::opencl_global:
2165     return 1;
2166   case LangAS::opencl_constant:
2167     return 2;
2168   case LangAS::opencl_local:
2169     return 3;
2170   case LangAS::opencl_generic:
2171     return 4; // Not in SPIR 2.0 specs.
2172   case LangAS::opencl_global_device:
2173     return 5;
2174   case LangAS::opencl_global_host:
2175     return 6;
2176   default:
2177     return 0; // Assume private.
2178   }
2179 }
2180 
2181 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
2182                                          const FunctionDecl *FD,
2183                                          CodeGenFunction *CGF) {
2184   assert(((FD && CGF) || (!FD && !CGF)) &&
2185          "Incorrect use - FD and CGF should either be both null or not!");
2186   // Create MDNodes that represent the kernel arg metadata.
2187   // Each MDNode is a list in the form of "key", N number of values which is
2188   // the same number of values as their are kernel arguments.
2189 
2190   const PrintingPolicy &Policy = Context.getPrintingPolicy();
2191 
2192   // MDNode for the kernel argument address space qualifiers.
2193   SmallVector<llvm::Metadata *, 8> addressQuals;
2194 
2195   // MDNode for the kernel argument access qualifiers (images only).
2196   SmallVector<llvm::Metadata *, 8> accessQuals;
2197 
2198   // MDNode for the kernel argument type names.
2199   SmallVector<llvm::Metadata *, 8> argTypeNames;
2200 
2201   // MDNode for the kernel argument base type names.
2202   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2203 
2204   // MDNode for the kernel argument type qualifiers.
2205   SmallVector<llvm::Metadata *, 8> argTypeQuals;
2206 
2207   // MDNode for the kernel argument names.
2208   SmallVector<llvm::Metadata *, 8> argNames;
2209 
2210   if (FD && CGF)
2211     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2212       const ParmVarDecl *parm = FD->getParamDecl(i);
2213       // Get argument name.
2214       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2215 
2216       if (!getLangOpts().OpenCL)
2217         continue;
2218       QualType ty = parm->getType();
2219       std::string typeQuals;
2220 
2221       // Get image and pipe access qualifier:
2222       if (ty->isImageType() || ty->isPipeType()) {
2223         const Decl *PDecl = parm;
2224         if (const auto *TD = ty->getAs<TypedefType>())
2225           PDecl = TD->getDecl();
2226         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2227         if (A && A->isWriteOnly())
2228           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2229         else if (A && A->isReadWrite())
2230           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2231         else
2232           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2233       } else
2234         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2235 
2236       auto getTypeSpelling = [&](QualType Ty) {
2237         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2238 
2239         if (Ty.isCanonical()) {
2240           StringRef typeNameRef = typeName;
2241           // Turn "unsigned type" to "utype"
2242           if (typeNameRef.consume_front("unsigned "))
2243             return std::string("u") + typeNameRef.str();
2244           if (typeNameRef.consume_front("signed "))
2245             return typeNameRef.str();
2246         }
2247 
2248         return typeName;
2249       };
2250 
2251       if (ty->isPointerType()) {
2252         QualType pointeeTy = ty->getPointeeType();
2253 
2254         // Get address qualifier.
2255         addressQuals.push_back(
2256             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2257                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2258 
2259         // Get argument type name.
2260         std::string typeName = getTypeSpelling(pointeeTy) + "*";
2261         std::string baseTypeName =
2262             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2263         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2264         argBaseTypeNames.push_back(
2265             llvm::MDString::get(VMContext, baseTypeName));
2266 
2267         // Get argument type qualifiers:
2268         if (ty.isRestrictQualified())
2269           typeQuals = "restrict";
2270         if (pointeeTy.isConstQualified() ||
2271             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
2272           typeQuals += typeQuals.empty() ? "const" : " const";
2273         if (pointeeTy.isVolatileQualified())
2274           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2275       } else {
2276         uint32_t AddrSpc = 0;
2277         bool isPipe = ty->isPipeType();
2278         if (ty->isImageType() || isPipe)
2279           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
2280 
2281         addressQuals.push_back(
2282             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2283 
2284         // Get argument type name.
2285         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2286         std::string typeName = getTypeSpelling(ty);
2287         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2288 
2289         // Remove access qualifiers on images
2290         // (as they are inseparable from type in clang implementation,
2291         // but OpenCL spec provides a special query to get access qualifier
2292         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2293         if (ty->isImageType()) {
2294           removeImageAccessQualifier(typeName);
2295           removeImageAccessQualifier(baseTypeName);
2296         }
2297 
2298         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2299         argBaseTypeNames.push_back(
2300             llvm::MDString::get(VMContext, baseTypeName));
2301 
2302         if (isPipe)
2303           typeQuals = "pipe";
2304       }
2305       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2306     }
2307 
2308   if (getLangOpts().OpenCL) {
2309     Fn->setMetadata("kernel_arg_addr_space",
2310                     llvm::MDNode::get(VMContext, addressQuals));
2311     Fn->setMetadata("kernel_arg_access_qual",
2312                     llvm::MDNode::get(VMContext, accessQuals));
2313     Fn->setMetadata("kernel_arg_type",
2314                     llvm::MDNode::get(VMContext, argTypeNames));
2315     Fn->setMetadata("kernel_arg_base_type",
2316                     llvm::MDNode::get(VMContext, argBaseTypeNames));
2317     Fn->setMetadata("kernel_arg_type_qual",
2318                     llvm::MDNode::get(VMContext, argTypeQuals));
2319   }
2320   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2321       getCodeGenOpts().HIPSaveKernelArgName)
2322     Fn->setMetadata("kernel_arg_name",
2323                     llvm::MDNode::get(VMContext, argNames));
2324 }
2325 
2326 /// Determines whether the language options require us to model
2327 /// unwind exceptions.  We treat -fexceptions as mandating this
2328 /// except under the fragile ObjC ABI with only ObjC exceptions
2329 /// enabled.  This means, for example, that C with -fexceptions
2330 /// enables this.
2331 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2332   // If exceptions are completely disabled, obviously this is false.
2333   if (!LangOpts.Exceptions) return false;
2334 
2335   // If C++ exceptions are enabled, this is true.
2336   if (LangOpts.CXXExceptions) return true;
2337 
2338   // If ObjC exceptions are enabled, this depends on the ABI.
2339   if (LangOpts.ObjCExceptions) {
2340     return LangOpts.ObjCRuntime.hasUnwindExceptions();
2341   }
2342 
2343   return true;
2344 }
2345 
2346 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
2347                                                       const CXXMethodDecl *MD) {
2348   // Check that the type metadata can ever actually be used by a call.
2349   if (!CGM.getCodeGenOpts().LTOUnit ||
2350       !CGM.HasHiddenLTOVisibility(MD->getParent()))
2351     return false;
2352 
2353   // Only functions whose address can be taken with a member function pointer
2354   // need this sort of type metadata.
2355   return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2356          !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2357 }
2358 
2359 SmallVector<const CXXRecordDecl *, 0>
2360 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
2361   llvm::SetVector<const CXXRecordDecl *> MostBases;
2362 
2363   std::function<void (const CXXRecordDecl *)> CollectMostBases;
2364   CollectMostBases = [&](const CXXRecordDecl *RD) {
2365     if (RD->getNumBases() == 0)
2366       MostBases.insert(RD);
2367     for (const CXXBaseSpecifier &B : RD->bases())
2368       CollectMostBases(B.getType()->getAsCXXRecordDecl());
2369   };
2370   CollectMostBases(RD);
2371   return MostBases.takeVector();
2372 }
2373 
2374 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2375                                                            llvm::Function *F) {
2376   llvm::AttrBuilder B(F->getContext());
2377 
2378   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2379     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2380 
2381   if (CodeGenOpts.StackClashProtector)
2382     B.addAttribute("probe-stack", "inline-asm");
2383 
2384   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2385     B.addAttribute("stack-probe-size",
2386                    std::to_string(CodeGenOpts.StackProbeSize));
2387 
2388   if (!hasUnwindExceptions(LangOpts))
2389     B.addAttribute(llvm::Attribute::NoUnwind);
2390 
2391   if (D && D->hasAttr<NoStackProtectorAttr>())
2392     ; // Do nothing.
2393   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2394            isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2395     B.addAttribute(llvm::Attribute::StackProtectStrong);
2396   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2397     B.addAttribute(llvm::Attribute::StackProtect);
2398   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong))
2399     B.addAttribute(llvm::Attribute::StackProtectStrong);
2400   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
2401     B.addAttribute(llvm::Attribute::StackProtectReq);
2402 
2403   if (!D) {
2404     // If we don't have a declaration to control inlining, the function isn't
2405     // explicitly marked as alwaysinline for semantic reasons, and inlining is
2406     // disabled, mark the function as noinline.
2407     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2408         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2409       B.addAttribute(llvm::Attribute::NoInline);
2410 
2411     F->addFnAttrs(B);
2412     return;
2413   }
2414 
2415   // Handle SME attributes that apply to function definitions,
2416   // rather than to function prototypes.
2417   if (D->hasAttr<ArmLocallyStreamingAttr>())
2418     B.addAttribute("aarch64_pstate_sm_body");
2419 
2420   if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2421     if (Attr->isNewZA())
2422       B.addAttribute("aarch64_new_za");
2423     if (Attr->isNewZT0())
2424       B.addAttribute("aarch64_new_zt0");
2425   }
2426 
2427   // Track whether we need to add the optnone LLVM attribute,
2428   // starting with the default for this optimization level.
2429   bool ShouldAddOptNone =
2430       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2431   // We can't add optnone in the following cases, it won't pass the verifier.
2432   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2433   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2434 
2435   // Add optnone, but do so only if the function isn't always_inline.
2436   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2437       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2438     B.addAttribute(llvm::Attribute::OptimizeNone);
2439 
2440     // OptimizeNone implies noinline; we should not be inlining such functions.
2441     B.addAttribute(llvm::Attribute::NoInline);
2442 
2443     // We still need to handle naked functions even though optnone subsumes
2444     // much of their semantics.
2445     if (D->hasAttr<NakedAttr>())
2446       B.addAttribute(llvm::Attribute::Naked);
2447 
2448     // OptimizeNone wins over OptimizeForSize and MinSize.
2449     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2450     F->removeFnAttr(llvm::Attribute::MinSize);
2451   } else if (D->hasAttr<NakedAttr>()) {
2452     // Naked implies noinline: we should not be inlining such functions.
2453     B.addAttribute(llvm::Attribute::Naked);
2454     B.addAttribute(llvm::Attribute::NoInline);
2455   } else if (D->hasAttr<NoDuplicateAttr>()) {
2456     B.addAttribute(llvm::Attribute::NoDuplicate);
2457   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2458     // Add noinline if the function isn't always_inline.
2459     B.addAttribute(llvm::Attribute::NoInline);
2460   } else if (D->hasAttr<AlwaysInlineAttr>() &&
2461              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2462     // (noinline wins over always_inline, and we can't specify both in IR)
2463     B.addAttribute(llvm::Attribute::AlwaysInline);
2464   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2465     // If we're not inlining, then force everything that isn't always_inline to
2466     // carry an explicit noinline attribute.
2467     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2468       B.addAttribute(llvm::Attribute::NoInline);
2469   } else {
2470     // Otherwise, propagate the inline hint attribute and potentially use its
2471     // absence to mark things as noinline.
2472     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2473       // Search function and template pattern redeclarations for inline.
2474       auto CheckForInline = [](const FunctionDecl *FD) {
2475         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2476           return Redecl->isInlineSpecified();
2477         };
2478         if (any_of(FD->redecls(), CheckRedeclForInline))
2479           return true;
2480         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2481         if (!Pattern)
2482           return false;
2483         return any_of(Pattern->redecls(), CheckRedeclForInline);
2484       };
2485       if (CheckForInline(FD)) {
2486         B.addAttribute(llvm::Attribute::InlineHint);
2487       } else if (CodeGenOpts.getInlining() ==
2488                      CodeGenOptions::OnlyHintInlining &&
2489                  !FD->isInlined() &&
2490                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2491         B.addAttribute(llvm::Attribute::NoInline);
2492       }
2493     }
2494   }
2495 
2496   // Add other optimization related attributes if we are optimizing this
2497   // function.
2498   if (!D->hasAttr<OptimizeNoneAttr>()) {
2499     if (D->hasAttr<ColdAttr>()) {
2500       if (!ShouldAddOptNone)
2501         B.addAttribute(llvm::Attribute::OptimizeForSize);
2502       B.addAttribute(llvm::Attribute::Cold);
2503     }
2504     if (D->hasAttr<HotAttr>())
2505       B.addAttribute(llvm::Attribute::Hot);
2506     if (D->hasAttr<MinSizeAttr>())
2507       B.addAttribute(llvm::Attribute::MinSize);
2508   }
2509 
2510   F->addFnAttrs(B);
2511 
2512   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2513   if (alignment)
2514     F->setAlignment(llvm::Align(alignment));
2515 
2516   if (!D->hasAttr<AlignedAttr>())
2517     if (LangOpts.FunctionAlignment)
2518       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2519 
2520   // Some C++ ABIs require 2-byte alignment for member functions, in order to
2521   // reserve a bit for differentiating between virtual and non-virtual member
2522   // functions. If the current target's C++ ABI requires this and this is a
2523   // member function, set its alignment accordingly.
2524   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2525     if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2526       F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2527   }
2528 
2529   // In the cross-dso CFI mode with canonical jump tables, we want !type
2530   // attributes on definitions only.
2531   if (CodeGenOpts.SanitizeCfiCrossDso &&
2532       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2533     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2534       // Skip available_externally functions. They won't be codegen'ed in the
2535       // current module anyway.
2536       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2537         CreateFunctionTypeMetadataForIcall(FD, F);
2538     }
2539   }
2540 
2541   // Emit type metadata on member functions for member function pointer checks.
2542   // These are only ever necessary on definitions; we're guaranteed that the
2543   // definition will be present in the LTO unit as a result of LTO visibility.
2544   auto *MD = dyn_cast<CXXMethodDecl>(D);
2545   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2546     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2547       llvm::Metadata *Id =
2548           CreateMetadataIdentifierForType(Context.getMemberPointerType(
2549               MD->getType(), Context.getRecordType(Base).getTypePtr()));
2550       F->addTypeMetadata(0, Id);
2551     }
2552   }
2553 }
2554 
2555 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2556   const Decl *D = GD.getDecl();
2557   if (isa_and_nonnull<NamedDecl>(D))
2558     setGVProperties(GV, GD);
2559   else
2560     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2561 
2562   if (D && D->hasAttr<UsedAttr>())
2563     addUsedOrCompilerUsedGlobal(GV);
2564 
2565   if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2566       VD &&
2567       ((CodeGenOpts.KeepPersistentStorageVariables &&
2568         (VD->getStorageDuration() == SD_Static ||
2569          VD->getStorageDuration() == SD_Thread)) ||
2570        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2571         VD->getType().isConstQualified())))
2572     addUsedOrCompilerUsedGlobal(GV);
2573 }
2574 
2575 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2576                                                 llvm::AttrBuilder &Attrs,
2577                                                 bool SetTargetFeatures) {
2578   // Add target-cpu and target-features attributes to functions. If
2579   // we have a decl for the function and it has a target attribute then
2580   // parse that and add it to the feature set.
2581   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2582   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2583   std::vector<std::string> Features;
2584   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2585   FD = FD ? FD->getMostRecentDecl() : FD;
2586   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2587   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2588   assert((!TD || !TV) && "both target_version and target specified");
2589   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2590   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2591   bool AddedAttr = false;
2592   if (TD || TV || SD || TC) {
2593     llvm::StringMap<bool> FeatureMap;
2594     getContext().getFunctionFeatureMap(FeatureMap, GD);
2595 
2596     // Produce the canonical string for this set of features.
2597     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2598       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2599 
2600     // Now add the target-cpu and target-features to the function.
2601     // While we populated the feature map above, we still need to
2602     // get and parse the target attribute so we can get the cpu for
2603     // the function.
2604     if (TD) {
2605       ParsedTargetAttr ParsedAttr =
2606           Target.parseTargetAttr(TD->getFeaturesStr());
2607       if (!ParsedAttr.CPU.empty() &&
2608           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2609         TargetCPU = ParsedAttr.CPU;
2610         TuneCPU = ""; // Clear the tune CPU.
2611       }
2612       if (!ParsedAttr.Tune.empty() &&
2613           getTarget().isValidCPUName(ParsedAttr.Tune))
2614         TuneCPU = ParsedAttr.Tune;
2615     }
2616 
2617     if (SD) {
2618       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2619       // favor this processor.
2620       TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2621     }
2622   } else {
2623     // Otherwise just add the existing target cpu and target features to the
2624     // function.
2625     Features = getTarget().getTargetOpts().Features;
2626   }
2627 
2628   if (!TargetCPU.empty()) {
2629     Attrs.addAttribute("target-cpu", TargetCPU);
2630     AddedAttr = true;
2631   }
2632   if (!TuneCPU.empty()) {
2633     Attrs.addAttribute("tune-cpu", TuneCPU);
2634     AddedAttr = true;
2635   }
2636   if (!Features.empty() && SetTargetFeatures) {
2637     llvm::erase_if(Features, [&](const std::string& F) {
2638        return getTarget().isReadOnlyFeature(F.substr(1));
2639     });
2640     llvm::sort(Features);
2641     Attrs.addAttribute("target-features", llvm::join(Features, ","));
2642     AddedAttr = true;
2643   }
2644 
2645   return AddedAttr;
2646 }
2647 
2648 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2649                                           llvm::GlobalObject *GO) {
2650   const Decl *D = GD.getDecl();
2651   SetCommonAttributes(GD, GO);
2652 
2653   if (D) {
2654     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2655       if (D->hasAttr<RetainAttr>())
2656         addUsedGlobal(GV);
2657       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2658         GV->addAttribute("bss-section", SA->getName());
2659       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2660         GV->addAttribute("data-section", SA->getName());
2661       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2662         GV->addAttribute("rodata-section", SA->getName());
2663       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2664         GV->addAttribute("relro-section", SA->getName());
2665     }
2666 
2667     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2668       if (D->hasAttr<RetainAttr>())
2669         addUsedGlobal(F);
2670       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2671         if (!D->getAttr<SectionAttr>())
2672           F->setSection(SA->getName());
2673 
2674       llvm::AttrBuilder Attrs(F->getContext());
2675       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2676         // We know that GetCPUAndFeaturesAttributes will always have the
2677         // newest set, since it has the newest possible FunctionDecl, so the
2678         // new ones should replace the old.
2679         llvm::AttributeMask RemoveAttrs;
2680         RemoveAttrs.addAttribute("target-cpu");
2681         RemoveAttrs.addAttribute("target-features");
2682         RemoveAttrs.addAttribute("tune-cpu");
2683         F->removeFnAttrs(RemoveAttrs);
2684         F->addFnAttrs(Attrs);
2685       }
2686     }
2687 
2688     if (const auto *CSA = D->getAttr<CodeSegAttr>())
2689       GO->setSection(CSA->getName());
2690     else if (const auto *SA = D->getAttr<SectionAttr>())
2691       GO->setSection(SA->getName());
2692   }
2693 
2694   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2695 }
2696 
2697 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2698                                                   llvm::Function *F,
2699                                                   const CGFunctionInfo &FI) {
2700   const Decl *D = GD.getDecl();
2701   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2702   SetLLVMFunctionAttributesForDefinition(D, F);
2703 
2704   F->setLinkage(llvm::Function::InternalLinkage);
2705 
2706   setNonAliasAttributes(GD, F);
2707 }
2708 
2709 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2710   // Set linkage and visibility in case we never see a definition.
2711   LinkageInfo LV = ND->getLinkageAndVisibility();
2712   // Don't set internal linkage on declarations.
2713   // "extern_weak" is overloaded in LLVM; we probably should have
2714   // separate linkage types for this.
2715   if (isExternallyVisible(LV.getLinkage()) &&
2716       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2717     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2718 }
2719 
2720 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2721                                                        llvm::Function *F) {
2722   // Only if we are checking indirect calls.
2723   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2724     return;
2725 
2726   // Non-static class methods are handled via vtable or member function pointer
2727   // checks elsewhere.
2728   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2729     return;
2730 
2731   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2732   F->addTypeMetadata(0, MD);
2733   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2734 
2735   // Emit a hash-based bit set entry for cross-DSO calls.
2736   if (CodeGenOpts.SanitizeCfiCrossDso)
2737     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2738       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2739 }
2740 
2741 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2742   llvm::LLVMContext &Ctx = F->getContext();
2743   llvm::MDBuilder MDB(Ctx);
2744   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2745                  llvm::MDNode::get(
2746                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2747 }
2748 
2749 static bool allowKCFIIdentifier(StringRef Name) {
2750   // KCFI type identifier constants are only necessary for external assembly
2751   // functions, which means it's safe to skip unusual names. Subset of
2752   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2753   return llvm::all_of(Name, [](const char &C) {
2754     return llvm::isAlnum(C) || C == '_' || C == '.';
2755   });
2756 }
2757 
2758 void CodeGenModule::finalizeKCFITypes() {
2759   llvm::Module &M = getModule();
2760   for (auto &F : M.functions()) {
2761     // Remove KCFI type metadata from non-address-taken local functions.
2762     bool AddressTaken = F.hasAddressTaken();
2763     if (!AddressTaken && F.hasLocalLinkage())
2764       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2765 
2766     // Generate a constant with the expected KCFI type identifier for all
2767     // address-taken function declarations to support annotating indirectly
2768     // called assembly functions.
2769     if (!AddressTaken || !F.isDeclaration())
2770       continue;
2771 
2772     const llvm::ConstantInt *Type;
2773     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2774       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2775     else
2776       continue;
2777 
2778     StringRef Name = F.getName();
2779     if (!allowKCFIIdentifier(Name))
2780       continue;
2781 
2782     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2783                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2784                           .str();
2785     M.appendModuleInlineAsm(Asm);
2786   }
2787 }
2788 
2789 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2790                                           bool IsIncompleteFunction,
2791                                           bool IsThunk) {
2792 
2793   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2794     // If this is an intrinsic function, set the function's attributes
2795     // to the intrinsic's attributes.
2796     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2797     return;
2798   }
2799 
2800   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2801 
2802   if (!IsIncompleteFunction)
2803     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2804                               IsThunk);
2805 
2806   // Add the Returned attribute for "this", except for iOS 5 and earlier
2807   // where substantial code, including the libstdc++ dylib, was compiled with
2808   // GCC and does not actually return "this".
2809   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2810       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2811     assert(!F->arg_empty() &&
2812            F->arg_begin()->getType()
2813              ->canLosslesslyBitCastTo(F->getReturnType()) &&
2814            "unexpected this return");
2815     F->addParamAttr(0, llvm::Attribute::Returned);
2816   }
2817 
2818   // Only a few attributes are set on declarations; these may later be
2819   // overridden by a definition.
2820 
2821   setLinkageForGV(F, FD);
2822   setGVProperties(F, FD);
2823 
2824   // Setup target-specific attributes.
2825   if (!IsIncompleteFunction && F->isDeclaration())
2826     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2827 
2828   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2829     F->setSection(CSA->getName());
2830   else if (const auto *SA = FD->getAttr<SectionAttr>())
2831      F->setSection(SA->getName());
2832 
2833   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2834     if (EA->isError())
2835       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2836     else if (EA->isWarning())
2837       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2838   }
2839 
2840   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2841   if (FD->isInlineBuiltinDeclaration()) {
2842     const FunctionDecl *FDBody;
2843     bool HasBody = FD->hasBody(FDBody);
2844     (void)HasBody;
2845     assert(HasBody && "Inline builtin declarations should always have an "
2846                       "available body!");
2847     if (shouldEmitFunction(FDBody))
2848       F->addFnAttr(llvm::Attribute::NoBuiltin);
2849   }
2850 
2851   if (FD->isReplaceableGlobalAllocationFunction()) {
2852     // A replaceable global allocation function does not act like a builtin by
2853     // default, only if it is invoked by a new-expression or delete-expression.
2854     F->addFnAttr(llvm::Attribute::NoBuiltin);
2855   }
2856 
2857   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2858     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2859   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2860     if (MD->isVirtual())
2861       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2862 
2863   // Don't emit entries for function declarations in the cross-DSO mode. This
2864   // is handled with better precision by the receiving DSO. But if jump tables
2865   // are non-canonical then we need type metadata in order to produce the local
2866   // jump table.
2867   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2868       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2869     CreateFunctionTypeMetadataForIcall(FD, F);
2870 
2871   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2872     setKCFIType(FD, F);
2873 
2874   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2875     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2876 
2877   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2878     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2879 
2880   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2881     // Annotate the callback behavior as metadata:
2882     //  - The callback callee (as argument number).
2883     //  - The callback payloads (as argument numbers).
2884     llvm::LLVMContext &Ctx = F->getContext();
2885     llvm::MDBuilder MDB(Ctx);
2886 
2887     // The payload indices are all but the first one in the encoding. The first
2888     // identifies the callback callee.
2889     int CalleeIdx = *CB->encoding_begin();
2890     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2891     F->addMetadata(llvm::LLVMContext::MD_callback,
2892                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2893                                                CalleeIdx, PayloadIndices,
2894                                                /* VarArgsArePassed */ false)}));
2895   }
2896 }
2897 
2898 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2899   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2900          "Only globals with definition can force usage.");
2901   LLVMUsed.emplace_back(GV);
2902 }
2903 
2904 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2905   assert(!GV->isDeclaration() &&
2906          "Only globals with definition can force usage.");
2907   LLVMCompilerUsed.emplace_back(GV);
2908 }
2909 
2910 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2911   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2912          "Only globals with definition can force usage.");
2913   if (getTriple().isOSBinFormatELF())
2914     LLVMCompilerUsed.emplace_back(GV);
2915   else
2916     LLVMUsed.emplace_back(GV);
2917 }
2918 
2919 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2920                      std::vector<llvm::WeakTrackingVH> &List) {
2921   // Don't create llvm.used if there is no need.
2922   if (List.empty())
2923     return;
2924 
2925   // Convert List to what ConstantArray needs.
2926   SmallVector<llvm::Constant*, 8> UsedArray;
2927   UsedArray.resize(List.size());
2928   for (unsigned i = 0, e = List.size(); i != e; ++i) {
2929     UsedArray[i] =
2930         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2931             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2932   }
2933 
2934   if (UsedArray.empty())
2935     return;
2936   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2937 
2938   auto *GV = new llvm::GlobalVariable(
2939       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2940       llvm::ConstantArray::get(ATy, UsedArray), Name);
2941 
2942   GV->setSection("llvm.metadata");
2943 }
2944 
2945 void CodeGenModule::emitLLVMUsed() {
2946   emitUsed(*this, "llvm.used", LLVMUsed);
2947   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2948 }
2949 
2950 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2951   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2952   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2953 }
2954 
2955 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2956   llvm::SmallString<32> Opt;
2957   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2958   if (Opt.empty())
2959     return;
2960   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2961   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2962 }
2963 
2964 void CodeGenModule::AddDependentLib(StringRef Lib) {
2965   auto &C = getLLVMContext();
2966   if (getTarget().getTriple().isOSBinFormatELF()) {
2967       ELFDependentLibraries.push_back(
2968         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2969     return;
2970   }
2971 
2972   llvm::SmallString<24> Opt;
2973   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2974   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2975   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2976 }
2977 
2978 /// Add link options implied by the given module, including modules
2979 /// it depends on, using a postorder walk.
2980 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2981                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2982                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2983   // Import this module's parent.
2984   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2985     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2986   }
2987 
2988   // Import this module's dependencies.
2989   for (Module *Import : llvm::reverse(Mod->Imports)) {
2990     if (Visited.insert(Import).second)
2991       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2992   }
2993 
2994   // Add linker options to link against the libraries/frameworks
2995   // described by this module.
2996   llvm::LLVMContext &Context = CGM.getLLVMContext();
2997   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2998 
2999   // For modules that use export_as for linking, use that module
3000   // name instead.
3001   if (Mod->UseExportAsModuleLinkName)
3002     return;
3003 
3004   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
3005     // Link against a framework.  Frameworks are currently Darwin only, so we
3006     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3007     if (LL.IsFramework) {
3008       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3009                                  llvm::MDString::get(Context, LL.Library)};
3010 
3011       Metadata.push_back(llvm::MDNode::get(Context, Args));
3012       continue;
3013     }
3014 
3015     // Link against a library.
3016     if (IsELF) {
3017       llvm::Metadata *Args[2] = {
3018           llvm::MDString::get(Context, "lib"),
3019           llvm::MDString::get(Context, LL.Library),
3020       };
3021       Metadata.push_back(llvm::MDNode::get(Context, Args));
3022     } else {
3023       llvm::SmallString<24> Opt;
3024       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
3025       auto *OptString = llvm::MDString::get(Context, Opt);
3026       Metadata.push_back(llvm::MDNode::get(Context, OptString));
3027     }
3028   }
3029 }
3030 
3031 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3032   assert(Primary->isNamedModuleUnit() &&
3033          "We should only emit module initializers for named modules.");
3034 
3035   // Emit the initializers in the order that sub-modules appear in the
3036   // source, first Global Module Fragments, if present.
3037   if (auto GMF = Primary->getGlobalModuleFragment()) {
3038     for (Decl *D : getContext().getModuleInitializers(GMF)) {
3039       if (isa<ImportDecl>(D))
3040         continue;
3041       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3042       EmitTopLevelDecl(D);
3043     }
3044   }
3045   // Second any associated with the module, itself.
3046   for (Decl *D : getContext().getModuleInitializers(Primary)) {
3047     // Skip import decls, the inits for those are called explicitly.
3048     if (isa<ImportDecl>(D))
3049       continue;
3050     EmitTopLevelDecl(D);
3051   }
3052   // Third any associated with the Privat eMOdule Fragment, if present.
3053   if (auto PMF = Primary->getPrivateModuleFragment()) {
3054     for (Decl *D : getContext().getModuleInitializers(PMF)) {
3055       // Skip import decls, the inits for those are called explicitly.
3056       if (isa<ImportDecl>(D))
3057         continue;
3058       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3059       EmitTopLevelDecl(D);
3060     }
3061   }
3062 }
3063 
3064 void CodeGenModule::EmitModuleLinkOptions() {
3065   // Collect the set of all of the modules we want to visit to emit link
3066   // options, which is essentially the imported modules and all of their
3067   // non-explicit child modules.
3068   llvm::SetVector<clang::Module *> LinkModules;
3069   llvm::SmallPtrSet<clang::Module *, 16> Visited;
3070   SmallVector<clang::Module *, 16> Stack;
3071 
3072   // Seed the stack with imported modules.
3073   for (Module *M : ImportedModules) {
3074     // Do not add any link flags when an implementation TU of a module imports
3075     // a header of that same module.
3076     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3077         !getLangOpts().isCompilingModule())
3078       continue;
3079     if (Visited.insert(M).second)
3080       Stack.push_back(M);
3081   }
3082 
3083   // Find all of the modules to import, making a little effort to prune
3084   // non-leaf modules.
3085   while (!Stack.empty()) {
3086     clang::Module *Mod = Stack.pop_back_val();
3087 
3088     bool AnyChildren = false;
3089 
3090     // Visit the submodules of this module.
3091     for (const auto &SM : Mod->submodules()) {
3092       // Skip explicit children; they need to be explicitly imported to be
3093       // linked against.
3094       if (SM->IsExplicit)
3095         continue;
3096 
3097       if (Visited.insert(SM).second) {
3098         Stack.push_back(SM);
3099         AnyChildren = true;
3100       }
3101     }
3102 
3103     // We didn't find any children, so add this module to the list of
3104     // modules to link against.
3105     if (!AnyChildren) {
3106       LinkModules.insert(Mod);
3107     }
3108   }
3109 
3110   // Add link options for all of the imported modules in reverse topological
3111   // order.  We don't do anything to try to order import link flags with respect
3112   // to linker options inserted by things like #pragma comment().
3113   SmallVector<llvm::MDNode *, 16> MetadataArgs;
3114   Visited.clear();
3115   for (Module *M : LinkModules)
3116     if (Visited.insert(M).second)
3117       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
3118   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3119   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3120 
3121   // Add the linker options metadata flag.
3122   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
3123   for (auto *MD : LinkerOptionsMetadata)
3124     NMD->addOperand(MD);
3125 }
3126 
3127 void CodeGenModule::EmitDeferred() {
3128   // Emit deferred declare target declarations.
3129   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3130     getOpenMPRuntime().emitDeferredTargetDecls();
3131 
3132   // Emit code for any potentially referenced deferred decls.  Since a
3133   // previously unused static decl may become used during the generation of code
3134   // for a static function, iterate until no changes are made.
3135 
3136   if (!DeferredVTables.empty()) {
3137     EmitDeferredVTables();
3138 
3139     // Emitting a vtable doesn't directly cause more vtables to
3140     // become deferred, although it can cause functions to be
3141     // emitted that then need those vtables.
3142     assert(DeferredVTables.empty());
3143   }
3144 
3145   // Emit CUDA/HIP static device variables referenced by host code only.
3146   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3147   // needed for further handling.
3148   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3149     llvm::append_range(DeferredDeclsToEmit,
3150                        getContext().CUDADeviceVarODRUsedByHost);
3151 
3152   // Stop if we're out of both deferred vtables and deferred declarations.
3153   if (DeferredDeclsToEmit.empty())
3154     return;
3155 
3156   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3157   // work, it will not interfere with this.
3158   std::vector<GlobalDecl> CurDeclsToEmit;
3159   CurDeclsToEmit.swap(DeferredDeclsToEmit);
3160 
3161   for (GlobalDecl &D : CurDeclsToEmit) {
3162     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3163     // to get GlobalValue with exactly the type we need, not something that
3164     // might had been created for another decl with the same mangled name but
3165     // different type.
3166     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3167         GetAddrOfGlobal(D, ForDefinition));
3168 
3169     // In case of different address spaces, we may still get a cast, even with
3170     // IsForDefinition equal to true. Query mangled names table to get
3171     // GlobalValue.
3172     if (!GV)
3173       GV = GetGlobalValue(getMangledName(D));
3174 
3175     // Make sure GetGlobalValue returned non-null.
3176     assert(GV);
3177 
3178     // Check to see if we've already emitted this.  This is necessary
3179     // for a couple of reasons: first, decls can end up in the
3180     // deferred-decls queue multiple times, and second, decls can end
3181     // up with definitions in unusual ways (e.g. by an extern inline
3182     // function acquiring a strong function redefinition).  Just
3183     // ignore these cases.
3184     if (!GV->isDeclaration())
3185       continue;
3186 
3187     // If this is OpenMP, check if it is legal to emit this global normally.
3188     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3189       continue;
3190 
3191     // Otherwise, emit the definition and move on to the next one.
3192     EmitGlobalDefinition(D, GV);
3193 
3194     // If we found out that we need to emit more decls, do that recursively.
3195     // This has the advantage that the decls are emitted in a DFS and related
3196     // ones are close together, which is convenient for testing.
3197     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3198       EmitDeferred();
3199       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3200     }
3201   }
3202 }
3203 
3204 void CodeGenModule::EmitVTablesOpportunistically() {
3205   // Try to emit external vtables as available_externally if they have emitted
3206   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
3207   // is not allowed to create new references to things that need to be emitted
3208   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3209 
3210   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3211          && "Only emit opportunistic vtables with optimizations");
3212 
3213   for (const CXXRecordDecl *RD : OpportunisticVTables) {
3214     assert(getVTables().isVTableExternal(RD) &&
3215            "This queue should only contain external vtables");
3216     if (getCXXABI().canSpeculativelyEmitVTable(RD))
3217       VTables.GenerateClassData(RD);
3218   }
3219   OpportunisticVTables.clear();
3220 }
3221 
3222 void CodeGenModule::EmitGlobalAnnotations() {
3223   for (const auto& [MangledName, VD] : DeferredAnnotations) {
3224     llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3225     if (GV)
3226       AddGlobalAnnotations(VD, GV);
3227   }
3228   DeferredAnnotations.clear();
3229 
3230   if (Annotations.empty())
3231     return;
3232 
3233   // Create a new global variable for the ConstantStruct in the Module.
3234   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3235     Annotations[0]->getType(), Annotations.size()), Annotations);
3236   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3237                                       llvm::GlobalValue::AppendingLinkage,
3238                                       Array, "llvm.global.annotations");
3239   gv->setSection(AnnotationSection);
3240 }
3241 
3242 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3243   llvm::Constant *&AStr = AnnotationStrings[Str];
3244   if (AStr)
3245     return AStr;
3246 
3247   // Not found yet, create a new global.
3248   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3249   auto *gv = new llvm::GlobalVariable(
3250       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3251       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3252       ConstGlobalsPtrTy->getAddressSpace());
3253   gv->setSection(AnnotationSection);
3254   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3255   AStr = gv;
3256   return gv;
3257 }
3258 
3259 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
3260   SourceManager &SM = getContext().getSourceManager();
3261   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3262   if (PLoc.isValid())
3263     return EmitAnnotationString(PLoc.getFilename());
3264   return EmitAnnotationString(SM.getBufferName(Loc));
3265 }
3266 
3267 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
3268   SourceManager &SM = getContext().getSourceManager();
3269   PresumedLoc PLoc = SM.getPresumedLoc(L);
3270   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3271     SM.getExpansionLineNumber(L);
3272   return llvm::ConstantInt::get(Int32Ty, LineNo);
3273 }
3274 
3275 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3276   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3277   if (Exprs.empty())
3278     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3279 
3280   llvm::FoldingSetNodeID ID;
3281   for (Expr *E : Exprs) {
3282     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3283   }
3284   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3285   if (Lookup)
3286     return Lookup;
3287 
3288   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3289   LLVMArgs.reserve(Exprs.size());
3290   ConstantEmitter ConstEmiter(*this);
3291   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3292     const auto *CE = cast<clang::ConstantExpr>(E);
3293     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3294                                     CE->getType());
3295   });
3296   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3297   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3298                                       llvm::GlobalValue::PrivateLinkage, Struct,
3299                                       ".args");
3300   GV->setSection(AnnotationSection);
3301   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3302 
3303   Lookup = GV;
3304   return GV;
3305 }
3306 
3307 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3308                                                 const AnnotateAttr *AA,
3309                                                 SourceLocation L) {
3310   // Get the globals for file name, annotation, and the line number.
3311   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3312                  *UnitGV = EmitAnnotationUnit(L),
3313                  *LineNoCst = EmitAnnotationLineNo(L),
3314                  *Args = EmitAnnotationArgs(AA);
3315 
3316   llvm::Constant *GVInGlobalsAS = GV;
3317   if (GV->getAddressSpace() !=
3318       getDataLayout().getDefaultGlobalsAddressSpace()) {
3319     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3320         GV,
3321         llvm::PointerType::get(
3322             GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3323   }
3324 
3325   // Create the ConstantStruct for the global annotation.
3326   llvm::Constant *Fields[] = {
3327       GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3328   };
3329   return llvm::ConstantStruct::getAnon(Fields);
3330 }
3331 
3332 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
3333                                          llvm::GlobalValue *GV) {
3334   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3335   // Get the struct elements for these annotations.
3336   for (const auto *I : D->specific_attrs<AnnotateAttr>())
3337     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3338 }
3339 
3340 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
3341                                        SourceLocation Loc) const {
3342   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3343   // NoSanitize by function name.
3344   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3345     return true;
3346   // NoSanitize by location. Check "mainfile" prefix.
3347   auto &SM = Context.getSourceManager();
3348   FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3349   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3350     return true;
3351 
3352   // Check "src" prefix.
3353   if (Loc.isValid())
3354     return NoSanitizeL.containsLocation(Kind, Loc);
3355   // If location is unknown, this may be a compiler-generated function. Assume
3356   // it's located in the main file.
3357   return NoSanitizeL.containsFile(Kind, MainFile.getName());
3358 }
3359 
3360 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
3361                                        llvm::GlobalVariable *GV,
3362                                        SourceLocation Loc, QualType Ty,
3363                                        StringRef Category) const {
3364   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3365   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3366     return true;
3367   auto &SM = Context.getSourceManager();
3368   if (NoSanitizeL.containsMainFile(
3369           Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3370           Category))
3371     return true;
3372   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3373     return true;
3374 
3375   // Check global type.
3376   if (!Ty.isNull()) {
3377     // Drill down the array types: if global variable of a fixed type is
3378     // not sanitized, we also don't instrument arrays of them.
3379     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3380       Ty = AT->getElementType();
3381     Ty = Ty.getCanonicalType().getUnqualifiedType();
3382     // Only record types (classes, structs etc.) are ignored.
3383     if (Ty->isRecordType()) {
3384       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3385       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3386         return true;
3387     }
3388   }
3389   return false;
3390 }
3391 
3392 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3393                                    StringRef Category) const {
3394   const auto &XRayFilter = getContext().getXRayFilter();
3395   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3396   auto Attr = ImbueAttr::NONE;
3397   if (Loc.isValid())
3398     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3399   if (Attr == ImbueAttr::NONE)
3400     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3401   switch (Attr) {
3402   case ImbueAttr::NONE:
3403     return false;
3404   case ImbueAttr::ALWAYS:
3405     Fn->addFnAttr("function-instrument", "xray-always");
3406     break;
3407   case ImbueAttr::ALWAYS_ARG1:
3408     Fn->addFnAttr("function-instrument", "xray-always");
3409     Fn->addFnAttr("xray-log-args", "1");
3410     break;
3411   case ImbueAttr::NEVER:
3412     Fn->addFnAttr("function-instrument", "xray-never");
3413     break;
3414   }
3415   return true;
3416 }
3417 
3418 ProfileList::ExclusionType
3419 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3420                                               SourceLocation Loc) const {
3421   const auto &ProfileList = getContext().getProfileList();
3422   // If the profile list is empty, then instrument everything.
3423   if (ProfileList.isEmpty())
3424     return ProfileList::Allow;
3425   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3426   // First, check the function name.
3427   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3428     return *V;
3429   // Next, check the source location.
3430   if (Loc.isValid())
3431     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3432       return *V;
3433   // If location is unknown, this may be a compiler-generated function. Assume
3434   // it's located in the main file.
3435   auto &SM = Context.getSourceManager();
3436   if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3437     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3438       return *V;
3439   return ProfileList.getDefault(Kind);
3440 }
3441 
3442 ProfileList::ExclusionType
3443 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3444                                                  SourceLocation Loc) const {
3445   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3446   if (V != ProfileList::Allow)
3447     return V;
3448 
3449   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3450   if (NumGroups > 1) {
3451     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3452     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3453       return ProfileList::Skip;
3454   }
3455   return ProfileList::Allow;
3456 }
3457 
3458 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3459   // Never defer when EmitAllDecls is specified.
3460   if (LangOpts.EmitAllDecls)
3461     return true;
3462 
3463   const auto *VD = dyn_cast<VarDecl>(Global);
3464   if (VD &&
3465       ((CodeGenOpts.KeepPersistentStorageVariables &&
3466         (VD->getStorageDuration() == SD_Static ||
3467          VD->getStorageDuration() == SD_Thread)) ||
3468        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3469         VD->getType().isConstQualified())))
3470     return true;
3471 
3472   return getContext().DeclMustBeEmitted(Global);
3473 }
3474 
3475 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3476   // In OpenMP 5.0 variables and function may be marked as
3477   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3478   // that they must be emitted on the host/device. To be sure we need to have
3479   // seen a declare target with an explicit mentioning of the function, we know
3480   // we have if the level of the declare target attribute is -1. Note that we
3481   // check somewhere else if we should emit this at all.
3482   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3483     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3484         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3485     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3486       return false;
3487   }
3488 
3489   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3490     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3491       // Implicit template instantiations may change linkage if they are later
3492       // explicitly instantiated, so they should not be emitted eagerly.
3493       return false;
3494     // Defer until all versions have been semantically checked.
3495     if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion())
3496       return false;
3497   }
3498   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3499     if (Context.getInlineVariableDefinitionKind(VD) ==
3500         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3501       // A definition of an inline constexpr static data member may change
3502       // linkage later if it's redeclared outside the class.
3503       return false;
3504     if (CXX20ModuleInits && VD->getOwningModule() &&
3505         !VD->getOwningModule()->isModuleMapModule()) {
3506       // For CXX20, module-owned initializers need to be deferred, since it is
3507       // not known at this point if they will be run for the current module or
3508       // as part of the initializer for an imported one.
3509       return false;
3510     }
3511   }
3512   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3513   // codegen for global variables, because they may be marked as threadprivate.
3514   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3515       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3516       !Global->getType().isConstantStorage(getContext(), false, false) &&
3517       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3518     return false;
3519 
3520   return true;
3521 }
3522 
3523 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3524   StringRef Name = getMangledName(GD);
3525 
3526   // The UUID descriptor should be pointer aligned.
3527   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3528 
3529   // Look for an existing global.
3530   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3531     return ConstantAddress(GV, GV->getValueType(), Alignment);
3532 
3533   ConstantEmitter Emitter(*this);
3534   llvm::Constant *Init;
3535 
3536   APValue &V = GD->getAsAPValue();
3537   if (!V.isAbsent()) {
3538     // If possible, emit the APValue version of the initializer. In particular,
3539     // this gets the type of the constant right.
3540     Init = Emitter.emitForInitializer(
3541         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3542   } else {
3543     // As a fallback, directly construct the constant.
3544     // FIXME: This may get padding wrong under esoteric struct layout rules.
3545     // MSVC appears to create a complete type 'struct __s_GUID' that it
3546     // presumably uses to represent these constants.
3547     MSGuidDecl::Parts Parts = GD->getParts();
3548     llvm::Constant *Fields[4] = {
3549         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3550         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3551         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3552         llvm::ConstantDataArray::getRaw(
3553             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3554             Int8Ty)};
3555     Init = llvm::ConstantStruct::getAnon(Fields);
3556   }
3557 
3558   auto *GV = new llvm::GlobalVariable(
3559       getModule(), Init->getType(),
3560       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3561   if (supportsCOMDAT())
3562     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3563   setDSOLocal(GV);
3564 
3565   if (!V.isAbsent()) {
3566     Emitter.finalize(GV);
3567     return ConstantAddress(GV, GV->getValueType(), Alignment);
3568   }
3569 
3570   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3571   return ConstantAddress(GV, Ty, Alignment);
3572 }
3573 
3574 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3575     const UnnamedGlobalConstantDecl *GCD) {
3576   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3577 
3578   llvm::GlobalVariable **Entry = nullptr;
3579   Entry = &UnnamedGlobalConstantDeclMap[GCD];
3580   if (*Entry)
3581     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3582 
3583   ConstantEmitter Emitter(*this);
3584   llvm::Constant *Init;
3585 
3586   const APValue &V = GCD->getValue();
3587 
3588   assert(!V.isAbsent());
3589   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3590                                     GCD->getType());
3591 
3592   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3593                                       /*isConstant=*/true,
3594                                       llvm::GlobalValue::PrivateLinkage, Init,
3595                                       ".constant");
3596   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3597   GV->setAlignment(Alignment.getAsAlign());
3598 
3599   Emitter.finalize(GV);
3600 
3601   *Entry = GV;
3602   return ConstantAddress(GV, GV->getValueType(), Alignment);
3603 }
3604 
3605 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3606     const TemplateParamObjectDecl *TPO) {
3607   StringRef Name = getMangledName(TPO);
3608   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3609 
3610   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3611     return ConstantAddress(GV, GV->getValueType(), Alignment);
3612 
3613   ConstantEmitter Emitter(*this);
3614   llvm::Constant *Init = Emitter.emitForInitializer(
3615         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3616 
3617   if (!Init) {
3618     ErrorUnsupported(TPO, "template parameter object");
3619     return ConstantAddress::invalid();
3620   }
3621 
3622   llvm::GlobalValue::LinkageTypes Linkage =
3623       isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
3624           ? llvm::GlobalValue::LinkOnceODRLinkage
3625           : llvm::GlobalValue::InternalLinkage;
3626   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3627                                       /*isConstant=*/true, Linkage, Init, Name);
3628   setGVProperties(GV, TPO);
3629   if (supportsCOMDAT())
3630     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3631   Emitter.finalize(GV);
3632 
3633     return ConstantAddress(GV, GV->getValueType(), Alignment);
3634 }
3635 
3636 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3637   const AliasAttr *AA = VD->getAttr<AliasAttr>();
3638   assert(AA && "No alias?");
3639 
3640   CharUnits Alignment = getContext().getDeclAlign(VD);
3641   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3642 
3643   // See if there is already something with the target's name in the module.
3644   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3645   if (Entry)
3646     return ConstantAddress(Entry, DeclTy, Alignment);
3647 
3648   llvm::Constant *Aliasee;
3649   if (isa<llvm::FunctionType>(DeclTy))
3650     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3651                                       GlobalDecl(cast<FunctionDecl>(VD)),
3652                                       /*ForVTable=*/false);
3653   else
3654     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3655                                     nullptr);
3656 
3657   auto *F = cast<llvm::GlobalValue>(Aliasee);
3658   F->setLinkage(llvm::Function::ExternalWeakLinkage);
3659   WeakRefReferences.insert(F);
3660 
3661   return ConstantAddress(Aliasee, DeclTy, Alignment);
3662 }
3663 
3664 template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
3665   if (!D)
3666     return false;
3667   if (auto *A = D->getAttr<AttrT>())
3668     return A->isImplicit();
3669   return D->isImplicit();
3670 }
3671 
3672 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3673   const auto *Global = cast<ValueDecl>(GD.getDecl());
3674 
3675   // Weak references don't produce any output by themselves.
3676   if (Global->hasAttr<WeakRefAttr>())
3677     return;
3678 
3679   // If this is an alias definition (which otherwise looks like a declaration)
3680   // emit it now.
3681   if (Global->hasAttr<AliasAttr>())
3682     return EmitAliasDefinition(GD);
3683 
3684   // IFunc like an alias whose value is resolved at runtime by calling resolver.
3685   if (Global->hasAttr<IFuncAttr>())
3686     return emitIFuncDefinition(GD);
3687 
3688   // If this is a cpu_dispatch multiversion function, emit the resolver.
3689   if (Global->hasAttr<CPUDispatchAttr>())
3690     return emitCPUDispatchDefinition(GD);
3691 
3692   // If this is CUDA, be selective about which declarations we emit.
3693   // Non-constexpr non-lambda implicit host device functions are not emitted
3694   // unless they are used on device side.
3695   if (LangOpts.CUDA) {
3696     if (LangOpts.CUDAIsDevice) {
3697       const auto *FD = dyn_cast<FunctionDecl>(Global);
3698       if ((!Global->hasAttr<CUDADeviceAttr>() ||
3699            (LangOpts.OffloadImplicitHostDeviceTemplates && FD &&
3700             hasImplicitAttr<CUDAHostAttr>(FD) &&
3701             hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
3702             !isLambdaCallOperator(FD) &&
3703             !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3704           !Global->hasAttr<CUDAGlobalAttr>() &&
3705           !Global->hasAttr<CUDAConstantAttr>() &&
3706           !Global->hasAttr<CUDASharedAttr>() &&
3707           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3708           !Global->getType()->isCUDADeviceBuiltinTextureType() &&
3709           !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
3710             !Global->hasAttr<CUDAHostAttr>()))
3711         return;
3712     } else {
3713       // We need to emit host-side 'shadows' for all global
3714       // device-side variables because the CUDA runtime needs their
3715       // size and host-side address in order to provide access to
3716       // their device-side incarnations.
3717 
3718       // So device-only functions are the only things we skip.
3719       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3720           Global->hasAttr<CUDADeviceAttr>())
3721         return;
3722 
3723       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3724              "Expected Variable or Function");
3725     }
3726   }
3727 
3728   if (LangOpts.OpenMP) {
3729     // If this is OpenMP, check if it is legal to emit this global normally.
3730     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3731       return;
3732     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3733       if (MustBeEmitted(Global))
3734         EmitOMPDeclareReduction(DRD);
3735       return;
3736     }
3737     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3738       if (MustBeEmitted(Global))
3739         EmitOMPDeclareMapper(DMD);
3740       return;
3741     }
3742   }
3743 
3744   // Ignore declarations, they will be emitted on their first use.
3745   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3746     // Update deferred annotations with the latest declaration if the function
3747     // function was already used or defined.
3748     if (FD->hasAttr<AnnotateAttr>()) {
3749       StringRef MangledName = getMangledName(GD);
3750       if (GetGlobalValue(MangledName))
3751         DeferredAnnotations[MangledName] = FD;
3752     }
3753 
3754     // Forward declarations are emitted lazily on first use.
3755     if (!FD->doesThisDeclarationHaveABody()) {
3756       if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
3757           (!FD->isMultiVersion() ||
3758            !FD->getASTContext().getTargetInfo().getTriple().isAArch64()))
3759         return;
3760 
3761       StringRef MangledName = getMangledName(GD);
3762 
3763       // Compute the function info and LLVM type.
3764       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3765       llvm::Type *Ty = getTypes().GetFunctionType(FI);
3766 
3767       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3768                               /*DontDefer=*/false);
3769       return;
3770     }
3771   } else {
3772     const auto *VD = cast<VarDecl>(Global);
3773     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3774     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3775         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3776       if (LangOpts.OpenMP) {
3777         // Emit declaration of the must-be-emitted declare target variable.
3778         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3779                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3780 
3781           // If this variable has external storage and doesn't require special
3782           // link handling we defer to its canonical definition.
3783           if (VD->hasExternalStorage() &&
3784               Res != OMPDeclareTargetDeclAttr::MT_Link)
3785             return;
3786 
3787           bool UnifiedMemoryEnabled =
3788               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3789           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3790                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3791               !UnifiedMemoryEnabled) {
3792             (void)GetAddrOfGlobalVar(VD);
3793           } else {
3794             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3795                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3796                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3797                      UnifiedMemoryEnabled)) &&
3798                    "Link clause or to clause with unified memory expected.");
3799             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3800           }
3801 
3802           return;
3803         }
3804       }
3805       // If this declaration may have caused an inline variable definition to
3806       // change linkage, make sure that it's emitted.
3807       if (Context.getInlineVariableDefinitionKind(VD) ==
3808           ASTContext::InlineVariableDefinitionKind::Strong)
3809         GetAddrOfGlobalVar(VD);
3810       return;
3811     }
3812   }
3813 
3814   // Defer code generation to first use when possible, e.g. if this is an inline
3815   // function. If the global must always be emitted, do it eagerly if possible
3816   // to benefit from cache locality.
3817   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3818     // Emit the definition if it can't be deferred.
3819     EmitGlobalDefinition(GD);
3820     addEmittedDeferredDecl(GD);
3821     return;
3822   }
3823 
3824   // If we're deferring emission of a C++ variable with an
3825   // initializer, remember the order in which it appeared in the file.
3826   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3827       cast<VarDecl>(Global)->hasInit()) {
3828     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3829     CXXGlobalInits.push_back(nullptr);
3830   }
3831 
3832   StringRef MangledName = getMangledName(GD);
3833   if (GetGlobalValue(MangledName) != nullptr) {
3834     // The value has already been used and should therefore be emitted.
3835     addDeferredDeclToEmit(GD);
3836   } else if (MustBeEmitted(Global)) {
3837     // The value must be emitted, but cannot be emitted eagerly.
3838     assert(!MayBeEmittedEagerly(Global));
3839     addDeferredDeclToEmit(GD);
3840   } else {
3841     // Otherwise, remember that we saw a deferred decl with this name.  The
3842     // first use of the mangled name will cause it to move into
3843     // DeferredDeclsToEmit.
3844     DeferredDecls[MangledName] = GD;
3845   }
3846 }
3847 
3848 // Check if T is a class type with a destructor that's not dllimport.
3849 static bool HasNonDllImportDtor(QualType T) {
3850   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3851     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3852       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3853         return true;
3854 
3855   return false;
3856 }
3857 
3858 namespace {
3859   struct FunctionIsDirectlyRecursive
3860       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3861     const StringRef Name;
3862     const Builtin::Context &BI;
3863     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3864         : Name(N), BI(C) {}
3865 
3866     bool VisitCallExpr(const CallExpr *E) {
3867       const FunctionDecl *FD = E->getDirectCallee();
3868       if (!FD)
3869         return false;
3870       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3871       if (Attr && Name == Attr->getLabel())
3872         return true;
3873       unsigned BuiltinID = FD->getBuiltinID();
3874       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3875         return false;
3876       StringRef BuiltinName = BI.getName(BuiltinID);
3877       if (BuiltinName.starts_with("__builtin_") &&
3878           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3879         return true;
3880       }
3881       return false;
3882     }
3883 
3884     bool VisitStmt(const Stmt *S) {
3885       for (const Stmt *Child : S->children())
3886         if (Child && this->Visit(Child))
3887           return true;
3888       return false;
3889     }
3890   };
3891 
3892   // Make sure we're not referencing non-imported vars or functions.
3893   struct DLLImportFunctionVisitor
3894       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3895     bool SafeToInline = true;
3896 
3897     bool shouldVisitImplicitCode() const { return true; }
3898 
3899     bool VisitVarDecl(VarDecl *VD) {
3900       if (VD->getTLSKind()) {
3901         // A thread-local variable cannot be imported.
3902         SafeToInline = false;
3903         return SafeToInline;
3904       }
3905 
3906       // A variable definition might imply a destructor call.
3907       if (VD->isThisDeclarationADefinition())
3908         SafeToInline = !HasNonDllImportDtor(VD->getType());
3909 
3910       return SafeToInline;
3911     }
3912 
3913     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3914       if (const auto *D = E->getTemporary()->getDestructor())
3915         SafeToInline = D->hasAttr<DLLImportAttr>();
3916       return SafeToInline;
3917     }
3918 
3919     bool VisitDeclRefExpr(DeclRefExpr *E) {
3920       ValueDecl *VD = E->getDecl();
3921       if (isa<FunctionDecl>(VD))
3922         SafeToInline = VD->hasAttr<DLLImportAttr>();
3923       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3924         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3925       return SafeToInline;
3926     }
3927 
3928     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3929       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3930       return SafeToInline;
3931     }
3932 
3933     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3934       CXXMethodDecl *M = E->getMethodDecl();
3935       if (!M) {
3936         // Call through a pointer to member function. This is safe to inline.
3937         SafeToInline = true;
3938       } else {
3939         SafeToInline = M->hasAttr<DLLImportAttr>();
3940       }
3941       return SafeToInline;
3942     }
3943 
3944     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3945       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3946       return SafeToInline;
3947     }
3948 
3949     bool VisitCXXNewExpr(CXXNewExpr *E) {
3950       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3951       return SafeToInline;
3952     }
3953   };
3954 }
3955 
3956 // isTriviallyRecursive - Check if this function calls another
3957 // decl that, because of the asm attribute or the other decl being a builtin,
3958 // ends up pointing to itself.
3959 bool
3960 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3961   StringRef Name;
3962   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3963     // asm labels are a special kind of mangling we have to support.
3964     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3965     if (!Attr)
3966       return false;
3967     Name = Attr->getLabel();
3968   } else {
3969     Name = FD->getName();
3970   }
3971 
3972   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3973   const Stmt *Body = FD->getBody();
3974   return Body ? Walker.Visit(Body) : false;
3975 }
3976 
3977 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3978   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3979     return true;
3980 
3981   const auto *F = cast<FunctionDecl>(GD.getDecl());
3982   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3983     return false;
3984 
3985   // We don't import function bodies from other named module units since that
3986   // behavior may break ABI compatibility of the current unit.
3987   if (const Module *M = F->getOwningModule();
3988       M && M->getTopLevelModule()->isNamedModule() &&
3989       getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
3990     // There are practices to mark template member function as always-inline
3991     // and mark the template as extern explicit instantiation but not give
3992     // the definition for member function. So we have to emit the function
3993     // from explicitly instantiation with always-inline.
3994     //
3995     // See https://github.com/llvm/llvm-project/issues/86893 for details.
3996     //
3997     // TODO: Maybe it is better to give it a warning if we call a non-inline
3998     // function from other module units which is marked as always-inline.
3999     if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4000       return false;
4001     }
4002   }
4003 
4004   if (F->hasAttr<NoInlineAttr>())
4005     return false;
4006 
4007   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4008     // Check whether it would be safe to inline this dllimport function.
4009     DLLImportFunctionVisitor Visitor;
4010     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
4011     if (!Visitor.SafeToInline)
4012       return false;
4013 
4014     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4015       // Implicit destructor invocations aren't captured in the AST, so the
4016       // check above can't see them. Check for them manually here.
4017       for (const Decl *Member : Dtor->getParent()->decls())
4018         if (isa<FieldDecl>(Member))
4019           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
4020             return false;
4021       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4022         if (HasNonDllImportDtor(B.getType()))
4023           return false;
4024     }
4025   }
4026 
4027   // Inline builtins declaration must be emitted. They often are fortified
4028   // functions.
4029   if (F->isInlineBuiltinDeclaration())
4030     return true;
4031 
4032   // PR9614. Avoid cases where the source code is lying to us. An available
4033   // externally function should have an equivalent function somewhere else,
4034   // but a function that calls itself through asm label/`__builtin_` trickery is
4035   // clearly not equivalent to the real implementation.
4036   // This happens in glibc's btowc and in some configure checks.
4037   return !isTriviallyRecursive(F);
4038 }
4039 
4040 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4041   return CodeGenOpts.OptimizationLevel > 0;
4042 }
4043 
4044 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4045                                                        llvm::GlobalValue *GV) {
4046   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4047 
4048   if (FD->isCPUSpecificMultiVersion()) {
4049     auto *Spec = FD->getAttr<CPUSpecificAttr>();
4050     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
4051       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4052   } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) {
4053     for (unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4054       // AArch64 favors the default target version over the clone if any.
4055       if ((!TC->isDefaultVersion(I) || !getTarget().getTriple().isAArch64()) &&
4056           TC->isFirstOfVersion(I))
4057         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4058     // Ensure that the resolver function is also emitted.
4059     GetOrCreateMultiVersionResolver(GD);
4060   } else
4061     EmitGlobalFunctionDefinition(GD, GV);
4062 
4063   // Defer the resolver emission until we can reason whether the TU
4064   // contains a default target version implementation.
4065   if (FD->isTargetVersionMultiVersion())
4066     AddDeferredMultiVersionResolverToEmit(GD);
4067 }
4068 
4069 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4070   const auto *D = cast<ValueDecl>(GD.getDecl());
4071 
4072   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
4073                                  Context.getSourceManager(),
4074                                  "Generating code for declaration");
4075 
4076   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4077     // At -O0, don't generate IR for functions with available_externally
4078     // linkage.
4079     if (!shouldEmitFunction(GD))
4080       return;
4081 
4082     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
4083       std::string Name;
4084       llvm::raw_string_ostream OS(Name);
4085       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
4086                                /*Qualified=*/true);
4087       return Name;
4088     });
4089 
4090     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4091       // Make sure to emit the definition(s) before we emit the thunks.
4092       // This is necessary for the generation of certain thunks.
4093       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4094         ABI->emitCXXStructor(GD);
4095       else if (FD->isMultiVersion())
4096         EmitMultiVersionFunctionDefinition(GD, GV);
4097       else
4098         EmitGlobalFunctionDefinition(GD, GV);
4099 
4100       if (Method->isVirtual())
4101         getVTables().EmitThunks(GD);
4102 
4103       return;
4104     }
4105 
4106     if (FD->isMultiVersion())
4107       return EmitMultiVersionFunctionDefinition(GD, GV);
4108     return EmitGlobalFunctionDefinition(GD, GV);
4109   }
4110 
4111   if (const auto *VD = dyn_cast<VarDecl>(D))
4112     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4113 
4114   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4115 }
4116 
4117 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4118                                                       llvm::Function *NewFn);
4119 
4120 static unsigned
4121 TargetMVPriority(const TargetInfo &TI,
4122                  const CodeGenFunction::MultiVersionResolverOption &RO) {
4123   unsigned Priority = 0;
4124   unsigned NumFeatures = 0;
4125   for (StringRef Feat : RO.Conditions.Features) {
4126     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
4127     NumFeatures++;
4128   }
4129 
4130   if (!RO.Conditions.Architecture.empty())
4131     Priority = std::max(
4132         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
4133 
4134   Priority += TI.multiVersionFeatureCost() * NumFeatures;
4135 
4136   return Priority;
4137 }
4138 
4139 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4140 // TU can forward declare the function without causing problems.  Particularly
4141 // in the cases of CPUDispatch, this causes issues. This also makes sure we
4142 // work with internal linkage functions, so that the same function name can be
4143 // used with internal linkage in multiple TUs.
4144 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
4145                                                        GlobalDecl GD) {
4146   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4147   if (FD->getFormalLinkage() == Linkage::Internal)
4148     return llvm::GlobalValue::InternalLinkage;
4149   return llvm::GlobalValue::WeakODRLinkage;
4150 }
4151 
4152 static FunctionDecl *createDefaultTargetVersionFrom(const FunctionDecl *FD) {
4153   auto *DeclCtx = const_cast<DeclContext *>(FD->getDeclContext());
4154   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
4155   StorageClass SC = FD->getStorageClass();
4156   DeclarationName Name = FD->getNameInfo().getName();
4157 
4158   FunctionDecl *NewDecl =
4159       FunctionDecl::Create(FD->getASTContext(), DeclCtx, FD->getBeginLoc(),
4160                            FD->getEndLoc(), Name, TInfo->getType(), TInfo, SC);
4161 
4162   NewDecl->setIsMultiVersion();
4163   NewDecl->addAttr(TargetVersionAttr::CreateImplicit(
4164       NewDecl->getASTContext(), "default", NewDecl->getSourceRange()));
4165 
4166   return NewDecl;
4167 }
4168 
4169 void CodeGenModule::emitMultiVersionFunctions() {
4170   std::vector<GlobalDecl> MVFuncsToEmit;
4171   MultiVersionFuncs.swap(MVFuncsToEmit);
4172   for (GlobalDecl GD : MVFuncsToEmit) {
4173     const auto *FD = cast<FunctionDecl>(GD.getDecl());
4174     assert(FD && "Expected a FunctionDecl");
4175 
4176     auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
4177       GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx};
4178       StringRef MangledName = getMangledName(CurGD);
4179       llvm::Constant *Func = GetGlobalValue(MangledName);
4180       if (!Func) {
4181         if (Decl->isDefined()) {
4182           EmitGlobalFunctionDefinition(CurGD, nullptr);
4183           Func = GetGlobalValue(MangledName);
4184         } else {
4185           const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(CurGD);
4186           llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4187           Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4188                                    /*DontDefer=*/false, ForDefinition);
4189         }
4190         assert(Func && "This should have just been created");
4191       }
4192       return cast<llvm::Function>(Func);
4193     };
4194 
4195     bool HasDefaultDecl = !FD->isTargetVersionMultiVersion();
4196     bool ShouldEmitResolver =
4197         !getContext().getTargetInfo().getTriple().isAArch64();
4198     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4199 
4200     getContext().forEachMultiversionedFunctionVersion(
4201         FD, [&](const FunctionDecl *CurFD) {
4202           llvm::SmallVector<StringRef, 8> Feats;
4203 
4204           if (const auto *TA = CurFD->getAttr<TargetAttr>()) {
4205             TA->getAddedFeatures(Feats);
4206             llvm::Function *Func = createFunction(CurFD);
4207             Options.emplace_back(Func, TA->getArchitecture(), Feats);
4208           } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) {
4209             bool HasDefaultDef = TVA->isDefaultVersion() &&
4210                                  CurFD->doesThisDeclarationHaveABody();
4211             HasDefaultDecl |= TVA->isDefaultVersion();
4212             ShouldEmitResolver |= (CurFD->isUsed() || HasDefaultDef);
4213             TVA->getFeatures(Feats);
4214             llvm::Function *Func = createFunction(CurFD);
4215             Options.emplace_back(Func, /*Architecture*/ "", Feats);
4216           } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) {
4217             ShouldEmitResolver |= CurFD->doesThisDeclarationHaveABody();
4218             for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4219               if (!TC->isFirstOfVersion(I))
4220                 continue;
4221 
4222               llvm::Function *Func = createFunction(CurFD, I);
4223               StringRef Architecture;
4224               Feats.clear();
4225               if (getTarget().getTriple().isAArch64())
4226                 TC->getFeatures(Feats, I);
4227               else {
4228                 StringRef Version = TC->getFeatureStr(I);
4229                 if (Version.starts_with("arch="))
4230                   Architecture = Version.drop_front(sizeof("arch=") - 1);
4231                 else if (Version != "default")
4232                   Feats.push_back(Version);
4233               }
4234               Options.emplace_back(Func, Architecture, Feats);
4235             }
4236           } else
4237             llvm_unreachable("unexpected MultiVersionKind");
4238         });
4239 
4240     if (!ShouldEmitResolver)
4241       continue;
4242 
4243     if (!HasDefaultDecl) {
4244       FunctionDecl *NewFD = createDefaultTargetVersionFrom(FD);
4245       llvm::Function *Func = createFunction(NewFD);
4246       llvm::SmallVector<StringRef, 1> Feats;
4247       Options.emplace_back(Func, /*Architecture*/ "", Feats);
4248     }
4249 
4250     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4251     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4252       ResolverConstant = IFunc->getResolver();
4253       if (FD->isTargetClonesMultiVersion() ||
4254           FD->isTargetVersionMultiVersion()) {
4255         std::string MangledName = getMangledNameImpl(
4256             *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4257         if (!GetGlobalValue(MangledName + ".ifunc")) {
4258           const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4259           llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4260           // In prior versions of Clang, the mangling for ifuncs incorrectly
4261           // included an .ifunc suffix. This alias is generated for backward
4262           // compatibility. It is deprecated, and may be removed in the future.
4263           auto *Alias = llvm::GlobalAlias::create(
4264               DeclTy, 0, getMultiversionLinkage(*this, GD),
4265               MangledName + ".ifunc", IFunc, &getModule());
4266           SetCommonAttributes(FD, Alias);
4267         }
4268       }
4269     }
4270     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4271 
4272     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4273 
4274     if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
4275       ResolverFunc->setComdat(
4276           getModule().getOrInsertComdat(ResolverFunc->getName()));
4277 
4278     const TargetInfo &TI = getTarget();
4279     llvm::stable_sort(
4280         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
4281                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
4282           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
4283         });
4284     CodeGenFunction CGF(*this);
4285     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4286   }
4287 
4288   // Ensure that any additions to the deferred decls list caused by emitting a
4289   // variant are emitted.  This can happen when the variant itself is inline and
4290   // calls a function without linkage.
4291   if (!MVFuncsToEmit.empty())
4292     EmitDeferred();
4293 
4294   // Ensure that any additions to the multiversion funcs list from either the
4295   // deferred decls or the multiversion functions themselves are emitted.
4296   if (!MultiVersionFuncs.empty())
4297     emitMultiVersionFunctions();
4298 }
4299 
4300 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4301   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4302   assert(FD && "Not a FunctionDecl?");
4303   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4304   const auto *DD = FD->getAttr<CPUDispatchAttr>();
4305   assert(DD && "Not a cpu_dispatch Function?");
4306 
4307   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4308   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4309 
4310   StringRef ResolverName = getMangledName(GD);
4311   UpdateMultiVersionNames(GD, FD, ResolverName);
4312 
4313   llvm::Type *ResolverType;
4314   GlobalDecl ResolverGD;
4315   if (getTarget().supportsIFunc()) {
4316     ResolverType = llvm::FunctionType::get(
4317         llvm::PointerType::get(DeclTy,
4318                                getTypes().getTargetAddressSpace(FD->getType())),
4319         false);
4320   }
4321   else {
4322     ResolverType = DeclTy;
4323     ResolverGD = GD;
4324   }
4325 
4326   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4327       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4328   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4329   if (supportsCOMDAT())
4330     ResolverFunc->setComdat(
4331         getModule().getOrInsertComdat(ResolverFunc->getName()));
4332 
4333   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4334   const TargetInfo &Target = getTarget();
4335   unsigned Index = 0;
4336   for (const IdentifierInfo *II : DD->cpus()) {
4337     // Get the name of the target function so we can look it up/create it.
4338     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4339                               getCPUSpecificMangling(*this, II->getName());
4340 
4341     llvm::Constant *Func = GetGlobalValue(MangledName);
4342 
4343     if (!Func) {
4344       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4345       if (ExistingDecl.getDecl() &&
4346           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4347         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4348         Func = GetGlobalValue(MangledName);
4349       } else {
4350         if (!ExistingDecl.getDecl())
4351           ExistingDecl = GD.getWithMultiVersionIndex(Index);
4352 
4353       Func = GetOrCreateLLVMFunction(
4354           MangledName, DeclTy, ExistingDecl,
4355           /*ForVTable=*/false, /*DontDefer=*/true,
4356           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4357       }
4358     }
4359 
4360     llvm::SmallVector<StringRef, 32> Features;
4361     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4362     llvm::transform(Features, Features.begin(),
4363                     [](StringRef Str) { return Str.substr(1); });
4364     llvm::erase_if(Features, [&Target](StringRef Feat) {
4365       return !Target.validateCpuSupports(Feat);
4366     });
4367     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
4368     ++Index;
4369   }
4370 
4371   llvm::stable_sort(
4372       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
4373                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
4374         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4375                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4376       });
4377 
4378   // If the list contains multiple 'default' versions, such as when it contains
4379   // 'pentium' and 'generic', don't emit the call to the generic one (since we
4380   // always run on at least a 'pentium'). We do this by deleting the 'least
4381   // advanced' (read, lowest mangling letter).
4382   while (Options.size() > 1 &&
4383          llvm::all_of(llvm::X86::getCpuSupportsMask(
4384                           (Options.end() - 2)->Conditions.Features),
4385                       [](auto X) { return X == 0; })) {
4386     StringRef LHSName = (Options.end() - 2)->Function->getName();
4387     StringRef RHSName = (Options.end() - 1)->Function->getName();
4388     if (LHSName.compare(RHSName) < 0)
4389       Options.erase(Options.end() - 2);
4390     else
4391       Options.erase(Options.end() - 1);
4392   }
4393 
4394   CodeGenFunction CGF(*this);
4395   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4396 
4397   if (getTarget().supportsIFunc()) {
4398     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4399     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4400 
4401     // Fix up function declarations that were created for cpu_specific before
4402     // cpu_dispatch was known
4403     if (!isa<llvm::GlobalIFunc>(IFunc)) {
4404       assert(cast<llvm::Function>(IFunc)->isDeclaration());
4405       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
4406                                            &getModule());
4407       GI->takeName(IFunc);
4408       IFunc->replaceAllUsesWith(GI);
4409       IFunc->eraseFromParent();
4410       IFunc = GI;
4411     }
4412 
4413     std::string AliasName = getMangledNameImpl(
4414         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4415     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4416     if (!AliasFunc) {
4417       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
4418                                            &getModule());
4419       SetCommonAttributes(GD, GA);
4420     }
4421   }
4422 }
4423 
4424 /// Adds a declaration to the list of multi version functions if not present.
4425 void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4426   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4427   assert(FD && "Not a FunctionDecl?");
4428 
4429   if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) {
4430     std::string MangledName =
4431         getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4432     if (!DeferredResolversToEmit.insert(MangledName).second)
4433       return;
4434   }
4435   MultiVersionFuncs.push_back(GD);
4436 }
4437 
4438 /// If a dispatcher for the specified mangled name is not in the module, create
4439 /// and return an llvm Function with the specified type.
4440 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4441   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4442   assert(FD && "Not a FunctionDecl?");
4443 
4444   std::string MangledName =
4445       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4446 
4447   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4448   // a separate resolver).
4449   std::string ResolverName = MangledName;
4450   if (getTarget().supportsIFunc()) {
4451     switch (FD->getMultiVersionKind()) {
4452     case MultiVersionKind::None:
4453       llvm_unreachable("unexpected MultiVersionKind::None for resolver");
4454     case MultiVersionKind::Target:
4455     case MultiVersionKind::CPUSpecific:
4456     case MultiVersionKind::CPUDispatch:
4457       ResolverName += ".ifunc";
4458       break;
4459     case MultiVersionKind::TargetClones:
4460     case MultiVersionKind::TargetVersion:
4461       break;
4462     }
4463   } else if (FD->isTargetMultiVersion()) {
4464     ResolverName += ".resolver";
4465   }
4466 
4467   // If the resolver has already been created, just return it.
4468   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
4469     return ResolverGV;
4470 
4471   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4472   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4473 
4474   // The resolver needs to be created. For target and target_clones, defer
4475   // creation until the end of the TU.
4476   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
4477     AddDeferredMultiVersionResolverToEmit(GD);
4478 
4479   // For cpu_specific, don't create an ifunc yet because we don't know if the
4480   // cpu_dispatch will be emitted in this translation unit.
4481   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
4482     llvm::Type *ResolverType = llvm::FunctionType::get(
4483         llvm::PointerType::get(DeclTy,
4484                                getTypes().getTargetAddressSpace(FD->getType())),
4485         false);
4486     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4487         MangledName + ".resolver", ResolverType, GlobalDecl{},
4488         /*ForVTable=*/false);
4489     llvm::GlobalIFunc *GIF =
4490         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4491                                   "", Resolver, &getModule());
4492     GIF->setName(ResolverName);
4493     SetCommonAttributes(FD, GIF);
4494 
4495     return GIF;
4496   }
4497 
4498   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4499       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
4500   assert(isa<llvm::GlobalValue>(Resolver) &&
4501          "Resolver should be created for the first time");
4502   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
4503   return Resolver;
4504 }
4505 
4506 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
4507 /// module, create and return an llvm Function with the specified type. If there
4508 /// is something in the module with the specified name, return it potentially
4509 /// bitcasted to the right type.
4510 ///
4511 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4512 /// to set the attributes on the function when it is first created.
4513 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4514     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
4515     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
4516     ForDefinition_t IsForDefinition) {
4517   const Decl *D = GD.getDecl();
4518 
4519   // Any attempts to use a MultiVersion function should result in retrieving
4520   // the iFunc instead. Name Mangling will handle the rest of the changes.
4521   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4522     // For the device mark the function as one that should be emitted.
4523     if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4524         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
4525         !DontDefer && !IsForDefinition) {
4526       if (const FunctionDecl *FDDef = FD->getDefinition()) {
4527         GlobalDecl GDDef;
4528         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4529           GDDef = GlobalDecl(CD, GD.getCtorType());
4530         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4531           GDDef = GlobalDecl(DD, GD.getDtorType());
4532         else
4533           GDDef = GlobalDecl(FDDef);
4534         EmitGlobal(GDDef);
4535       }
4536     }
4537 
4538     if (FD->isMultiVersion()) {
4539       UpdateMultiVersionNames(GD, FD, MangledName);
4540       if (FD->getASTContext().getTargetInfo().getTriple().isAArch64() &&
4541           !FD->isUsed())
4542         AddDeferredMultiVersionResolverToEmit(GD);
4543       else if (!IsForDefinition)
4544         return GetOrCreateMultiVersionResolver(GD);
4545     }
4546   }
4547 
4548   // Lookup the entry, lazily creating it if necessary.
4549   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4550   if (Entry) {
4551     if (WeakRefReferences.erase(Entry)) {
4552       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4553       if (FD && !FD->hasAttr<WeakAttr>())
4554         Entry->setLinkage(llvm::Function::ExternalLinkage);
4555     }
4556 
4557     // Handle dropped DLL attributes.
4558     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4559         !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
4560       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4561       setDSOLocal(Entry);
4562     }
4563 
4564     // If there are two attempts to define the same mangled name, issue an
4565     // error.
4566     if (IsForDefinition && !Entry->isDeclaration()) {
4567       GlobalDecl OtherGD;
4568       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4569       // to make sure that we issue an error only once.
4570       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4571           (GD.getCanonicalDecl().getDecl() !=
4572            OtherGD.getCanonicalDecl().getDecl()) &&
4573           DiagnosedConflictingDefinitions.insert(GD).second) {
4574         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4575             << MangledName;
4576         getDiags().Report(OtherGD.getDecl()->getLocation(),
4577                           diag::note_previous_definition);
4578       }
4579     }
4580 
4581     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4582         (Entry->getValueType() == Ty)) {
4583       return Entry;
4584     }
4585 
4586     // Make sure the result is of the correct type.
4587     // (If function is requested for a definition, we always need to create a new
4588     // function, not just return a bitcast.)
4589     if (!IsForDefinition)
4590       return Entry;
4591   }
4592 
4593   // This function doesn't have a complete type (for example, the return
4594   // type is an incomplete struct). Use a fake type instead, and make
4595   // sure not to try to set attributes.
4596   bool IsIncompleteFunction = false;
4597 
4598   llvm::FunctionType *FTy;
4599   if (isa<llvm::FunctionType>(Ty)) {
4600     FTy = cast<llvm::FunctionType>(Ty);
4601   } else {
4602     FTy = llvm::FunctionType::get(VoidTy, false);
4603     IsIncompleteFunction = true;
4604   }
4605 
4606   llvm::Function *F =
4607       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4608                              Entry ? StringRef() : MangledName, &getModule());
4609 
4610   // Store the declaration associated with this function so it is potentially
4611   // updated by further declarations or definitions and emitted at the end.
4612   if (D && D->hasAttr<AnnotateAttr>())
4613     DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
4614 
4615   // If we already created a function with the same mangled name (but different
4616   // type) before, take its name and add it to the list of functions to be
4617   // replaced with F at the end of CodeGen.
4618   //
4619   // This happens if there is a prototype for a function (e.g. "int f()") and
4620   // then a definition of a different type (e.g. "int f(int x)").
4621   if (Entry) {
4622     F->takeName(Entry);
4623 
4624     // This might be an implementation of a function without a prototype, in
4625     // which case, try to do special replacement of calls which match the new
4626     // prototype.  The really key thing here is that we also potentially drop
4627     // arguments from the call site so as to make a direct call, which makes the
4628     // inliner happier and suppresses a number of optimizer warnings (!) about
4629     // dropping arguments.
4630     if (!Entry->use_empty()) {
4631       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
4632       Entry->removeDeadConstantUsers();
4633     }
4634 
4635     addGlobalValReplacement(Entry, F);
4636   }
4637 
4638   assert(F->getName() == MangledName && "name was uniqued!");
4639   if (D)
4640     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4641   if (ExtraAttrs.hasFnAttrs()) {
4642     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4643     F->addFnAttrs(B);
4644   }
4645 
4646   if (!DontDefer) {
4647     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4648     // each other bottoming out with the base dtor.  Therefore we emit non-base
4649     // dtors on usage, even if there is no dtor definition in the TU.
4650     if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4651         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4652                                            GD.getDtorType()))
4653       addDeferredDeclToEmit(GD);
4654 
4655     // This is the first use or definition of a mangled name.  If there is a
4656     // deferred decl with this name, remember that we need to emit it at the end
4657     // of the file.
4658     auto DDI = DeferredDecls.find(MangledName);
4659     if (DDI != DeferredDecls.end()) {
4660       // Move the potentially referenced deferred decl to the
4661       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4662       // don't need it anymore).
4663       addDeferredDeclToEmit(DDI->second);
4664       DeferredDecls.erase(DDI);
4665 
4666       // Otherwise, there are cases we have to worry about where we're
4667       // using a declaration for which we must emit a definition but where
4668       // we might not find a top-level definition:
4669       //   - member functions defined inline in their classes
4670       //   - friend functions defined inline in some class
4671       //   - special member functions with implicit definitions
4672       // If we ever change our AST traversal to walk into class methods,
4673       // this will be unnecessary.
4674       //
4675       // We also don't emit a definition for a function if it's going to be an
4676       // entry in a vtable, unless it's already marked as used.
4677     } else if (getLangOpts().CPlusPlus && D) {
4678       // Look for a declaration that's lexically in a record.
4679       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4680            FD = FD->getPreviousDecl()) {
4681         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4682           if (FD->doesThisDeclarationHaveABody()) {
4683             addDeferredDeclToEmit(GD.getWithDecl(FD));
4684             break;
4685           }
4686         }
4687       }
4688     }
4689   }
4690 
4691   // Make sure the result is of the requested type.
4692   if (!IsIncompleteFunction) {
4693     assert(F->getFunctionType() == Ty);
4694     return F;
4695   }
4696 
4697   return F;
4698 }
4699 
4700 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
4701 /// non-null, then this function will use the specified type if it has to
4702 /// create it (this occurs when we see a definition of the function).
4703 llvm::Constant *
4704 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
4705                                  bool DontDefer,
4706                                  ForDefinition_t IsForDefinition) {
4707   // If there was no specific requested type, just convert it now.
4708   if (!Ty) {
4709     const auto *FD = cast<FunctionDecl>(GD.getDecl());
4710     Ty = getTypes().ConvertType(FD->getType());
4711   }
4712 
4713   // Devirtualized destructor calls may come through here instead of via
4714   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4715   // of the complete destructor when necessary.
4716   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4717     if (getTarget().getCXXABI().isMicrosoft() &&
4718         GD.getDtorType() == Dtor_Complete &&
4719         DD->getParent()->getNumVBases() == 0)
4720       GD = GlobalDecl(DD, Dtor_Base);
4721   }
4722 
4723   StringRef MangledName = getMangledName(GD);
4724   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4725                                     /*IsThunk=*/false, llvm::AttributeList(),
4726                                     IsForDefinition);
4727   // Returns kernel handle for HIP kernel stub function.
4728   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4729       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4730     auto *Handle = getCUDARuntime().getKernelHandle(
4731         cast<llvm::Function>(F->stripPointerCasts()), GD);
4732     if (IsForDefinition)
4733       return F;
4734     return Handle;
4735   }
4736   return F;
4737 }
4738 
4739 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4740   llvm::GlobalValue *F =
4741       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4742 
4743   return llvm::NoCFIValue::get(F);
4744 }
4745 
4746 static const FunctionDecl *
4747 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4748   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4749   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4750 
4751   IdentifierInfo &CII = C.Idents.get(Name);
4752   for (const auto *Result : DC->lookup(&CII))
4753     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4754       return FD;
4755 
4756   if (!C.getLangOpts().CPlusPlus)
4757     return nullptr;
4758 
4759   // Demangle the premangled name from getTerminateFn()
4760   IdentifierInfo &CXXII =
4761       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4762           ? C.Idents.get("terminate")
4763           : C.Idents.get(Name);
4764 
4765   for (const auto &N : {"__cxxabiv1", "std"}) {
4766     IdentifierInfo &NS = C.Idents.get(N);
4767     for (const auto *Result : DC->lookup(&NS)) {
4768       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4769       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4770         for (const auto *Result : LSD->lookup(&NS))
4771           if ((ND = dyn_cast<NamespaceDecl>(Result)))
4772             break;
4773 
4774       if (ND)
4775         for (const auto *Result : ND->lookup(&CXXII))
4776           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4777             return FD;
4778     }
4779   }
4780 
4781   return nullptr;
4782 }
4783 
4784 /// CreateRuntimeFunction - Create a new runtime function with the specified
4785 /// type and name.
4786 llvm::FunctionCallee
4787 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4788                                      llvm::AttributeList ExtraAttrs, bool Local,
4789                                      bool AssumeConvergent) {
4790   if (AssumeConvergent) {
4791     ExtraAttrs =
4792         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4793   }
4794 
4795   llvm::Constant *C =
4796       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4797                               /*DontDefer=*/false, /*IsThunk=*/false,
4798                               ExtraAttrs);
4799 
4800   if (auto *F = dyn_cast<llvm::Function>(C)) {
4801     if (F->empty()) {
4802       F->setCallingConv(getRuntimeCC());
4803 
4804       // In Windows Itanium environments, try to mark runtime functions
4805       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4806       // will link their standard library statically or dynamically. Marking
4807       // functions imported when they are not imported can cause linker errors
4808       // and warnings.
4809       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4810           !getCodeGenOpts().LTOVisibilityPublicStd) {
4811         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4812         if (!FD || FD->hasAttr<DLLImportAttr>()) {
4813           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4814           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4815         }
4816       }
4817       setDSOLocal(F);
4818       // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
4819       // of trying to approximate the attributes using the LLVM function
4820       // signature. This requires revising the API of CreateRuntimeFunction().
4821       markRegisterParameterAttributes(F);
4822     }
4823   }
4824 
4825   return {FTy, C};
4826 }
4827 
4828 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4829 /// create and return an llvm GlobalVariable with the specified type and address
4830 /// space. If there is something in the module with the specified name, return
4831 /// it potentially bitcasted to the right type.
4832 ///
4833 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4834 /// to set the attributes on the global when it is first created.
4835 ///
4836 /// If IsForDefinition is true, it is guaranteed that an actual global with
4837 /// type Ty will be returned, not conversion of a variable with the same
4838 /// mangled name but some other type.
4839 llvm::Constant *
4840 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4841                                      LangAS AddrSpace, const VarDecl *D,
4842                                      ForDefinition_t IsForDefinition) {
4843   // Lookup the entry, lazily creating it if necessary.
4844   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4845   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4846   if (Entry) {
4847     if (WeakRefReferences.erase(Entry)) {
4848       if (D && !D->hasAttr<WeakAttr>())
4849         Entry->setLinkage(llvm::Function::ExternalLinkage);
4850     }
4851 
4852     // Handle dropped DLL attributes.
4853     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4854         !shouldMapVisibilityToDLLExport(D))
4855       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4856 
4857     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4858       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4859 
4860     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4861       return Entry;
4862 
4863     // If there are two attempts to define the same mangled name, issue an
4864     // error.
4865     if (IsForDefinition && !Entry->isDeclaration()) {
4866       GlobalDecl OtherGD;
4867       const VarDecl *OtherD;
4868 
4869       // Check that D is not yet in DiagnosedConflictingDefinitions is required
4870       // to make sure that we issue an error only once.
4871       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4872           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4873           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4874           OtherD->hasInit() &&
4875           DiagnosedConflictingDefinitions.insert(D).second) {
4876         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4877             << MangledName;
4878         getDiags().Report(OtherGD.getDecl()->getLocation(),
4879                           diag::note_previous_definition);
4880       }
4881     }
4882 
4883     // Make sure the result is of the correct type.
4884     if (Entry->getType()->getAddressSpace() != TargetAS)
4885       return llvm::ConstantExpr::getAddrSpaceCast(
4886           Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
4887 
4888     // (If global is requested for a definition, we always need to create a new
4889     // global, not just return a bitcast.)
4890     if (!IsForDefinition)
4891       return Entry;
4892   }
4893 
4894   auto DAddrSpace = GetGlobalVarAddressSpace(D);
4895 
4896   auto *GV = new llvm::GlobalVariable(
4897       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4898       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4899       getContext().getTargetAddressSpace(DAddrSpace));
4900 
4901   // If we already created a global with the same mangled name (but different
4902   // type) before, take its name and remove it from its parent.
4903   if (Entry) {
4904     GV->takeName(Entry);
4905 
4906     if (!Entry->use_empty()) {
4907       Entry->replaceAllUsesWith(GV);
4908     }
4909 
4910     Entry->eraseFromParent();
4911   }
4912 
4913   // This is the first use or definition of a mangled name.  If there is a
4914   // deferred decl with this name, remember that we need to emit it at the end
4915   // of the file.
4916   auto DDI = DeferredDecls.find(MangledName);
4917   if (DDI != DeferredDecls.end()) {
4918     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4919     // list, and remove it from DeferredDecls (since we don't need it anymore).
4920     addDeferredDeclToEmit(DDI->second);
4921     DeferredDecls.erase(DDI);
4922   }
4923 
4924   // Handle things which are present even on external declarations.
4925   if (D) {
4926     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4927       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4928 
4929     // FIXME: This code is overly simple and should be merged with other global
4930     // handling.
4931     GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
4932 
4933     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4934 
4935     setLinkageForGV(GV, D);
4936 
4937     if (D->getTLSKind()) {
4938       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4939         CXXThreadLocals.push_back(D);
4940       setTLSMode(GV, *D);
4941     }
4942 
4943     setGVProperties(GV, D);
4944 
4945     // If required by the ABI, treat declarations of static data members with
4946     // inline initializers as definitions.
4947     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4948       EmitGlobalVarDefinition(D);
4949     }
4950 
4951     // Emit section information for extern variables.
4952     if (D->hasExternalStorage()) {
4953       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4954         GV->setSection(SA->getName());
4955     }
4956 
4957     // Handle XCore specific ABI requirements.
4958     if (getTriple().getArch() == llvm::Triple::xcore &&
4959         D->getLanguageLinkage() == CLanguageLinkage &&
4960         D->getType().isConstant(Context) &&
4961         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4962       GV->setSection(".cp.rodata");
4963 
4964     // Handle code model attribute
4965     if (const auto *CMA = D->getAttr<CodeModelAttr>())
4966       GV->setCodeModel(CMA->getModel());
4967 
4968     // Check if we a have a const declaration with an initializer, we may be
4969     // able to emit it as available_externally to expose it's value to the
4970     // optimizer.
4971     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4972         D->getType().isConstQualified() && !GV->hasInitializer() &&
4973         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4974       const auto *Record =
4975           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4976       bool HasMutableFields = Record && Record->hasMutableFields();
4977       if (!HasMutableFields) {
4978         const VarDecl *InitDecl;
4979         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4980         if (InitExpr) {
4981           ConstantEmitter emitter(*this);
4982           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4983           if (Init) {
4984             auto *InitType = Init->getType();
4985             if (GV->getValueType() != InitType) {
4986               // The type of the initializer does not match the definition.
4987               // This happens when an initializer has a different type from
4988               // the type of the global (because of padding at the end of a
4989               // structure for instance).
4990               GV->setName(StringRef());
4991               // Make a new global with the correct type, this is now guaranteed
4992               // to work.
4993               auto *NewGV = cast<llvm::GlobalVariable>(
4994                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4995                       ->stripPointerCasts());
4996 
4997               // Erase the old global, since it is no longer used.
4998               GV->eraseFromParent();
4999               GV = NewGV;
5000             } else {
5001               GV->setInitializer(Init);
5002               GV->setConstant(true);
5003               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5004             }
5005             emitter.finalize(GV);
5006           }
5007         }
5008       }
5009     }
5010   }
5011 
5012   if (D &&
5013       D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
5014     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
5015     // External HIP managed variables needed to be recorded for transformation
5016     // in both device and host compilations.
5017     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
5018         D->hasExternalStorage())
5019       getCUDARuntime().handleVarRegistration(D, *GV);
5020   }
5021 
5022   if (D)
5023     SanitizerMD->reportGlobal(GV, *D);
5024 
5025   LangAS ExpectedAS =
5026       D ? D->getType().getAddressSpace()
5027         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
5028   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5029   if (DAddrSpace != ExpectedAS) {
5030     return getTargetCodeGenInfo().performAddrSpaceCast(
5031         *this, GV, DAddrSpace, ExpectedAS,
5032         llvm::PointerType::get(getLLVMContext(), TargetAS));
5033   }
5034 
5035   return GV;
5036 }
5037 
5038 llvm::Constant *
5039 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
5040   const Decl *D = GD.getDecl();
5041 
5042   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
5043     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
5044                                 /*DontDefer=*/false, IsForDefinition);
5045 
5046   if (isa<CXXMethodDecl>(D)) {
5047     auto FInfo =
5048         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
5049     auto Ty = getTypes().GetFunctionType(*FInfo);
5050     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5051                              IsForDefinition);
5052   }
5053 
5054   if (isa<FunctionDecl>(D)) {
5055     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5056     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5057     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5058                              IsForDefinition);
5059   }
5060 
5061   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
5062 }
5063 
5064 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
5065     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
5066     llvm::Align Alignment) {
5067   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
5068   llvm::GlobalVariable *OldGV = nullptr;
5069 
5070   if (GV) {
5071     // Check if the variable has the right type.
5072     if (GV->getValueType() == Ty)
5073       return GV;
5074 
5075     // Because C++ name mangling, the only way we can end up with an already
5076     // existing global with the same name is if it has been declared extern "C".
5077     assert(GV->isDeclaration() && "Declaration has wrong type!");
5078     OldGV = GV;
5079   }
5080 
5081   // Create a new variable.
5082   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
5083                                 Linkage, nullptr, Name);
5084 
5085   if (OldGV) {
5086     // Replace occurrences of the old variable if needed.
5087     GV->takeName(OldGV);
5088 
5089     if (!OldGV->use_empty()) {
5090       OldGV->replaceAllUsesWith(GV);
5091     }
5092 
5093     OldGV->eraseFromParent();
5094   }
5095 
5096   if (supportsCOMDAT() && GV->isWeakForLinker() &&
5097       !GV->hasAvailableExternallyLinkage())
5098     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5099 
5100   GV->setAlignment(Alignment);
5101 
5102   return GV;
5103 }
5104 
5105 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
5106 /// given global variable.  If Ty is non-null and if the global doesn't exist,
5107 /// then it will be created with the specified type instead of whatever the
5108 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
5109 /// that an actual global with type Ty will be returned, not conversion of a
5110 /// variable with the same mangled name but some other type.
5111 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
5112                                                   llvm::Type *Ty,
5113                                            ForDefinition_t IsForDefinition) {
5114   assert(D->hasGlobalStorage() && "Not a global variable");
5115   QualType ASTTy = D->getType();
5116   if (!Ty)
5117     Ty = getTypes().ConvertTypeForMem(ASTTy);
5118 
5119   StringRef MangledName = getMangledName(D);
5120   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
5121                                IsForDefinition);
5122 }
5123 
5124 /// CreateRuntimeVariable - Create a new runtime global variable with the
5125 /// specified type and name.
5126 llvm::Constant *
5127 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
5128                                      StringRef Name) {
5129   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
5130                                                        : LangAS::Default;
5131   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
5132   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5133   return Ret;
5134 }
5135 
5136 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
5137   assert(!D->getInit() && "Cannot emit definite definitions here!");
5138 
5139   StringRef MangledName = getMangledName(D);
5140   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
5141 
5142   // We already have a definition, not declaration, with the same mangled name.
5143   // Emitting of declaration is not required (and actually overwrites emitted
5144   // definition).
5145   if (GV && !GV->isDeclaration())
5146     return;
5147 
5148   // If we have not seen a reference to this variable yet, place it into the
5149   // deferred declarations table to be emitted if needed later.
5150   if (!MustBeEmitted(D) && !GV) {
5151       DeferredDecls[MangledName] = D;
5152       return;
5153   }
5154 
5155   // The tentative definition is the only definition.
5156   EmitGlobalVarDefinition(D);
5157 }
5158 
5159 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
5160   EmitExternalVarDeclaration(D);
5161 }
5162 
5163 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
5164   return Context.toCharUnitsFromBits(
5165       getDataLayout().getTypeStoreSizeInBits(Ty));
5166 }
5167 
5168 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
5169   if (LangOpts.OpenCL) {
5170     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
5171     assert(AS == LangAS::opencl_global ||
5172            AS == LangAS::opencl_global_device ||
5173            AS == LangAS::opencl_global_host ||
5174            AS == LangAS::opencl_constant ||
5175            AS == LangAS::opencl_local ||
5176            AS >= LangAS::FirstTargetAddressSpace);
5177     return AS;
5178   }
5179 
5180   if (LangOpts.SYCLIsDevice &&
5181       (!D || D->getType().getAddressSpace() == LangAS::Default))
5182     return LangAS::sycl_global;
5183 
5184   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5185     if (D) {
5186       if (D->hasAttr<CUDAConstantAttr>())
5187         return LangAS::cuda_constant;
5188       if (D->hasAttr<CUDASharedAttr>())
5189         return LangAS::cuda_shared;
5190       if (D->hasAttr<CUDADeviceAttr>())
5191         return LangAS::cuda_device;
5192       if (D->getType().isConstQualified())
5193         return LangAS::cuda_constant;
5194     }
5195     return LangAS::cuda_device;
5196   }
5197 
5198   if (LangOpts.OpenMP) {
5199     LangAS AS;
5200     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5201       return AS;
5202   }
5203   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
5204 }
5205 
5206 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
5207   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
5208   if (LangOpts.OpenCL)
5209     return LangAS::opencl_constant;
5210   if (LangOpts.SYCLIsDevice)
5211     return LangAS::sycl_global;
5212   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
5213     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5214     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5215     // with OpVariable instructions with Generic storage class which is not
5216     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5217     // UniformConstant storage class is not viable as pointers to it may not be
5218     // casted to Generic pointers which are used to model HIP's "flat" pointers.
5219     return LangAS::cuda_device;
5220   if (auto AS = getTarget().getConstantAddressSpace())
5221     return *AS;
5222   return LangAS::Default;
5223 }
5224 
5225 // In address space agnostic languages, string literals are in default address
5226 // space in AST. However, certain targets (e.g. amdgcn) request them to be
5227 // emitted in constant address space in LLVM IR. To be consistent with other
5228 // parts of AST, string literal global variables in constant address space
5229 // need to be casted to default address space before being put into address
5230 // map and referenced by other part of CodeGen.
5231 // In OpenCL, string literals are in constant address space in AST, therefore
5232 // they should not be casted to default address space.
5233 static llvm::Constant *
5234 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
5235                                        llvm::GlobalVariable *GV) {
5236   llvm::Constant *Cast = GV;
5237   if (!CGM.getLangOpts().OpenCL) {
5238     auto AS = CGM.GetGlobalConstantAddressSpace();
5239     if (AS != LangAS::Default)
5240       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
5241           CGM, GV, AS, LangAS::Default,
5242           llvm::PointerType::get(
5243               CGM.getLLVMContext(),
5244               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
5245   }
5246   return Cast;
5247 }
5248 
5249 template<typename SomeDecl>
5250 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
5251                                                llvm::GlobalValue *GV) {
5252   if (!getLangOpts().CPlusPlus)
5253     return;
5254 
5255   // Must have 'used' attribute, or else inline assembly can't rely on
5256   // the name existing.
5257   if (!D->template hasAttr<UsedAttr>())
5258     return;
5259 
5260   // Must have internal linkage and an ordinary name.
5261   if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal)
5262     return;
5263 
5264   // Must be in an extern "C" context. Entities declared directly within
5265   // a record are not extern "C" even if the record is in such a context.
5266   const SomeDecl *First = D->getFirstDecl();
5267   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
5268     return;
5269 
5270   // OK, this is an internal linkage entity inside an extern "C" linkage
5271   // specification. Make a note of that so we can give it the "expected"
5272   // mangled name if nothing else is using that name.
5273   std::pair<StaticExternCMap::iterator, bool> R =
5274       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5275 
5276   // If we have multiple internal linkage entities with the same name
5277   // in extern "C" regions, none of them gets that name.
5278   if (!R.second)
5279     R.first->second = nullptr;
5280 }
5281 
5282 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
5283   if (!CGM.supportsCOMDAT())
5284     return false;
5285 
5286   if (D.hasAttr<SelectAnyAttr>())
5287     return true;
5288 
5289   GVALinkage Linkage;
5290   if (auto *VD = dyn_cast<VarDecl>(&D))
5291     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
5292   else
5293     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
5294 
5295   switch (Linkage) {
5296   case GVA_Internal:
5297   case GVA_AvailableExternally:
5298   case GVA_StrongExternal:
5299     return false;
5300   case GVA_DiscardableODR:
5301   case GVA_StrongODR:
5302     return true;
5303   }
5304   llvm_unreachable("No such linkage");
5305 }
5306 
5307 bool CodeGenModule::supportsCOMDAT() const {
5308   return getTriple().supportsCOMDAT();
5309 }
5310 
5311 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
5312                                           llvm::GlobalObject &GO) {
5313   if (!shouldBeInCOMDAT(*this, D))
5314     return;
5315   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5316 }
5317 
5318 /// Pass IsTentative as true if you want to create a tentative definition.
5319 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
5320                                             bool IsTentative) {
5321   // OpenCL global variables of sampler type are translated to function calls,
5322   // therefore no need to be translated.
5323   QualType ASTTy = D->getType();
5324   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
5325     return;
5326 
5327   // If this is OpenMP device, check if it is legal to emit this global
5328   // normally.
5329   if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5330       OpenMPRuntime->emitTargetGlobalVariable(D))
5331     return;
5332 
5333   llvm::TrackingVH<llvm::Constant> Init;
5334   bool NeedsGlobalCtor = false;
5335   // Whether the definition of the variable is available externally.
5336   // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5337   // since this is the job for its original source.
5338   bool IsDefinitionAvailableExternally =
5339       getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5340   bool NeedsGlobalDtor =
5341       !IsDefinitionAvailableExternally &&
5342       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
5343 
5344   // It is helpless to emit the definition for an available_externally variable
5345   // which can't be marked as const.
5346   // We don't need to check if it needs global ctor or dtor. See the above
5347   // comment for ideas.
5348   if (IsDefinitionAvailableExternally &&
5349       (!D->hasConstantInitialization() ||
5350        // TODO: Update this when we have interface to check constexpr
5351        // destructor.
5352        D->needsDestruction(getContext()) ||
5353        !D->getType().isConstantStorage(getContext(), true, true)))
5354     return;
5355 
5356   const VarDecl *InitDecl;
5357   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5358 
5359   std::optional<ConstantEmitter> emitter;
5360 
5361   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5362   // as part of their declaration."  Sema has already checked for
5363   // error cases, so we just need to set Init to UndefValue.
5364   bool IsCUDASharedVar =
5365       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5366   // Shadows of initialized device-side global variables are also left
5367   // undefined.
5368   // Managed Variables should be initialized on both host side and device side.
5369   bool IsCUDAShadowVar =
5370       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5371       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
5372        D->hasAttr<CUDASharedAttr>());
5373   bool IsCUDADeviceShadowVar =
5374       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5375       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5376        D->getType()->isCUDADeviceBuiltinTextureType());
5377   if (getLangOpts().CUDA &&
5378       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5379     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5380   else if (D->hasAttr<LoaderUninitializedAttr>())
5381     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5382   else if (!InitExpr) {
5383     // This is a tentative definition; tentative definitions are
5384     // implicitly initialized with { 0 }.
5385     //
5386     // Note that tentative definitions are only emitted at the end of
5387     // a translation unit, so they should never have incomplete
5388     // type. In addition, EmitTentativeDefinition makes sure that we
5389     // never attempt to emit a tentative definition if a real one
5390     // exists. A use may still exists, however, so we still may need
5391     // to do a RAUW.
5392     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
5393     Init = EmitNullConstant(D->getType());
5394   } else {
5395     initializedGlobalDecl = GlobalDecl(D);
5396     emitter.emplace(*this);
5397     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5398     if (!Initializer) {
5399       QualType T = InitExpr->getType();
5400       if (D->getType()->isReferenceType())
5401         T = D->getType();
5402 
5403       if (getLangOpts().CPlusPlus) {
5404         if (InitDecl->hasFlexibleArrayInit(getContext()))
5405           ErrorUnsupported(D, "flexible array initializer");
5406         Init = EmitNullConstant(T);
5407 
5408         if (!IsDefinitionAvailableExternally)
5409           NeedsGlobalCtor = true;
5410       } else {
5411         ErrorUnsupported(D, "static initializer");
5412         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
5413       }
5414     } else {
5415       Init = Initializer;
5416       // We don't need an initializer, so remove the entry for the delayed
5417       // initializer position (just in case this entry was delayed) if we
5418       // also don't need to register a destructor.
5419       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
5420         DelayedCXXInitPosition.erase(D);
5421 
5422 #ifndef NDEBUG
5423       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
5424                           InitDecl->getFlexibleArrayInitChars(getContext());
5425       CharUnits CstSize = CharUnits::fromQuantity(
5426           getDataLayout().getTypeAllocSize(Init->getType()));
5427       assert(VarSize == CstSize && "Emitted constant has unexpected size");
5428 #endif
5429     }
5430   }
5431 
5432   llvm::Type* InitType = Init->getType();
5433   llvm::Constant *Entry =
5434       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
5435 
5436   // Strip off pointer casts if we got them.
5437   Entry = Entry->stripPointerCasts();
5438 
5439   // Entry is now either a Function or GlobalVariable.
5440   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5441 
5442   // We have a definition after a declaration with the wrong type.
5443   // We must make a new GlobalVariable* and update everything that used OldGV
5444   // (a declaration or tentative definition) with the new GlobalVariable*
5445   // (which will be a definition).
5446   //
5447   // This happens if there is a prototype for a global (e.g.
5448   // "extern int x[];") and then a definition of a different type (e.g.
5449   // "int x[10];"). This also happens when an initializer has a different type
5450   // from the type of the global (this happens with unions).
5451   if (!GV || GV->getValueType() != InitType ||
5452       GV->getType()->getAddressSpace() !=
5453           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
5454 
5455     // Move the old entry aside so that we'll create a new one.
5456     Entry->setName(StringRef());
5457 
5458     // Make a new global with the correct type, this is now guaranteed to work.
5459     GV = cast<llvm::GlobalVariable>(
5460         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5461             ->stripPointerCasts());
5462 
5463     // Replace all uses of the old global with the new global
5464     llvm::Constant *NewPtrForOldDecl =
5465         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5466                                                              Entry->getType());
5467     Entry->replaceAllUsesWith(NewPtrForOldDecl);
5468 
5469     // Erase the old global, since it is no longer used.
5470     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5471   }
5472 
5473   MaybeHandleStaticInExternC(D, GV);
5474 
5475   if (D->hasAttr<AnnotateAttr>())
5476     AddGlobalAnnotations(D, GV);
5477 
5478   // Set the llvm linkage type as appropriate.
5479   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
5480 
5481   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
5482   // the device. [...]"
5483   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
5484   // __device__, declares a variable that: [...]
5485   // Is accessible from all the threads within the grid and from the host
5486   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
5487   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
5488   if (LangOpts.CUDA) {
5489     if (LangOpts.CUDAIsDevice) {
5490       if (Linkage != llvm::GlobalValue::InternalLinkage &&
5491           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5492            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5493            D->getType()->isCUDADeviceBuiltinTextureType()))
5494         GV->setExternallyInitialized(true);
5495     } else {
5496       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
5497     }
5498     getCUDARuntime().handleVarRegistration(D, *GV);
5499   }
5500 
5501   GV->setInitializer(Init);
5502   if (emitter)
5503     emitter->finalize(GV);
5504 
5505   // If it is safe to mark the global 'constant', do so now.
5506   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5507                   D->getType().isConstantStorage(getContext(), true, true));
5508 
5509   // If it is in a read-only section, mark it 'constant'.
5510   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
5511     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
5512     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
5513       GV->setConstant(true);
5514   }
5515 
5516   CharUnits AlignVal = getContext().getDeclAlign(D);
5517   // Check for alignment specifed in an 'omp allocate' directive.
5518   if (std::optional<CharUnits> AlignValFromAllocate =
5519           getOMPAllocateAlignment(D))
5520     AlignVal = *AlignValFromAllocate;
5521   GV->setAlignment(AlignVal.getAsAlign());
5522 
5523   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5524   // function is only defined alongside the variable, not also alongside
5525   // callers. Normally, all accesses to a thread_local go through the
5526   // thread-wrapper in order to ensure initialization has occurred, underlying
5527   // variable will never be used other than the thread-wrapper, so it can be
5528   // converted to internal linkage.
5529   //
5530   // However, if the variable has the 'constinit' attribute, it _can_ be
5531   // referenced directly, without calling the thread-wrapper, so the linkage
5532   // must not be changed.
5533   //
5534   // Additionally, if the variable isn't plain external linkage, e.g. if it's
5535   // weak or linkonce, the de-duplication semantics are important to preserve,
5536   // so we don't change the linkage.
5537   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
5538       Linkage == llvm::GlobalValue::ExternalLinkage &&
5539       Context.getTargetInfo().getTriple().isOSDarwin() &&
5540       !D->hasAttr<ConstInitAttr>())
5541     Linkage = llvm::GlobalValue::InternalLinkage;
5542 
5543   GV->setLinkage(Linkage);
5544   if (D->hasAttr<DLLImportAttr>())
5545     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5546   else if (D->hasAttr<DLLExportAttr>())
5547     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5548   else
5549     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5550 
5551   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
5552     // common vars aren't constant even if declared const.
5553     GV->setConstant(false);
5554     // Tentative definition of global variables may be initialized with
5555     // non-zero null pointers. In this case they should have weak linkage
5556     // since common linkage must have zero initializer and must not have
5557     // explicit section therefore cannot have non-zero initial value.
5558     if (!GV->getInitializer()->isNullValue())
5559       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5560   }
5561 
5562   setNonAliasAttributes(D, GV);
5563 
5564   if (D->getTLSKind() && !GV->isThreadLocal()) {
5565     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5566       CXXThreadLocals.push_back(D);
5567     setTLSMode(GV, *D);
5568   }
5569 
5570   maybeSetTrivialComdat(*D, *GV);
5571 
5572   // Emit the initializer function if necessary.
5573   if (NeedsGlobalCtor || NeedsGlobalDtor)
5574     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5575 
5576   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5577 
5578   // Emit global variable debug information.
5579   if (CGDebugInfo *DI = getModuleDebugInfo())
5580     if (getCodeGenOpts().hasReducedDebugInfo())
5581       DI->EmitGlobalVariable(GV, D);
5582 }
5583 
5584 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5585   if (CGDebugInfo *DI = getModuleDebugInfo())
5586     if (getCodeGenOpts().hasReducedDebugInfo()) {
5587       QualType ASTTy = D->getType();
5588       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5589       llvm::Constant *GV =
5590           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5591       DI->EmitExternalVariable(
5592           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5593     }
5594 }
5595 
5596 static bool isVarDeclStrongDefinition(const ASTContext &Context,
5597                                       CodeGenModule &CGM, const VarDecl *D,
5598                                       bool NoCommon) {
5599   // Don't give variables common linkage if -fno-common was specified unless it
5600   // was overridden by a NoCommon attribute.
5601   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
5602     return true;
5603 
5604   // C11 6.9.2/2:
5605   //   A declaration of an identifier for an object that has file scope without
5606   //   an initializer, and without a storage-class specifier or with the
5607   //   storage-class specifier static, constitutes a tentative definition.
5608   if (D->getInit() || D->hasExternalStorage())
5609     return true;
5610 
5611   // A variable cannot be both common and exist in a section.
5612   if (D->hasAttr<SectionAttr>())
5613     return true;
5614 
5615   // A variable cannot be both common and exist in a section.
5616   // We don't try to determine which is the right section in the front-end.
5617   // If no specialized section name is applicable, it will resort to default.
5618   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
5619       D->hasAttr<PragmaClangDataSectionAttr>() ||
5620       D->hasAttr<PragmaClangRelroSectionAttr>() ||
5621       D->hasAttr<PragmaClangRodataSectionAttr>())
5622     return true;
5623 
5624   // Thread local vars aren't considered common linkage.
5625   if (D->getTLSKind())
5626     return true;
5627 
5628   // Tentative definitions marked with WeakImportAttr are true definitions.
5629   if (D->hasAttr<WeakImportAttr>())
5630     return true;
5631 
5632   // A variable cannot be both common and exist in a comdat.
5633   if (shouldBeInCOMDAT(CGM, *D))
5634     return true;
5635 
5636   // Declarations with a required alignment do not have common linkage in MSVC
5637   // mode.
5638   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5639     if (D->hasAttr<AlignedAttr>())
5640       return true;
5641     QualType VarType = D->getType();
5642     if (Context.isAlignmentRequired(VarType))
5643       return true;
5644 
5645     if (const auto *RT = VarType->getAs<RecordType>()) {
5646       const RecordDecl *RD = RT->getDecl();
5647       for (const FieldDecl *FD : RD->fields()) {
5648         if (FD->isBitField())
5649           continue;
5650         if (FD->hasAttr<AlignedAttr>())
5651           return true;
5652         if (Context.isAlignmentRequired(FD->getType()))
5653           return true;
5654       }
5655     }
5656   }
5657 
5658   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5659   // common symbols, so symbols with greater alignment requirements cannot be
5660   // common.
5661   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5662   // alignments for common symbols via the aligncomm directive, so this
5663   // restriction only applies to MSVC environments.
5664   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5665       Context.getTypeAlignIfKnown(D->getType()) >
5666           Context.toBits(CharUnits::fromQuantity(32)))
5667     return true;
5668 
5669   return false;
5670 }
5671 
5672 llvm::GlobalValue::LinkageTypes
5673 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
5674                                            GVALinkage Linkage) {
5675   if (Linkage == GVA_Internal)
5676     return llvm::Function::InternalLinkage;
5677 
5678   if (D->hasAttr<WeakAttr>())
5679     return llvm::GlobalVariable::WeakAnyLinkage;
5680 
5681   if (const auto *FD = D->getAsFunction())
5682     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
5683       return llvm::GlobalVariable::LinkOnceAnyLinkage;
5684 
5685   // We are guaranteed to have a strong definition somewhere else,
5686   // so we can use available_externally linkage.
5687   if (Linkage == GVA_AvailableExternally)
5688     return llvm::GlobalValue::AvailableExternallyLinkage;
5689 
5690   // Note that Apple's kernel linker doesn't support symbol
5691   // coalescing, so we need to avoid linkonce and weak linkages there.
5692   // Normally, this means we just map to internal, but for explicit
5693   // instantiations we'll map to external.
5694 
5695   // In C++, the compiler has to emit a definition in every translation unit
5696   // that references the function.  We should use linkonce_odr because
5697   // a) if all references in this translation unit are optimized away, we
5698   // don't need to codegen it.  b) if the function persists, it needs to be
5699   // merged with other definitions. c) C++ has the ODR, so we know the
5700   // definition is dependable.
5701   if (Linkage == GVA_DiscardableODR)
5702     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5703                                             : llvm::Function::InternalLinkage;
5704 
5705   // An explicit instantiation of a template has weak linkage, since
5706   // explicit instantiations can occur in multiple translation units
5707   // and must all be equivalent. However, we are not allowed to
5708   // throw away these explicit instantiations.
5709   //
5710   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5711   // so say that CUDA templates are either external (for kernels) or internal.
5712   // This lets llvm perform aggressive inter-procedural optimizations. For
5713   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5714   // therefore we need to follow the normal linkage paradigm.
5715   if (Linkage == GVA_StrongODR) {
5716     if (getLangOpts().AppleKext)
5717       return llvm::Function::ExternalLinkage;
5718     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5719         !getLangOpts().GPURelocatableDeviceCode)
5720       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5721                                           : llvm::Function::InternalLinkage;
5722     return llvm::Function::WeakODRLinkage;
5723   }
5724 
5725   // C++ doesn't have tentative definitions and thus cannot have common
5726   // linkage.
5727   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5728       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
5729                                  CodeGenOpts.NoCommon))
5730     return llvm::GlobalVariable::CommonLinkage;
5731 
5732   // selectany symbols are externally visible, so use weak instead of
5733   // linkonce.  MSVC optimizes away references to const selectany globals, so
5734   // all definitions should be the same and ODR linkage should be used.
5735   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5736   if (D->hasAttr<SelectAnyAttr>())
5737     return llvm::GlobalVariable::WeakODRLinkage;
5738 
5739   // Otherwise, we have strong external linkage.
5740   assert(Linkage == GVA_StrongExternal);
5741   return llvm::GlobalVariable::ExternalLinkage;
5742 }
5743 
5744 llvm::GlobalValue::LinkageTypes
5745 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
5746   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5747   return getLLVMLinkageForDeclarator(VD, Linkage);
5748 }
5749 
5750 /// Replace the uses of a function that was declared with a non-proto type.
5751 /// We want to silently drop extra arguments from call sites
5752 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5753                                           llvm::Function *newFn) {
5754   // Fast path.
5755   if (old->use_empty())
5756     return;
5757 
5758   llvm::Type *newRetTy = newFn->getReturnType();
5759   SmallVector<llvm::Value *, 4> newArgs;
5760 
5761   SmallVector<llvm::CallBase *> callSitesToBeRemovedFromParent;
5762 
5763   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5764        ui != ue; ui++) {
5765     llvm::User *user = ui->getUser();
5766 
5767     // Recognize and replace uses of bitcasts.  Most calls to
5768     // unprototyped functions will use bitcasts.
5769     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5770       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5771         replaceUsesOfNonProtoConstant(bitcast, newFn);
5772       continue;
5773     }
5774 
5775     // Recognize calls to the function.
5776     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5777     if (!callSite)
5778       continue;
5779     if (!callSite->isCallee(&*ui))
5780       continue;
5781 
5782     // If the return types don't match exactly, then we can't
5783     // transform this call unless it's dead.
5784     if (callSite->getType() != newRetTy && !callSite->use_empty())
5785       continue;
5786 
5787     // Get the call site's attribute list.
5788     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5789     llvm::AttributeList oldAttrs = callSite->getAttributes();
5790 
5791     // If the function was passed too few arguments, don't transform.
5792     unsigned newNumArgs = newFn->arg_size();
5793     if (callSite->arg_size() < newNumArgs)
5794       continue;
5795 
5796     // If extra arguments were passed, we silently drop them.
5797     // If any of the types mismatch, we don't transform.
5798     unsigned argNo = 0;
5799     bool dontTransform = false;
5800     for (llvm::Argument &A : newFn->args()) {
5801       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5802         dontTransform = true;
5803         break;
5804       }
5805 
5806       // Add any parameter attributes.
5807       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5808       argNo++;
5809     }
5810     if (dontTransform)
5811       continue;
5812 
5813     // Okay, we can transform this.  Create the new call instruction and copy
5814     // over the required information.
5815     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5816 
5817     // Copy over any operand bundles.
5818     SmallVector<llvm::OperandBundleDef, 1> newBundles;
5819     callSite->getOperandBundlesAsDefs(newBundles);
5820 
5821     llvm::CallBase *newCall;
5822     if (isa<llvm::CallInst>(callSite)) {
5823       newCall =
5824           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5825     } else {
5826       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5827       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5828                                          oldInvoke->getUnwindDest(), newArgs,
5829                                          newBundles, "", callSite);
5830     }
5831     newArgs.clear(); // for the next iteration
5832 
5833     if (!newCall->getType()->isVoidTy())
5834       newCall->takeName(callSite);
5835     newCall->setAttributes(
5836         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5837                                  oldAttrs.getRetAttrs(), newArgAttrs));
5838     newCall->setCallingConv(callSite->getCallingConv());
5839 
5840     // Finally, remove the old call, replacing any uses with the new one.
5841     if (!callSite->use_empty())
5842       callSite->replaceAllUsesWith(newCall);
5843 
5844     // Copy debug location attached to CI.
5845     if (callSite->getDebugLoc())
5846       newCall->setDebugLoc(callSite->getDebugLoc());
5847 
5848     callSitesToBeRemovedFromParent.push_back(callSite);
5849   }
5850 
5851   for (auto *callSite : callSitesToBeRemovedFromParent) {
5852     callSite->eraseFromParent();
5853   }
5854 }
5855 
5856 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5857 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
5858 /// existing call uses of the old function in the module, this adjusts them to
5859 /// call the new function directly.
5860 ///
5861 /// This is not just a cleanup: the always_inline pass requires direct calls to
5862 /// functions to be able to inline them.  If there is a bitcast in the way, it
5863 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
5864 /// run at -O0.
5865 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5866                                                       llvm::Function *NewFn) {
5867   // If we're redefining a global as a function, don't transform it.
5868   if (!isa<llvm::Function>(Old)) return;
5869 
5870   replaceUsesOfNonProtoConstant(Old, NewFn);
5871 }
5872 
5873 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5874   auto DK = VD->isThisDeclarationADefinition();
5875   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5876     return;
5877 
5878   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5879   // If we have a definition, this might be a deferred decl. If the
5880   // instantiation is explicit, make sure we emit it at the end.
5881   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5882     GetAddrOfGlobalVar(VD);
5883 
5884   EmitTopLevelDecl(VD);
5885 }
5886 
5887 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5888                                                  llvm::GlobalValue *GV) {
5889   const auto *D = cast<FunctionDecl>(GD.getDecl());
5890 
5891   // Compute the function info and LLVM type.
5892   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5893   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5894 
5895   // Get or create the prototype for the function.
5896   if (!GV || (GV->getValueType() != Ty))
5897     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5898                                                    /*DontDefer=*/true,
5899                                                    ForDefinition));
5900 
5901   // Already emitted.
5902   if (!GV->isDeclaration())
5903     return;
5904 
5905   // We need to set linkage and visibility on the function before
5906   // generating code for it because various parts of IR generation
5907   // want to propagate this information down (e.g. to local static
5908   // declarations).
5909   auto *Fn = cast<llvm::Function>(GV);
5910   setFunctionLinkage(GD, Fn);
5911 
5912   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5913   setGVProperties(Fn, GD);
5914 
5915   MaybeHandleStaticInExternC(D, Fn);
5916 
5917   maybeSetTrivialComdat(*D, *Fn);
5918 
5919   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5920 
5921   setNonAliasAttributes(GD, Fn);
5922   SetLLVMFunctionAttributesForDefinition(D, Fn);
5923 
5924   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5925     AddGlobalCtor(Fn, CA->getPriority());
5926   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5927     AddGlobalDtor(Fn, DA->getPriority(), true);
5928   if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
5929     getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
5930 }
5931 
5932 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5933   const auto *D = cast<ValueDecl>(GD.getDecl());
5934   const AliasAttr *AA = D->getAttr<AliasAttr>();
5935   assert(AA && "Not an alias?");
5936 
5937   StringRef MangledName = getMangledName(GD);
5938 
5939   if (AA->getAliasee() == MangledName) {
5940     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5941     return;
5942   }
5943 
5944   // If there is a definition in the module, then it wins over the alias.
5945   // This is dubious, but allow it to be safe.  Just ignore the alias.
5946   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5947   if (Entry && !Entry->isDeclaration())
5948     return;
5949 
5950   Aliases.push_back(GD);
5951 
5952   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5953 
5954   // Create a reference to the named value.  This ensures that it is emitted
5955   // if a deferred decl.
5956   llvm::Constant *Aliasee;
5957   llvm::GlobalValue::LinkageTypes LT;
5958   if (isa<llvm::FunctionType>(DeclTy)) {
5959     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5960                                       /*ForVTable=*/false);
5961     LT = getFunctionLinkage(GD);
5962   } else {
5963     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5964                                     /*D=*/nullptr);
5965     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5966       LT = getLLVMLinkageVarDefinition(VD);
5967     else
5968       LT = getFunctionLinkage(GD);
5969   }
5970 
5971   // Create the new alias itself, but don't set a name yet.
5972   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5973   auto *GA =
5974       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5975 
5976   if (Entry) {
5977     if (GA->getAliasee() == Entry) {
5978       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5979       return;
5980     }
5981 
5982     assert(Entry->isDeclaration());
5983 
5984     // If there is a declaration in the module, then we had an extern followed
5985     // by the alias, as in:
5986     //   extern int test6();
5987     //   ...
5988     //   int test6() __attribute__((alias("test7")));
5989     //
5990     // Remove it and replace uses of it with the alias.
5991     GA->takeName(Entry);
5992 
5993     Entry->replaceAllUsesWith(GA);
5994     Entry->eraseFromParent();
5995   } else {
5996     GA->setName(MangledName);
5997   }
5998 
5999   // Set attributes which are particular to an alias; this is a
6000   // specialization of the attributes which may be set on a global
6001   // variable/function.
6002   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
6003       D->isWeakImported()) {
6004     GA->setLinkage(llvm::Function::WeakAnyLinkage);
6005   }
6006 
6007   if (const auto *VD = dyn_cast<VarDecl>(D))
6008     if (VD->getTLSKind())
6009       setTLSMode(GA, *VD);
6010 
6011   SetCommonAttributes(GD, GA);
6012 
6013   // Emit global alias debug information.
6014   if (isa<VarDecl>(D))
6015     if (CGDebugInfo *DI = getModuleDebugInfo())
6016       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6017 }
6018 
6019 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6020   const auto *D = cast<ValueDecl>(GD.getDecl());
6021   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
6022   assert(IFA && "Not an ifunc?");
6023 
6024   StringRef MangledName = getMangledName(GD);
6025 
6026   if (IFA->getResolver() == MangledName) {
6027     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6028     return;
6029   }
6030 
6031   // Report an error if some definition overrides ifunc.
6032   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6033   if (Entry && !Entry->isDeclaration()) {
6034     GlobalDecl OtherGD;
6035     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
6036         DiagnosedConflictingDefinitions.insert(GD).second) {
6037       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
6038           << MangledName;
6039       Diags.Report(OtherGD.getDecl()->getLocation(),
6040                    diag::note_previous_definition);
6041     }
6042     return;
6043   }
6044 
6045   Aliases.push_back(GD);
6046 
6047   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6048   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
6049   llvm::Constant *Resolver =
6050       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
6051                               /*ForVTable=*/false);
6052   llvm::GlobalIFunc *GIF =
6053       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
6054                                 "", Resolver, &getModule());
6055   if (Entry) {
6056     if (GIF->getResolver() == Entry) {
6057       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6058       return;
6059     }
6060     assert(Entry->isDeclaration());
6061 
6062     // If there is a declaration in the module, then we had an extern followed
6063     // by the ifunc, as in:
6064     //   extern int test();
6065     //   ...
6066     //   int test() __attribute__((ifunc("resolver")));
6067     //
6068     // Remove it and replace uses of it with the ifunc.
6069     GIF->takeName(Entry);
6070 
6071     Entry->replaceAllUsesWith(GIF);
6072     Entry->eraseFromParent();
6073   } else
6074     GIF->setName(MangledName);
6075   if (auto *F = dyn_cast<llvm::Function>(Resolver)) {
6076     F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
6077   }
6078   SetCommonAttributes(GD, GIF);
6079 }
6080 
6081 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
6082                                             ArrayRef<llvm::Type*> Tys) {
6083   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
6084                                          Tys);
6085 }
6086 
6087 static llvm::StringMapEntry<llvm::GlobalVariable *> &
6088 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
6089                          const StringLiteral *Literal, bool TargetIsLSB,
6090                          bool &IsUTF16, unsigned &StringLength) {
6091   StringRef String = Literal->getString();
6092   unsigned NumBytes = String.size();
6093 
6094   // Check for simple case.
6095   if (!Literal->containsNonAsciiOrNull()) {
6096     StringLength = NumBytes;
6097     return *Map.insert(std::make_pair(String, nullptr)).first;
6098   }
6099 
6100   // Otherwise, convert the UTF8 literals into a string of shorts.
6101   IsUTF16 = true;
6102 
6103   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
6104   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6105   llvm::UTF16 *ToPtr = &ToBuf[0];
6106 
6107   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6108                                  ToPtr + NumBytes, llvm::strictConversion);
6109 
6110   // ConvertUTF8toUTF16 returns the length in ToPtr.
6111   StringLength = ToPtr - &ToBuf[0];
6112 
6113   // Add an explicit null.
6114   *ToPtr = 0;
6115   return *Map.insert(std::make_pair(
6116                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
6117                                    (StringLength + 1) * 2),
6118                          nullptr)).first;
6119 }
6120 
6121 ConstantAddress
6122 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
6123   unsigned StringLength = 0;
6124   bool isUTF16 = false;
6125   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6126       GetConstantCFStringEntry(CFConstantStringMap, Literal,
6127                                getDataLayout().isLittleEndian(), isUTF16,
6128                                StringLength);
6129 
6130   if (auto *C = Entry.second)
6131     return ConstantAddress(
6132         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
6133 
6134   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
6135   llvm::Constant *Zeros[] = { Zero, Zero };
6136 
6137   const ASTContext &Context = getContext();
6138   const llvm::Triple &Triple = getTriple();
6139 
6140   const auto CFRuntime = getLangOpts().CFRuntime;
6141   const bool IsSwiftABI =
6142       static_cast<unsigned>(CFRuntime) >=
6143       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
6144   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
6145 
6146   // If we don't already have it, get __CFConstantStringClassReference.
6147   if (!CFConstantStringClassRef) {
6148     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
6149     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
6150     Ty = llvm::ArrayType::get(Ty, 0);
6151 
6152     switch (CFRuntime) {
6153     default: break;
6154     case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
6155     case LangOptions::CoreFoundationABI::Swift5_0:
6156       CFConstantStringClassName =
6157           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
6158                               : "$s10Foundation19_NSCFConstantStringCN";
6159       Ty = IntPtrTy;
6160       break;
6161     case LangOptions::CoreFoundationABI::Swift4_2:
6162       CFConstantStringClassName =
6163           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
6164                               : "$S10Foundation19_NSCFConstantStringCN";
6165       Ty = IntPtrTy;
6166       break;
6167     case LangOptions::CoreFoundationABI::Swift4_1:
6168       CFConstantStringClassName =
6169           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
6170                               : "__T010Foundation19_NSCFConstantStringCN";
6171       Ty = IntPtrTy;
6172       break;
6173     }
6174 
6175     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
6176 
6177     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6178       llvm::GlobalValue *GV = nullptr;
6179 
6180       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
6181         IdentifierInfo &II = Context.Idents.get(GV->getName());
6182         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
6183         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6184 
6185         const VarDecl *VD = nullptr;
6186         for (const auto *Result : DC->lookup(&II))
6187           if ((VD = dyn_cast<VarDecl>(Result)))
6188             break;
6189 
6190         if (Triple.isOSBinFormatELF()) {
6191           if (!VD)
6192             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6193         } else {
6194           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6195           if (!VD || !VD->hasAttr<DLLExportAttr>())
6196             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6197           else
6198             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6199         }
6200 
6201         setDSOLocal(GV);
6202       }
6203     }
6204 
6205     // Decay array -> ptr
6206     CFConstantStringClassRef =
6207         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
6208                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
6209   }
6210 
6211   QualType CFTy = Context.getCFConstantStringType();
6212 
6213   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
6214 
6215   ConstantInitBuilder Builder(*this);
6216   auto Fields = Builder.beginStruct(STy);
6217 
6218   // Class pointer.
6219   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6220 
6221   // Flags.
6222   if (IsSwiftABI) {
6223     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6224     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6225   } else {
6226     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6227   }
6228 
6229   // String pointer.
6230   llvm::Constant *C = nullptr;
6231   if (isUTF16) {
6232     auto Arr = llvm::ArrayRef(
6233         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
6234         Entry.first().size() / 2);
6235     C = llvm::ConstantDataArray::get(VMContext, Arr);
6236   } else {
6237     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6238   }
6239 
6240   // Note: -fwritable-strings doesn't make the backing store strings of
6241   // CFStrings writable.
6242   auto *GV =
6243       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
6244                                llvm::GlobalValue::PrivateLinkage, C, ".str");
6245   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6246   // Don't enforce the target's minimum global alignment, since the only use
6247   // of the string is via this class initializer.
6248   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6249                             : Context.getTypeAlignInChars(Context.CharTy);
6250   GV->setAlignment(Align.getAsAlign());
6251 
6252   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
6253   // Without it LLVM can merge the string with a non unnamed_addr one during
6254   // LTO.  Doing that changes the section it ends in, which surprises ld64.
6255   if (Triple.isOSBinFormatMachO())
6256     GV->setSection(isUTF16 ? "__TEXT,__ustring"
6257                            : "__TEXT,__cstring,cstring_literals");
6258   // Make sure the literal ends up in .rodata to allow for safe ICF and for
6259   // the static linker to adjust permissions to read-only later on.
6260   else if (Triple.isOSBinFormatELF())
6261     GV->setSection(".rodata");
6262 
6263   // String.
6264   llvm::Constant *Str =
6265       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
6266 
6267   Fields.add(Str);
6268 
6269   // String length.
6270   llvm::IntegerType *LengthTy =
6271       llvm::IntegerType::get(getModule().getContext(),
6272                              Context.getTargetInfo().getLongWidth());
6273   if (IsSwiftABI) {
6274     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6275         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6276       LengthTy = Int32Ty;
6277     else
6278       LengthTy = IntPtrTy;
6279   }
6280   Fields.addInt(LengthTy, StringLength);
6281 
6282   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6283   // properly aligned on 32-bit platforms.
6284   CharUnits Alignment =
6285       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
6286 
6287   // The struct.
6288   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
6289                                     /*isConstant=*/false,
6290                                     llvm::GlobalVariable::PrivateLinkage);
6291   GV->addAttribute("objc_arc_inert");
6292   switch (Triple.getObjectFormat()) {
6293   case llvm::Triple::UnknownObjectFormat:
6294     llvm_unreachable("unknown file format");
6295   case llvm::Triple::DXContainer:
6296   case llvm::Triple::GOFF:
6297   case llvm::Triple::SPIRV:
6298   case llvm::Triple::XCOFF:
6299     llvm_unreachable("unimplemented");
6300   case llvm::Triple::COFF:
6301   case llvm::Triple::ELF:
6302   case llvm::Triple::Wasm:
6303     GV->setSection("cfstring");
6304     break;
6305   case llvm::Triple::MachO:
6306     GV->setSection("__DATA,__cfstring");
6307     break;
6308   }
6309   Entry.second = GV;
6310 
6311   return ConstantAddress(GV, GV->getValueType(), Alignment);
6312 }
6313 
6314 bool CodeGenModule::getExpressionLocationsEnabled() const {
6315   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6316 }
6317 
6318 QualType CodeGenModule::getObjCFastEnumerationStateType() {
6319   if (ObjCFastEnumerationStateType.isNull()) {
6320     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
6321     D->startDefinition();
6322 
6323     QualType FieldTypes[] = {
6324         Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
6325         Context.getPointerType(Context.UnsignedLongTy),
6326         Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6327                                      nullptr, ArraySizeModifier::Normal, 0)};
6328 
6329     for (size_t i = 0; i < 4; ++i) {
6330       FieldDecl *Field = FieldDecl::Create(Context,
6331                                            D,
6332                                            SourceLocation(),
6333                                            SourceLocation(), nullptr,
6334                                            FieldTypes[i], /*TInfo=*/nullptr,
6335                                            /*BitWidth=*/nullptr,
6336                                            /*Mutable=*/false,
6337                                            ICIS_NoInit);
6338       Field->setAccess(AS_public);
6339       D->addDecl(Field);
6340     }
6341 
6342     D->completeDefinition();
6343     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
6344   }
6345 
6346   return ObjCFastEnumerationStateType;
6347 }
6348 
6349 llvm::Constant *
6350 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
6351   assert(!E->getType()->isPointerType() && "Strings are always arrays");
6352 
6353   // Don't emit it as the address of the string, emit the string data itself
6354   // as an inline array.
6355   if (E->getCharByteWidth() == 1) {
6356     SmallString<64> Str(E->getString());
6357 
6358     // Resize the string to the right size, which is indicated by its type.
6359     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
6360     assert(CAT && "String literal not of constant array type!");
6361     Str.resize(CAT->getZExtSize());
6362     return llvm::ConstantDataArray::getString(VMContext, Str, false);
6363   }
6364 
6365   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
6366   llvm::Type *ElemTy = AType->getElementType();
6367   unsigned NumElements = AType->getNumElements();
6368 
6369   // Wide strings have either 2-byte or 4-byte elements.
6370   if (ElemTy->getPrimitiveSizeInBits() == 16) {
6371     SmallVector<uint16_t, 32> Elements;
6372     Elements.reserve(NumElements);
6373 
6374     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6375       Elements.push_back(E->getCodeUnit(i));
6376     Elements.resize(NumElements);
6377     return llvm::ConstantDataArray::get(VMContext, Elements);
6378   }
6379 
6380   assert(ElemTy->getPrimitiveSizeInBits() == 32);
6381   SmallVector<uint32_t, 32> Elements;
6382   Elements.reserve(NumElements);
6383 
6384   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6385     Elements.push_back(E->getCodeUnit(i));
6386   Elements.resize(NumElements);
6387   return llvm::ConstantDataArray::get(VMContext, Elements);
6388 }
6389 
6390 static llvm::GlobalVariable *
6391 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
6392                       CodeGenModule &CGM, StringRef GlobalName,
6393                       CharUnits Alignment) {
6394   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6395       CGM.GetGlobalConstantAddressSpace());
6396 
6397   llvm::Module &M = CGM.getModule();
6398   // Create a global variable for this string
6399   auto *GV = new llvm::GlobalVariable(
6400       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
6401       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6402   GV->setAlignment(Alignment.getAsAlign());
6403   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6404   if (GV->isWeakForLinker()) {
6405     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
6406     GV->setComdat(M.getOrInsertComdat(GV->getName()));
6407   }
6408   CGM.setDSOLocal(GV);
6409 
6410   return GV;
6411 }
6412 
6413 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
6414 /// constant array for the given string literal.
6415 ConstantAddress
6416 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
6417                                                   StringRef Name) {
6418   CharUnits Alignment =
6419       getContext().getAlignOfGlobalVarInChars(S->getType(), /*VD=*/nullptr);
6420 
6421   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
6422   llvm::GlobalVariable **Entry = nullptr;
6423   if (!LangOpts.WritableStrings) {
6424     Entry = &ConstantStringMap[C];
6425     if (auto GV = *Entry) {
6426       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6427         GV->setAlignment(Alignment.getAsAlign());
6428       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6429                              GV->getValueType(), Alignment);
6430     }
6431   }
6432 
6433   SmallString<256> MangledNameBuffer;
6434   StringRef GlobalVariableName;
6435   llvm::GlobalValue::LinkageTypes LT;
6436 
6437   // Mangle the string literal if that's how the ABI merges duplicate strings.
6438   // Don't do it if they are writable, since we don't want writes in one TU to
6439   // affect strings in another.
6440   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6441       !LangOpts.WritableStrings) {
6442     llvm::raw_svector_ostream Out(MangledNameBuffer);
6443     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
6444     LT = llvm::GlobalValue::LinkOnceODRLinkage;
6445     GlobalVariableName = MangledNameBuffer;
6446   } else {
6447     LT = llvm::GlobalValue::PrivateLinkage;
6448     GlobalVariableName = Name;
6449   }
6450 
6451   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
6452 
6453   CGDebugInfo *DI = getModuleDebugInfo();
6454   if (DI && getCodeGenOpts().hasReducedDebugInfo())
6455     DI->AddStringLiteralDebugInfo(GV, S);
6456 
6457   if (Entry)
6458     *Entry = GV;
6459 
6460   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
6461 
6462   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6463                          GV->getValueType(), Alignment);
6464 }
6465 
6466 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
6467 /// array for the given ObjCEncodeExpr node.
6468 ConstantAddress
6469 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
6470   std::string Str;
6471   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
6472 
6473   return GetAddrOfConstantCString(Str);
6474 }
6475 
6476 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
6477 /// the literal and a terminating '\0' character.
6478 /// The result has pointer to array type.
6479 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
6480     const std::string &Str, const char *GlobalName) {
6481   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6482   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(
6483       getContext().CharTy, /*VD=*/nullptr);
6484 
6485   llvm::Constant *C =
6486       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
6487 
6488   // Don't share any string literals if strings aren't constant.
6489   llvm::GlobalVariable **Entry = nullptr;
6490   if (!LangOpts.WritableStrings) {
6491     Entry = &ConstantStringMap[C];
6492     if (auto GV = *Entry) {
6493       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6494         GV->setAlignment(Alignment.getAsAlign());
6495       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6496                              GV->getValueType(), Alignment);
6497     }
6498   }
6499 
6500   // Get the default prefix if a name wasn't specified.
6501   if (!GlobalName)
6502     GlobalName = ".str";
6503   // Create a global variable for this.
6504   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
6505                                   GlobalName, Alignment);
6506   if (Entry)
6507     *Entry = GV;
6508 
6509   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6510                          GV->getValueType(), Alignment);
6511 }
6512 
6513 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6514     const MaterializeTemporaryExpr *E, const Expr *Init) {
6515   assert((E->getStorageDuration() == SD_Static ||
6516           E->getStorageDuration() == SD_Thread) && "not a global temporary");
6517   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6518 
6519   // If we're not materializing a subobject of the temporary, keep the
6520   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6521   QualType MaterializedType = Init->getType();
6522   if (Init == E->getSubExpr())
6523     MaterializedType = E->getType();
6524 
6525   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6526 
6527   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6528   if (!InsertResult.second) {
6529     // We've seen this before: either we already created it or we're in the
6530     // process of doing so.
6531     if (!InsertResult.first->second) {
6532       // We recursively re-entered this function, probably during emission of
6533       // the initializer. Create a placeholder. We'll clean this up in the
6534       // outer call, at the end of this function.
6535       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6536       InsertResult.first->second = new llvm::GlobalVariable(
6537           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6538           nullptr);
6539     }
6540     return ConstantAddress(InsertResult.first->second,
6541                            llvm::cast<llvm::GlobalVariable>(
6542                                InsertResult.first->second->stripPointerCasts())
6543                                ->getValueType(),
6544                            Align);
6545   }
6546 
6547   // FIXME: If an externally-visible declaration extends multiple temporaries,
6548   // we need to give each temporary the same name in every translation unit (and
6549   // we also need to make the temporaries externally-visible).
6550   SmallString<256> Name;
6551   llvm::raw_svector_ostream Out(Name);
6552   getCXXABI().getMangleContext().mangleReferenceTemporary(
6553       VD, E->getManglingNumber(), Out);
6554 
6555   APValue *Value = nullptr;
6556   if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
6557     // If the initializer of the extending declaration is a constant
6558     // initializer, we should have a cached constant initializer for this
6559     // temporary. Note that this might have a different value from the value
6560     // computed by evaluating the initializer if the surrounding constant
6561     // expression modifies the temporary.
6562     Value = E->getOrCreateValue(false);
6563   }
6564 
6565   // Try evaluating it now, it might have a constant initializer.
6566   Expr::EvalResult EvalResult;
6567   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6568       !EvalResult.hasSideEffects())
6569     Value = &EvalResult.Val;
6570 
6571   LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
6572 
6573   std::optional<ConstantEmitter> emitter;
6574   llvm::Constant *InitialValue = nullptr;
6575   bool Constant = false;
6576   llvm::Type *Type;
6577   if (Value) {
6578     // The temporary has a constant initializer, use it.
6579     emitter.emplace(*this);
6580     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6581                                                MaterializedType);
6582     Constant =
6583         MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
6584                                            /*ExcludeDtor*/ false);
6585     Type = InitialValue->getType();
6586   } else {
6587     // No initializer, the initialization will be provided when we
6588     // initialize the declaration which performed lifetime extension.
6589     Type = getTypes().ConvertTypeForMem(MaterializedType);
6590   }
6591 
6592   // Create a global variable for this lifetime-extended temporary.
6593   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
6594   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6595     const VarDecl *InitVD;
6596     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6597         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6598       // Temporaries defined inside a class get linkonce_odr linkage because the
6599       // class can be defined in multiple translation units.
6600       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6601     } else {
6602       // There is no need for this temporary to have external linkage if the
6603       // VarDecl has external linkage.
6604       Linkage = llvm::GlobalVariable::InternalLinkage;
6605     }
6606   }
6607   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6608   auto *GV = new llvm::GlobalVariable(
6609       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6610       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6611   if (emitter) emitter->finalize(GV);
6612   // Don't assign dllimport or dllexport to local linkage globals.
6613   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6614     setGVProperties(GV, VD);
6615     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6616       // The reference temporary should never be dllexport.
6617       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6618   }
6619   GV->setAlignment(Align.getAsAlign());
6620   if (supportsCOMDAT() && GV->isWeakForLinker())
6621     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6622   if (VD->getTLSKind())
6623     setTLSMode(GV, *VD);
6624   llvm::Constant *CV = GV;
6625   if (AddrSpace != LangAS::Default)
6626     CV = getTargetCodeGenInfo().performAddrSpaceCast(
6627         *this, GV, AddrSpace, LangAS::Default,
6628         llvm::PointerType::get(
6629             getLLVMContext(),
6630             getContext().getTargetAddressSpace(LangAS::Default)));
6631 
6632   // Update the map with the new temporary. If we created a placeholder above,
6633   // replace it with the new global now.
6634   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6635   if (Entry) {
6636     Entry->replaceAllUsesWith(CV);
6637     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6638   }
6639   Entry = CV;
6640 
6641   return ConstantAddress(CV, Type, Align);
6642 }
6643 
6644 /// EmitObjCPropertyImplementations - Emit information for synthesized
6645 /// properties for an implementation.
6646 void CodeGenModule::EmitObjCPropertyImplementations(const
6647                                                     ObjCImplementationDecl *D) {
6648   for (const auto *PID : D->property_impls()) {
6649     // Dynamic is just for type-checking.
6650     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6651       ObjCPropertyDecl *PD = PID->getPropertyDecl();
6652 
6653       // Determine which methods need to be implemented, some may have
6654       // been overridden. Note that ::isPropertyAccessor is not the method
6655       // we want, that just indicates if the decl came from a
6656       // property. What we want to know is if the method is defined in
6657       // this implementation.
6658       auto *Getter = PID->getGetterMethodDecl();
6659       if (!Getter || Getter->isSynthesizedAccessorStub())
6660         CodeGenFunction(*this).GenerateObjCGetter(
6661             const_cast<ObjCImplementationDecl *>(D), PID);
6662       auto *Setter = PID->getSetterMethodDecl();
6663       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6664         CodeGenFunction(*this).GenerateObjCSetter(
6665                                  const_cast<ObjCImplementationDecl *>(D), PID);
6666     }
6667   }
6668 }
6669 
6670 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6671   const ObjCInterfaceDecl *iface = impl->getClassInterface();
6672   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6673        ivar; ivar = ivar->getNextIvar())
6674     if (ivar->getType().isDestructedType())
6675       return true;
6676 
6677   return false;
6678 }
6679 
6680 static bool AllTrivialInitializers(CodeGenModule &CGM,
6681                                    ObjCImplementationDecl *D) {
6682   CodeGenFunction CGF(CGM);
6683   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6684        E = D->init_end(); B != E; ++B) {
6685     CXXCtorInitializer *CtorInitExp = *B;
6686     Expr *Init = CtorInitExp->getInit();
6687     if (!CGF.isTrivialInitializer(Init))
6688       return false;
6689   }
6690   return true;
6691 }
6692 
6693 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6694 /// for an implementation.
6695 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6696   // We might need a .cxx_destruct even if we don't have any ivar initializers.
6697   if (needsDestructMethod(D)) {
6698     const IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6699     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6700     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6701         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6702         getContext().VoidTy, nullptr, D,
6703         /*isInstance=*/true, /*isVariadic=*/false,
6704         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6705         /*isImplicitlyDeclared=*/true,
6706         /*isDefined=*/false, ObjCImplementationControl::Required);
6707     D->addInstanceMethod(DTORMethod);
6708     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6709     D->setHasDestructors(true);
6710   }
6711 
6712   // If the implementation doesn't have any ivar initializers, we don't need
6713   // a .cxx_construct.
6714   if (D->getNumIvarInitializers() == 0 ||
6715       AllTrivialInitializers(*this, D))
6716     return;
6717 
6718   const IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6719   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6720   // The constructor returns 'self'.
6721   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6722       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6723       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6724       /*isVariadic=*/false,
6725       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6726       /*isImplicitlyDeclared=*/true,
6727       /*isDefined=*/false, ObjCImplementationControl::Required);
6728   D->addInstanceMethod(CTORMethod);
6729   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6730   D->setHasNonZeroConstructors(true);
6731 }
6732 
6733 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6734 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6735   if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
6736       LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) {
6737     ErrorUnsupported(LSD, "linkage spec");
6738     return;
6739   }
6740 
6741   EmitDeclContext(LSD);
6742 }
6743 
6744 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6745   // Device code should not be at top level.
6746   if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6747     return;
6748 
6749   std::unique_ptr<CodeGenFunction> &CurCGF =
6750       GlobalTopLevelStmtBlockInFlight.first;
6751 
6752   // We emitted a top-level stmt but after it there is initialization.
6753   // Stop squashing the top-level stmts into a single function.
6754   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6755     CurCGF->FinishFunction(D->getEndLoc());
6756     CurCGF = nullptr;
6757   }
6758 
6759   if (!CurCGF) {
6760     // void __stmts__N(void)
6761     // FIXME: Ask the ABI name mangler to pick a name.
6762     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6763     FunctionArgList Args;
6764     QualType RetTy = getContext().VoidTy;
6765     const CGFunctionInfo &FnInfo =
6766         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6767     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6768     llvm::Function *Fn = llvm::Function::Create(
6769         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6770 
6771     CurCGF.reset(new CodeGenFunction(*this));
6772     GlobalTopLevelStmtBlockInFlight.second = D;
6773     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6774                           D->getBeginLoc(), D->getBeginLoc());
6775     CXXGlobalInits.push_back(Fn);
6776   }
6777 
6778   CurCGF->EmitStmt(D->getStmt());
6779 }
6780 
6781 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6782   for (auto *I : DC->decls()) {
6783     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6784     // are themselves considered "top-level", so EmitTopLevelDecl on an
6785     // ObjCImplDecl does not recursively visit them. We need to do that in
6786     // case they're nested inside another construct (LinkageSpecDecl /
6787     // ExportDecl) that does stop them from being considered "top-level".
6788     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6789       for (auto *M : OID->methods())
6790         EmitTopLevelDecl(M);
6791     }
6792 
6793     EmitTopLevelDecl(I);
6794   }
6795 }
6796 
6797 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6798 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6799   // Ignore dependent declarations.
6800   if (D->isTemplated())
6801     return;
6802 
6803   // Consteval function shouldn't be emitted.
6804   if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
6805     return;
6806 
6807   switch (D->getKind()) {
6808   case Decl::CXXConversion:
6809   case Decl::CXXMethod:
6810   case Decl::Function:
6811     EmitGlobal(cast<FunctionDecl>(D));
6812     // Always provide some coverage mapping
6813     // even for the functions that aren't emitted.
6814     AddDeferredUnusedCoverageMapping(D);
6815     break;
6816 
6817   case Decl::CXXDeductionGuide:
6818     // Function-like, but does not result in code emission.
6819     break;
6820 
6821   case Decl::Var:
6822   case Decl::Decomposition:
6823   case Decl::VarTemplateSpecialization:
6824     EmitGlobal(cast<VarDecl>(D));
6825     if (auto *DD = dyn_cast<DecompositionDecl>(D))
6826       for (auto *B : DD->bindings())
6827         if (auto *HD = B->getHoldingVar())
6828           EmitGlobal(HD);
6829     break;
6830 
6831   // Indirect fields from global anonymous structs and unions can be
6832   // ignored; only the actual variable requires IR gen support.
6833   case Decl::IndirectField:
6834     break;
6835 
6836   // C++ Decls
6837   case Decl::Namespace:
6838     EmitDeclContext(cast<NamespaceDecl>(D));
6839     break;
6840   case Decl::ClassTemplateSpecialization: {
6841     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6842     if (CGDebugInfo *DI = getModuleDebugInfo())
6843       if (Spec->getSpecializationKind() ==
6844               TSK_ExplicitInstantiationDefinition &&
6845           Spec->hasDefinition())
6846         DI->completeTemplateDefinition(*Spec);
6847   } [[fallthrough]];
6848   case Decl::CXXRecord: {
6849     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6850     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6851       if (CRD->hasDefinition())
6852         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6853       if (auto *ES = D->getASTContext().getExternalSource())
6854         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6855           DI->completeUnusedClass(*CRD);
6856     }
6857     // Emit any static data members, they may be definitions.
6858     for (auto *I : CRD->decls())
6859       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6860         EmitTopLevelDecl(I);
6861     break;
6862   }
6863     // No code generation needed.
6864   case Decl::UsingShadow:
6865   case Decl::ClassTemplate:
6866   case Decl::VarTemplate:
6867   case Decl::Concept:
6868   case Decl::VarTemplatePartialSpecialization:
6869   case Decl::FunctionTemplate:
6870   case Decl::TypeAliasTemplate:
6871   case Decl::Block:
6872   case Decl::Empty:
6873   case Decl::Binding:
6874     break;
6875   case Decl::Using:          // using X; [C++]
6876     if (CGDebugInfo *DI = getModuleDebugInfo())
6877         DI->EmitUsingDecl(cast<UsingDecl>(*D));
6878     break;
6879   case Decl::UsingEnum: // using enum X; [C++]
6880     if (CGDebugInfo *DI = getModuleDebugInfo())
6881       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6882     break;
6883   case Decl::NamespaceAlias:
6884     if (CGDebugInfo *DI = getModuleDebugInfo())
6885         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6886     break;
6887   case Decl::UsingDirective: // using namespace X; [C++]
6888     if (CGDebugInfo *DI = getModuleDebugInfo())
6889       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6890     break;
6891   case Decl::CXXConstructor:
6892     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6893     break;
6894   case Decl::CXXDestructor:
6895     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6896     break;
6897 
6898   case Decl::StaticAssert:
6899     // Nothing to do.
6900     break;
6901 
6902   // Objective-C Decls
6903 
6904   // Forward declarations, no (immediate) code generation.
6905   case Decl::ObjCInterface:
6906   case Decl::ObjCCategory:
6907     break;
6908 
6909   case Decl::ObjCProtocol: {
6910     auto *Proto = cast<ObjCProtocolDecl>(D);
6911     if (Proto->isThisDeclarationADefinition())
6912       ObjCRuntime->GenerateProtocol(Proto);
6913     break;
6914   }
6915 
6916   case Decl::ObjCCategoryImpl:
6917     // Categories have properties but don't support synthesize so we
6918     // can ignore them here.
6919     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6920     break;
6921 
6922   case Decl::ObjCImplementation: {
6923     auto *OMD = cast<ObjCImplementationDecl>(D);
6924     EmitObjCPropertyImplementations(OMD);
6925     EmitObjCIvarInitializations(OMD);
6926     ObjCRuntime->GenerateClass(OMD);
6927     // Emit global variable debug information.
6928     if (CGDebugInfo *DI = getModuleDebugInfo())
6929       if (getCodeGenOpts().hasReducedDebugInfo())
6930         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6931             OMD->getClassInterface()), OMD->getLocation());
6932     break;
6933   }
6934   case Decl::ObjCMethod: {
6935     auto *OMD = cast<ObjCMethodDecl>(D);
6936     // If this is not a prototype, emit the body.
6937     if (OMD->getBody())
6938       CodeGenFunction(*this).GenerateObjCMethod(OMD);
6939     break;
6940   }
6941   case Decl::ObjCCompatibleAlias:
6942     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6943     break;
6944 
6945   case Decl::PragmaComment: {
6946     const auto *PCD = cast<PragmaCommentDecl>(D);
6947     switch (PCD->getCommentKind()) {
6948     case PCK_Unknown:
6949       llvm_unreachable("unexpected pragma comment kind");
6950     case PCK_Linker:
6951       AppendLinkerOptions(PCD->getArg());
6952       break;
6953     case PCK_Lib:
6954         AddDependentLib(PCD->getArg());
6955       break;
6956     case PCK_Compiler:
6957     case PCK_ExeStr:
6958     case PCK_User:
6959       break; // We ignore all of these.
6960     }
6961     break;
6962   }
6963 
6964   case Decl::PragmaDetectMismatch: {
6965     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6966     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6967     break;
6968   }
6969 
6970   case Decl::LinkageSpec:
6971     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6972     break;
6973 
6974   case Decl::FileScopeAsm: {
6975     // File-scope asm is ignored during device-side CUDA compilation.
6976     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6977       break;
6978     // File-scope asm is ignored during device-side OpenMP compilation.
6979     if (LangOpts.OpenMPIsTargetDevice)
6980       break;
6981     // File-scope asm is ignored during device-side SYCL compilation.
6982     if (LangOpts.SYCLIsDevice)
6983       break;
6984     auto *AD = cast<FileScopeAsmDecl>(D);
6985     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6986     break;
6987   }
6988 
6989   case Decl::TopLevelStmt:
6990     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6991     break;
6992 
6993   case Decl::Import: {
6994     auto *Import = cast<ImportDecl>(D);
6995 
6996     // If we've already imported this module, we're done.
6997     if (!ImportedModules.insert(Import->getImportedModule()))
6998       break;
6999 
7000     // Emit debug information for direct imports.
7001     if (!Import->getImportedOwningModule()) {
7002       if (CGDebugInfo *DI = getModuleDebugInfo())
7003         DI->EmitImportDecl(*Import);
7004     }
7005 
7006     // For C++ standard modules we are done - we will call the module
7007     // initializer for imported modules, and that will likewise call those for
7008     // any imports it has.
7009     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
7010         !Import->getImportedOwningModule()->isModuleMapModule())
7011       break;
7012 
7013     // For clang C++ module map modules the initializers for sub-modules are
7014     // emitted here.
7015 
7016     // Find all of the submodules and emit the module initializers.
7017     llvm::SmallPtrSet<clang::Module *, 16> Visited;
7018     SmallVector<clang::Module *, 16> Stack;
7019     Visited.insert(Import->getImportedModule());
7020     Stack.push_back(Import->getImportedModule());
7021 
7022     while (!Stack.empty()) {
7023       clang::Module *Mod = Stack.pop_back_val();
7024       if (!EmittedModuleInitializers.insert(Mod).second)
7025         continue;
7026 
7027       for (auto *D : Context.getModuleInitializers(Mod))
7028         EmitTopLevelDecl(D);
7029 
7030       // Visit the submodules of this module.
7031       for (auto *Submodule : Mod->submodules()) {
7032         // Skip explicit children; they need to be explicitly imported to emit
7033         // the initializers.
7034         if (Submodule->IsExplicit)
7035           continue;
7036 
7037         if (Visited.insert(Submodule).second)
7038           Stack.push_back(Submodule);
7039       }
7040     }
7041     break;
7042   }
7043 
7044   case Decl::Export:
7045     EmitDeclContext(cast<ExportDecl>(D));
7046     break;
7047 
7048   case Decl::OMPThreadPrivate:
7049     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
7050     break;
7051 
7052   case Decl::OMPAllocate:
7053     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
7054     break;
7055 
7056   case Decl::OMPDeclareReduction:
7057     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
7058     break;
7059 
7060   case Decl::OMPDeclareMapper:
7061     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
7062     break;
7063 
7064   case Decl::OMPRequires:
7065     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
7066     break;
7067 
7068   case Decl::Typedef:
7069   case Decl::TypeAlias: // using foo = bar; [C++11]
7070     if (CGDebugInfo *DI = getModuleDebugInfo())
7071       DI->EmitAndRetainType(
7072           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
7073     break;
7074 
7075   case Decl::Record:
7076     if (CGDebugInfo *DI = getModuleDebugInfo())
7077       if (cast<RecordDecl>(D)->getDefinition())
7078         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
7079     break;
7080 
7081   case Decl::Enum:
7082     if (CGDebugInfo *DI = getModuleDebugInfo())
7083       if (cast<EnumDecl>(D)->getDefinition())
7084         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
7085     break;
7086 
7087   case Decl::HLSLBuffer:
7088     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
7089     break;
7090 
7091   default:
7092     // Make sure we handled everything we should, every other kind is a
7093     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
7094     // function. Need to recode Decl::Kind to do that easily.
7095     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
7096     break;
7097   }
7098 }
7099 
7100 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
7101   // Do we need to generate coverage mapping?
7102   if (!CodeGenOpts.CoverageMapping)
7103     return;
7104   switch (D->getKind()) {
7105   case Decl::CXXConversion:
7106   case Decl::CXXMethod:
7107   case Decl::Function:
7108   case Decl::ObjCMethod:
7109   case Decl::CXXConstructor:
7110   case Decl::CXXDestructor: {
7111     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
7112       break;
7113     SourceManager &SM = getContext().getSourceManager();
7114     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
7115       break;
7116     DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
7117     break;
7118   }
7119   default:
7120     break;
7121   };
7122 }
7123 
7124 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
7125   // Do we need to generate coverage mapping?
7126   if (!CodeGenOpts.CoverageMapping)
7127     return;
7128   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7129     if (Fn->isTemplateInstantiation())
7130       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
7131   }
7132   DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
7133 }
7134 
7135 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
7136   // We call takeVector() here to avoid use-after-free.
7137   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
7138   // we deserialize function bodies to emit coverage info for them, and that
7139   // deserializes more declarations. How should we handle that case?
7140   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7141     if (!Entry.second)
7142       continue;
7143     const Decl *D = Entry.first;
7144     switch (D->getKind()) {
7145     case Decl::CXXConversion:
7146     case Decl::CXXMethod:
7147     case Decl::Function:
7148     case Decl::ObjCMethod: {
7149       CodeGenPGO PGO(*this);
7150       GlobalDecl GD(cast<FunctionDecl>(D));
7151       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7152                                   getFunctionLinkage(GD));
7153       break;
7154     }
7155     case Decl::CXXConstructor: {
7156       CodeGenPGO PGO(*this);
7157       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
7158       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7159                                   getFunctionLinkage(GD));
7160       break;
7161     }
7162     case Decl::CXXDestructor: {
7163       CodeGenPGO PGO(*this);
7164       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
7165       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7166                                   getFunctionLinkage(GD));
7167       break;
7168     }
7169     default:
7170       break;
7171     };
7172   }
7173 }
7174 
7175 void CodeGenModule::EmitMainVoidAlias() {
7176   // In order to transition away from "__original_main" gracefully, emit an
7177   // alias for "main" in the no-argument case so that libc can detect when
7178   // new-style no-argument main is in used.
7179   if (llvm::Function *F = getModule().getFunction("main")) {
7180     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7181         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7182       auto *GA = llvm::GlobalAlias::create("__main_void", F);
7183       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7184     }
7185   }
7186 }
7187 
7188 /// Turns the given pointer into a constant.
7189 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
7190                                           const void *Ptr) {
7191   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
7192   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7193   return llvm::ConstantInt::get(i64, PtrInt);
7194 }
7195 
7196 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
7197                                    llvm::NamedMDNode *&GlobalMetadata,
7198                                    GlobalDecl D,
7199                                    llvm::GlobalValue *Addr) {
7200   if (!GlobalMetadata)
7201     GlobalMetadata =
7202       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
7203 
7204   // TODO: should we report variant information for ctors/dtors?
7205   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7206                            llvm::ConstantAsMetadata::get(GetPointerConstant(
7207                                CGM.getLLVMContext(), D.getDecl()))};
7208   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
7209 }
7210 
7211 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7212                                                  llvm::GlobalValue *CppFunc) {
7213   // Store the list of ifuncs we need to replace uses in.
7214   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7215   // List of ConstantExprs that we should be able to delete when we're done
7216   // here.
7217   llvm::SmallVector<llvm::ConstantExpr *> CEs;
7218 
7219   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
7220   if (Elem == CppFunc)
7221     return false;
7222 
7223   // First make sure that all users of this are ifuncs (or ifuncs via a
7224   // bitcast), and collect the list of ifuncs and CEs so we can work on them
7225   // later.
7226   for (llvm::User *User : Elem->users()) {
7227     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
7228     // ifunc directly. In any other case, just give up, as we don't know what we
7229     // could break by changing those.
7230     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7231       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7232         return false;
7233 
7234       for (llvm::User *CEUser : ConstExpr->users()) {
7235         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7236           IFuncs.push_back(IFunc);
7237         } else {
7238           return false;
7239         }
7240       }
7241       CEs.push_back(ConstExpr);
7242     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7243       IFuncs.push_back(IFunc);
7244     } else {
7245       // This user is one we don't know how to handle, so fail redirection. This
7246       // will result in an ifunc retaining a resolver name that will ultimately
7247       // fail to be resolved to a defined function.
7248       return false;
7249     }
7250   }
7251 
7252   // Now we know this is a valid case where we can do this alias replacement, we
7253   // need to remove all of the references to Elem (and the bitcasts!) so we can
7254   // delete it.
7255   for (llvm::GlobalIFunc *IFunc : IFuncs)
7256     IFunc->setResolver(nullptr);
7257   for (llvm::ConstantExpr *ConstExpr : CEs)
7258     ConstExpr->destroyConstant();
7259 
7260   // We should now be out of uses for the 'old' version of this function, so we
7261   // can erase it as well.
7262   Elem->eraseFromParent();
7263 
7264   for (llvm::GlobalIFunc *IFunc : IFuncs) {
7265     // The type of the resolver is always just a function-type that returns the
7266     // type of the IFunc, so create that here. If the type of the actual
7267     // resolver doesn't match, it just gets bitcast to the right thing.
7268     auto *ResolverTy =
7269         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7270     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7271         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7272     IFunc->setResolver(Resolver);
7273   }
7274   return true;
7275 }
7276 
7277 /// For each function which is declared within an extern "C" region and marked
7278 /// as 'used', but has internal linkage, create an alias from the unmangled
7279 /// name to the mangled name if possible. People expect to be able to refer
7280 /// to such functions with an unmangled name from inline assembly within the
7281 /// same translation unit.
7282 void CodeGenModule::EmitStaticExternCAliases() {
7283   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7284     return;
7285   for (auto &I : StaticExternCValues) {
7286     const IdentifierInfo *Name = I.first;
7287     llvm::GlobalValue *Val = I.second;
7288 
7289     // If Val is null, that implies there were multiple declarations that each
7290     // had a claim to the unmangled name. In this case, generation of the alias
7291     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7292     if (!Val)
7293       break;
7294 
7295     llvm::GlobalValue *ExistingElem =
7296         getModule().getNamedValue(Name->getName());
7297 
7298     // If there is either not something already by this name, or we were able to
7299     // replace all uses from IFuncs, create the alias.
7300     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7301       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7302   }
7303 }
7304 
7305 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
7306                                              GlobalDecl &Result) const {
7307   auto Res = Manglings.find(MangledName);
7308   if (Res == Manglings.end())
7309     return false;
7310   Result = Res->getValue();
7311   return true;
7312 }
7313 
7314 /// Emits metadata nodes associating all the global values in the
7315 /// current module with the Decls they came from.  This is useful for
7316 /// projects using IR gen as a subroutine.
7317 ///
7318 /// Since there's currently no way to associate an MDNode directly
7319 /// with an llvm::GlobalValue, we create a global named metadata
7320 /// with the name 'clang.global.decl.ptrs'.
7321 void CodeGenModule::EmitDeclMetadata() {
7322   llvm::NamedMDNode *GlobalMetadata = nullptr;
7323 
7324   for (auto &I : MangledDeclNames) {
7325     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7326     // Some mangled names don't necessarily have an associated GlobalValue
7327     // in this module, e.g. if we mangled it for DebugInfo.
7328     if (Addr)
7329       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7330   }
7331 }
7332 
7333 /// Emits metadata nodes for all the local variables in the current
7334 /// function.
7335 void CodeGenFunction::EmitDeclMetadata() {
7336   if (LocalDeclMap.empty()) return;
7337 
7338   llvm::LLVMContext &Context = getLLVMContext();
7339 
7340   // Find the unique metadata ID for this name.
7341   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
7342 
7343   llvm::NamedMDNode *GlobalMetadata = nullptr;
7344 
7345   for (auto &I : LocalDeclMap) {
7346     const Decl *D = I.first;
7347     llvm::Value *Addr = I.second.emitRawPointer(*this);
7348     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7349       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
7350       Alloca->setMetadata(
7351           DeclPtrKind, llvm::MDNode::get(
7352                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7353     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7354       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
7355       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
7356     }
7357   }
7358 }
7359 
7360 void CodeGenModule::EmitVersionIdentMetadata() {
7361   llvm::NamedMDNode *IdentMetadata =
7362     TheModule.getOrInsertNamedMetadata("llvm.ident");
7363   std::string Version = getClangFullVersion();
7364   llvm::LLVMContext &Ctx = TheModule.getContext();
7365 
7366   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7367   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7368 }
7369 
7370 void CodeGenModule::EmitCommandLineMetadata() {
7371   llvm::NamedMDNode *CommandLineMetadata =
7372     TheModule.getOrInsertNamedMetadata("llvm.commandline");
7373   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
7374   llvm::LLVMContext &Ctx = TheModule.getContext();
7375 
7376   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7377   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7378 }
7379 
7380 void CodeGenModule::EmitCoverageFile() {
7381   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
7382   if (!CUNode)
7383     return;
7384 
7385   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
7386   llvm::LLVMContext &Ctx = TheModule.getContext();
7387   auto *CoverageDataFile =
7388       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
7389   auto *CoverageNotesFile =
7390       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
7391   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7392     llvm::MDNode *CU = CUNode->getOperand(i);
7393     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7394     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7395   }
7396 }
7397 
7398 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
7399                                                        bool ForEH) {
7400   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
7401   // FIXME: should we even be calling this method if RTTI is disabled
7402   // and it's not for EH?
7403   if (!shouldEmitRTTI(ForEH))
7404     return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
7405 
7406   if (ForEH && Ty->isObjCObjectPointerType() &&
7407       LangOpts.ObjCRuntime.isGNUFamily())
7408     return ObjCRuntime->GetEHType(Ty);
7409 
7410   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
7411 }
7412 
7413 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
7414   // Do not emit threadprivates in simd-only mode.
7415   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7416     return;
7417   for (auto RefExpr : D->varlists()) {
7418     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7419     bool PerformInit =
7420         VD->getAnyInitializer() &&
7421         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
7422                                                         /*ForRef=*/false);
7423 
7424     Address Addr(GetAddrOfGlobalVar(VD),
7425                  getTypes().ConvertTypeForMem(VD->getType()),
7426                  getContext().getDeclAlign(VD));
7427     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
7428             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7429       CXXGlobalInits.push_back(InitFunction);
7430   }
7431 }
7432 
7433 llvm::Metadata *
7434 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
7435                                             StringRef Suffix) {
7436   if (auto *FnType = T->getAs<FunctionProtoType>())
7437     T = getContext().getFunctionType(
7438         FnType->getReturnType(), FnType->getParamTypes(),
7439         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
7440 
7441   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
7442   if (InternalId)
7443     return InternalId;
7444 
7445   if (isExternallyVisible(T->getLinkage())) {
7446     std::string OutName;
7447     llvm::raw_string_ostream Out(OutName);
7448     getCXXABI().getMangleContext().mangleCanonicalTypeName(
7449         T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
7450 
7451     if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
7452       Out << ".normalized";
7453 
7454     Out << Suffix;
7455 
7456     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
7457   } else {
7458     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
7459                                            llvm::ArrayRef<llvm::Metadata *>());
7460   }
7461 
7462   return InternalId;
7463 }
7464 
7465 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
7466   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
7467 }
7468 
7469 llvm::Metadata *
7470 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
7471   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
7472 }
7473 
7474 // Generalize pointer types to a void pointer with the qualifiers of the
7475 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
7476 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
7477 // 'void *'.
7478 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
7479   if (!Ty->isPointerType())
7480     return Ty;
7481 
7482   return Ctx.getPointerType(
7483       QualType(Ctx.VoidTy).withCVRQualifiers(
7484           Ty->getPointeeType().getCVRQualifiers()));
7485 }
7486 
7487 // Apply type generalization to a FunctionType's return and argument types
7488 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
7489   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
7490     SmallVector<QualType, 8> GeneralizedParams;
7491     for (auto &Param : FnType->param_types())
7492       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
7493 
7494     return Ctx.getFunctionType(
7495         GeneralizeType(Ctx, FnType->getReturnType()),
7496         GeneralizedParams, FnType->getExtProtoInfo());
7497   }
7498 
7499   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
7500     return Ctx.getFunctionNoProtoType(
7501         GeneralizeType(Ctx, FnType->getReturnType()));
7502 
7503   llvm_unreachable("Encountered unknown FunctionType");
7504 }
7505 
7506 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7507   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7508                                       GeneralizedMetadataIdMap, ".generalized");
7509 }
7510 
7511 /// Returns whether this module needs the "all-vtables" type identifier.
7512 bool CodeGenModule::NeedAllVtablesTypeId() const {
7513   // Returns true if at least one of vtable-based CFI checkers is enabled and
7514   // is not in the trapping mode.
7515   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7516            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7517           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7518            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7519           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7520            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7521           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7522            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7523 }
7524 
7525 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7526                                           CharUnits Offset,
7527                                           const CXXRecordDecl *RD) {
7528   llvm::Metadata *MD =
7529       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7530   VTable->addTypeMetadata(Offset.getQuantity(), MD);
7531 
7532   if (CodeGenOpts.SanitizeCfiCrossDso)
7533     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7534       VTable->addTypeMetadata(Offset.getQuantity(),
7535                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7536 
7537   if (NeedAllVtablesTypeId()) {
7538     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7539     VTable->addTypeMetadata(Offset.getQuantity(), MD);
7540   }
7541 }
7542 
7543 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7544   if (!SanStats)
7545     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7546 
7547   return *SanStats;
7548 }
7549 
7550 llvm::Value *
7551 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7552                                                   CodeGenFunction &CGF) {
7553   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7554   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7555   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7556   auto *Call = CGF.EmitRuntimeCall(
7557       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7558   return Call;
7559 }
7560 
7561 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7562     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7563   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7564                                  /* forPointeeType= */ true);
7565 }
7566 
7567 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7568                                                  LValueBaseInfo *BaseInfo,
7569                                                  TBAAAccessInfo *TBAAInfo,
7570                                                  bool forPointeeType) {
7571   if (TBAAInfo)
7572     *TBAAInfo = getTBAAAccessInfo(T);
7573 
7574   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7575   // that doesn't return the information we need to compute BaseInfo.
7576 
7577   // Honor alignment typedef attributes even on incomplete types.
7578   // We also honor them straight for C++ class types, even as pointees;
7579   // there's an expressivity gap here.
7580   if (auto TT = T->getAs<TypedefType>()) {
7581     if (auto Align = TT->getDecl()->getMaxAlignment()) {
7582       if (BaseInfo)
7583         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7584       return getContext().toCharUnitsFromBits(Align);
7585     }
7586   }
7587 
7588   bool AlignForArray = T->isArrayType();
7589 
7590   // Analyze the base element type, so we don't get confused by incomplete
7591   // array types.
7592   T = getContext().getBaseElementType(T);
7593 
7594   if (T->isIncompleteType()) {
7595     // We could try to replicate the logic from
7596     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7597     // type is incomplete, so it's impossible to test. We could try to reuse
7598     // getTypeAlignIfKnown, but that doesn't return the information we need
7599     // to set BaseInfo.  So just ignore the possibility that the alignment is
7600     // greater than one.
7601     if (BaseInfo)
7602       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7603     return CharUnits::One();
7604   }
7605 
7606   if (BaseInfo)
7607     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7608 
7609   CharUnits Alignment;
7610   const CXXRecordDecl *RD;
7611   if (T.getQualifiers().hasUnaligned()) {
7612     Alignment = CharUnits::One();
7613   } else if (forPointeeType && !AlignForArray &&
7614              (RD = T->getAsCXXRecordDecl())) {
7615     // For C++ class pointees, we don't know whether we're pointing at a
7616     // base or a complete object, so we generally need to use the
7617     // non-virtual alignment.
7618     Alignment = getClassPointerAlignment(RD);
7619   } else {
7620     Alignment = getContext().getTypeAlignInChars(T);
7621   }
7622 
7623   // Cap to the global maximum type alignment unless the alignment
7624   // was somehow explicit on the type.
7625   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7626     if (Alignment.getQuantity() > MaxAlign &&
7627         !getContext().isAlignmentRequired(T))
7628       Alignment = CharUnits::fromQuantity(MaxAlign);
7629   }
7630   return Alignment;
7631 }
7632 
7633 bool CodeGenModule::stopAutoInit() {
7634   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7635   if (StopAfter) {
7636     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7637     // used
7638     if (NumAutoVarInit >= StopAfter) {
7639       return true;
7640     }
7641     if (!NumAutoVarInit) {
7642       unsigned DiagID = getDiags().getCustomDiagID(
7643           DiagnosticsEngine::Warning,
7644           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7645           "number of times ftrivial-auto-var-init=%1 gets applied.");
7646       getDiags().Report(DiagID)
7647           << StopAfter
7648           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7649                       LangOptions::TrivialAutoVarInitKind::Zero
7650                   ? "zero"
7651                   : "pattern");
7652     }
7653     ++NumAutoVarInit;
7654   }
7655   return false;
7656 }
7657 
7658 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7659                                                     const Decl *D) const {
7660   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7661   // postfix beginning with '.' since the symbol name can be demangled.
7662   if (LangOpts.HIP)
7663     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7664   else
7665     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7666 
7667   // If the CUID is not specified we try to generate a unique postfix.
7668   if (getLangOpts().CUID.empty()) {
7669     SourceManager &SM = getContext().getSourceManager();
7670     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7671     assert(PLoc.isValid() && "Source location is expected to be valid.");
7672 
7673     // Get the hash of the user defined macros.
7674     llvm::MD5 Hash;
7675     llvm::MD5::MD5Result Result;
7676     for (const auto &Arg : PreprocessorOpts.Macros)
7677       Hash.update(Arg.first);
7678     Hash.final(Result);
7679 
7680     // Get the UniqueID for the file containing the decl.
7681     llvm::sys::fs::UniqueID ID;
7682     if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7683       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7684       assert(PLoc.isValid() && "Source location is expected to be valid.");
7685       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7686         SM.getDiagnostics().Report(diag::err_cannot_open_file)
7687             << PLoc.getFilename() << EC.message();
7688     }
7689     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7690        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7691   } else {
7692     OS << getContext().getCUIDHash();
7693   }
7694 }
7695 
7696 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7697   assert(DeferredDeclsToEmit.empty() &&
7698          "Should have emitted all decls deferred to emit.");
7699   assert(NewBuilder->DeferredDecls.empty() &&
7700          "Newly created module should not have deferred decls");
7701   NewBuilder->DeferredDecls = std::move(DeferredDecls);
7702   assert(EmittedDeferredDecls.empty() &&
7703          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7704 
7705   assert(NewBuilder->DeferredVTables.empty() &&
7706          "Newly created module should not have deferred vtables");
7707   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7708 
7709   assert(NewBuilder->MangledDeclNames.empty() &&
7710          "Newly created module should not have mangled decl names");
7711   assert(NewBuilder->Manglings.empty() &&
7712          "Newly created module should not have manglings");
7713   NewBuilder->Manglings = std::move(Manglings);
7714 
7715   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7716 
7717   NewBuilder->TBAA = std::move(TBAA);
7718 
7719   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7720 }
7721