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