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