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