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