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