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