xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 8a4dda33d67586ca2624f2a38417baa03a533a7f)
10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenModule.h"
14fcaf7f86SDimitry Andric #include "ABIInfo.h"
150b57cec5SDimitry Andric #include "CGBlocks.h"
160b57cec5SDimitry Andric #include "CGCUDARuntime.h"
170b57cec5SDimitry Andric #include "CGCXXABI.h"
180b57cec5SDimitry Andric #include "CGCall.h"
190b57cec5SDimitry Andric #include "CGDebugInfo.h"
2081ad6265SDimitry Andric #include "CGHLSLRuntime.h"
210b57cec5SDimitry Andric #include "CGObjCRuntime.h"
220b57cec5SDimitry Andric #include "CGOpenCLRuntime.h"
230b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
24349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h"
250b57cec5SDimitry Andric #include "CodeGenFunction.h"
260b57cec5SDimitry Andric #include "CodeGenPGO.h"
270b57cec5SDimitry Andric #include "ConstantEmitter.h"
280b57cec5SDimitry Andric #include "CoverageMappingGen.h"
290b57cec5SDimitry Andric #include "TargetInfo.h"
300b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
310b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
320b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
330b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
340b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
350b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
360b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
370b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
380b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
390b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
400b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
410b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
425ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
430b57cec5SDimitry Andric #include "clang/Basic/Module.h"
440b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
450b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
460b57cec5SDimitry Andric #include "clang/Basic/Version.h"
4781ad6265SDimitry Andric #include "clang/CodeGen/BackendUtil.h"
480b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
490b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
50bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h"
51bdd1243dSDimitry Andric #include "llvm/ADT/StringExtras.h"
520b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
530b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
54480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
5506c3fb27SDimitry Andric #include "llvm/IR/AttributeMask.h"
560b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
570b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
580b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
590b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
600b57cec5SDimitry Andric #include "llvm/IR/Module.h"
610b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
620b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
63bdd1243dSDimitry Andric #include "llvm/ProfileData/SampleProf.h"
64fcaf7f86SDimitry Andric #include "llvm/Support/CRC.h"
650b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
66480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
670b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
680b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
690b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
70bdd1243dSDimitry Andric #include "llvm/Support/xxhash.h"
7106c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
7206c3fb27SDimitry Andric #include "llvm/TargetParser/X86TargetParser.h"
73bdd1243dSDimitry Andric #include <optional>
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric using namespace clang;
760b57cec5SDimitry Andric using namespace CodeGen;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
7981ad6265SDimitry Andric     "limited-coverage-experimental", llvm::cl::Hidden,
8081ad6265SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
85fe6060f1SDimitry Andric   switch (CGM.getContext().getCXXABIKind()) {
86e8d8bef9SDimitry Andric   case TargetCXXABI::AppleARM64:
87480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
880b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
890b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
900b57cec5SDimitry Andric   case TargetCXXABI::iOS:
910b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
920b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
930b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
940b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
955ffd83dbSDimitry Andric   case TargetCXXABI::XL:
960b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
970b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
980b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
990b57cec5SDimitry Andric   }
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric 
10406c3fb27SDimitry Andric static std::unique_ptr<TargetCodeGenInfo>
10506c3fb27SDimitry Andric createTargetCodeGenInfo(CodeGenModule &CGM) {
10606c3fb27SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
10706c3fb27SDimitry Andric   const llvm::Triple &Triple = Target.getTriple();
10806c3fb27SDimitry Andric   const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
10906c3fb27SDimitry Andric 
11006c3fb27SDimitry Andric   switch (Triple.getArch()) {
11106c3fb27SDimitry Andric   default:
11206c3fb27SDimitry Andric     return createDefaultTargetCodeGenInfo(CGM);
11306c3fb27SDimitry Andric 
11406c3fb27SDimitry Andric   case llvm::Triple::le32:
11506c3fb27SDimitry Andric     return createPNaClTargetCodeGenInfo(CGM);
11606c3fb27SDimitry Andric   case llvm::Triple::m68k:
11706c3fb27SDimitry Andric     return createM68kTargetCodeGenInfo(CGM);
11806c3fb27SDimitry Andric   case llvm::Triple::mips:
11906c3fb27SDimitry Andric   case llvm::Triple::mipsel:
12006c3fb27SDimitry Andric     if (Triple.getOS() == llvm::Triple::NaCl)
12106c3fb27SDimitry Andric       return createPNaClTargetCodeGenInfo(CGM);
12206c3fb27SDimitry Andric     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
12306c3fb27SDimitry Andric 
12406c3fb27SDimitry Andric   case llvm::Triple::mips64:
12506c3fb27SDimitry Andric   case llvm::Triple::mips64el:
12606c3fb27SDimitry Andric     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
12706c3fb27SDimitry Andric 
12806c3fb27SDimitry Andric   case llvm::Triple::avr: {
12906c3fb27SDimitry Andric     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
13006c3fb27SDimitry Andric     // on avrtiny. For passing return value, R18~R25 are used on avr, and
13106c3fb27SDimitry Andric     // R22~R25 are used on avrtiny.
13206c3fb27SDimitry Andric     unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
13306c3fb27SDimitry Andric     unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
13406c3fb27SDimitry Andric     return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
13506c3fb27SDimitry Andric   }
13606c3fb27SDimitry Andric 
13706c3fb27SDimitry Andric   case llvm::Triple::aarch64:
13806c3fb27SDimitry Andric   case llvm::Triple::aarch64_32:
13906c3fb27SDimitry Andric   case llvm::Triple::aarch64_be: {
14006c3fb27SDimitry Andric     AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
14106c3fb27SDimitry Andric     if (Target.getABI() == "darwinpcs")
14206c3fb27SDimitry Andric       Kind = AArch64ABIKind::DarwinPCS;
14306c3fb27SDimitry Andric     else if (Triple.isOSWindows())
14406c3fb27SDimitry Andric       return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
14506c3fb27SDimitry Andric 
14606c3fb27SDimitry Andric     return createAArch64TargetCodeGenInfo(CGM, Kind);
14706c3fb27SDimitry Andric   }
14806c3fb27SDimitry Andric 
14906c3fb27SDimitry Andric   case llvm::Triple::wasm32:
15006c3fb27SDimitry Andric   case llvm::Triple::wasm64: {
15106c3fb27SDimitry Andric     WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
15206c3fb27SDimitry Andric     if (Target.getABI() == "experimental-mv")
15306c3fb27SDimitry Andric       Kind = WebAssemblyABIKind::ExperimentalMV;
15406c3fb27SDimitry Andric     return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
15506c3fb27SDimitry Andric   }
15606c3fb27SDimitry Andric 
15706c3fb27SDimitry Andric   case llvm::Triple::arm:
15806c3fb27SDimitry Andric   case llvm::Triple::armeb:
15906c3fb27SDimitry Andric   case llvm::Triple::thumb:
16006c3fb27SDimitry Andric   case llvm::Triple::thumbeb: {
16106c3fb27SDimitry Andric     if (Triple.getOS() == llvm::Triple::Win32)
16206c3fb27SDimitry Andric       return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
16306c3fb27SDimitry Andric 
16406c3fb27SDimitry Andric     ARMABIKind Kind = ARMABIKind::AAPCS;
16506c3fb27SDimitry Andric     StringRef ABIStr = Target.getABI();
16606c3fb27SDimitry Andric     if (ABIStr == "apcs-gnu")
16706c3fb27SDimitry Andric       Kind = ARMABIKind::APCS;
16806c3fb27SDimitry Andric     else if (ABIStr == "aapcs16")
16906c3fb27SDimitry Andric       Kind = ARMABIKind::AAPCS16_VFP;
17006c3fb27SDimitry Andric     else if (CodeGenOpts.FloatABI == "hard" ||
17106c3fb27SDimitry Andric              (CodeGenOpts.FloatABI != "soft" &&
17206c3fb27SDimitry Andric               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
17306c3fb27SDimitry Andric                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
17406c3fb27SDimitry Andric                Triple.getEnvironment() == llvm::Triple::EABIHF)))
17506c3fb27SDimitry Andric       Kind = ARMABIKind::AAPCS_VFP;
17606c3fb27SDimitry Andric 
17706c3fb27SDimitry Andric     return createARMTargetCodeGenInfo(CGM, Kind);
17806c3fb27SDimitry Andric   }
17906c3fb27SDimitry Andric 
18006c3fb27SDimitry Andric   case llvm::Triple::ppc: {
18106c3fb27SDimitry Andric     if (Triple.isOSAIX())
18206c3fb27SDimitry Andric       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
18306c3fb27SDimitry Andric 
18406c3fb27SDimitry Andric     bool IsSoftFloat =
18506c3fb27SDimitry Andric         CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
18606c3fb27SDimitry Andric     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
18706c3fb27SDimitry Andric   }
18806c3fb27SDimitry Andric   case llvm::Triple::ppcle: {
18906c3fb27SDimitry Andric     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
19006c3fb27SDimitry Andric     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
19106c3fb27SDimitry Andric   }
19206c3fb27SDimitry Andric   case llvm::Triple::ppc64:
19306c3fb27SDimitry Andric     if (Triple.isOSAIX())
19406c3fb27SDimitry Andric       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
19506c3fb27SDimitry Andric 
19606c3fb27SDimitry Andric     if (Triple.isOSBinFormatELF()) {
19706c3fb27SDimitry Andric       PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
19806c3fb27SDimitry Andric       if (Target.getABI() == "elfv2")
19906c3fb27SDimitry Andric         Kind = PPC64_SVR4_ABIKind::ELFv2;
20006c3fb27SDimitry Andric       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
20106c3fb27SDimitry Andric 
20206c3fb27SDimitry Andric       return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
20306c3fb27SDimitry Andric     }
20406c3fb27SDimitry Andric     return createPPC64TargetCodeGenInfo(CGM);
20506c3fb27SDimitry Andric   case llvm::Triple::ppc64le: {
20606c3fb27SDimitry Andric     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
20706c3fb27SDimitry Andric     PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
20806c3fb27SDimitry Andric     if (Target.getABI() == "elfv1")
20906c3fb27SDimitry Andric       Kind = PPC64_SVR4_ABIKind::ELFv1;
21006c3fb27SDimitry Andric     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
21106c3fb27SDimitry Andric 
21206c3fb27SDimitry Andric     return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
21306c3fb27SDimitry Andric   }
21406c3fb27SDimitry Andric 
21506c3fb27SDimitry Andric   case llvm::Triple::nvptx:
21606c3fb27SDimitry Andric   case llvm::Triple::nvptx64:
21706c3fb27SDimitry Andric     return createNVPTXTargetCodeGenInfo(CGM);
21806c3fb27SDimitry Andric 
21906c3fb27SDimitry Andric   case llvm::Triple::msp430:
22006c3fb27SDimitry Andric     return createMSP430TargetCodeGenInfo(CGM);
22106c3fb27SDimitry Andric 
22206c3fb27SDimitry Andric   case llvm::Triple::riscv32:
22306c3fb27SDimitry Andric   case llvm::Triple::riscv64: {
22406c3fb27SDimitry Andric     StringRef ABIStr = Target.getABI();
22506c3fb27SDimitry Andric     unsigned XLen = Target.getPointerWidth(LangAS::Default);
22606c3fb27SDimitry Andric     unsigned ABIFLen = 0;
22706c3fb27SDimitry Andric     if (ABIStr.endswith("f"))
22806c3fb27SDimitry Andric       ABIFLen = 32;
22906c3fb27SDimitry Andric     else if (ABIStr.endswith("d"))
23006c3fb27SDimitry Andric       ABIFLen = 64;
23106c3fb27SDimitry Andric     return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen);
23206c3fb27SDimitry Andric   }
23306c3fb27SDimitry Andric 
23406c3fb27SDimitry Andric   case llvm::Triple::systemz: {
23506c3fb27SDimitry Andric     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
23606c3fb27SDimitry Andric     bool HasVector = !SoftFloat && Target.getABI() == "vector";
23706c3fb27SDimitry Andric     return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
23806c3fb27SDimitry Andric   }
23906c3fb27SDimitry Andric 
24006c3fb27SDimitry Andric   case llvm::Triple::tce:
24106c3fb27SDimitry Andric   case llvm::Triple::tcele:
24206c3fb27SDimitry Andric     return createTCETargetCodeGenInfo(CGM);
24306c3fb27SDimitry Andric 
24406c3fb27SDimitry Andric   case llvm::Triple::x86: {
24506c3fb27SDimitry Andric     bool IsDarwinVectorABI = Triple.isOSDarwin();
24606c3fb27SDimitry Andric     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
24706c3fb27SDimitry Andric 
24806c3fb27SDimitry Andric     if (Triple.getOS() == llvm::Triple::Win32) {
24906c3fb27SDimitry Andric       return createWinX86_32TargetCodeGenInfo(
25006c3fb27SDimitry Andric           CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
25106c3fb27SDimitry Andric           CodeGenOpts.NumRegisterParameters);
25206c3fb27SDimitry Andric     }
25306c3fb27SDimitry Andric     return createX86_32TargetCodeGenInfo(
25406c3fb27SDimitry Andric         CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
25506c3fb27SDimitry Andric         CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
25606c3fb27SDimitry Andric   }
25706c3fb27SDimitry Andric 
25806c3fb27SDimitry Andric   case llvm::Triple::x86_64: {
25906c3fb27SDimitry Andric     StringRef ABI = Target.getABI();
26006c3fb27SDimitry Andric     X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
26106c3fb27SDimitry Andric                                : ABI == "avx"  ? X86AVXABILevel::AVX
26206c3fb27SDimitry Andric                                                : X86AVXABILevel::None);
26306c3fb27SDimitry Andric 
26406c3fb27SDimitry Andric     switch (Triple.getOS()) {
26506c3fb27SDimitry Andric     case llvm::Triple::Win32:
26606c3fb27SDimitry Andric       return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
26706c3fb27SDimitry Andric     default:
26806c3fb27SDimitry Andric       return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
26906c3fb27SDimitry Andric     }
27006c3fb27SDimitry Andric   }
27106c3fb27SDimitry Andric   case llvm::Triple::hexagon:
27206c3fb27SDimitry Andric     return createHexagonTargetCodeGenInfo(CGM);
27306c3fb27SDimitry Andric   case llvm::Triple::lanai:
27406c3fb27SDimitry Andric     return createLanaiTargetCodeGenInfo(CGM);
27506c3fb27SDimitry Andric   case llvm::Triple::r600:
27606c3fb27SDimitry Andric     return createAMDGPUTargetCodeGenInfo(CGM);
27706c3fb27SDimitry Andric   case llvm::Triple::amdgcn:
27806c3fb27SDimitry Andric     return createAMDGPUTargetCodeGenInfo(CGM);
27906c3fb27SDimitry Andric   case llvm::Triple::sparc:
28006c3fb27SDimitry Andric     return createSparcV8TargetCodeGenInfo(CGM);
28106c3fb27SDimitry Andric   case llvm::Triple::sparcv9:
28206c3fb27SDimitry Andric     return createSparcV9TargetCodeGenInfo(CGM);
28306c3fb27SDimitry Andric   case llvm::Triple::xcore:
28406c3fb27SDimitry Andric     return createXCoreTargetCodeGenInfo(CGM);
28506c3fb27SDimitry Andric   case llvm::Triple::arc:
28606c3fb27SDimitry Andric     return createARCTargetCodeGenInfo(CGM);
28706c3fb27SDimitry Andric   case llvm::Triple::spir:
28806c3fb27SDimitry Andric   case llvm::Triple::spir64:
28906c3fb27SDimitry Andric     return createCommonSPIRTargetCodeGenInfo(CGM);
29006c3fb27SDimitry Andric   case llvm::Triple::spirv32:
29106c3fb27SDimitry Andric   case llvm::Triple::spirv64:
29206c3fb27SDimitry Andric     return createSPIRVTargetCodeGenInfo(CGM);
29306c3fb27SDimitry Andric   case llvm::Triple::ve:
29406c3fb27SDimitry Andric     return createVETargetCodeGenInfo(CGM);
29506c3fb27SDimitry Andric   case llvm::Triple::csky: {
29606c3fb27SDimitry Andric     bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
29706c3fb27SDimitry Andric     bool hasFP64 =
29806c3fb27SDimitry Andric         Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
29906c3fb27SDimitry Andric     return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
30006c3fb27SDimitry Andric                                             : hasFP64   ? 64
30106c3fb27SDimitry Andric                                                         : 32);
30206c3fb27SDimitry Andric   }
30306c3fb27SDimitry Andric   case llvm::Triple::bpfeb:
30406c3fb27SDimitry Andric   case llvm::Triple::bpfel:
30506c3fb27SDimitry Andric     return createBPFTargetCodeGenInfo(CGM);
30606c3fb27SDimitry Andric   case llvm::Triple::loongarch32:
30706c3fb27SDimitry Andric   case llvm::Triple::loongarch64: {
30806c3fb27SDimitry Andric     StringRef ABIStr = Target.getABI();
30906c3fb27SDimitry Andric     unsigned ABIFRLen = 0;
31006c3fb27SDimitry Andric     if (ABIStr.endswith("f"))
31106c3fb27SDimitry Andric       ABIFRLen = 32;
31206c3fb27SDimitry Andric     else if (ABIStr.endswith("d"))
31306c3fb27SDimitry Andric       ABIFRLen = 64;
31406c3fb27SDimitry Andric     return createLoongArchTargetCodeGenInfo(
31506c3fb27SDimitry Andric         CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
31606c3fb27SDimitry Andric   }
31706c3fb27SDimitry Andric   }
31806c3fb27SDimitry Andric }
31906c3fb27SDimitry Andric 
32006c3fb27SDimitry Andric const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
32106c3fb27SDimitry Andric   if (!TheTargetCodeGenInfo)
32206c3fb27SDimitry Andric     TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
32306c3fb27SDimitry Andric   return *TheTargetCodeGenInfo;
32406c3fb27SDimitry Andric }
32506c3fb27SDimitry Andric 
326972a253aSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C,
327972a253aSDimitry Andric                              IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
328972a253aSDimitry Andric                              const HeaderSearchOptions &HSO,
3290b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
3300b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
3310b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
3320b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
33306c3fb27SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
33406c3fb27SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
33506c3fb27SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
33606c3fb27SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
33706c3fb27SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   // Initialize the type cache.
3400b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
3410b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
3420b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
3430b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
3440b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
3450b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
3460b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
3475ffd83dbSDimitry Andric   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
3480b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
3490b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
350bdd1243dSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
3510b57cec5SDimitry Andric   PointerAlignInBytes =
352bdd1243dSDimitry Andric       C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
353bdd1243dSDimitry Andric           .getQuantity();
3540b57cec5SDimitry Andric   SizeSizeInBytes =
3550b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
3560b57cec5SDimitry Andric   IntAlignInBytes =
3570b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
358e8d8bef9SDimitry Andric   CharTy =
359e8d8bef9SDimitry Andric     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
3600b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
3610b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
3620b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
3630b57cec5SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
3640b57cec5SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
365349cc55cSDimitry Andric   const llvm::DataLayout &DL = M.getDataLayout();
366349cc55cSDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
367349cc55cSDimitry Andric   GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
368bdd1243dSDimitry Andric   ConstGlobalsPtrTy = Int8Ty->getPointerTo(
369bdd1243dSDimitry Andric       C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
3700b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
3710b57cec5SDimitry Andric 
372fcaf7f86SDimitry Andric   // Build C++20 Module initializers.
373fcaf7f86SDimitry Andric   // TODO: Add Microsoft here once we know the mangling required for the
374fcaf7f86SDimitry Andric   // initializers.
375fcaf7f86SDimitry Andric   CXX20ModuleInits =
376fcaf7f86SDimitry Andric       LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
377fcaf7f86SDimitry Andric                                        ItaniumMangleContext::MK_Itanium;
378fcaf7f86SDimitry Andric 
3790b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   if (LangOpts.ObjC)
3820b57cec5SDimitry Andric     createObjCRuntime();
3830b57cec5SDimitry Andric   if (LangOpts.OpenCL)
3840b57cec5SDimitry Andric     createOpenCLRuntime();
3850b57cec5SDimitry Andric   if (LangOpts.OpenMP)
3860b57cec5SDimitry Andric     createOpenMPRuntime();
3870b57cec5SDimitry Andric   if (LangOpts.CUDA)
3880b57cec5SDimitry Andric     createCUDARuntime();
38981ad6265SDimitry Andric   if (LangOpts.HLSL)
39081ad6265SDimitry Andric     createHLSLRuntime();
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
3930b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
3940b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
3950b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
3960b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
3990b57cec5SDimitry Andric   // object.
40006c3fb27SDimitry Andric   if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
40106c3fb27SDimitry Andric       CodeGenOpts.CoverageNotesFile.size() ||
40206c3fb27SDimitry Andric       CodeGenOpts.CoverageDataFile.size())
4030b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
4080b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
4110b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
41206c3fb27SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, *FS,
41306c3fb27SDimitry Andric         CodeGenOpts.ProfileRemappingFile);
414bdd1243dSDimitry Andric     // We're checking for profile read errors in CompilerInvocation, so if
415bdd1243dSDimitry Andric     // there was an error it should've already been caught. If it hasn't been
416bdd1243dSDimitry Andric     // somehow, trip an assertion.
417bdd1243dSDimitry Andric     assert(ReaderOrErr);
4180b57cec5SDimitry Andric     PGOReader = std::move(ReaderOrErr.get());
4190b57cec5SDimitry Andric   }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
4220b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
4230b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
4240b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
425fe6060f1SDimitry Andric 
426fe6060f1SDimitry Andric   // Generate the module name hash here if needed.
427fe6060f1SDimitry Andric   if (CodeGenOpts.UniqueInternalLinkageNames &&
428fe6060f1SDimitry Andric       !getModule().getSourceFileName().empty()) {
429fe6060f1SDimitry Andric     std::string Path = getModule().getSourceFileName();
430fe6060f1SDimitry Andric     // Check if a path substitution is needed from the MacroPrefixMap.
4316e75b2fbSDimitry Andric     for (const auto &Entry : LangOpts.MacroPrefixMap)
432fe6060f1SDimitry Andric       if (Path.rfind(Entry.first, 0) != std::string::npos) {
433fe6060f1SDimitry Andric         Path = Entry.second + Path.substr(Entry.first.size());
434fe6060f1SDimitry Andric         break;
435fe6060f1SDimitry Andric       }
436bdd1243dSDimitry Andric     ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
437fe6060f1SDimitry Andric   }
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
4430b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
4440b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
4450b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
4460b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
4470b57cec5SDimitry Andric   case ObjCRuntime::GCC:
4480b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
4490b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
4500b57cec5SDimitry Andric     return;
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
4530b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
4540b57cec5SDimitry Andric   case ObjCRuntime::iOS:
4550b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
4560b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
4570b57cec5SDimitry Andric     return;
4580b57cec5SDimitry Andric   }
4590b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
4630b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
4670b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
4680b57cec5SDimitry Andric   // If it does not exist use the default implementation.
4690b57cec5SDimitry Andric   switch (getTriple().getArch()) {
4700b57cec5SDimitry Andric   case llvm::Triple::nvptx:
4710b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
472e8d8bef9SDimitry Andric   case llvm::Triple::amdgcn:
47306c3fb27SDimitry Andric     assert(getLangOpts().OpenMPIsTargetDevice &&
474349cc55cSDimitry Andric            "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
475349cc55cSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
476e8d8bef9SDimitry Andric     break;
4770b57cec5SDimitry Andric   default:
4780b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
4790b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
4800b57cec5SDimitry Andric     else
4810b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
4820b57cec5SDimitry Andric     break;
4830b57cec5SDimitry Andric   }
4840b57cec5SDimitry Andric }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
4870b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric 
49081ad6265SDimitry Andric void CodeGenModule::createHLSLRuntime() {
49181ad6265SDimitry Andric   HLSLRuntime.reset(new CGHLSLRuntime(*this));
49281ad6265SDimitry Andric }
49381ad6265SDimitry Andric 
4940b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
4950b57cec5SDimitry Andric   Replacements[Name] = C;
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
4990b57cec5SDimitry Andric   for (auto &I : Replacements) {
50006c3fb27SDimitry Andric     StringRef MangledName = I.first;
5010b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
5020b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5030b57cec5SDimitry Andric     if (!Entry)
5040b57cec5SDimitry Andric       continue;
5050b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
5060b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
5070b57cec5SDimitry Andric     if (!NewF) {
5080b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
5090b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
5100b57cec5SDimitry Andric       } else {
5110b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
5120b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
5130b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
5140b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
5150b57cec5SDimitry Andric       }
5160b57cec5SDimitry Andric     }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
5190b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
5200b57cec5SDimitry Andric     if (NewF) {
5210b57cec5SDimitry Andric       NewF->removeFromParent();
5220b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
5230b57cec5SDimitry Andric                                                        NewF);
5240b57cec5SDimitry Andric     }
5250b57cec5SDimitry Andric     OldF->eraseFromParent();
5260b57cec5SDimitry Andric   }
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
5300b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
5310b57cec5SDimitry Andric }
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
5340b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
5350b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
5360b57cec5SDimitry Andric     llvm::Constant *C = I.second;
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
5390b57cec5SDimitry Andric     GV->eraseFromParent();
5400b57cec5SDimitry Andric   }
5410b57cec5SDimitry Andric }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
5440b57cec5SDimitry Andric // linear structure.
545349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
546349cc55cSDimitry Andric   const llvm::Constant *C;
547349cc55cSDimitry Andric   if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
548349cc55cSDimitry Andric     C = GA->getAliasee();
549349cc55cSDimitry Andric   else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
550349cc55cSDimitry Andric     C = GI->getResolver();
551349cc55cSDimitry Andric   else
552349cc55cSDimitry Andric     return GV;
553349cc55cSDimitry Andric 
554349cc55cSDimitry Andric   const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
555349cc55cSDimitry Andric   if (!AliaseeGV)
5560b57cec5SDimitry Andric     return nullptr;
557349cc55cSDimitry Andric 
558349cc55cSDimitry Andric   const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
559349cc55cSDimitry Andric   if (FinalGV == GV)
5600b57cec5SDimitry Andric     return nullptr;
561349cc55cSDimitry Andric 
562349cc55cSDimitry Andric   return FinalGV;
5630b57cec5SDimitry Andric }
564349cc55cSDimitry Andric 
56506c3fb27SDimitry Andric static bool checkAliasedGlobal(
56606c3fb27SDimitry Andric     DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc,
56706c3fb27SDimitry Andric     const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
56806c3fb27SDimitry Andric     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
56906c3fb27SDimitry Andric     SourceRange AliasRange) {
570349cc55cSDimitry Andric   GV = getAliasedGlobal(Alias);
571349cc55cSDimitry Andric   if (!GV) {
572349cc55cSDimitry Andric     Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
573349cc55cSDimitry Andric     return false;
574349cc55cSDimitry Andric   }
575349cc55cSDimitry Andric 
576349cc55cSDimitry Andric   if (GV->isDeclaration()) {
577349cc55cSDimitry Andric     Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
57806c3fb27SDimitry Andric     Diags.Report(Location, diag::note_alias_requires_mangled_name)
57906c3fb27SDimitry Andric         << IsIFunc << IsIFunc;
58006c3fb27SDimitry Andric     // Provide a note if the given function is not found and exists as a
58106c3fb27SDimitry Andric     // mangled name.
58206c3fb27SDimitry Andric     for (const auto &[Decl, Name] : MangledDeclNames) {
58306c3fb27SDimitry Andric       if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
58406c3fb27SDimitry Andric         if (ND->getName() == GV->getName()) {
58506c3fb27SDimitry Andric           Diags.Report(Location, diag::note_alias_mangled_name_alternative)
58606c3fb27SDimitry Andric               << Name
58706c3fb27SDimitry Andric               << FixItHint::CreateReplacement(
58806c3fb27SDimitry Andric                      AliasRange,
58906c3fb27SDimitry Andric                      (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
59006c3fb27SDimitry Andric                          .str());
59106c3fb27SDimitry Andric         }
59206c3fb27SDimitry Andric       }
59306c3fb27SDimitry Andric     }
594349cc55cSDimitry Andric     return false;
595349cc55cSDimitry Andric   }
596349cc55cSDimitry Andric 
597349cc55cSDimitry Andric   if (IsIFunc) {
598349cc55cSDimitry Andric     // Check resolver function type.
599349cc55cSDimitry Andric     const auto *F = dyn_cast<llvm::Function>(GV);
600349cc55cSDimitry Andric     if (!F) {
601349cc55cSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
602349cc55cSDimitry Andric           << IsIFunc << IsIFunc;
603349cc55cSDimitry Andric       return false;
604349cc55cSDimitry Andric     }
605349cc55cSDimitry Andric 
606349cc55cSDimitry Andric     llvm::FunctionType *FTy = F->getFunctionType();
607349cc55cSDimitry Andric     if (!FTy->getReturnType()->isPointerTy()) {
608349cc55cSDimitry Andric       Diags.Report(Location, diag::err_ifunc_resolver_return);
609349cc55cSDimitry Andric       return false;
610349cc55cSDimitry Andric     }
611349cc55cSDimitry Andric   }
612349cc55cSDimitry Andric 
613349cc55cSDimitry Andric   return true;
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
6170b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
6180b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
6190b57cec5SDimitry Andric   // and aliases during codegen.
6200b57cec5SDimitry Andric   bool Error = false;
6210b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
6220b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
6230b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
6240b57cec5SDimitry Andric     SourceLocation Location;
62506c3fb27SDimitry Andric     SourceRange Range;
6260b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
62706c3fb27SDimitry Andric     if (const Attr *A = D->getDefiningAttr()) {
6280b57cec5SDimitry Andric       Location = A->getLocation();
62906c3fb27SDimitry Andric       Range = A->getRange();
63006c3fb27SDimitry Andric     } else
6310b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
632349cc55cSDimitry Andric 
6330b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
634349cc55cSDimitry Andric     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
635349cc55cSDimitry Andric     const llvm::GlobalValue *GV = nullptr;
63606c3fb27SDimitry Andric     if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV,
63706c3fb27SDimitry Andric                             MangledDeclNames, Range)) {
6380b57cec5SDimitry Andric       Error = true;
639349cc55cSDimitry Andric       continue;
6400b57cec5SDimitry Andric     }
6410b57cec5SDimitry Andric 
642349cc55cSDimitry Andric     llvm::Constant *Aliasee =
643349cc55cSDimitry Andric         IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
644349cc55cSDimitry Andric                 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
645349cc55cSDimitry Andric 
6460b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
6470b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
6480b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
6490b57cec5SDimitry Andric     else
6500b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
6530b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
6540b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
6550b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
6560b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
6570b57cec5SDimitry Andric     }
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
6600b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
6610b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
6620b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
6630b57cec5SDimitry Andric     // expecting the link to be weak.
664349cc55cSDimitry Andric     if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
6650b57cec5SDimitry Andric       if (GA->isInterposable()) {
6660b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
6670b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
6680b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
669349cc55cSDimitry Andric             GA->getAliasee(), Alias->getType());
670349cc55cSDimitry Andric 
671349cc55cSDimitry Andric         if (IsIFunc)
672349cc55cSDimitry Andric           cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
673349cc55cSDimitry Andric         else
674349cc55cSDimitry Andric           cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
6750b57cec5SDimitry Andric       }
6760b57cec5SDimitry Andric     }
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric   if (!Error)
6790b57cec5SDimitry Andric     return;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
6820b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
683349cc55cSDimitry Andric     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
6840b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
6850b57cec5SDimitry Andric     Alias->eraseFromParent();
6860b57cec5SDimitry Andric   }
6870b57cec5SDimitry Andric }
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric void CodeGenModule::clear() {
6900b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
691753f127fSDimitry Andric   EmittedDeferredDecls.clear();
6920b57cec5SDimitry Andric   if (OpenMPRuntime)
6930b57cec5SDimitry Andric     OpenMPRuntime->clear();
6940b57cec5SDimitry Andric }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
6970b57cec5SDimitry Andric                                        StringRef MainFile) {
6980b57cec5SDimitry Andric   if (!hasDiagnostics())
6990b57cec5SDimitry Andric     return;
7000b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
7010b57cec5SDimitry Andric     if (MainFile.empty())
7020b57cec5SDimitry Andric       MainFile = "<stdin>";
7030b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
7040b57cec5SDimitry Andric   } else {
7050b57cec5SDimitry Andric     if (Mismatched > 0)
7060b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     if (Missing > 0)
7090b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
7100b57cec5SDimitry Andric   }
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric 
713e8d8bef9SDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
714e8d8bef9SDimitry Andric                                              llvm::Module &M) {
715e8d8bef9SDimitry Andric   if (!LO.VisibilityFromDLLStorageClass)
716e8d8bef9SDimitry Andric     return;
717e8d8bef9SDimitry Andric 
718e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
719e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
720e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
721e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
722e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
723e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
724e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
725e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(
726e8d8bef9SDimitry Andric           LO.getExternDeclNoDLLStorageClassVisibility());
727e8d8bef9SDimitry Andric 
728e8d8bef9SDimitry Andric   for (llvm::GlobalValue &GV : M.global_values()) {
729e8d8bef9SDimitry Andric     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
730e8d8bef9SDimitry Andric       continue;
731e8d8bef9SDimitry Andric 
732e8d8bef9SDimitry Andric     // Reset DSO locality before setting the visibility. This removes
733e8d8bef9SDimitry Andric     // any effects that visibility options and annotations may have
734e8d8bef9SDimitry Andric     // had on the DSO locality. Setting the visibility will implicitly set
735e8d8bef9SDimitry Andric     // appropriate globals to DSO Local; however, this will be pessimistic
736e8d8bef9SDimitry Andric     // w.r.t. to the normal compiler IRGen.
737e8d8bef9SDimitry Andric     GV.setDSOLocal(false);
738e8d8bef9SDimitry Andric 
739e8d8bef9SDimitry Andric     if (GV.isDeclarationForLinker()) {
740e8d8bef9SDimitry Andric       GV.setVisibility(GV.getDLLStorageClass() ==
741e8d8bef9SDimitry Andric                                llvm::GlobalValue::DLLImportStorageClass
742e8d8bef9SDimitry Andric                            ? ExternDeclDLLImportVisibility
743e8d8bef9SDimitry Andric                            : ExternDeclNoDLLStorageClassVisibility);
744e8d8bef9SDimitry Andric     } else {
745e8d8bef9SDimitry Andric       GV.setVisibility(GV.getDLLStorageClass() ==
746e8d8bef9SDimitry Andric                                llvm::GlobalValue::DLLExportStorageClass
747e8d8bef9SDimitry Andric                            ? DLLExportVisibility
748e8d8bef9SDimitry Andric                            : NoDLLStorageClassVisibility);
749e8d8bef9SDimitry Andric     }
750e8d8bef9SDimitry Andric 
751e8d8bef9SDimitry Andric     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
752e8d8bef9SDimitry Andric   }
753e8d8bef9SDimitry Andric }
754e8d8bef9SDimitry Andric 
7550b57cec5SDimitry Andric void CodeGenModule::Release() {
75606c3fb27SDimitry Andric   Module *Primary = getContext().getCurrentNamedModule();
75761cfbce3SDimitry Andric   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
758fcaf7f86SDimitry Andric     EmitModuleInitializers(Primary);
7590b57cec5SDimitry Andric   EmitDeferred();
760753f127fSDimitry Andric   DeferredDecls.insert(EmittedDeferredDecls.begin(),
761753f127fSDimitry Andric                        EmittedDeferredDecls.end());
762753f127fSDimitry Andric   EmittedDeferredDecls.clear();
7630b57cec5SDimitry Andric   EmitVTablesOpportunistically();
7640b57cec5SDimitry Andric   applyGlobalValReplacements();
7650b57cec5SDimitry Andric   applyReplacements();
7660b57cec5SDimitry Andric   emitMultiVersionFunctions();
767bdd1243dSDimitry Andric 
768bdd1243dSDimitry Andric   if (Context.getLangOpts().IncrementalExtensions &&
769bdd1243dSDimitry Andric       GlobalTopLevelStmtBlockInFlight.first) {
770bdd1243dSDimitry Andric     const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
771bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
772bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
773bdd1243dSDimitry Andric   }
774bdd1243dSDimitry Andric 
77506c3fb27SDimitry Andric   // Module implementations are initialized the same way as a regular TU that
77606c3fb27SDimitry Andric   // imports one or more modules.
777fcaf7f86SDimitry Andric   if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
778fcaf7f86SDimitry Andric     EmitCXXModuleInitFunc(Primary);
779fcaf7f86SDimitry Andric   else
7800b57cec5SDimitry Andric     EmitCXXGlobalInitFunc();
7815ffd83dbSDimitry Andric   EmitCXXGlobalCleanUpFunc();
7820b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
7830b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
7840b57cec5SDimitry Andric   if (ObjCRuntime)
7850b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
7860b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
787fe6060f1SDimitry Andric   if (Context.getLangOpts().CUDA && CUDARuntime) {
788fe6060f1SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
7890b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
7900b57cec5SDimitry Andric   }
7910b57cec5SDimitry Andric   if (OpenMPRuntime) {
7920b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
7930b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
7940b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
7950b57cec5SDimitry Andric     }
796a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
7970b57cec5SDimitry Andric     OpenMPRuntime->clear();
7980b57cec5SDimitry Andric   }
7990b57cec5SDimitry Andric   if (PGOReader) {
8000b57cec5SDimitry Andric     getModule().setProfileSummary(
8010b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
8020b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
8030b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
8040b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
8050b57cec5SDimitry Andric   }
806bdd1243dSDimitry Andric   llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
807bdd1243dSDimitry Andric     return L.LexOrder < R.LexOrder;
808bdd1243dSDimitry Andric   });
8090b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
8100b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
8110b57cec5SDimitry Andric   EmitGlobalAnnotations();
8120b57cec5SDimitry Andric   EmitStaticExternCAliases();
81381ad6265SDimitry Andric   checkAliases();
8140b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
815fe6060f1SDimitry Andric   CodeGenPGO(*this).setValueProfilingFlag(getModule());
8160b57cec5SDimitry Andric   if (CoverageMapping)
8170b57cec5SDimitry Andric     CoverageMapping->emit();
8180b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
8190b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
8200b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
8210b57cec5SDimitry Andric   }
822bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
823bdd1243dSDimitry Andric     finalizeKCFITypes();
8240b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
82581ad6265SDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm())
8265ffd83dbSDimitry Andric     EmitMainVoidAlias();
827fe6060f1SDimitry Andric 
82881ad6265SDimitry Andric   if (getTriple().isAMDGPU()) {
82981ad6265SDimitry Andric     // Emit amdgpu_code_object_version module flag, which is code object version
83081ad6265SDimitry Andric     // times 100.
831bdd1243dSDimitry Andric     if (getTarget().getTargetOpts().CodeObjectVersion !=
832bdd1243dSDimitry Andric         TargetOptions::COV_None) {
83381ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Error,
83481ad6265SDimitry Andric                                 "amdgpu_code_object_version",
83581ad6265SDimitry Andric                                 getTarget().getTargetOpts().CodeObjectVersion);
83681ad6265SDimitry Andric     }
83706c3fb27SDimitry Andric 
83806c3fb27SDimitry Andric     // Currently, "-mprintf-kind" option is only supported for HIP
83906c3fb27SDimitry Andric     if (LangOpts.HIP) {
84006c3fb27SDimitry Andric       auto *MDStr = llvm::MDString::get(
84106c3fb27SDimitry Andric           getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
84206c3fb27SDimitry Andric                              TargetOptions::AMDGPUPrintfKind::Hostcall)
84306c3fb27SDimitry Andric                                 ? "hostcall"
84406c3fb27SDimitry Andric                                 : "buffered");
84506c3fb27SDimitry Andric       getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
84606c3fb27SDimitry Andric                                 MDStr);
84706c3fb27SDimitry Andric     }
84881ad6265SDimitry Andric   }
84981ad6265SDimitry Andric 
85081ad6265SDimitry Andric   // Emit a global array containing all external kernels or device variables
85181ad6265SDimitry Andric   // used by host functions and mark it as used for CUDA/HIP. This is necessary
85281ad6265SDimitry Andric   // to get kernels or device variables in archives linked in even if these
85381ad6265SDimitry Andric   // kernels or device variables are only used in host functions.
85481ad6265SDimitry Andric   if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
85581ad6265SDimitry Andric     SmallVector<llvm::Constant *, 8> UsedArray;
85681ad6265SDimitry Andric     for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
85781ad6265SDimitry Andric       GlobalDecl GD;
85881ad6265SDimitry Andric       if (auto *FD = dyn_cast<FunctionDecl>(D))
85981ad6265SDimitry Andric         GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
86081ad6265SDimitry Andric       else
86181ad6265SDimitry Andric         GD = GlobalDecl(D);
86281ad6265SDimitry Andric       UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
86381ad6265SDimitry Andric           GetAddrOfGlobal(GD), Int8PtrTy));
86481ad6265SDimitry Andric     }
86581ad6265SDimitry Andric 
86681ad6265SDimitry Andric     llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
86781ad6265SDimitry Andric 
86881ad6265SDimitry Andric     auto *GV = new llvm::GlobalVariable(
86981ad6265SDimitry Andric         getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
87081ad6265SDimitry Andric         llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
87181ad6265SDimitry Andric     addCompilerUsedGlobal(GV);
87204eeddc0SDimitry Andric   }
873fe6060f1SDimitry Andric 
8740b57cec5SDimitry Andric   emitLLVMUsed();
8750b57cec5SDimitry Andric   if (SanStats)
8760b57cec5SDimitry Andric     SanStats->finish();
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
8790b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
8800b57cec5SDimitry Andric     EmitModuleLinkOptions();
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
8840b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
8850b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
8860b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
8870b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
8880b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
8890b57cec5SDimitry Andric   // libs to the linker.
8900b57cec5SDimitry Andric   //
8910b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
8920b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
8930b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
8940b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
8950b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
8960b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
8970b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
8980b57cec5SDimitry Andric       NMD->addOperand(MD);
8990b57cec5SDimitry Andric   }
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
9020b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
9030b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
9040b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
907480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
9080b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
9090b57cec5SDimitry Andric   }
9105ffd83dbSDimitry Andric 
911fe6060f1SDimitry Andric   if (CodeGenOpts.Dwarf64)
912fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
913fe6060f1SDimitry Andric 
9145ffd83dbSDimitry Andric   if (Context.getLangOpts().SemanticInterposition)
9155ffd83dbSDimitry Andric     // Require various optimization to respect semantic interposition.
91604eeddc0SDimitry Andric     getModule().setSemanticInterposition(true);
9175ffd83dbSDimitry Andric 
9180b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
9190b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
9200b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
9210b57cec5SDimitry Andric   }
9220b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
9230b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
9240b57cec5SDimitry Andric   }
9250b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
926480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
927480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
928480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
929480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
930480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
9310b57cec5SDimitry Andric   }
932fe6060f1SDimitry Andric   if (CodeGenOpts.EHContGuard) {
933fe6060f1SDimitry Andric     // Function ID tables for EH Continuation Guard.
934fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
935fe6060f1SDimitry Andric   }
936bdd1243dSDimitry Andric   if (Context.getLangOpts().Kernel) {
937bdd1243dSDimitry Andric     // Note if we are compiling with /kernel.
938bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
939bdd1243dSDimitry Andric   }
9400b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
9410b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
9420b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
9430b57cec5SDimitry Andric     // by StrictVTablePointers.
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
9480b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
9490b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
9500b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
9530b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
9540b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
9550b57cec5SDimitry Andric   }
9565ffd83dbSDimitry Andric   if (getModuleDebugInfo())
9570b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
9580b57cec5SDimitry Andric     // parser will drop debug info with a different version number
9590b57cec5SDimitry Andric     // (and warn about it, too).
9600b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
9610b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
9640b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
9650b57cec5SDimitry Andric   // TargetLibraryInfo.
9660b57cec5SDimitry Andric   uint64_t WCharWidth =
9670b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
9680b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
9710b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
9720b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
9730b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
9740b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
9750b57cec5SDimitry Andric     // The minimum width of an enum in bytes
9760b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
9770b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
9780b57cec5SDimitry Andric   }
9790b57cec5SDimitry Andric 
98013138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
98113138422SDimitry Andric     StringRef ABIStr = Target.getABI();
98213138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
98313138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
98413138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
98513138422SDimitry Andric   }
98613138422SDimitry Andric 
9870b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
9880b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
9890b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
9900b57cec5SDimitry Andric   }
9910b57cec5SDimitry Andric 
9925ffd83dbSDimitry Andric   if (CodeGenOpts.WholeProgramVTables) {
9935ffd83dbSDimitry Andric     // Indicate whether VFE was enabled for this module, so that the
9945ffd83dbSDimitry Andric     // vcall_visibility metadata added under whole program vtables is handled
9955ffd83dbSDimitry Andric     // appropriately in the optimizer.
9965ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
9975ffd83dbSDimitry Andric                               CodeGenOpts.VirtualFunctionElimination);
9985ffd83dbSDimitry Andric   }
9995ffd83dbSDimitry Andric 
1000a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1001a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
1002a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
1003a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1004a7dea167SDimitry Andric   }
1005a7dea167SDimitry Andric 
1006bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1007bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1008bdd1243dSDimitry Andric     // KCFI assumes patchable-function-prefix is the same for all indirectly
1009bdd1243dSDimitry Andric     // called functions. Store the expected offset for code generation.
1010bdd1243dSDimitry Andric     if (CodeGenOpts.PatchableFunctionEntryOffset)
1011bdd1243dSDimitry Andric       getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1012bdd1243dSDimitry Andric                                 CodeGenOpts.PatchableFunctionEntryOffset);
1013bdd1243dSDimitry Andric   }
1014bdd1243dSDimitry Andric 
10150b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
10160b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
10170b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
1018fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
10190b57cec5SDimitry Andric                               1);
10200b57cec5SDimitry Andric   }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
10230b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
10240b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
1025fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
10260b57cec5SDimitry Andric                               1);
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
1029fcaf7f86SDimitry Andric   if (CodeGenOpts.FunctionReturnThunks)
1030fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
103104eeddc0SDimitry Andric 
1032bdd1243dSDimitry Andric   if (CodeGenOpts.IndirectBranchCSPrefix)
1033bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1034bdd1243dSDimitry Andric 
10354824e7fdSDimitry Andric   // Add module metadata for return address signing (ignoring
10364824e7fdSDimitry Andric   // non-leaf/all) and stack tagging. These are actually turned on by function
10374824e7fdSDimitry Andric   // attributes, but we use module metadata to emit build attributes. This is
10384824e7fdSDimitry Andric   // needed for LTO, where the function attributes are inside bitcode
10394824e7fdSDimitry Andric   // serialised into a global variable by the time build attributes are
104081ad6265SDimitry Andric   // emitted, so we can't access them. LTO objects could be compiled with
104181ad6265SDimitry Andric   // different flags therefore module flags are set to "Min" behavior to achieve
104281ad6265SDimitry Andric   // the same end result of the normal build where e.g BTI is off if any object
104381ad6265SDimitry Andric   // doesn't support it.
10444824e7fdSDimitry Andric   if (Context.getTargetInfo().hasFeature("ptrauth") &&
10454824e7fdSDimitry Andric       LangOpts.getSignReturnAddressScope() !=
10464824e7fdSDimitry Andric           LangOptions::SignReturnAddressScopeKind::None)
10474824e7fdSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
10484824e7fdSDimitry Andric                               "sign-return-address-buildattr", 1);
104981ad6265SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
10504824e7fdSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
10514824e7fdSDimitry Andric                               "tag-stack-memory-buildattr", 1);
10524824e7fdSDimitry Andric 
10534824e7fdSDimitry Andric   if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
10541fd87a68SDimitry Andric       Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
10554824e7fdSDimitry Andric       Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
1056e8d8bef9SDimitry Andric       Arch == llvm::Triple::aarch64_be) {
1057972a253aSDimitry Andric     if (LangOpts.BranchTargetEnforcement)
105881ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1059972a253aSDimitry Andric                                 1);
1060972a253aSDimitry Andric     if (LangOpts.hasSignReturnAddress())
1061972a253aSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1062972a253aSDimitry Andric     if (LangOpts.isSignReturnAddressScopeAll())
106381ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1064972a253aSDimitry Andric                                 1);
1065972a253aSDimitry Andric     if (!LangOpts.isSignReturnAddressWithAKey())
106681ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min,
1067972a253aSDimitry Andric                                 "sign-return-address-with-bkey", 1);
1068e8d8bef9SDimitry Andric   }
1069e8d8bef9SDimitry Andric 
1070e8d8bef9SDimitry Andric   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1071e8d8bef9SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
1072e8d8bef9SDimitry Andric     getModule().addModuleFlag(
1073e8d8bef9SDimitry Andric         llvm::Module::Error, "MemProfProfileFilename",
1074e8d8bef9SDimitry Andric         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1075e8d8bef9SDimitry Andric   }
1076e8d8bef9SDimitry Andric 
10770b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
10780b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
10790b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
10800b57cec5SDimitry Andric     // property.)
10810b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
10825ffd83dbSDimitry Andric                               CodeGenOpts.FP32DenormalMode.Output !=
10835ffd83dbSDimitry Andric                                   llvm::DenormalMode::IEEE);
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
1086fe6060f1SDimitry Andric   if (LangOpts.EHAsynch)
1087fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1088fe6060f1SDimitry Andric 
1089fe6060f1SDimitry Andric   // Indicate whether this Module was compiled with -fopenmp
1090fe6060f1SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1091fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
109206c3fb27SDimitry Andric   if (getLangOpts().OpenMPIsTargetDevice)
1093fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1094fe6060f1SDimitry Andric                               LangOpts.OpenMP);
1095fe6060f1SDimitry Andric 
10960b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
109781ad6265SDimitry Andric   if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
10980b57cec5SDimitry Andric     EmitOpenCLMetadata();
10990b57cec5SDimitry Andric     // Emit SPIR version.
11000b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
11010b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
11020b57cec5SDimitry Andric       // opencl.spir.version named metadata.
1103349cc55cSDimitry Andric       // C++ for OpenCL has a distinct mapping for version compatibility with
1104349cc55cSDimitry Andric       // OpenCL.
1105349cc55cSDimitry Andric       auto Version = LangOpts.getOpenCLCompatibleVersion();
11060b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
11070b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
11080b57cec5SDimitry Andric               Int32Ty, Version / 100)),
11090b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
11100b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
11110b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
11120b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
11130b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
11140b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
11150b57cec5SDimitry Andric     }
11160b57cec5SDimitry Andric   }
11170b57cec5SDimitry Andric 
111881ad6265SDimitry Andric   // HLSL related end of code gen work items.
111981ad6265SDimitry Andric   if (LangOpts.HLSL)
112081ad6265SDimitry Andric     getHLSLRuntime().finishCodeGen();
112181ad6265SDimitry Andric 
11220b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
11230b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
11240b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
11250b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
11260b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
11270b57cec5SDimitry Andric   }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
11300b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
11310b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
11320b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
11330b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
11340b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
11350b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
11360b57cec5SDimitry Andric                   .Default(~0u);
11370b57cec5SDimitry Andric     if (CM != ~0u) {
11380b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
11390b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
11400b57cec5SDimitry Andric     }
11410b57cec5SDimitry Andric   }
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
11440b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
114506c3fb27SDimitry Andric   if (getTriple().isOSBinFormatELF() &&
114606c3fb27SDimitry Andric       CodeGenOpts.DirectAccessExternalData !=
114706c3fb27SDimitry Andric           getModule().getDirectAccessExternalData()) {
114806c3fb27SDimitry Andric     getModule().setDirectAccessExternalData(
114906c3fb27SDimitry Andric         CodeGenOpts.DirectAccessExternalData);
115006c3fb27SDimitry Andric   }
1151fe6060f1SDimitry Andric   if (CodeGenOpts.UnwindTables)
115281ad6265SDimitry Andric     getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1153fe6060f1SDimitry Andric 
1154fe6060f1SDimitry Andric   switch (CodeGenOpts.getFramePointer()) {
1155fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
1156fe6060f1SDimitry Andric     // 0 ("none") is the default.
1157fe6060f1SDimitry Andric     break;
1158fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
1159fe6060f1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1160fe6060f1SDimitry Andric     break;
1161fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
1162fe6060f1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::All);
1163fe6060f1SDimitry Andric     break;
1164fe6060f1SDimitry Andric   }
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   SimplifyPersonality();
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
11690b57cec5SDimitry Andric     EmitDeclMetadata();
11700b57cec5SDimitry Andric 
117106c3fb27SDimitry Andric   if (getCodeGenOpts().CoverageNotesFile.size() ||
117206c3fb27SDimitry Andric       getCodeGenOpts().CoverageDataFile.size())
11730b57cec5SDimitry Andric     EmitCoverageFile();
11740b57cec5SDimitry Andric 
11755ffd83dbSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
11765ffd83dbSDimitry Andric     DI->finalize();
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
11790b57cec5SDimitry Andric     EmitVersionIdentMetadata();
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
11820b57cec5SDimitry Andric     EmitCommandLineMetadata();
11830b57cec5SDimitry Andric 
1184fe6060f1SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuard.empty())
1185fe6060f1SDimitry Andric     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1186fe6060f1SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1187fe6060f1SDimitry Andric     getModule().setStackProtectorGuardReg(
1188fe6060f1SDimitry Andric         getCodeGenOpts().StackProtectorGuardReg);
1189753f127fSDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1190753f127fSDimitry Andric     getModule().setStackProtectorGuardSymbol(
1191753f127fSDimitry Andric         getCodeGenOpts().StackProtectorGuardSymbol);
1192fe6060f1SDimitry Andric   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1193fe6060f1SDimitry Andric     getModule().setStackProtectorGuardOffset(
1194fe6060f1SDimitry Andric         getCodeGenOpts().StackProtectorGuardOffset);
1195fe6060f1SDimitry Andric   if (getCodeGenOpts().StackAlignment)
1196fe6060f1SDimitry Andric     getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1197349cc55cSDimitry Andric   if (getCodeGenOpts().SkipRaxSetup)
1198349cc55cSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1199fe6060f1SDimitry Andric 
120006c3fb27SDimitry Andric   if (getContext().getTargetInfo().getMaxTLSAlign())
120106c3fb27SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
120206c3fb27SDimitry Andric                               getContext().getTargetInfo().getMaxTLSAlign());
120306c3fb27SDimitry Andric 
12045ffd83dbSDimitry Andric   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
12055ffd83dbSDimitry Andric 
12065ffd83dbSDimitry Andric   EmitBackendOptionsMetadata(getCodeGenOpts());
1207e8d8bef9SDimitry Andric 
120881ad6265SDimitry Andric   // If there is device offloading code embed it in the host now.
120981ad6265SDimitry Andric   EmbedObject(&getModule(), CodeGenOpts, getDiags());
121081ad6265SDimitry Andric 
1211e8d8bef9SDimitry Andric   // Set visibility from DLL storage class
1212e8d8bef9SDimitry Andric   // We do this at the end of LLVM IR generation; after any operation
1213e8d8bef9SDimitry Andric   // that might affect the DLL storage class or the visibility, and
1214e8d8bef9SDimitry Andric   // before anything that might act on these.
1215e8d8bef9SDimitry Andric   setVisibilityFromDLLStorageClass(LangOpts, getModule());
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
12190b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
12200b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
1221349cc55cSDimitry Andric   // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
1222349cc55cSDimitry Andric   auto Version = LangOpts.getOpenCLCompatibleVersion();
12230b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
12240b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
12250b57cec5SDimitry Andric           Int32Ty, Version / 100)),
12260b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
12270b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
12280b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
12290b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
12300b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
12310b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
12320b57cec5SDimitry Andric }
12330b57cec5SDimitry Andric 
12345ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata(
123506c3fb27SDimitry Andric     const CodeGenOptions &CodeGenOpts) {
1236bdd1243dSDimitry Andric   if (getTriple().isRISCV()) {
123706c3fb27SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
12385ffd83dbSDimitry Andric                               CodeGenOpts.SmallDataLimit);
12395ffd83dbSDimitry Andric   }
12405ffd83dbSDimitry Andric }
12415ffd83dbSDimitry Andric 
12420b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
12430b57cec5SDimitry Andric   // Make sure that this type is translated.
12440b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
12480b57cec5SDimitry Andric   // Make sure that this type is translated.
12490b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
12530b57cec5SDimitry Andric   if (!TBAA)
12540b57cec5SDimitry Andric     return nullptr;
12550b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
12590b57cec5SDimitry Andric   if (!TBAA)
12600b57cec5SDimitry Andric     return TBAAAccessInfo();
12615ffd83dbSDimitry Andric   if (getLangOpts().CUDAIsDevice) {
12625ffd83dbSDimitry Andric     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
12635ffd83dbSDimitry Andric     // access info.
12645ffd83dbSDimitry Andric     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
12655ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
12665ffd83dbSDimitry Andric           nullptr)
12675ffd83dbSDimitry Andric         return TBAAAccessInfo();
12685ffd83dbSDimitry Andric     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
12695ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
12705ffd83dbSDimitry Andric           nullptr)
12715ffd83dbSDimitry Andric         return TBAAAccessInfo();
12725ffd83dbSDimitry Andric     }
12735ffd83dbSDimitry Andric   }
12740b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
12750b57cec5SDimitry Andric }
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric TBAAAccessInfo
12780b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
12790b57cec5SDimitry Andric   if (!TBAA)
12800b57cec5SDimitry Andric     return TBAAAccessInfo();
12810b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
12820b57cec5SDimitry Andric }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
12850b57cec5SDimitry Andric   if (!TBAA)
12860b57cec5SDimitry Andric     return nullptr;
12870b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
12880b57cec5SDimitry Andric }
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
12910b57cec5SDimitry Andric   if (!TBAA)
12920b57cec5SDimitry Andric     return nullptr;
12930b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
12940b57cec5SDimitry Andric }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
12970b57cec5SDimitry Andric   if (!TBAA)
12980b57cec5SDimitry Andric     return nullptr;
12990b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
13000b57cec5SDimitry Andric }
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
13030b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
13040b57cec5SDimitry Andric   if (!TBAA)
13050b57cec5SDimitry Andric     return TBAAAccessInfo();
13060b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
13070b57cec5SDimitry Andric }
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric TBAAAccessInfo
13100b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
13110b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
13120b57cec5SDimitry Andric   if (!TBAA)
13130b57cec5SDimitry Andric     return TBAAAccessInfo();
13140b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
13150b57cec5SDimitry Andric }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric TBAAAccessInfo
13180b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
13190b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
13200b57cec5SDimitry Andric   if (!TBAA)
13210b57cec5SDimitry Andric     return TBAAAccessInfo();
13220b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
13260b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
13270b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
13280b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
13290b57cec5SDimitry Andric }
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
13320b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
13330b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
13340b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
13380b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
13390b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
13400b57cec5SDimitry Andric }
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
13430b57cec5SDimitry Andric /// specified stmt yet.
13440b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
13450b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
13460b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
13470b57cec5SDimitry Andric   std::string Msg = Type;
13480b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
13490b57cec5SDimitry Andric       << Msg << S->getSourceRange();
13500b57cec5SDimitry Andric }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
13530b57cec5SDimitry Andric /// specified decl yet.
13540b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
13550b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
13560b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
13570b57cec5SDimitry Andric   std::string Msg = Type;
13580b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
13590b57cec5SDimitry Andric }
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
13620b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
13660b57cec5SDimitry Andric                                         const NamedDecl *D) const {
13670b57cec5SDimitry Andric   // Internal definitions always have default visibility.
13680b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
13690b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
13700b57cec5SDimitry Andric     return;
13710b57cec5SDimitry Andric   }
13720b57cec5SDimitry Andric   if (!D)
13730b57cec5SDimitry Andric     return;
13740b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
13750b57cec5SDimitry Andric   // or set explicitly.
13760b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
1377bdd1243dSDimitry Andric   if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1378bdd1243dSDimitry Andric     // Reject incompatible dlllstorage and visibility annotations.
1379bdd1243dSDimitry Andric     if (!LV.isVisibilityExplicit())
1380bdd1243dSDimitry Andric       return;
1381bdd1243dSDimitry Andric     if (GV->hasDLLExportStorageClass()) {
1382bdd1243dSDimitry Andric       if (LV.getVisibility() == HiddenVisibility)
1383bdd1243dSDimitry Andric         getDiags().Report(D->getLocation(),
1384bdd1243dSDimitry Andric                           diag::err_hidden_visibility_dllexport);
1385bdd1243dSDimitry Andric     } else if (LV.getVisibility() != DefaultVisibility) {
1386bdd1243dSDimitry Andric       getDiags().Report(D->getLocation(),
1387bdd1243dSDimitry Andric                         diag::err_non_default_visibility_dllimport);
1388bdd1243dSDimitry Andric     }
1389bdd1243dSDimitry Andric     return;
1390bdd1243dSDimitry Andric   }
1391bdd1243dSDimitry Andric 
13920b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
13930b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
13940b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
13980b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
13990b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
14000b57cec5SDimitry Andric     return true;
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
14030b57cec5SDimitry Andric     return true;
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
14060b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
14070b57cec5SDimitry Andric     return false;
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
14100b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
14110b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
14120b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
14130b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
1414fe6060f1SDimitry Andric 
1415fe6060f1SDimitry Andric     // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1416fe6060f1SDimitry Andric     // (and this actually happens in the public interface of libstdc++), so
1417fe6060f1SDimitry Andric     // such variables can't be marked as DSO local. (Native TLS variables
1418fe6060f1SDimitry Andric     // can't be dllimported at all, though.)
14190b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1420fe6060f1SDimitry Andric         (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
14210b57cec5SDimitry Andric       return false;
14220b57cec5SDimitry Andric   }
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
14250b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
14260b57cec5SDimitry Andric   // outside the current DSO.
14270b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
14280b57cec5SDimitry Andric     return false;
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   // Every other GV is local on COFF.
14310b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
14320b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
14330b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
14340b57cec5SDimitry Andric   // FIXME: even thread local variables?
14350b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
14360b57cec5SDimitry Andric     return true;
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
14390b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
14400b57cec5SDimitry Andric     return false;
14410b57cec5SDimitry Andric 
1442fe6060f1SDimitry Andric   // If this is not an executable, don't assume anything is local.
1443fe6060f1SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
1444fe6060f1SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
1445fe6060f1SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
1446e8d8bef9SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1447e8d8bef9SDimitry Andric     // On ELF, if -fno-semantic-interposition is specified and the target
1448e8d8bef9SDimitry Andric     // supports local aliases, there will be neither CC1
1449e8d8bef9SDimitry Andric     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1450fe6060f1SDimitry Andric     // dso_local on the function if using a local alias is preferable (can avoid
1451fe6060f1SDimitry Andric     // PLT indirection).
1452fe6060f1SDimitry Andric     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
14530b57cec5SDimitry Andric       return false;
1454e8d8bef9SDimitry Andric     return !(CGM.getLangOpts().SemanticInterposition ||
1455e8d8bef9SDimitry Andric              CGM.getLangOpts().HalfNoSemanticInterposition);
1456e8d8bef9SDimitry Andric   }
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
14590b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
14600b57cec5SDimitry Andric     return true;
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
14630b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
14640b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
14650b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
14660b57cec5SDimitry Andric     return false;
14670b57cec5SDimitry Andric 
1468e8d8bef9SDimitry Andric   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1469e8d8bef9SDimitry Andric   if (TT.isPPC64())
14700b57cec5SDimitry Andric     return false;
14710b57cec5SDimitry Andric 
1472e8d8bef9SDimitry Andric   if (CGOpts.DirectAccessExternalData) {
1473e8d8bef9SDimitry Andric     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1474e8d8bef9SDimitry Andric     // for non-thread-local variables. If the symbol is not defined in the
1475e8d8bef9SDimitry Andric     // executable, a copy relocation will be needed at link time. dso_local is
1476e8d8bef9SDimitry Andric     // excluded for thread-local variables because they generally don't support
1477e8d8bef9SDimitry Andric     // copy relocations.
14780b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1479e8d8bef9SDimitry Andric       if (!Var->isThreadLocal())
14800b57cec5SDimitry Andric         return true;
14810b57cec5SDimitry Andric 
1482e8d8bef9SDimitry Andric     // -fno-pic sets dso_local on a function declaration to allow direct
1483e8d8bef9SDimitry Andric     // accesses when taking its address (similar to a data symbol). If the
1484e8d8bef9SDimitry Andric     // function is not defined in the executable, a canonical PLT entry will be
1485e8d8bef9SDimitry Andric     // needed at link time. -fno-direct-access-external-data can avoid the
1486e8d8bef9SDimitry Andric     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1487e8d8bef9SDimitry Andric     // it could just cause trouble without providing perceptible benefits.
14880b57cec5SDimitry Andric     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
14890b57cec5SDimitry Andric       return true;
1490e8d8bef9SDimitry Andric   }
1491e8d8bef9SDimitry Andric 
1492e8d8bef9SDimitry Andric   // If we can use copy relocations we can assume it is local.
14930b57cec5SDimitry Andric 
14945ffd83dbSDimitry Andric   // Otherwise don't assume it is local.
14950b57cec5SDimitry Andric   return false;
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
14990b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
15000b57cec5SDimitry Andric }
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
15030b57cec5SDimitry Andric                                           GlobalDecl GD) const {
15040b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
15050b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
15060b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
15070b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
15080b57cec5SDimitry Andric     return;
15090b57cec5SDimitry Andric   }
15100b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
15110b57cec5SDimitry Andric }
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
15140b57cec5SDimitry Andric                                           const NamedDecl *D) const {
15150b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
15160b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
15170b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
151881ad6265SDimitry Andric     else if ((D->hasAttr<DLLExportAttr>() ||
151981ad6265SDimitry Andric               shouldMapVisibilityToDLLExport(D)) &&
152081ad6265SDimitry Andric              !GV->isDeclarationForLinker())
15210b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric }
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
15260b57cec5SDimitry Andric                                     GlobalDecl GD) const {
15270b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
15280b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
15320b57cec5SDimitry Andric                                     const NamedDecl *D) const {
15330b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
15340b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
15350b57cec5SDimitry Andric }
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
15380b57cec5SDimitry Andric                                        const NamedDecl *D) const {
15390b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
15400b57cec5SDimitry Andric   setDSOLocal(GV);
15410b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
15420b57cec5SDimitry Andric }
15430b57cec5SDimitry Andric 
15440b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
15450b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
15460b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
15470b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
15480b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
15490b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
15500b57cec5SDimitry Andric }
15510b57cec5SDimitry Andric 
15525ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode
15535ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const {
15545ffd83dbSDimitry Andric   switch (CodeGenOpts.getDefaultTLSModel()) {
15550b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
15560b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
15570b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
15580b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
15590b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
15600b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
15610b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
15620b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
15630b57cec5SDimitry Andric   }
15640b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
15650b57cec5SDimitry Andric }
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
15680b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
15715ffd83dbSDimitry Andric   TLM = GetDefaultLLVMTLSModel();
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
15740b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
15750b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
15760b57cec5SDimitry Andric   }
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
15790b57cec5SDimitry Andric }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
15820b57cec5SDimitry Andric                                           StringRef Name) {
15830b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
15840b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
15850b57cec5SDimitry Andric }
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
15880b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
15890b57cec5SDimitry Andric                                                  unsigned CPUIndex,
15900b57cec5SDimitry Andric                                                  raw_ostream &Out) {
15910b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
15920b57cec5SDimitry Andric   // supported.
15930b57cec5SDimitry Andric   if (Attr)
15940b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
15950b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
15960b57cec5SDimitry Andric     Out << ".resolver";
15970b57cec5SDimitry Andric }
15980b57cec5SDimitry Andric 
1599bdd1243dSDimitry Andric static void AppendTargetVersionMangling(const CodeGenModule &CGM,
1600bdd1243dSDimitry Andric                                         const TargetVersionAttr *Attr,
1601bdd1243dSDimitry Andric                                         raw_ostream &Out) {
1602bdd1243dSDimitry Andric   if (Attr->isDefaultVersion())
1603bdd1243dSDimitry Andric     return;
1604bdd1243dSDimitry Andric   Out << "._";
160506c3fb27SDimitry Andric   const TargetInfo &TI = CGM.getTarget();
1606bdd1243dSDimitry Andric   llvm::SmallVector<StringRef, 8> Feats;
1607bdd1243dSDimitry Andric   Attr->getFeatures(Feats);
160806c3fb27SDimitry Andric   llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) {
160906c3fb27SDimitry Andric     return TI.multiVersionSortPriority(FeatL) <
161006c3fb27SDimitry Andric            TI.multiVersionSortPriority(FeatR);
161106c3fb27SDimitry Andric   });
1612bdd1243dSDimitry Andric   for (const auto &Feat : Feats) {
1613bdd1243dSDimitry Andric     Out << 'M';
1614bdd1243dSDimitry Andric     Out << Feat;
1615bdd1243dSDimitry Andric   }
1616bdd1243dSDimitry Andric }
1617bdd1243dSDimitry Andric 
16180b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
16190b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
16200b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
16210b57cec5SDimitry Andric     return;
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   Out << '.';
16240b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
1625bdd1243dSDimitry Andric   ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr());
1626bdd1243dSDimitry Andric   llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) {
16270b57cec5SDimitry Andric     // Multiversioning doesn't allow "no-${feature}", so we can
16280b57cec5SDimitry Andric     // only have "+" prefixes here.
16290b57cec5SDimitry Andric     assert(LHS.startswith("+") && RHS.startswith("+") &&
16300b57cec5SDimitry Andric            "Features should always have a prefix.");
16310b57cec5SDimitry Andric     return Target.multiVersionSortPriority(LHS.substr(1)) >
16320b57cec5SDimitry Andric            Target.multiVersionSortPriority(RHS.substr(1));
16330b57cec5SDimitry Andric   });
16340b57cec5SDimitry Andric 
16350b57cec5SDimitry Andric   bool IsFirst = true;
16360b57cec5SDimitry Andric 
1637bdd1243dSDimitry Andric   if (!Info.CPU.empty()) {
16380b57cec5SDimitry Andric     IsFirst = false;
1639bdd1243dSDimitry Andric     Out << "arch_" << Info.CPU;
16400b57cec5SDimitry Andric   }
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
16430b57cec5SDimitry Andric     if (!IsFirst)
16440b57cec5SDimitry Andric       Out << '_';
16450b57cec5SDimitry Andric     IsFirst = false;
16460b57cec5SDimitry Andric     Out << Feat.substr(1);
16470b57cec5SDimitry Andric   }
16480b57cec5SDimitry Andric }
16490b57cec5SDimitry Andric 
1650fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and
1651fe6060f1SDimitry Andric // needs a unique suffix after the mangled name.
1652fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1653fe6060f1SDimitry Andric                                         CodeGenModule &CGM) {
1654fe6060f1SDimitry Andric   const Decl *D = GD.getDecl();
1655fe6060f1SDimitry Andric   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1656fe6060f1SDimitry Andric          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1657fe6060f1SDimitry Andric }
1658fe6060f1SDimitry Andric 
16594824e7fdSDimitry Andric static void AppendTargetClonesMangling(const CodeGenModule &CGM,
16604824e7fdSDimitry Andric                                        const TargetClonesAttr *Attr,
16614824e7fdSDimitry Andric                                        unsigned VersionIndex,
16624824e7fdSDimitry Andric                                        raw_ostream &Out) {
166306c3fb27SDimitry Andric   const TargetInfo &TI = CGM.getTarget();
166406c3fb27SDimitry Andric   if (TI.getTriple().isAArch64()) {
1665bdd1243dSDimitry Andric     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1666bdd1243dSDimitry Andric     if (FeatureStr == "default")
1667bdd1243dSDimitry Andric       return;
1668bdd1243dSDimitry Andric     Out << "._";
1669bdd1243dSDimitry Andric     SmallVector<StringRef, 8> Features;
1670bdd1243dSDimitry Andric     FeatureStr.split(Features, "+");
167106c3fb27SDimitry Andric     llvm::stable_sort(Features,
167206c3fb27SDimitry Andric                       [&TI](const StringRef FeatL, const StringRef FeatR) {
167306c3fb27SDimitry Andric                         return TI.multiVersionSortPriority(FeatL) <
167406c3fb27SDimitry Andric                                TI.multiVersionSortPriority(FeatR);
167506c3fb27SDimitry Andric                       });
1676bdd1243dSDimitry Andric     for (auto &Feat : Features) {
1677bdd1243dSDimitry Andric       Out << 'M';
1678bdd1243dSDimitry Andric       Out << Feat;
1679bdd1243dSDimitry Andric     }
1680bdd1243dSDimitry Andric   } else {
16814824e7fdSDimitry Andric     Out << '.';
16824824e7fdSDimitry Andric     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
16834824e7fdSDimitry Andric     if (FeatureStr.startswith("arch="))
16844824e7fdSDimitry Andric       Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
16854824e7fdSDimitry Andric     else
16864824e7fdSDimitry Andric       Out << FeatureStr;
16874824e7fdSDimitry Andric 
16884824e7fdSDimitry Andric     Out << '.' << Attr->getMangledIndex(VersionIndex);
16894824e7fdSDimitry Andric   }
1690bdd1243dSDimitry Andric }
16914824e7fdSDimitry Andric 
1692fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
16930b57cec5SDimitry Andric                                       const NamedDecl *ND,
16940b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
16950b57cec5SDimitry Andric   SmallString<256> Buffer;
16960b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
16970b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
1698fe6060f1SDimitry Andric   if (!CGM.getModuleNameHash().empty())
1699fe6060f1SDimitry Andric     MC.needsUniqueInternalLinkageNames();
1700fe6060f1SDimitry Andric   bool ShouldMangle = MC.shouldMangleDeclName(ND);
1701fe6060f1SDimitry Andric   if (ShouldMangle)
17025ffd83dbSDimitry Andric     MC.mangleName(GD.getWithDecl(ND), Out);
17035ffd83dbSDimitry Andric   else {
17040b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
17050b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
17060b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric     if (FD &&
17090b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
17100b57cec5SDimitry Andric       Out << "__regcall3__" << II->getName();
17115ffd83dbSDimitry Andric     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
17125ffd83dbSDimitry Andric                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
17135ffd83dbSDimitry Andric       Out << "__device_stub__" << II->getName();
17140b57cec5SDimitry Andric     } else {
17150b57cec5SDimitry Andric       Out << II->getName();
17160b57cec5SDimitry Andric     }
17170b57cec5SDimitry Andric   }
17180b57cec5SDimitry Andric 
1719fe6060f1SDimitry Andric   // Check if the module name hash should be appended for internal linkage
1720fe6060f1SDimitry Andric   // symbols.   This should come before multi-version target suffixes are
1721fe6060f1SDimitry Andric   // appended. This is to keep the name and module hash suffix of the
1722fe6060f1SDimitry Andric   // internal linkage function together.  The unique suffix should only be
1723fe6060f1SDimitry Andric   // added when name mangling is done to make sure that the final name can
1724fe6060f1SDimitry Andric   // be properly demangled.  For example, for C functions without prototypes,
1725fe6060f1SDimitry Andric   // name mangling is not done and the unique suffix should not be appeneded
1726fe6060f1SDimitry Andric   // then.
1727fe6060f1SDimitry Andric   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1728fe6060f1SDimitry Andric     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1729fe6060f1SDimitry Andric            "Hash computed when not explicitly requested");
1730fe6060f1SDimitry Andric     Out << CGM.getModuleNameHash();
1731fe6060f1SDimitry Andric   }
1732fe6060f1SDimitry Andric 
17330b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
17340b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
17350b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
17360b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
17370b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
17380b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
17390b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
17400b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
17410b57cec5SDimitry Andric         break;
17420b57cec5SDimitry Andric       case MultiVersionKind::Target:
17430b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
17440b57cec5SDimitry Andric         break;
1745bdd1243dSDimitry Andric       case MultiVersionKind::TargetVersion:
1746bdd1243dSDimitry Andric         AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out);
1747bdd1243dSDimitry Andric         break;
17484824e7fdSDimitry Andric       case MultiVersionKind::TargetClones:
17494824e7fdSDimitry Andric         AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
17504824e7fdSDimitry Andric                                    GD.getMultiVersionIndex(), Out);
17514824e7fdSDimitry Andric         break;
17520b57cec5SDimitry Andric       case MultiVersionKind::None:
17530b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
17540b57cec5SDimitry Andric       }
17550b57cec5SDimitry Andric     }
17560b57cec5SDimitry Andric 
1757fe6060f1SDimitry Andric   // Make unique name for device side static file-scope variable for HIP.
175881ad6265SDimitry Andric   if (CGM.getContext().shouldExternalize(ND) &&
1759fe6060f1SDimitry Andric       CGM.getLangOpts().GPURelocatableDeviceCode &&
176081ad6265SDimitry Andric       CGM.getLangOpts().CUDAIsDevice)
17612a66634dSDimitry Andric     CGM.printPostfixForExternalizedDecl(Out, ND);
176281ad6265SDimitry Andric 
17635ffd83dbSDimitry Andric   return std::string(Out.str());
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
176704eeddc0SDimitry Andric                                             const FunctionDecl *FD,
176804eeddc0SDimitry Andric                                             StringRef &CurName) {
17690b57cec5SDimitry Andric   if (!FD->isMultiVersion())
17700b57cec5SDimitry Andric     return;
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
17730b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
17740b57cec5SDimitry Andric   // multiversion function.
17750b57cec5SDimitry Andric   std::string NonTargetName =
17760b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
17770b57cec5SDimitry Andric   GlobalDecl OtherGD;
17780b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
17790b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
17800b57cec5SDimitry Andric                .getDecl()
17810b57cec5SDimitry Andric                ->getAsFunction()
17820b57cec5SDimitry Andric                ->isMultiVersion() &&
17830b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
17840b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
17850b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
17860b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
17870b57cec5SDimitry Andric                                       .getDecl()
17880b57cec5SDimitry Andric                                       ->getAsFunction()
17890b57cec5SDimitry Andric                                       ->getMostRecentDecl();
17900b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
17910b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
17920b57cec5SDimitry Andric     // version, we don't try to update it.
17930b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
17940b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
17950b57cec5SDimitry Andric       // to this.
17960b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
17970b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
17980b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
17990b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
180004eeddc0SDimitry Andric       StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
180104eeddc0SDimitry Andric           Result.first->first();
180204eeddc0SDimitry Andric       // If this is the current decl is being created, make sure we update the name.
180304eeddc0SDimitry Andric       if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
180404eeddc0SDimitry Andric         CurName = OtherNameRef;
18050b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
18060b57cec5SDimitry Andric         Entry->setName(OtherName);
18070b57cec5SDimitry Andric     }
18080b57cec5SDimitry Andric   }
18090b57cec5SDimitry Andric }
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
18120b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
18150b57cec5SDimitry Andric   // complete constructors get mangled the same.
18160b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
18170b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
18180b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
18190b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
18200b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
18210b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
18220b57cec5SDimitry Andric     }
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric 
1825fe6060f1SDimitry Andric   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1826fe6060f1SDimitry Andric   // static device variable depends on whether the variable is referenced by
1827fe6060f1SDimitry Andric   // a host or device host function. Therefore the mangled name cannot be
1828fe6060f1SDimitry Andric   // cached.
182981ad6265SDimitry Andric   if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
18300b57cec5SDimitry Andric     auto FoundName = MangledDeclNames.find(CanonicalGD);
18310b57cec5SDimitry Andric     if (FoundName != MangledDeclNames.end())
18320b57cec5SDimitry Andric       return FoundName->second;
1833fe6060f1SDimitry Andric   }
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
18360b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
18370b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
18380b57cec5SDimitry Andric 
18395ffd83dbSDimitry Andric   // Ensure either we have different ABIs between host and device compilations,
18405ffd83dbSDimitry Andric   // says host compilation following MSVC ABI but device compilation follows
18415ffd83dbSDimitry Andric   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
18425ffd83dbSDimitry Andric   // mangling should be the same after name stubbing. The later checking is
18435ffd83dbSDimitry Andric   // very important as the device kernel name being mangled in host-compilation
18445ffd83dbSDimitry Andric   // is used to resolve the device binaries to be executed. Inconsistent naming
18455ffd83dbSDimitry Andric   // result in undefined behavior. Even though we cannot check that naming
18465ffd83dbSDimitry Andric   // directly between host- and device-compilations, the host- and
18475ffd83dbSDimitry Andric   // device-mangling in host compilation could help catching certain ones.
18485ffd83dbSDimitry Andric   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
184981ad6265SDimitry Andric          getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
18505ffd83dbSDimitry Andric          (getContext().getAuxTargetInfo() &&
18515ffd83dbSDimitry Andric           (getContext().getAuxTargetInfo()->getCXXABI() !=
18525ffd83dbSDimitry Andric            getContext().getTargetInfo().getCXXABI())) ||
18535ffd83dbSDimitry Andric          getCUDARuntime().getDeviceSideName(ND) ==
18545ffd83dbSDimitry Andric              getMangledNameImpl(
18555ffd83dbSDimitry Andric                  *this,
18565ffd83dbSDimitry Andric                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
18575ffd83dbSDimitry Andric                  ND));
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
18600b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
18610b57cec5SDimitry Andric }
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
18640b57cec5SDimitry Andric                                              const BlockDecl *BD) {
18650b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
18660b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   SmallString<256> Buffer;
18690b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
18700b57cec5SDimitry Andric   if (!D)
18710b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
18720b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
18730b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
18740b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
18750b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
18760b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
18770b57cec5SDimitry Andric   else
18780b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
18810b57cec5SDimitry Andric   return Result.first->first();
18820b57cec5SDimitry Andric }
18830b57cec5SDimitry Andric 
188481ad6265SDimitry Andric const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
188581ad6265SDimitry Andric   auto it = MangledDeclNames.begin();
188681ad6265SDimitry Andric   while (it != MangledDeclNames.end()) {
188781ad6265SDimitry Andric     if (it->second == Name)
188881ad6265SDimitry Andric       return it->first;
188981ad6265SDimitry Andric     it++;
189081ad6265SDimitry Andric   }
189181ad6265SDimitry Andric   return GlobalDecl();
189281ad6265SDimitry Andric }
189381ad6265SDimitry Andric 
18940b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
18950b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
18960b57cec5SDimitry Andric }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
18990b57cec5SDimitry Andric /// main() runs.
19000b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1901bdd1243dSDimitry Andric                                   unsigned LexOrder,
19020b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
19030b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
1904bdd1243dSDimitry Andric   GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
19050b57cec5SDimitry Andric }
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
19080b57cec5SDimitry Andric /// when the module is unloaded.
1909e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1910e8d8bef9SDimitry Andric                                   bool IsDtorAttrFunc) {
1911e8d8bef9SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1912e8d8bef9SDimitry Andric       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
19130b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
19140b57cec5SDimitry Andric     return;
19150b57cec5SDimitry Andric   }
19160b57cec5SDimitry Andric 
19170b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
1918bdd1243dSDimitry Andric   GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
19190b57cec5SDimitry Andric }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
19220b57cec5SDimitry Andric   if (Fns.empty()) return;
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   // Ctor function type is void()*.
19250b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
19260b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
19270b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
19300b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
19310b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
19340b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
19350b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
19360b57cec5SDimitry Andric   for (const auto &I : Fns) {
19370b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
19380b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
19390b57cec5SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
19400b57cec5SDimitry Andric     if (I.AssociatedData)
19410b57cec5SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
19420b57cec5SDimitry Andric     else
19430b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
19440b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
19450b57cec5SDimitry Andric   }
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric   auto list =
19480b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
19490b57cec5SDimitry Andric                                 /*constant*/ false,
19500b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
19530b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
1954bdd1243dSDimitry Andric   list->setAlignment(std::nullopt);
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric   Fns.clear();
19570b57cec5SDimitry Andric }
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
19600b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
19610b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
19660b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
19690b57cec5SDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
19700b57cec5SDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19710b57cec5SDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
19720b57cec5SDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
19730b57cec5SDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
19740b57cec5SDimitry Andric     return llvm::GlobalValue::InternalLinkage;
19750b57cec5SDimitry Andric   }
19760b57cec5SDimitry Andric 
1977*8a4dda33SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage);
19780b57cec5SDimitry Andric }
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
19810b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
19820b57cec5SDimitry Andric   if (!MDS) return nullptr;
19830b57cec5SDimitry Andric 
19840b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
19850b57cec5SDimitry Andric }
19860b57cec5SDimitry Andric 
1987bdd1243dSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
1988bdd1243dSDimitry Andric   if (auto *FnType = T->getAs<FunctionProtoType>())
1989bdd1243dSDimitry Andric     T = getContext().getFunctionType(
1990bdd1243dSDimitry Andric         FnType->getReturnType(), FnType->getParamTypes(),
1991bdd1243dSDimitry Andric         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
1992bdd1243dSDimitry Andric 
1993bdd1243dSDimitry Andric   std::string OutName;
1994bdd1243dSDimitry Andric   llvm::raw_string_ostream Out(OutName);
199506c3fb27SDimitry Andric   getCXXABI().getMangleContext().mangleTypeName(
199606c3fb27SDimitry Andric       T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
199706c3fb27SDimitry Andric 
199806c3fb27SDimitry Andric   if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
199906c3fb27SDimitry Andric     Out << ".normalized";
2000bdd1243dSDimitry Andric 
2001bdd1243dSDimitry Andric   return llvm::ConstantInt::get(Int32Ty,
2002bdd1243dSDimitry Andric                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2003bdd1243dSDimitry Andric }
2004bdd1243dSDimitry Andric 
20050b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
20060b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
2007fe6060f1SDimitry Andric                                               llvm::Function *F, bool IsThunk) {
20080b57cec5SDimitry Andric   unsigned CallingConv;
20090b57cec5SDimitry Andric   llvm::AttributeList PAL;
2010fe6060f1SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2011fe6060f1SDimitry Andric                          /*AttrOnCallSite=*/false, IsThunk);
20120b57cec5SDimitry Andric   F->setAttributes(PAL);
20130b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
20140b57cec5SDimitry Andric }
20150b57cec5SDimitry Andric 
20160b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
20170b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
20180b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
20190b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
20200b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
20210b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
20220b57cec5SDimitry Andric   else {
20230b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
20240b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
20250b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
20260b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
20270b57cec5SDimitry Andric     else {
20280b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
20290b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
20300b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
20310b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
20320b57cec5SDimitry Andric     }
20330b57cec5SDimitry Andric   }
20340b57cec5SDimitry Andric }
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric // Returns the address space id that should be produced to the
20370b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
20380b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
20390b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
20400b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
20410b57cec5SDimitry Andric // (basically all single AS CPUs).
20420b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
20430b57cec5SDimitry Andric   switch (AS) {
2044e8d8bef9SDimitry Andric   case LangAS::opencl_global:
2045e8d8bef9SDimitry Andric     return 1;
2046e8d8bef9SDimitry Andric   case LangAS::opencl_constant:
2047e8d8bef9SDimitry Andric     return 2;
2048e8d8bef9SDimitry Andric   case LangAS::opencl_local:
2049e8d8bef9SDimitry Andric     return 3;
2050e8d8bef9SDimitry Andric   case LangAS::opencl_generic:
2051e8d8bef9SDimitry Andric     return 4; // Not in SPIR 2.0 specs.
2052e8d8bef9SDimitry Andric   case LangAS::opencl_global_device:
2053e8d8bef9SDimitry Andric     return 5;
2054e8d8bef9SDimitry Andric   case LangAS::opencl_global_host:
2055e8d8bef9SDimitry Andric     return 6;
20560b57cec5SDimitry Andric   default:
20570b57cec5SDimitry Andric     return 0; // Assume private.
20580b57cec5SDimitry Andric   }
20590b57cec5SDimitry Andric }
20600b57cec5SDimitry Andric 
206181ad6265SDimitry Andric void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
20620b57cec5SDimitry Andric                                          const FunctionDecl *FD,
20630b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
20640b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
20650b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
20660b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
20670b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
20680b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
20730b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
20760b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
20790b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
20820b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
20850b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric   // MDNode for the kernel argument names.
20880b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   if (FD && CGF)
20910b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
20920b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
209381ad6265SDimitry Andric       // Get argument name.
209481ad6265SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
209581ad6265SDimitry Andric 
209681ad6265SDimitry Andric       if (!getLangOpts().OpenCL)
209781ad6265SDimitry Andric         continue;
20980b57cec5SDimitry Andric       QualType ty = parm->getType();
20990b57cec5SDimitry Andric       std::string typeQuals;
21000b57cec5SDimitry Andric 
2101fe6060f1SDimitry Andric       // Get image and pipe access qualifier:
2102fe6060f1SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
2103fe6060f1SDimitry Andric         const Decl *PDecl = parm;
2104bdd1243dSDimitry Andric         if (const auto *TD = ty->getAs<TypedefType>())
2105fe6060f1SDimitry Andric           PDecl = TD->getDecl();
2106fe6060f1SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2107fe6060f1SDimitry Andric         if (A && A->isWriteOnly())
2108fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2109fe6060f1SDimitry Andric         else if (A && A->isReadWrite())
2110fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2111fe6060f1SDimitry Andric         else
2112fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2113fe6060f1SDimitry Andric       } else
2114fe6060f1SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2115fe6060f1SDimitry Andric 
2116fe6060f1SDimitry Andric       auto getTypeSpelling = [&](QualType Ty) {
2117fe6060f1SDimitry Andric         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2118fe6060f1SDimitry Andric 
2119fe6060f1SDimitry Andric         if (Ty.isCanonical()) {
2120fe6060f1SDimitry Andric           StringRef typeNameRef = typeName;
2121fe6060f1SDimitry Andric           // Turn "unsigned type" to "utype"
2122fe6060f1SDimitry Andric           if (typeNameRef.consume_front("unsigned "))
2123fe6060f1SDimitry Andric             return std::string("u") + typeNameRef.str();
2124fe6060f1SDimitry Andric           if (typeNameRef.consume_front("signed "))
2125fe6060f1SDimitry Andric             return typeNameRef.str();
2126fe6060f1SDimitry Andric         }
2127fe6060f1SDimitry Andric 
2128fe6060f1SDimitry Andric         return typeName;
2129fe6060f1SDimitry Andric       };
2130fe6060f1SDimitry Andric 
21310b57cec5SDimitry Andric       if (ty->isPointerType()) {
21320b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric         // Get address qualifier.
21350b57cec5SDimitry Andric         addressQuals.push_back(
21360b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
21370b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric         // Get argument type name.
2140fe6060f1SDimitry Andric         std::string typeName = getTypeSpelling(pointeeTy) + "*";
21410b57cec5SDimitry Andric         std::string baseTypeName =
2142fe6060f1SDimitry Andric             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2143fe6060f1SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
21440b57cec5SDimitry Andric         argBaseTypeNames.push_back(
21450b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
21460b57cec5SDimitry Andric 
21470b57cec5SDimitry Andric         // Get argument type qualifiers:
21480b57cec5SDimitry Andric         if (ty.isRestrictQualified())
21490b57cec5SDimitry Andric           typeQuals = "restrict";
21500b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
21510b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
21520b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
21530b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
21540b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
21550b57cec5SDimitry Andric       } else {
21560b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
21570b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
21580b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
21590b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric         addressQuals.push_back(
21620b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
21630b57cec5SDimitry Andric 
21640b57cec5SDimitry Andric         // Get argument type name.
2165fe6060f1SDimitry Andric         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2166fe6060f1SDimitry Andric         std::string typeName = getTypeSpelling(ty);
2167fe6060f1SDimitry Andric         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
21680b57cec5SDimitry Andric 
21690b57cec5SDimitry Andric         // Remove access qualifiers on images
21700b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
21710b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
21720b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
21730b57cec5SDimitry Andric         if (ty->isImageType()) {
21740b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
21750b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
21760b57cec5SDimitry Andric         }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
21790b57cec5SDimitry Andric         argBaseTypeNames.push_back(
21800b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric         if (isPipe)
21830b57cec5SDimitry Andric           typeQuals = "pipe";
21840b57cec5SDimitry Andric       }
21850b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
21860b57cec5SDimitry Andric     }
21870b57cec5SDimitry Andric 
218881ad6265SDimitry Andric   if (getLangOpts().OpenCL) {
21890b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_addr_space",
21900b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, addressQuals));
21910b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_access_qual",
21920b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, accessQuals));
21930b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_type",
21940b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argTypeNames));
21950b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_base_type",
21960b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argBaseTypeNames));
21970b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_type_qual",
21980b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argTypeQuals));
219981ad6265SDimitry Andric   }
220081ad6265SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
220181ad6265SDimitry Andric       getCodeGenOpts().HIPSaveKernelArgName)
22020b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
22030b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric /// Determines whether the language options require us to model
22070b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
22080b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
22090b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
22100b57cec5SDimitry Andric /// enables this.
22110b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
22120b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
22130b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
22160b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
22190b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
22200b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
22210b57cec5SDimitry Andric   }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   return true;
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
22270b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
22280b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
22290b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
22300b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
22310b57cec5SDimitry Andric     return false;
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
22340b57cec5SDimitry Andric   // need this sort of type metadata.
22350b57cec5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
22360b57cec5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
22370b57cec5SDimitry Andric }
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric std::vector<const CXXRecordDecl *>
22400b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
22410b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
22440b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
22450b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
22460b57cec5SDimitry Andric       MostBases.insert(RD);
22470b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
22480b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
22490b57cec5SDimitry Andric   };
22500b57cec5SDimitry Andric   CollectMostBases(RD);
22510b57cec5SDimitry Andric   return MostBases.takeVector();
22520b57cec5SDimitry Andric }
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
22550b57cec5SDimitry Andric                                                            llvm::Function *F) {
225604eeddc0SDimitry Andric   llvm::AttrBuilder B(F->getContext());
22570b57cec5SDimitry Andric 
2258bdd1243dSDimitry Andric   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
225981ad6265SDimitry Andric     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
22600b57cec5SDimitry Andric 
22615ffd83dbSDimitry Andric   if (CodeGenOpts.StackClashProtector)
22625ffd83dbSDimitry Andric     B.addAttribute("probe-stack", "inline-asm");
22635ffd83dbSDimitry Andric 
22640b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
22650b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
22660b57cec5SDimitry Andric 
2267bdd1243dSDimitry Andric   if (D && D->hasAttr<NoStackProtectorAttr>())
2268bdd1243dSDimitry Andric     ; // Do nothing.
2269bdd1243dSDimitry Andric   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2270bdd1243dSDimitry Andric            LangOpts.getStackProtector() == LangOptions::SSPOn)
2271bdd1243dSDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
2272bdd1243dSDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPOn)
22730b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
22740b57cec5SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
22750b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
22760b57cec5SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
22770b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric   if (!D) {
22800b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
22810b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
22820b57cec5SDimitry Andric     // disabled, mark the function as noinline.
22830b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
22840b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
22850b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
22860b57cec5SDimitry Andric 
2287349cc55cSDimitry Andric     F->addFnAttrs(B);
22880b57cec5SDimitry Andric     return;
22890b57cec5SDimitry Andric   }
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
22920b57cec5SDimitry Andric   // starting with the default for this optimization level.
22930b57cec5SDimitry Andric   bool ShouldAddOptNone =
22940b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
22950b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
22960b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
22970b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
22980b57cec5SDimitry Andric 
2299480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
2300480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2301480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
23020b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
23050b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
23080b57cec5SDimitry Andric     // much of their semantics.
23090b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
23100b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
23130b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
23140b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
23150b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
23160b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
23170b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
23180b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
23190b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
23200b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
2321480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2322480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
23230b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
23240b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
23250b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
23260b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
23270b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
23280b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
23290b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
23300b57cec5SDimitry Andric     // carry an explicit noinline attribute.
23310b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
23320b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
23330b57cec5SDimitry Andric   } else {
23340b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
23350b57cec5SDimitry Andric     // absence to mark things as noinline.
23360b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
23370b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
23380b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
23390b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
23400b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
23410b57cec5SDimitry Andric         };
23420b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
23430b57cec5SDimitry Andric           return true;
23440b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
23450b57cec5SDimitry Andric         if (!Pattern)
23460b57cec5SDimitry Andric           return false;
23470b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
23480b57cec5SDimitry Andric       };
23490b57cec5SDimitry Andric       if (CheckForInline(FD)) {
23500b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
23510b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
23520b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
23530b57cec5SDimitry Andric                  !FD->isInlined() &&
23540b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
23550b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
23560b57cec5SDimitry Andric       }
23570b57cec5SDimitry Andric     }
23580b57cec5SDimitry Andric   }
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
23610b57cec5SDimitry Andric   // function.
23620b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
23630b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
23640b57cec5SDimitry Andric       if (!ShouldAddOptNone)
23650b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
23660b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
23670b57cec5SDimitry Andric     }
2368e8d8bef9SDimitry Andric     if (D->hasAttr<HotAttr>())
2369e8d8bef9SDimitry Andric       B.addAttribute(llvm::Attribute::Hot);
23700b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
23710b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
23720b57cec5SDimitry Andric   }
23730b57cec5SDimitry Andric 
2374349cc55cSDimitry Andric   F->addFnAttrs(B);
23750b57cec5SDimitry Andric 
23760b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
23770b57cec5SDimitry Andric   if (alignment)
2378a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
23810b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
2382a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
23850b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
23860b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
23870b57cec5SDimitry Andric   // member function, set its alignment accordingly.
23880b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2389*8a4dda33SDimitry Andric     if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
239006c3fb27SDimitry Andric       F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
23910b57cec5SDimitry Andric   }
23920b57cec5SDimitry Andric 
2393a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
2394a7dea167SDimitry Andric   // attributes on definitions only.
2395a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
2396a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2397a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2398a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
2399a7dea167SDimitry Andric       // current module anyway.
2400a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
24010b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
2402a7dea167SDimitry Andric     }
2403a7dea167SDimitry Andric   }
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
24060b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
24070b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
24080b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
24090b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
24100b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
24110b57cec5SDimitry Andric       llvm::Metadata *Id =
24120b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
24130b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
24140b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
24150b57cec5SDimitry Andric     }
24160b57cec5SDimitry Andric   }
24170b57cec5SDimitry Andric }
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
24200b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
2421349cc55cSDimitry Andric   if (isa_and_nonnull<NamedDecl>(D))
24220b57cec5SDimitry Andric     setGVProperties(GV, GD);
24230b57cec5SDimitry Andric   else
24240b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
2427fe6060f1SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
24280b57cec5SDimitry Andric 
242906c3fb27SDimitry Andric   if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
243006c3fb27SDimitry Andric       VD &&
243106c3fb27SDimitry Andric       ((CodeGenOpts.KeepPersistentStorageVariables &&
243206c3fb27SDimitry Andric         (VD->getStorageDuration() == SD_Static ||
243306c3fb27SDimitry Andric          VD->getStorageDuration() == SD_Thread)) ||
243406c3fb27SDimitry Andric        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
243506c3fb27SDimitry Andric         VD->getType().isConstQualified())))
2436fe6060f1SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
24370b57cec5SDimitry Andric }
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
244006c3fb27SDimitry Andric                                                 llvm::AttrBuilder &Attrs,
244106c3fb27SDimitry Andric                                                 bool SetTargetFeatures) {
24420b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
24430b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
24440b57cec5SDimitry Andric   // parse that and add it to the feature set.
24450b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2446e8d8bef9SDimitry Andric   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
24470b57cec5SDimitry Andric   std::vector<std::string> Features;
24480b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
24490b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
24500b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2451bdd1243dSDimitry Andric   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2452bdd1243dSDimitry Andric   assert((!TD || !TV) && "both target_version and target specified");
24530b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
24544824e7fdSDimitry Andric   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
24550b57cec5SDimitry Andric   bool AddedAttr = false;
2456bdd1243dSDimitry Andric   if (TD || TV || SD || TC) {
24570b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
2458480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
24610b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
24620b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
24650b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
24660b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
24670b57cec5SDimitry Andric     // the function.
24680b57cec5SDimitry Andric     if (TD) {
2469bdd1243dSDimitry Andric       ParsedTargetAttr ParsedAttr =
2470bdd1243dSDimitry Andric           Target.parseTargetAttr(TD->getFeaturesStr());
2471bdd1243dSDimitry Andric       if (!ParsedAttr.CPU.empty() &&
2472bdd1243dSDimitry Andric           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2473bdd1243dSDimitry Andric         TargetCPU = ParsedAttr.CPU;
2474e8d8bef9SDimitry Andric         TuneCPU = ""; // Clear the tune CPU.
2475e8d8bef9SDimitry Andric       }
2476e8d8bef9SDimitry Andric       if (!ParsedAttr.Tune.empty() &&
2477e8d8bef9SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Tune))
2478e8d8bef9SDimitry Andric         TuneCPU = ParsedAttr.Tune;
24790b57cec5SDimitry Andric     }
248081ad6265SDimitry Andric 
248181ad6265SDimitry Andric     if (SD) {
248281ad6265SDimitry Andric       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
248381ad6265SDimitry Andric       // favor this processor.
248406c3fb27SDimitry Andric       TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
248581ad6265SDimitry Andric     }
24860b57cec5SDimitry Andric   } else {
24870b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
24880b57cec5SDimitry Andric     // function.
24890b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
24900b57cec5SDimitry Andric   }
24910b57cec5SDimitry Andric 
2492e8d8bef9SDimitry Andric   if (!TargetCPU.empty()) {
24930b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
24940b57cec5SDimitry Andric     AddedAttr = true;
24950b57cec5SDimitry Andric   }
2496e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
2497e8d8bef9SDimitry Andric     Attrs.addAttribute("tune-cpu", TuneCPU);
2498e8d8bef9SDimitry Andric     AddedAttr = true;
2499e8d8bef9SDimitry Andric   }
250006c3fb27SDimitry Andric   if (!Features.empty() && SetTargetFeatures) {
250106c3fb27SDimitry Andric     llvm::erase_if(Features, [&](const std::string& F) {
250206c3fb27SDimitry Andric        return getTarget().isReadOnlyFeature(F.substr(1));
250306c3fb27SDimitry Andric     });
25040b57cec5SDimitry Andric     llvm::sort(Features);
25050b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
25060b57cec5SDimitry Andric     AddedAttr = true;
25070b57cec5SDimitry Andric   }
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric   return AddedAttr;
25100b57cec5SDimitry Andric }
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
25130b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
25140b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
25150b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   if (D) {
25180b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2519fe6060f1SDimitry Andric       if (D->hasAttr<RetainAttr>())
2520fe6060f1SDimitry Andric         addUsedGlobal(GV);
25210b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
25220b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
25230b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
25240b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
25250b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
25260b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
2527a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2528a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
25290b57cec5SDimitry Andric     }
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2532fe6060f1SDimitry Andric       if (D->hasAttr<RetainAttr>())
2533fe6060f1SDimitry Andric         addUsedGlobal(F);
25340b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
25350b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
25360b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
25370b57cec5SDimitry Andric 
253804eeddc0SDimitry Andric       llvm::AttrBuilder Attrs(F->getContext());
25390b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
25400b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
25410b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
25420b57cec5SDimitry Andric         // new ones should replace the old.
254304eeddc0SDimitry Andric         llvm::AttributeMask RemoveAttrs;
2544e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-cpu");
2545e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-features");
2546e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("tune-cpu");
2547349cc55cSDimitry Andric         F->removeFnAttrs(RemoveAttrs);
2548349cc55cSDimitry Andric         F->addFnAttrs(Attrs);
25490b57cec5SDimitry Andric       }
25500b57cec5SDimitry Andric     }
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
25530b57cec5SDimitry Andric       GO->setSection(CSA->getName());
25540b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
25550b57cec5SDimitry Andric       GO->setSection(SA->getName());
25560b57cec5SDimitry Andric   }
25570b57cec5SDimitry Andric 
25580b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
25590b57cec5SDimitry Andric }
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
25620b57cec5SDimitry Andric                                                   llvm::Function *F,
25630b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
25640b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
2565fe6060f1SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
25660b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
25710b57cec5SDimitry Andric }
25720b57cec5SDimitry Andric 
25730b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
25740b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
25750b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
25760b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
25770b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
25780b57cec5SDimitry Andric   // separate linkage types for this.
25790b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
25800b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
25810b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
25820b57cec5SDimitry Andric }
25830b57cec5SDimitry Andric 
25840b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
25850b57cec5SDimitry Andric                                                        llvm::Function *F) {
25860b57cec5SDimitry Andric   // Only if we are checking indirect calls.
25870b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
25880b57cec5SDimitry Andric     return;
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
25910b57cec5SDimitry Andric   // checks elsewhere.
25920b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
25930b57cec5SDimitry Andric     return;
25940b57cec5SDimitry Andric 
25950b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
25960b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
25970b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
26000b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
26010b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
26020b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
26030b57cec5SDimitry Andric }
26040b57cec5SDimitry Andric 
2605bdd1243dSDimitry Andric void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2606bdd1243dSDimitry Andric   llvm::LLVMContext &Ctx = F->getContext();
2607bdd1243dSDimitry Andric   llvm::MDBuilder MDB(Ctx);
2608bdd1243dSDimitry Andric   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2609bdd1243dSDimitry Andric                  llvm::MDNode::get(
2610bdd1243dSDimitry Andric                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2611bdd1243dSDimitry Andric }
2612bdd1243dSDimitry Andric 
2613bdd1243dSDimitry Andric static bool allowKCFIIdentifier(StringRef Name) {
2614bdd1243dSDimitry Andric   // KCFI type identifier constants are only necessary for external assembly
2615bdd1243dSDimitry Andric   // functions, which means it's safe to skip unusual names. Subset of
2616bdd1243dSDimitry Andric   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2617bdd1243dSDimitry Andric   return llvm::all_of(Name, [](const char &C) {
2618bdd1243dSDimitry Andric     return llvm::isAlnum(C) || C == '_' || C == '.';
2619bdd1243dSDimitry Andric   });
2620bdd1243dSDimitry Andric }
2621bdd1243dSDimitry Andric 
2622bdd1243dSDimitry Andric void CodeGenModule::finalizeKCFITypes() {
2623bdd1243dSDimitry Andric   llvm::Module &M = getModule();
2624bdd1243dSDimitry Andric   for (auto &F : M.functions()) {
2625bdd1243dSDimitry Andric     // Remove KCFI type metadata from non-address-taken local functions.
2626bdd1243dSDimitry Andric     bool AddressTaken = F.hasAddressTaken();
2627bdd1243dSDimitry Andric     if (!AddressTaken && F.hasLocalLinkage())
2628bdd1243dSDimitry Andric       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2629bdd1243dSDimitry Andric 
2630bdd1243dSDimitry Andric     // Generate a constant with the expected KCFI type identifier for all
2631bdd1243dSDimitry Andric     // address-taken function declarations to support annotating indirectly
2632bdd1243dSDimitry Andric     // called assembly functions.
2633bdd1243dSDimitry Andric     if (!AddressTaken || !F.isDeclaration())
2634bdd1243dSDimitry Andric       continue;
2635bdd1243dSDimitry Andric 
2636bdd1243dSDimitry Andric     const llvm::ConstantInt *Type;
2637bdd1243dSDimitry Andric     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2638bdd1243dSDimitry Andric       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2639bdd1243dSDimitry Andric     else
2640bdd1243dSDimitry Andric       continue;
2641bdd1243dSDimitry Andric 
2642bdd1243dSDimitry Andric     StringRef Name = F.getName();
2643bdd1243dSDimitry Andric     if (!allowKCFIIdentifier(Name))
2644bdd1243dSDimitry Andric       continue;
2645bdd1243dSDimitry Andric 
2646bdd1243dSDimitry Andric     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2647bdd1243dSDimitry Andric                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2648bdd1243dSDimitry Andric                           .str();
2649bdd1243dSDimitry Andric     M.appendModuleInlineAsm(Asm);
2650bdd1243dSDimitry Andric   }
2651bdd1243dSDimitry Andric }
2652bdd1243dSDimitry Andric 
26530b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
26540b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
26550b57cec5SDimitry Andric                                           bool IsThunk) {
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
26580b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
26590b57cec5SDimitry Andric     // to the intrinsic's attributes.
26600b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
26610b57cec5SDimitry Andric     return;
26620b57cec5SDimitry Andric   }
26630b57cec5SDimitry Andric 
26640b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
26650b57cec5SDimitry Andric 
26660b57cec5SDimitry Andric   if (!IsIncompleteFunction)
2667fe6060f1SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2668fe6060f1SDimitry Andric                               IsThunk);
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
26710b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
26720b57cec5SDimitry Andric   // GCC and does not actually return "this".
26730b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
26740b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
26750b57cec5SDimitry Andric     assert(!F->arg_empty() &&
26760b57cec5SDimitry Andric            F->arg_begin()->getType()
26770b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
26780b57cec5SDimitry Andric            "unexpected this return");
2679349cc55cSDimitry Andric     F->addParamAttr(0, llvm::Attribute::Returned);
26800b57cec5SDimitry Andric   }
26810b57cec5SDimitry Andric 
26820b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
26830b57cec5SDimitry Andric   // overridden by a definition.
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric   setLinkageForGV(F, FD);
26860b57cec5SDimitry Andric   setGVProperties(F, FD);
26870b57cec5SDimitry Andric 
26880b57cec5SDimitry Andric   // Setup target-specific attributes.
26890b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
26900b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
26930b57cec5SDimitry Andric     F->setSection(CSA->getName());
26940b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
26950b57cec5SDimitry Andric      F->setSection(SA->getName());
26960b57cec5SDimitry Andric 
2697349cc55cSDimitry Andric   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2698349cc55cSDimitry Andric     if (EA->isError())
2699349cc55cSDimitry Andric       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2700349cc55cSDimitry Andric     else if (EA->isWarning())
2701349cc55cSDimitry Andric       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2702349cc55cSDimitry Andric   }
2703349cc55cSDimitry Andric 
2704d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2705480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
2706d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
2707d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
2708d65cd7a5SDimitry Andric     (void)HasBody;
2709d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
2710d65cd7a5SDimitry Andric                       "available body!");
2711d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
2712349cc55cSDimitry Andric       F->addFnAttr(llvm::Attribute::NoBuiltin);
2713480093f4SDimitry Andric   }
2714480093f4SDimitry Andric 
27150b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
27160b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
27170b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
2718349cc55cSDimitry Andric     F->addFnAttr(llvm::Attribute::NoBuiltin);
27190b57cec5SDimitry Andric   }
27200b57cec5SDimitry Andric 
27210b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
27220b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
27230b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
27240b57cec5SDimitry Andric     if (MD->isVirtual())
27250b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
2728a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
2729a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
2730a7dea167SDimitry Andric   // jump table.
2731a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2732a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
27330b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
27340b57cec5SDimitry Andric 
2735bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2736bdd1243dSDimitry Andric     setKCFIType(FD, F);
2737bdd1243dSDimitry Andric 
27380b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
27390b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
27400b57cec5SDimitry Andric 
2741bdd1243dSDimitry Andric   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2742bdd1243dSDimitry Andric     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2743bdd1243dSDimitry Andric 
27440b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
27450b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
27460b57cec5SDimitry Andric     //  - The callback callee (as argument number).
27470b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
27480b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
27490b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
27500b57cec5SDimitry Andric 
27510b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
27520b57cec5SDimitry Andric     // identifies the callback callee.
27530b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
27540b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
27550b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
27560b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
27570b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
27580b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
27590b57cec5SDimitry Andric   }
27600b57cec5SDimitry Andric }
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2763e8d8bef9SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
27640b57cec5SDimitry Andric          "Only globals with definition can force usage.");
27650b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
27660b57cec5SDimitry Andric }
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
27690b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
27700b57cec5SDimitry Andric          "Only globals with definition can force usage.");
27710b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
27720b57cec5SDimitry Andric }
27730b57cec5SDimitry Andric 
2774fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2775fe6060f1SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2776fe6060f1SDimitry Andric          "Only globals with definition can force usage.");
2777fe6060f1SDimitry Andric   if (getTriple().isOSBinFormatELF())
2778fe6060f1SDimitry Andric     LLVMCompilerUsed.emplace_back(GV);
2779fe6060f1SDimitry Andric   else
2780fe6060f1SDimitry Andric     LLVMUsed.emplace_back(GV);
2781fe6060f1SDimitry Andric }
2782fe6060f1SDimitry Andric 
27830b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
27840b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
27850b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
27860b57cec5SDimitry Andric   if (List.empty())
27870b57cec5SDimitry Andric     return;
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
27900b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
27910b57cec5SDimitry Andric   UsedArray.resize(List.size());
27920b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
27930b57cec5SDimitry Andric     UsedArray[i] =
27940b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
27950b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
27960b57cec5SDimitry Andric   }
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric   if (UsedArray.empty())
27990b57cec5SDimitry Andric     return;
28000b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
28010b57cec5SDimitry Andric 
28020b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
28030b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
28040b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
28050b57cec5SDimitry Andric 
28060b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
28070b57cec5SDimitry Andric }
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
28100b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
28110b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
28120b57cec5SDimitry Andric }
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
28150b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
28160b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
28170b57cec5SDimitry Andric }
28180b57cec5SDimitry Andric 
28190b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
28200b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
28210b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2822480093f4SDimitry Andric   if (Opt.empty())
2823480093f4SDimitry Andric     return;
28240b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
28250b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
28260b57cec5SDimitry Andric }
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
28290b57cec5SDimitry Andric   auto &C = getLLVMContext();
28300b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
28310b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
28320b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
28330b57cec5SDimitry Andric     return;
28340b57cec5SDimitry Andric   }
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
28370b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
28380b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
28390b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
28400b57cec5SDimitry Andric }
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
28430b57cec5SDimitry Andric /// it depends on, using a postorder walk.
28440b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
28450b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
28460b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
28470b57cec5SDimitry Andric   // Import this module's parent.
28480b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
28490b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
28500b57cec5SDimitry Andric   }
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   // Import this module's dependencies.
2853349cc55cSDimitry Andric   for (Module *Import : llvm::reverse(Mod->Imports)) {
2854349cc55cSDimitry Andric     if (Visited.insert(Import).second)
2855349cc55cSDimitry Andric       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
28560b57cec5SDimitry Andric   }
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
28590b57cec5SDimitry Andric   // described by this module.
28600b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
28610b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
28620b57cec5SDimitry Andric 
28630b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
28640b57cec5SDimitry Andric   // name instead.
28650b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
28660b57cec5SDimitry Andric     return;
28670b57cec5SDimitry Andric 
2868349cc55cSDimitry Andric   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
28690b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
28700b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2871349cc55cSDimitry Andric     if (LL.IsFramework) {
2872349cc55cSDimitry Andric       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2873349cc55cSDimitry Andric                                  llvm::MDString::get(Context, LL.Library)};
28740b57cec5SDimitry Andric 
28750b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
28760b57cec5SDimitry Andric       continue;
28770b57cec5SDimitry Andric     }
28780b57cec5SDimitry Andric 
28790b57cec5SDimitry Andric     // Link against a library.
28800b57cec5SDimitry Andric     if (IsELF) {
28810b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
28820b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
2883349cc55cSDimitry Andric           llvm::MDString::get(Context, LL.Library),
28840b57cec5SDimitry Andric       };
28850b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
28860b57cec5SDimitry Andric     } else {
28870b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
2888349cc55cSDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
28890b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
28900b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
28910b57cec5SDimitry Andric     }
28920b57cec5SDimitry Andric   }
28930b57cec5SDimitry Andric }
28940b57cec5SDimitry Andric 
2895fcaf7f86SDimitry Andric void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
2896fcaf7f86SDimitry Andric   // Emit the initializers in the order that sub-modules appear in the
2897fcaf7f86SDimitry Andric   // source, first Global Module Fragments, if present.
2898fcaf7f86SDimitry Andric   if (auto GMF = Primary->getGlobalModuleFragment()) {
2899fcaf7f86SDimitry Andric     for (Decl *D : getContext().getModuleInitializers(GMF)) {
290061cfbce3SDimitry Andric       if (isa<ImportDecl>(D))
290161cfbce3SDimitry Andric         continue;
290261cfbce3SDimitry Andric       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
2903fcaf7f86SDimitry Andric       EmitTopLevelDecl(D);
2904fcaf7f86SDimitry Andric     }
2905fcaf7f86SDimitry Andric   }
2906fcaf7f86SDimitry Andric   // Second any associated with the module, itself.
2907fcaf7f86SDimitry Andric   for (Decl *D : getContext().getModuleInitializers(Primary)) {
2908fcaf7f86SDimitry Andric     // Skip import decls, the inits for those are called explicitly.
290961cfbce3SDimitry Andric     if (isa<ImportDecl>(D))
2910fcaf7f86SDimitry Andric       continue;
2911fcaf7f86SDimitry Andric     EmitTopLevelDecl(D);
2912fcaf7f86SDimitry Andric   }
2913fcaf7f86SDimitry Andric   // Third any associated with the Privat eMOdule Fragment, if present.
2914fcaf7f86SDimitry Andric   if (auto PMF = Primary->getPrivateModuleFragment()) {
2915fcaf7f86SDimitry Andric     for (Decl *D : getContext().getModuleInitializers(PMF)) {
291661cfbce3SDimitry Andric       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
2917fcaf7f86SDimitry Andric       EmitTopLevelDecl(D);
2918fcaf7f86SDimitry Andric     }
2919fcaf7f86SDimitry Andric   }
2920fcaf7f86SDimitry Andric }
2921fcaf7f86SDimitry Andric 
29220b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
29230b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
29240b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
29250b57cec5SDimitry Andric   // non-explicit child modules.
29260b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
29270b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
29280b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   // Seed the stack with imported modules.
29310b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
29320b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
29330b57cec5SDimitry Andric     // a header of that same module.
29340b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
29350b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
29360b57cec5SDimitry Andric       continue;
29370b57cec5SDimitry Andric     if (Visited.insert(M).second)
29380b57cec5SDimitry Andric       Stack.push_back(M);
29390b57cec5SDimitry Andric   }
29400b57cec5SDimitry Andric 
29410b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
29420b57cec5SDimitry Andric   // non-leaf modules.
29430b57cec5SDimitry Andric   while (!Stack.empty()) {
29440b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric     bool AnyChildren = false;
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric     // Visit the submodules of this module.
29490b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
29500b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
29510b57cec5SDimitry Andric       // linked against.
29520b57cec5SDimitry Andric       if (SM->IsExplicit)
29530b57cec5SDimitry Andric         continue;
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
29560b57cec5SDimitry Andric         Stack.push_back(SM);
29570b57cec5SDimitry Andric         AnyChildren = true;
29580b57cec5SDimitry Andric       }
29590b57cec5SDimitry Andric     }
29600b57cec5SDimitry Andric 
29610b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
29620b57cec5SDimitry Andric     // modules to link against.
29630b57cec5SDimitry Andric     if (!AnyChildren) {
29640b57cec5SDimitry Andric       LinkModules.insert(Mod);
29650b57cec5SDimitry Andric     }
29660b57cec5SDimitry Andric   }
29670b57cec5SDimitry Andric 
29680b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
29690b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
29700b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
29710b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
29720b57cec5SDimitry Andric   Visited.clear();
29730b57cec5SDimitry Andric   for (Module *M : LinkModules)
29740b57cec5SDimitry Andric     if (Visited.insert(M).second)
29750b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
29760b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
29770b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric   // Add the linker options metadata flag.
29800b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
29810b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
29820b57cec5SDimitry Andric     NMD->addOperand(MD);
29830b57cec5SDimitry Andric }
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
29860b57cec5SDimitry Andric   // Emit deferred declare target declarations.
29870b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
29880b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
29910b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
29920b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
29930b57cec5SDimitry Andric 
29940b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
29950b57cec5SDimitry Andric     EmitDeferredVTables();
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
29980b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
29990b57cec5SDimitry Andric     // emitted that then need those vtables.
30000b57cec5SDimitry Andric     assert(DeferredVTables.empty());
30010b57cec5SDimitry Andric   }
30020b57cec5SDimitry Andric 
3003e8d8bef9SDimitry Andric   // Emit CUDA/HIP static device variables referenced by host code only.
3004fe6060f1SDimitry Andric   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3005fe6060f1SDimitry Andric   // needed for further handling.
3006fe6060f1SDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
300781ad6265SDimitry Andric     llvm::append_range(DeferredDeclsToEmit,
300881ad6265SDimitry Andric                        getContext().CUDADeviceVarODRUsedByHost);
3009e8d8bef9SDimitry Andric 
30100b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
30110b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
30120b57cec5SDimitry Andric     return;
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
30150b57cec5SDimitry Andric   // work, it will not interfere with this.
30160b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
30170b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
30200b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
30210b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
30220b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
30230b57cec5SDimitry Andric     // different type.
30240b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
30250b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
30280b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
30290b57cec5SDimitry Andric     // GlobalValue.
30300b57cec5SDimitry Andric     if (!GV)
30310b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
30320b57cec5SDimitry Andric 
30330b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
30340b57cec5SDimitry Andric     assert(GV);
30350b57cec5SDimitry Andric 
30360b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
30370b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
30380b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
30390b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
30400b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
30410b57cec5SDimitry Andric     // ignore these cases.
30420b57cec5SDimitry Andric     if (!GV->isDeclaration())
30430b57cec5SDimitry Andric       continue;
30440b57cec5SDimitry Andric 
3045a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
3046a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3047a7dea167SDimitry Andric       continue;
3048a7dea167SDimitry Andric 
30490b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
30500b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
30530b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
30540b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
30550b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
30560b57cec5SDimitry Andric       EmitDeferred();
30570b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
30580b57cec5SDimitry Andric     }
30590b57cec5SDimitry Andric   }
30600b57cec5SDimitry Andric }
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
30630b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
30640b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
30650b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
30660b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
30690b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
30720b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
30730b57cec5SDimitry Andric            "This queue should only contain external vtables");
30740b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
30750b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
30760b57cec5SDimitry Andric   }
30770b57cec5SDimitry Andric   OpportunisticVTables.clear();
30780b57cec5SDimitry Andric }
30790b57cec5SDimitry Andric 
30800b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
30810b57cec5SDimitry Andric   if (Annotations.empty())
30820b57cec5SDimitry Andric     return;
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
30850b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
30860b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
30870b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
30880b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
30890b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
30900b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
30910b57cec5SDimitry Andric }
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
30940b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
30950b57cec5SDimitry Andric   if (AStr)
30960b57cec5SDimitry Andric     return AStr;
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric   // Not found yet, create a new global.
30990b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3100bdd1243dSDimitry Andric   auto *gv = new llvm::GlobalVariable(
3101bdd1243dSDimitry Andric       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3102bdd1243dSDimitry Andric       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3103bdd1243dSDimitry Andric       ConstGlobalsPtrTy->getAddressSpace());
31040b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
31050b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
31060b57cec5SDimitry Andric   AStr = gv;
31070b57cec5SDimitry Andric   return gv;
31080b57cec5SDimitry Andric }
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
31110b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
31120b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
31130b57cec5SDimitry Andric   if (PLoc.isValid())
31140b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
31150b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
31160b57cec5SDimitry Andric }
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
31190b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
31200b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
31210b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
31220b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
31230b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
31240b57cec5SDimitry Andric }
31250b57cec5SDimitry Andric 
3126e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3127e8d8bef9SDimitry Andric   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3128e8d8bef9SDimitry Andric   if (Exprs.empty())
3129bdd1243dSDimitry Andric     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3130e8d8bef9SDimitry Andric 
3131e8d8bef9SDimitry Andric   llvm::FoldingSetNodeID ID;
3132e8d8bef9SDimitry Andric   for (Expr *E : Exprs) {
3133e8d8bef9SDimitry Andric     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3134e8d8bef9SDimitry Andric   }
3135e8d8bef9SDimitry Andric   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3136e8d8bef9SDimitry Andric   if (Lookup)
3137e8d8bef9SDimitry Andric     return Lookup;
3138e8d8bef9SDimitry Andric 
3139e8d8bef9SDimitry Andric   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3140e8d8bef9SDimitry Andric   LLVMArgs.reserve(Exprs.size());
3141e8d8bef9SDimitry Andric   ConstantEmitter ConstEmiter(*this);
3142e8d8bef9SDimitry Andric   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3143e8d8bef9SDimitry Andric     const auto *CE = cast<clang::ConstantExpr>(E);
3144e8d8bef9SDimitry Andric     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3145e8d8bef9SDimitry Andric                                     CE->getType());
3146e8d8bef9SDimitry Andric   });
3147e8d8bef9SDimitry Andric   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3148e8d8bef9SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3149e8d8bef9SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Struct,
3150e8d8bef9SDimitry Andric                                       ".args");
3151e8d8bef9SDimitry Andric   GV->setSection(AnnotationSection);
3152e8d8bef9SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3153349cc55cSDimitry Andric   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
3154e8d8bef9SDimitry Andric 
3155e8d8bef9SDimitry Andric   Lookup = Bitcasted;
3156e8d8bef9SDimitry Andric   return Bitcasted;
3157e8d8bef9SDimitry Andric }
3158e8d8bef9SDimitry Andric 
31590b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
31600b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
31610b57cec5SDimitry Andric                                                 SourceLocation L) {
31620b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
31630b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
31640b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
3165e8d8bef9SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L),
3166e8d8bef9SDimitry Andric                  *Args = EmitAnnotationArgs(AA);
31670b57cec5SDimitry Andric 
3168349cc55cSDimitry Andric   llvm::Constant *GVInGlobalsAS = GV;
3169349cc55cSDimitry Andric   if (GV->getAddressSpace() !=
3170349cc55cSDimitry Andric       getDataLayout().getDefaultGlobalsAddressSpace()) {
3171349cc55cSDimitry Andric     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3172349cc55cSDimitry Andric         GV, GV->getValueType()->getPointerTo(
3173349cc55cSDimitry Andric                 getDataLayout().getDefaultGlobalsAddressSpace()));
3174480093f4SDimitry Andric   }
3175480093f4SDimitry Andric 
31760b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
3177e8d8bef9SDimitry Andric   llvm::Constant *Fields[] = {
3178349cc55cSDimitry Andric       llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
3179bdd1243dSDimitry Andric       llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy),
3180bdd1243dSDimitry Andric       llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy),
3181e8d8bef9SDimitry Andric       LineNoCst,
3182e8d8bef9SDimitry Andric       Args,
31830b57cec5SDimitry Andric   };
31840b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
31850b57cec5SDimitry Andric }
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
31880b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
31890b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
31900b57cec5SDimitry Andric   // Get the struct elements for these annotations.
31910b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
31920b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
31930b57cec5SDimitry Andric }
31940b57cec5SDimitry Andric 
3195fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
31960b57cec5SDimitry Andric                                        SourceLocation Loc) const {
3197fe6060f1SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3198fe6060f1SDimitry Andric   // NoSanitize by function name.
3199fe6060f1SDimitry Andric   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
32000b57cec5SDimitry Andric     return true;
3201fcaf7f86SDimitry Andric   // NoSanitize by location. Check "mainfile" prefix.
3202fcaf7f86SDimitry Andric   auto &SM = Context.getSourceManager();
3203fcaf7f86SDimitry Andric   const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID());
3204fcaf7f86SDimitry Andric   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3205fcaf7f86SDimitry Andric     return true;
3206fcaf7f86SDimitry Andric 
3207fcaf7f86SDimitry Andric   // Check "src" prefix.
32080b57cec5SDimitry Andric   if (Loc.isValid())
3209fe6060f1SDimitry Andric     return NoSanitizeL.containsLocation(Kind, Loc);
32100b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
32110b57cec5SDimitry Andric   // it's located in the main file.
3212fcaf7f86SDimitry Andric   return NoSanitizeL.containsFile(Kind, MainFile.getName());
32130b57cec5SDimitry Andric }
32140b57cec5SDimitry Andric 
321581ad6265SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
321681ad6265SDimitry Andric                                        llvm::GlobalVariable *GV,
32170b57cec5SDimitry Andric                                        SourceLocation Loc, QualType Ty,
32180b57cec5SDimitry Andric                                        StringRef Category) const {
3219fe6060f1SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
322081ad6265SDimitry Andric   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
32210b57cec5SDimitry Andric     return true;
3222fcaf7f86SDimitry Andric   auto &SM = Context.getSourceManager();
3223fcaf7f86SDimitry Andric   if (NoSanitizeL.containsMainFile(
3224fcaf7f86SDimitry Andric           Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
3225fcaf7f86SDimitry Andric     return true;
322681ad6265SDimitry Andric   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
32270b57cec5SDimitry Andric     return true;
3228fcaf7f86SDimitry Andric 
32290b57cec5SDimitry Andric   // Check global type.
32300b57cec5SDimitry Andric   if (!Ty.isNull()) {
32310b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
3232fe6060f1SDimitry Andric     // not sanitized, we also don't instrument arrays of them.
32330b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
32340b57cec5SDimitry Andric       Ty = AT->getElementType();
32350b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
3236fe6060f1SDimitry Andric     // Only record types (classes, structs etc.) are ignored.
32370b57cec5SDimitry Andric     if (Ty->isRecordType()) {
32380b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
323981ad6265SDimitry Andric       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
32400b57cec5SDimitry Andric         return true;
32410b57cec5SDimitry Andric     }
32420b57cec5SDimitry Andric   }
32430b57cec5SDimitry Andric   return false;
32440b57cec5SDimitry Andric }
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
32470b57cec5SDimitry Andric                                    StringRef Category) const {
32480b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
32490b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
32500b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
32510b57cec5SDimitry Andric   if (Loc.isValid())
32520b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
32530b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
32540b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
32550b57cec5SDimitry Andric   switch (Attr) {
32560b57cec5SDimitry Andric   case ImbueAttr::NONE:
32570b57cec5SDimitry Andric     return false;
32580b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
32590b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
32600b57cec5SDimitry Andric     break;
32610b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
32620b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
32630b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
32640b57cec5SDimitry Andric     break;
32650b57cec5SDimitry Andric   case ImbueAttr::NEVER:
32660b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
32670b57cec5SDimitry Andric     break;
32680b57cec5SDimitry Andric   }
32690b57cec5SDimitry Andric   return true;
32700b57cec5SDimitry Andric }
32710b57cec5SDimitry Andric 
3272bdd1243dSDimitry Andric ProfileList::ExclusionType
3273bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3274e8d8bef9SDimitry Andric                                               SourceLocation Loc) const {
3275e8d8bef9SDimitry Andric   const auto &ProfileList = getContext().getProfileList();
3276e8d8bef9SDimitry Andric   // If the profile list is empty, then instrument everything.
3277e8d8bef9SDimitry Andric   if (ProfileList.isEmpty())
3278bdd1243dSDimitry Andric     return ProfileList::Allow;
3279e8d8bef9SDimitry Andric   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3280e8d8bef9SDimitry Andric   // First, check the function name.
3281bdd1243dSDimitry Andric   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3282e8d8bef9SDimitry Andric     return *V;
3283e8d8bef9SDimitry Andric   // Next, check the source location.
3284bdd1243dSDimitry Andric   if (Loc.isValid())
3285bdd1243dSDimitry Andric     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3286e8d8bef9SDimitry Andric       return *V;
3287e8d8bef9SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
3288e8d8bef9SDimitry Andric   // it's located in the main file.
3289e8d8bef9SDimitry Andric   auto &SM = Context.getSourceManager();
3290bdd1243dSDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
3291bdd1243dSDimitry Andric     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3292e8d8bef9SDimitry Andric       return *V;
3293bdd1243dSDimitry Andric   return ProfileList.getDefault(Kind);
3294e8d8bef9SDimitry Andric }
3295e8d8bef9SDimitry Andric 
3296bdd1243dSDimitry Andric ProfileList::ExclusionType
3297bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3298bdd1243dSDimitry Andric                                                  SourceLocation Loc) const {
3299bdd1243dSDimitry Andric   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3300bdd1243dSDimitry Andric   if (V != ProfileList::Allow)
3301bdd1243dSDimitry Andric     return V;
3302fcaf7f86SDimitry Andric 
3303fcaf7f86SDimitry Andric   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3304fcaf7f86SDimitry Andric   if (NumGroups > 1) {
3305fcaf7f86SDimitry Andric     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3306fcaf7f86SDimitry Andric     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3307bdd1243dSDimitry Andric       return ProfileList::Skip;
3308fcaf7f86SDimitry Andric   }
3309bdd1243dSDimitry Andric   return ProfileList::Allow;
3310fcaf7f86SDimitry Andric }
3311fcaf7f86SDimitry Andric 
33120b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
33130b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
33140b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
33150b57cec5SDimitry Andric     return true;
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric   const auto *VD = dyn_cast<VarDecl>(Global);
331806c3fb27SDimitry Andric   if (VD &&
331906c3fb27SDimitry Andric       ((CodeGenOpts.KeepPersistentStorageVariables &&
332006c3fb27SDimitry Andric         (VD->getStorageDuration() == SD_Static ||
332106c3fb27SDimitry Andric          VD->getStorageDuration() == SD_Thread)) ||
332206c3fb27SDimitry Andric        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
332306c3fb27SDimitry Andric         VD->getType().isConstQualified())))
33240b57cec5SDimitry Andric     return true;
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
33270b57cec5SDimitry Andric }
33280b57cec5SDimitry Andric 
33290b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3330fe6060f1SDimitry Andric   // In OpenMP 5.0 variables and function may be marked as
3331fe6060f1SDimitry Andric   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3332fe6060f1SDimitry Andric   // that they must be emitted on the host/device. To be sure we need to have
3333fe6060f1SDimitry Andric   // seen a declare target with an explicit mentioning of the function, we know
3334fe6060f1SDimitry Andric   // we have if the level of the declare target attribute is -1. Note that we
3335fe6060f1SDimitry Andric   // check somewhere else if we should emit this at all.
3336fe6060f1SDimitry Andric   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3337bdd1243dSDimitry Andric     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3338fe6060f1SDimitry Andric         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3339fe6060f1SDimitry Andric     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3340fe6060f1SDimitry Andric       return false;
3341fe6060f1SDimitry Andric   }
3342fe6060f1SDimitry Andric 
3343a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
33440b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
33450b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
33460b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
33470b57cec5SDimitry Andric       return false;
3348a7dea167SDimitry Andric   }
3349fcaf7f86SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
33500b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
33510b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
33520b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
33530b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
33540b57cec5SDimitry Andric       return false;
3355fcaf7f86SDimitry Andric     if (CXX20ModuleInits && VD->getOwningModule() &&
3356fcaf7f86SDimitry Andric         !VD->getOwningModule()->isModuleMapModule()) {
3357fcaf7f86SDimitry Andric       // For CXX20, module-owned initializers need to be deferred, since it is
3358fcaf7f86SDimitry Andric       // not known at this point if they will be run for the current module or
3359fcaf7f86SDimitry Andric       // as part of the initializer for an imported one.
3360fcaf7f86SDimitry Andric       return false;
3361fcaf7f86SDimitry Andric     }
3362fcaf7f86SDimitry Andric   }
33630b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
33640b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
33650b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
33660b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
336706c3fb27SDimitry Andric       !isTypeConstant(Global->getType(), false, false) &&
33680b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
33690b57cec5SDimitry Andric     return false;
33700b57cec5SDimitry Andric 
33710b57cec5SDimitry Andric   return true;
33720b57cec5SDimitry Andric }
33730b57cec5SDimitry Andric 
33745ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
33755ffd83dbSDimitry Andric   StringRef Name = getMangledName(GD);
33760b57cec5SDimitry Andric 
33770b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
33780b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
33790b57cec5SDimitry Andric 
33800b57cec5SDimitry Andric   // Look for an existing global.
33810b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
33820eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
33830b57cec5SDimitry Andric 
33845ffd83dbSDimitry Andric   ConstantEmitter Emitter(*this);
33855ffd83dbSDimitry Andric   llvm::Constant *Init;
33865ffd83dbSDimitry Andric 
33875ffd83dbSDimitry Andric   APValue &V = GD->getAsAPValue();
33885ffd83dbSDimitry Andric   if (!V.isAbsent()) {
33895ffd83dbSDimitry Andric     // If possible, emit the APValue version of the initializer. In particular,
33905ffd83dbSDimitry Andric     // this gets the type of the constant right.
33915ffd83dbSDimitry Andric     Init = Emitter.emitForInitializer(
33925ffd83dbSDimitry Andric         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
33935ffd83dbSDimitry Andric   } else {
33945ffd83dbSDimitry Andric     // As a fallback, directly construct the constant.
33955ffd83dbSDimitry Andric     // FIXME: This may get padding wrong under esoteric struct layout rules.
33965ffd83dbSDimitry Andric     // MSVC appears to create a complete type 'struct __s_GUID' that it
33975ffd83dbSDimitry Andric     // presumably uses to represent these constants.
33985ffd83dbSDimitry Andric     MSGuidDecl::Parts Parts = GD->getParts();
33995ffd83dbSDimitry Andric     llvm::Constant *Fields[4] = {
34005ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
34015ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
34025ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
34035ffd83dbSDimitry Andric         llvm::ConstantDataArray::getRaw(
34045ffd83dbSDimitry Andric             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
34055ffd83dbSDimitry Andric             Int8Ty)};
34065ffd83dbSDimitry Andric     Init = llvm::ConstantStruct::getAnon(Fields);
34075ffd83dbSDimitry Andric   }
34080b57cec5SDimitry Andric 
34090b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
34100b57cec5SDimitry Andric       getModule(), Init->getType(),
34110b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
34120b57cec5SDimitry Andric   if (supportsCOMDAT())
34130b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
34140b57cec5SDimitry Andric   setDSOLocal(GV);
34155ffd83dbSDimitry Andric 
34165ffd83dbSDimitry Andric   if (!V.isAbsent()) {
34175ffd83dbSDimitry Andric     Emitter.finalize(GV);
34180eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
34195ffd83dbSDimitry Andric   }
34200eae32dcSDimitry Andric 
34210eae32dcSDimitry Andric   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
34220eae32dcSDimitry Andric   llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
34230eae32dcSDimitry Andric       GV, Ty->getPointerTo(GV->getAddressSpace()));
34240eae32dcSDimitry Andric   return ConstantAddress(Addr, Ty, Alignment);
34250b57cec5SDimitry Andric }
34260b57cec5SDimitry Andric 
342781ad6265SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
342881ad6265SDimitry Andric     const UnnamedGlobalConstantDecl *GCD) {
342981ad6265SDimitry Andric   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
343081ad6265SDimitry Andric 
343181ad6265SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
343281ad6265SDimitry Andric   Entry = &UnnamedGlobalConstantDeclMap[GCD];
343381ad6265SDimitry Andric   if (*Entry)
343481ad6265SDimitry Andric     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
343581ad6265SDimitry Andric 
343681ad6265SDimitry Andric   ConstantEmitter Emitter(*this);
343781ad6265SDimitry Andric   llvm::Constant *Init;
343881ad6265SDimitry Andric 
343981ad6265SDimitry Andric   const APValue &V = GCD->getValue();
344081ad6265SDimitry Andric 
344181ad6265SDimitry Andric   assert(!V.isAbsent());
344281ad6265SDimitry Andric   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
344381ad6265SDimitry Andric                                     GCD->getType());
344481ad6265SDimitry Andric 
344581ad6265SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
344681ad6265SDimitry Andric                                       /*isConstant=*/true,
344781ad6265SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Init,
344881ad6265SDimitry Andric                                       ".constant");
344981ad6265SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
345081ad6265SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
345181ad6265SDimitry Andric 
345281ad6265SDimitry Andric   Emitter.finalize(GV);
345381ad6265SDimitry Andric 
345481ad6265SDimitry Andric   *Entry = GV;
345581ad6265SDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
345681ad6265SDimitry Andric }
345781ad6265SDimitry Andric 
3458e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3459e8d8bef9SDimitry Andric     const TemplateParamObjectDecl *TPO) {
3460e8d8bef9SDimitry Andric   StringRef Name = getMangledName(TPO);
3461e8d8bef9SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3462e8d8bef9SDimitry Andric 
3463e8d8bef9SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
34640eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
3465e8d8bef9SDimitry Andric 
3466e8d8bef9SDimitry Andric   ConstantEmitter Emitter(*this);
3467e8d8bef9SDimitry Andric   llvm::Constant *Init = Emitter.emitForInitializer(
3468e8d8bef9SDimitry Andric         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3469e8d8bef9SDimitry Andric 
3470e8d8bef9SDimitry Andric   if (!Init) {
3471e8d8bef9SDimitry Andric     ErrorUnsupported(TPO, "template parameter object");
3472e8d8bef9SDimitry Andric     return ConstantAddress::invalid();
3473e8d8bef9SDimitry Andric   }
3474e8d8bef9SDimitry Andric 
347506c3fb27SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
347606c3fb27SDimitry Andric       isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
347706c3fb27SDimitry Andric           ? llvm::GlobalValue::LinkOnceODRLinkage
347806c3fb27SDimitry Andric           : llvm::GlobalValue::InternalLinkage;
347906c3fb27SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
348006c3fb27SDimitry Andric                                       /*isConstant=*/true, Linkage, Init, Name);
348106c3fb27SDimitry Andric   setGVProperties(GV, TPO);
3482e8d8bef9SDimitry Andric   if (supportsCOMDAT())
3483e8d8bef9SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3484e8d8bef9SDimitry Andric   Emitter.finalize(GV);
3485e8d8bef9SDimitry Andric 
34860eae32dcSDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
3487e8d8bef9SDimitry Andric }
3488e8d8bef9SDimitry Andric 
34890b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
34900b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
34910b57cec5SDimitry Andric   assert(AA && "No alias?");
34920b57cec5SDimitry Andric 
34930b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
34940b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
34970b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
34980b57cec5SDimitry Andric   if (Entry) {
3499bdd1243dSDimitry Andric     unsigned AS = getTypes().getTargetAddressSpace(VD->getType());
35000b57cec5SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
35010eae32dcSDimitry Andric     return ConstantAddress(Ptr, DeclTy, Alignment);
35020b57cec5SDimitry Andric   }
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric   llvm::Constant *Aliasee;
35050b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
35060b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
35070b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
35080b57cec5SDimitry Andric                                       /*ForVTable=*/false);
35090b57cec5SDimitry Andric   else
3510349cc55cSDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3511349cc55cSDimitry Andric                                     nullptr);
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
35140b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
35150b57cec5SDimitry Andric   WeakRefReferences.insert(F);
35160b57cec5SDimitry Andric 
35170eae32dcSDimitry Andric   return ConstantAddress(Aliasee, DeclTy, Alignment);
35180b57cec5SDimitry Andric }
35190b57cec5SDimitry Andric 
35200b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
35210b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
35220b57cec5SDimitry Andric 
35230b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
35240b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
35250b57cec5SDimitry Andric     return;
35260b57cec5SDimitry Andric 
35270b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
35280b57cec5SDimitry Andric   // emit it now.
35290b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
35300b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
35310b57cec5SDimitry Andric 
35320b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
35330b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
35340b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
35370b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
35380b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
35390b57cec5SDimitry Andric 
35400b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
35410b57cec5SDimitry Andric   if (LangOpts.CUDA) {
35420b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
35430b57cec5SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
35440b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
35450b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
35460b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
35475ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
35485ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinTextureType())
35490b57cec5SDimitry Andric         return;
35500b57cec5SDimitry Andric     } else {
35510b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
35520b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
35530b57cec5SDimitry Andric       // size and host-side address in order to provide access to
35540b57cec5SDimitry Andric       // their device-side incarnations.
35550b57cec5SDimitry Andric 
35560b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
35570b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
35580b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
35590b57cec5SDimitry Andric         return;
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
35620b57cec5SDimitry Andric              "Expected Variable or Function");
35630b57cec5SDimitry Andric     }
35640b57cec5SDimitry Andric   }
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
3567a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
35680b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
35690b57cec5SDimitry Andric       return;
35700b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
35710b57cec5SDimitry Andric       if (MustBeEmitted(Global))
35720b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
35730b57cec5SDimitry Andric       return;
357406c3fb27SDimitry Andric     }
357506c3fb27SDimitry Andric     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
35760b57cec5SDimitry Andric       if (MustBeEmitted(Global))
35770b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
35780b57cec5SDimitry Andric       return;
35790b57cec5SDimitry Andric     }
35800b57cec5SDimitry Andric   }
35810b57cec5SDimitry Andric 
35820b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
35830b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
35840b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
35850b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
35860b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
35870b57cec5SDimitry Andric         return;
35880b57cec5SDimitry Andric 
35890b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
35900b57cec5SDimitry Andric 
35910b57cec5SDimitry Andric       // Compute the function info and LLVM type.
35920b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
35930b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
35940b57cec5SDimitry Andric 
35950b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
35960b57cec5SDimitry Andric                               /*DontDefer=*/false);
35970b57cec5SDimitry Andric       return;
35980b57cec5SDimitry Andric     }
35990b57cec5SDimitry Andric   } else {
36000b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
36010b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
36020b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
36030b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
36040b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
36050b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
3606bdd1243dSDimitry Andric         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
36070b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3608*8a4dda33SDimitry Andric 
3609*8a4dda33SDimitry Andric           // If this variable has external storage and doesn't require special
3610*8a4dda33SDimitry Andric           // link handling we defer to its canonical definition.
3611*8a4dda33SDimitry Andric           if (VD->hasExternalStorage() &&
3612*8a4dda33SDimitry Andric               Res != OMPDeclareTargetDeclAttr::MT_Link)
3613*8a4dda33SDimitry Andric             return;
3614*8a4dda33SDimitry Andric 
36150b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
36160b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3617bdd1243dSDimitry Andric           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3618bdd1243dSDimitry Andric                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
36190b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
36200b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
36210b57cec5SDimitry Andric           } else {
36220b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3623bdd1243dSDimitry Andric                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3624bdd1243dSDimitry Andric                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
36250b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
36260b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
36270b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
36280b57cec5SDimitry Andric           }
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric           return;
36310b57cec5SDimitry Andric         }
36320b57cec5SDimitry Andric       }
36330b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
36340b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
36350b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
36360b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
36370b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
36380b57cec5SDimitry Andric       return;
36390b57cec5SDimitry Andric     }
36400b57cec5SDimitry Andric   }
36410b57cec5SDimitry Andric 
36420b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
36430b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
36440b57cec5SDimitry Andric   // to benefit from cache locality.
36450b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
36460b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
36470b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
3648*8a4dda33SDimitry Andric     addEmittedDeferredDecl(GD);
36490b57cec5SDimitry Andric     return;
36500b57cec5SDimitry Andric   }
36510b57cec5SDimitry Andric 
36520b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
36530b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
36540b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
36550b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
36560b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
36570b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
36580b57cec5SDimitry Andric   }
36590b57cec5SDimitry Andric 
36600b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
36610b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
36620b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
36630b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
36640b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
36650b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
36660b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
36670b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
36680b57cec5SDimitry Andric   } else {
36690b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
36700b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
36710b57cec5SDimitry Andric     // DeferredDeclsToEmit.
36720b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
36730b57cec5SDimitry Andric   }
36740b57cec5SDimitry Andric }
36750b57cec5SDimitry Andric 
36760b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
36770b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
36780b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
36790b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
36800b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
36810b57cec5SDimitry Andric         return true;
36820b57cec5SDimitry Andric 
36830b57cec5SDimitry Andric   return false;
36840b57cec5SDimitry Andric }
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric namespace {
36870b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
36880b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
36890b57cec5SDimitry Andric     const StringRef Name;
36900b57cec5SDimitry Andric     const Builtin::Context &BI;
36910b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
36920b57cec5SDimitry Andric         : Name(N), BI(C) {}
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
36950b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
36960b57cec5SDimitry Andric       if (!FD)
36970b57cec5SDimitry Andric         return false;
36980b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
36990b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
37000b57cec5SDimitry Andric         return true;
37010b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
37020b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
37030b57cec5SDimitry Andric         return false;
37040b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
37050b57cec5SDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
37060b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
37070b57cec5SDimitry Andric         return true;
37080b57cec5SDimitry Andric       }
37090b57cec5SDimitry Andric       return false;
37100b57cec5SDimitry Andric     }
37110b57cec5SDimitry Andric 
37120b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
37130b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
37140b57cec5SDimitry Andric         if (Child && this->Visit(Child))
37150b57cec5SDimitry Andric           return true;
37160b57cec5SDimitry Andric       return false;
37170b57cec5SDimitry Andric     }
37180b57cec5SDimitry Andric   };
37190b57cec5SDimitry Andric 
37200b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
37210b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
37220b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
37230b57cec5SDimitry Andric     bool SafeToInline = true;
37240b57cec5SDimitry Andric 
37250b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
37260b57cec5SDimitry Andric 
37270b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
37280b57cec5SDimitry Andric       if (VD->getTLSKind()) {
37290b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
37300b57cec5SDimitry Andric         SafeToInline = false;
37310b57cec5SDimitry Andric         return SafeToInline;
37320b57cec5SDimitry Andric       }
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
37350b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
37360b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
37370b57cec5SDimitry Andric 
37380b57cec5SDimitry Andric       return SafeToInline;
37390b57cec5SDimitry Andric     }
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
37420b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
37430b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
37440b57cec5SDimitry Andric       return SafeToInline;
37450b57cec5SDimitry Andric     }
37460b57cec5SDimitry Andric 
37470b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
37480b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
37490b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
37500b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
37510b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
37520b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
37530b57cec5SDimitry Andric       return SafeToInline;
37540b57cec5SDimitry Andric     }
37550b57cec5SDimitry Andric 
37560b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
37570b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
37580b57cec5SDimitry Andric       return SafeToInline;
37590b57cec5SDimitry Andric     }
37600b57cec5SDimitry Andric 
37610b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
37620b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
37630b57cec5SDimitry Andric       if (!M) {
37640b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
37650b57cec5SDimitry Andric         SafeToInline = true;
37660b57cec5SDimitry Andric       } else {
37670b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
37680b57cec5SDimitry Andric       }
37690b57cec5SDimitry Andric       return SafeToInline;
37700b57cec5SDimitry Andric     }
37710b57cec5SDimitry Andric 
37720b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
37730b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
37740b57cec5SDimitry Andric       return SafeToInline;
37750b57cec5SDimitry Andric     }
37760b57cec5SDimitry Andric 
37770b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
37780b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
37790b57cec5SDimitry Andric       return SafeToInline;
37800b57cec5SDimitry Andric     }
37810b57cec5SDimitry Andric   };
37820b57cec5SDimitry Andric }
37830b57cec5SDimitry Andric 
37840b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
37850b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
37860b57cec5SDimitry Andric // ends up pointing to itself.
37870b57cec5SDimitry Andric bool
37880b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
37890b57cec5SDimitry Andric   StringRef Name;
37900b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
37910b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
37920b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
37930b57cec5SDimitry Andric     if (!Attr)
37940b57cec5SDimitry Andric       return false;
37950b57cec5SDimitry Andric     Name = Attr->getLabel();
37960b57cec5SDimitry Andric   } else {
37970b57cec5SDimitry Andric     Name = FD->getName();
37980b57cec5SDimitry Andric   }
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
38010b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
38020b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
38030b57cec5SDimitry Andric }
38040b57cec5SDimitry Andric 
38050b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
38060b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
38070b57cec5SDimitry Andric     return true;
38080b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
38090b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
38100b57cec5SDimitry Andric     return false;
38110b57cec5SDimitry Andric 
3812fe6060f1SDimitry Andric   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
38130b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
38140b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
38150b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
38160b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
38170b57cec5SDimitry Andric       return false;
38180b57cec5SDimitry Andric 
38190b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
38200b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
38210b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
38220b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
38230b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
38240b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
38250b57cec5SDimitry Andric             return false;
38260b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
38270b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
38280b57cec5SDimitry Andric           return false;
38290b57cec5SDimitry Andric     }
38300b57cec5SDimitry Andric   }
38310b57cec5SDimitry Andric 
3832349cc55cSDimitry Andric   // Inline builtins declaration must be emitted. They often are fortified
3833349cc55cSDimitry Andric   // functions.
3834349cc55cSDimitry Andric   if (F->isInlineBuiltinDeclaration())
3835349cc55cSDimitry Andric     return true;
3836349cc55cSDimitry Andric 
38370b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
38380b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
38395ffd83dbSDimitry Andric   // but a function that calls itself through asm label/`__builtin_` trickery is
38405ffd83dbSDimitry Andric   // clearly not equivalent to the real implementation.
38410b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
38420b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
38430b57cec5SDimitry Andric }
38440b57cec5SDimitry Andric 
38450b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
38460b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
38470b57cec5SDimitry Andric }
38480b57cec5SDimitry Andric 
38490b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
38500b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
38510b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
38540b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
38550b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
38560b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
38574824e7fdSDimitry Andric   } else if (FD->isTargetClonesMultiVersion()) {
38584824e7fdSDimitry Andric     auto *Clone = FD->getAttr<TargetClonesAttr>();
38594824e7fdSDimitry Andric     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
38604824e7fdSDimitry Andric       if (Clone->isFirstOfVersion(I))
38614824e7fdSDimitry Andric         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
386281ad6265SDimitry Andric     // Ensure that the resolver function is also emitted.
386381ad6265SDimitry Andric     GetOrCreateMultiVersionResolver(GD);
38640b57cec5SDimitry Andric   } else
38650b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
38660b57cec5SDimitry Andric }
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
38690b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
38700b57cec5SDimitry Andric 
38710b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
38720b57cec5SDimitry Andric                                  Context.getSourceManager(),
38730b57cec5SDimitry Andric                                  "Generating code for declaration");
38740b57cec5SDimitry Andric 
38750b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
38760b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
38770b57cec5SDimitry Andric     // linkage.
38780b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
38790b57cec5SDimitry Andric       return;
38800b57cec5SDimitry Andric 
38810b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
38820b57cec5SDimitry Andric       std::string Name;
38830b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
38840b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
38850b57cec5SDimitry Andric                                /*Qualified=*/true);
38860b57cec5SDimitry Andric       return Name;
38870b57cec5SDimitry Andric     });
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
38900b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
38910b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
38920b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
38930b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
38940b57cec5SDimitry Andric       else if (FD->isMultiVersion())
38950b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
38960b57cec5SDimitry Andric       else
38970b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric       if (Method->isVirtual())
39000b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
39010b57cec5SDimitry Andric 
39020b57cec5SDimitry Andric       return;
39030b57cec5SDimitry Andric     }
39040b57cec5SDimitry Andric 
39050b57cec5SDimitry Andric     if (FD->isMultiVersion())
39060b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
39070b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
39080b57cec5SDimitry Andric   }
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
39110b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
39120b57cec5SDimitry Andric 
39130b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
39140b57cec5SDimitry Andric }
39150b57cec5SDimitry Andric 
39160b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
39170b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
39180b57cec5SDimitry Andric 
39190b57cec5SDimitry Andric static unsigned
39200b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
39210b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
39220b57cec5SDimitry Andric   unsigned Priority = 0;
3923bdd1243dSDimitry Andric   unsigned NumFeatures = 0;
3924bdd1243dSDimitry Andric   for (StringRef Feat : RO.Conditions.Features) {
39250b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3926bdd1243dSDimitry Andric     NumFeatures++;
3927bdd1243dSDimitry Andric   }
39280b57cec5SDimitry Andric 
39290b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
39300b57cec5SDimitry Andric     Priority = std::max(
39310b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3932bdd1243dSDimitry Andric 
3933bdd1243dSDimitry Andric   Priority += TI.multiVersionFeatureCost() * NumFeatures;
3934bdd1243dSDimitry Andric 
39350b57cec5SDimitry Andric   return Priority;
39360b57cec5SDimitry Andric }
39370b57cec5SDimitry Andric 
3938349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3939349cc55cSDimitry Andric // TU can forward declare the function without causing problems.  Particularly
3940349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we
3941349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be
3942349cc55cSDimitry Andric // used with internal linkage in multiple TUs.
3943349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3944349cc55cSDimitry Andric                                                        GlobalDecl GD) {
3945349cc55cSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3946349cc55cSDimitry Andric   if (FD->getFormalLinkage() == InternalLinkage)
3947349cc55cSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
3948349cc55cSDimitry Andric   return llvm::GlobalValue::WeakODRLinkage;
3949349cc55cSDimitry Andric }
3950349cc55cSDimitry Andric 
39510b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
3952fe6060f1SDimitry Andric   std::vector<GlobalDecl> MVFuncsToEmit;
3953fe6060f1SDimitry Andric   MultiVersionFuncs.swap(MVFuncsToEmit);
3954fe6060f1SDimitry Andric   for (GlobalDecl GD : MVFuncsToEmit) {
395581ad6265SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
395681ad6265SDimitry Andric     assert(FD && "Expected a FunctionDecl");
395781ad6265SDimitry Andric 
39580b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
395981ad6265SDimitry Andric     if (FD->isTargetMultiVersion()) {
39600b57cec5SDimitry Andric       getContext().forEachMultiversionedFunctionVersion(
39610b57cec5SDimitry Andric           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
39620b57cec5SDimitry Andric             GlobalDecl CurGD{
39630b57cec5SDimitry Andric                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
39640b57cec5SDimitry Andric             StringRef MangledName = getMangledName(CurGD);
39650b57cec5SDimitry Andric             llvm::Constant *Func = GetGlobalValue(MangledName);
39660b57cec5SDimitry Andric             if (!Func) {
39670b57cec5SDimitry Andric               if (CurFD->isDefined()) {
39680b57cec5SDimitry Andric                 EmitGlobalFunctionDefinition(CurGD, nullptr);
39690b57cec5SDimitry Andric                 Func = GetGlobalValue(MangledName);
39700b57cec5SDimitry Andric               } else {
39710b57cec5SDimitry Andric                 const CGFunctionInfo &FI =
39720b57cec5SDimitry Andric                     getTypes().arrangeGlobalDeclaration(GD);
39730b57cec5SDimitry Andric                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
39740b57cec5SDimitry Andric                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
39750b57cec5SDimitry Andric                                          /*DontDefer=*/false, ForDefinition);
39760b57cec5SDimitry Andric               }
39770b57cec5SDimitry Andric               assert(Func && "This should have just been created");
39780b57cec5SDimitry Andric             }
3979bdd1243dSDimitry Andric             if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
39800b57cec5SDimitry Andric               const auto *TA = CurFD->getAttr<TargetAttr>();
39810b57cec5SDimitry Andric               llvm::SmallVector<StringRef, 8> Feats;
39820b57cec5SDimitry Andric               TA->getAddedFeatures(Feats);
39830b57cec5SDimitry Andric               Options.emplace_back(cast<llvm::Function>(Func),
39840b57cec5SDimitry Andric                                    TA->getArchitecture(), Feats);
3985bdd1243dSDimitry Andric             } else {
3986bdd1243dSDimitry Andric               const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
3987bdd1243dSDimitry Andric               llvm::SmallVector<StringRef, 8> Feats;
3988bdd1243dSDimitry Andric               TVA->getFeatures(Feats);
3989bdd1243dSDimitry Andric               Options.emplace_back(cast<llvm::Function>(Func),
3990bdd1243dSDimitry Andric                                    /*Architecture*/ "", Feats);
3991bdd1243dSDimitry Andric             }
39920b57cec5SDimitry Andric           });
399381ad6265SDimitry Andric     } else if (FD->isTargetClonesMultiVersion()) {
399481ad6265SDimitry Andric       const auto *TC = FD->getAttr<TargetClonesAttr>();
399581ad6265SDimitry Andric       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
399681ad6265SDimitry Andric            ++VersionIndex) {
399781ad6265SDimitry Andric         if (!TC->isFirstOfVersion(VersionIndex))
399881ad6265SDimitry Andric           continue;
399981ad6265SDimitry Andric         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
400081ad6265SDimitry Andric                          VersionIndex};
400181ad6265SDimitry Andric         StringRef Version = TC->getFeatureStr(VersionIndex);
400281ad6265SDimitry Andric         StringRef MangledName = getMangledName(CurGD);
400381ad6265SDimitry Andric         llvm::Constant *Func = GetGlobalValue(MangledName);
400481ad6265SDimitry Andric         if (!Func) {
400581ad6265SDimitry Andric           if (FD->isDefined()) {
400681ad6265SDimitry Andric             EmitGlobalFunctionDefinition(CurGD, nullptr);
400781ad6265SDimitry Andric             Func = GetGlobalValue(MangledName);
4008a7dea167SDimitry Andric           } else {
400981ad6265SDimitry Andric             const CGFunctionInfo &FI =
401081ad6265SDimitry Andric                 getTypes().arrangeGlobalDeclaration(CurGD);
401181ad6265SDimitry Andric             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
401281ad6265SDimitry Andric             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
401381ad6265SDimitry Andric                                      /*DontDefer=*/false, ForDefinition);
4014a7dea167SDimitry Andric           }
401581ad6265SDimitry Andric           assert(Func && "This should have just been created");
401681ad6265SDimitry Andric         }
401781ad6265SDimitry Andric 
401881ad6265SDimitry Andric         StringRef Architecture;
401981ad6265SDimitry Andric         llvm::SmallVector<StringRef, 1> Feature;
402081ad6265SDimitry Andric 
4021bdd1243dSDimitry Andric         if (getTarget().getTriple().isAArch64()) {
4022bdd1243dSDimitry Andric           if (Version != "default") {
4023bdd1243dSDimitry Andric             llvm::SmallVector<StringRef, 8> VerFeats;
4024bdd1243dSDimitry Andric             Version.split(VerFeats, "+");
4025bdd1243dSDimitry Andric             for (auto &CurFeat : VerFeats)
4026bdd1243dSDimitry Andric               Feature.push_back(CurFeat.trim());
4027bdd1243dSDimitry Andric           }
4028bdd1243dSDimitry Andric         } else {
402981ad6265SDimitry Andric           if (Version.startswith("arch="))
403081ad6265SDimitry Andric             Architecture = Version.drop_front(sizeof("arch=") - 1);
403181ad6265SDimitry Andric           else if (Version != "default")
403281ad6265SDimitry Andric             Feature.push_back(Version);
4033bdd1243dSDimitry Andric         }
403481ad6265SDimitry Andric 
403581ad6265SDimitry Andric         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
403681ad6265SDimitry Andric       }
403781ad6265SDimitry Andric     } else {
403881ad6265SDimitry Andric       assert(0 && "Expected a target or target_clones multiversion function");
403981ad6265SDimitry Andric       continue;
404081ad6265SDimitry Andric     }
404181ad6265SDimitry Andric 
404281ad6265SDimitry Andric     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
404381ad6265SDimitry Andric     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
404481ad6265SDimitry Andric       ResolverConstant = IFunc->getResolver();
404581ad6265SDimitry Andric     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
404681ad6265SDimitry Andric 
404781ad6265SDimitry Andric     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric     if (supportsCOMDAT())
40500b57cec5SDimitry Andric       ResolverFunc->setComdat(
40510b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
40520b57cec5SDimitry Andric 
405381ad6265SDimitry Andric     const TargetInfo &TI = getTarget();
40540b57cec5SDimitry Andric     llvm::stable_sort(
40550b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
40560b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
40570b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
40580b57cec5SDimitry Andric         });
40590b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
40600b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
40610b57cec5SDimitry Andric   }
4062fe6060f1SDimitry Andric 
4063fe6060f1SDimitry Andric   // Ensure that any additions to the deferred decls list caused by emitting a
4064fe6060f1SDimitry Andric   // variant are emitted.  This can happen when the variant itself is inline and
4065fe6060f1SDimitry Andric   // calls a function without linkage.
4066fe6060f1SDimitry Andric   if (!MVFuncsToEmit.empty())
4067fe6060f1SDimitry Andric     EmitDeferred();
4068fe6060f1SDimitry Andric 
4069fe6060f1SDimitry Andric   // Ensure that any additions to the multiversion funcs list from either the
4070fe6060f1SDimitry Andric   // deferred decls or the multiversion functions themselves are emitted.
4071fe6060f1SDimitry Andric   if (!MultiVersionFuncs.empty())
4072fe6060f1SDimitry Andric     emitMultiVersionFunctions();
40730b57cec5SDimitry Andric }
40740b57cec5SDimitry Andric 
40750b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
40760b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
40770b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
407804eeddc0SDimitry Andric   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
40790b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
40800b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
40810b57cec5SDimitry Andric 
408281ad6265SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
408381ad6265SDimitry Andric   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
40840b57cec5SDimitry Andric 
40850b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
408604eeddc0SDimitry Andric   UpdateMultiVersionNames(GD, FD, ResolverName);
40870b57cec5SDimitry Andric 
40880b57cec5SDimitry Andric   llvm::Type *ResolverType;
40890b57cec5SDimitry Andric   GlobalDecl ResolverGD;
409004eeddc0SDimitry Andric   if (getTarget().supportsIFunc()) {
40910b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
40920b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
4093bdd1243dSDimitry Andric                                getTypes().getTargetAddressSpace(FD->getType())),
40940b57cec5SDimitry Andric         false);
409504eeddc0SDimitry Andric   }
40960b57cec5SDimitry Andric   else {
40970b57cec5SDimitry Andric     ResolverType = DeclTy;
40980b57cec5SDimitry Andric     ResolverGD = GD;
40990b57cec5SDimitry Andric   }
41000b57cec5SDimitry Andric 
41010b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
41020b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4103349cc55cSDimitry Andric   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4104a7dea167SDimitry Andric   if (supportsCOMDAT())
4105a7dea167SDimitry Andric     ResolverFunc->setComdat(
4106a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
41090b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
41100b57cec5SDimitry Andric   unsigned Index = 0;
41110b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
41120b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
41130b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
41140b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
41170b57cec5SDimitry Andric 
41180b57cec5SDimitry Andric     if (!Func) {
41190b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
41200b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
41210b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
41220b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
41230b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
41240b57cec5SDimitry Andric       } else {
41250b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
41260b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
41270b57cec5SDimitry Andric 
41280b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
41290b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
41300b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
41310b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
41320b57cec5SDimitry Andric       }
41330b57cec5SDimitry Andric     }
41340b57cec5SDimitry Andric 
41350b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
41360b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
41370b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
41380b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
4139349cc55cSDimitry Andric     llvm::erase_if(Features, [&Target](StringRef Feat) {
41400b57cec5SDimitry Andric       return !Target.validateCpuSupports(Feat);
4141349cc55cSDimitry Andric     });
41420b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
41430b57cec5SDimitry Andric     ++Index;
41440b57cec5SDimitry Andric   }
41450b57cec5SDimitry Andric 
4146fe6060f1SDimitry Andric   llvm::stable_sort(
41470b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
41480b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
4149349cc55cSDimitry Andric         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4150349cc55cSDimitry Andric                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
41510b57cec5SDimitry Andric       });
41520b57cec5SDimitry Andric 
41530b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
41540b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
41550b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
41560b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
41570b57cec5SDimitry Andric   while (Options.size() > 1 &&
4158349cc55cSDimitry Andric          llvm::X86::getCpuSupportsMask(
41590b57cec5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
41600b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
41610b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
41620b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
41630b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
41640b57cec5SDimitry Andric     else
41650b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
41660b57cec5SDimitry Andric   }
41670b57cec5SDimitry Andric 
41680b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
41690b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4170a7dea167SDimitry Andric 
4171a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
417281ad6265SDimitry Andric     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
417381ad6265SDimitry Andric     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
417481ad6265SDimitry Andric 
417581ad6265SDimitry Andric     // Fix up function declarations that were created for cpu_specific before
417681ad6265SDimitry Andric     // cpu_dispatch was known
417781ad6265SDimitry Andric     if (!isa<llvm::GlobalIFunc>(IFunc)) {
417881ad6265SDimitry Andric       assert(cast<llvm::Function>(IFunc)->isDeclaration());
417981ad6265SDimitry Andric       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
418081ad6265SDimitry Andric                                            &getModule());
418181ad6265SDimitry Andric       GI->takeName(IFunc);
418281ad6265SDimitry Andric       IFunc->replaceAllUsesWith(GI);
418381ad6265SDimitry Andric       IFunc->eraseFromParent();
418481ad6265SDimitry Andric       IFunc = GI;
418581ad6265SDimitry Andric     }
418681ad6265SDimitry Andric 
4187a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
4188a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4189a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4190a7dea167SDimitry Andric     if (!AliasFunc) {
419181ad6265SDimitry Andric       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
419281ad6265SDimitry Andric                                            &getModule());
4193a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
4194a7dea167SDimitry Andric     }
4195a7dea167SDimitry Andric   }
41960b57cec5SDimitry Andric }
41970b57cec5SDimitry Andric 
41980b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
41990b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
420081ad6265SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
420181ad6265SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
420281ad6265SDimitry Andric   assert(FD && "Not a FunctionDecl?");
420381ad6265SDimitry Andric 
42040b57cec5SDimitry Andric   std::string MangledName =
42050b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
42060b57cec5SDimitry Andric 
42070b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
42080b57cec5SDimitry Andric   // a separate resolver).
42090b57cec5SDimitry Andric   std::string ResolverName = MangledName;
42100b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
42110b57cec5SDimitry Andric     ResolverName += ".ifunc";
42120b57cec5SDimitry Andric   else if (FD->isTargetMultiVersion())
42130b57cec5SDimitry Andric     ResolverName += ".resolver";
42140b57cec5SDimitry Andric 
421581ad6265SDimitry Andric   // If the resolver has already been created, just return it.
42160b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
42170b57cec5SDimitry Andric     return ResolverGV;
42180b57cec5SDimitry Andric 
421981ad6265SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
422081ad6265SDimitry Andric   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
42210b57cec5SDimitry Andric 
422281ad6265SDimitry Andric   // The resolver needs to be created. For target and target_clones, defer
422381ad6265SDimitry Andric   // creation until the end of the TU.
422481ad6265SDimitry Andric   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
422581ad6265SDimitry Andric     MultiVersionFuncs.push_back(GD);
422681ad6265SDimitry Andric 
422781ad6265SDimitry Andric   // For cpu_specific, don't create an ifunc yet because we don't know if the
422881ad6265SDimitry Andric   // cpu_dispatch will be emitted in this translation unit.
422981ad6265SDimitry Andric   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
42300b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
4231bdd1243dSDimitry Andric         llvm::PointerType::get(DeclTy,
4232bdd1243dSDimitry Andric                                getTypes().getTargetAddressSpace(FD->getType())),
42330b57cec5SDimitry Andric         false);
42340b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
42350b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
42360b57cec5SDimitry Andric         /*ForVTable=*/false);
4237349cc55cSDimitry Andric     llvm::GlobalIFunc *GIF =
4238349cc55cSDimitry Andric         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4239349cc55cSDimitry Andric                                   "", Resolver, &getModule());
42400b57cec5SDimitry Andric     GIF->setName(ResolverName);
42410b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric     return GIF;
42440b57cec5SDimitry Andric   }
42450b57cec5SDimitry Andric 
42460b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
42470b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
42480b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
42490b57cec5SDimitry Andric          "Resolver should be created for the first time");
42500b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
42510b57cec5SDimitry Andric   return Resolver;
42520b57cec5SDimitry Andric }
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
42550b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
42560b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
42570b57cec5SDimitry Andric /// bitcasted to the right type.
42580b57cec5SDimitry Andric ///
42590b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
42600b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
42610b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
42620b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
42630b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
42640b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
42650b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
42660b57cec5SDimitry Andric 
42670b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
42680b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
42690b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
42700b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
427106c3fb27SDimitry Andric     if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
42720b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
42730b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
42740b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
42750b57cec5SDimitry Andric         GlobalDecl GDDef;
42760b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
42770b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
42780b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
42790b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
42800b57cec5SDimitry Andric         else
42810b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
42820b57cec5SDimitry Andric         EmitGlobal(GDDef);
42830b57cec5SDimitry Andric       }
42840b57cec5SDimitry Andric     }
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
428704eeddc0SDimitry Andric       UpdateMultiVersionNames(GD, FD, MangledName);
42880b57cec5SDimitry Andric       if (!IsForDefinition)
428981ad6265SDimitry Andric         return GetOrCreateMultiVersionResolver(GD);
42900b57cec5SDimitry Andric     }
42910b57cec5SDimitry Andric   }
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
42940b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
42950b57cec5SDimitry Andric   if (Entry) {
42960b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
42970b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
42980b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
42990b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
43000b57cec5SDimitry Andric     }
43010b57cec5SDimitry Andric 
43020b57cec5SDimitry Andric     // Handle dropped DLL attributes.
430381ad6265SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
430481ad6265SDimitry Andric         !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
43050b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
43060b57cec5SDimitry Andric       setDSOLocal(Entry);
43070b57cec5SDimitry Andric     }
43080b57cec5SDimitry Andric 
43090b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
43100b57cec5SDimitry Andric     // error.
43110b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
43120b57cec5SDimitry Andric       GlobalDecl OtherGD;
43130b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
43140b57cec5SDimitry Andric       // to make sure that we issue an error only once.
43150b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
43160b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
43170b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
43180b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
43190b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
43200b57cec5SDimitry Andric             << MangledName;
43210b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
43220b57cec5SDimitry Andric                           diag::note_previous_definition);
43230b57cec5SDimitry Andric       }
43240b57cec5SDimitry Andric     }
43250b57cec5SDimitry Andric 
43260b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
43275ffd83dbSDimitry Andric         (Entry->getValueType() == Ty)) {
43280b57cec5SDimitry Andric       return Entry;
43290b57cec5SDimitry Andric     }
43300b57cec5SDimitry Andric 
43310b57cec5SDimitry Andric     // Make sure the result is of the correct type.
43320b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
43330b57cec5SDimitry Andric     // function, not just return a bitcast.)
43340b57cec5SDimitry Andric     if (!IsForDefinition)
4335bdd1243dSDimitry Andric       return llvm::ConstantExpr::getBitCast(
4336bdd1243dSDimitry Andric           Entry, Ty->getPointerTo(Entry->getAddressSpace()));
43370b57cec5SDimitry Andric   }
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
43400b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
43410b57cec5SDimitry Andric   // sure not to try to set attributes.
43420b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
43430b57cec5SDimitry Andric 
43440b57cec5SDimitry Andric   llvm::FunctionType *FTy;
43450b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
43460b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
43470b57cec5SDimitry Andric   } else {
43480b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
43490b57cec5SDimitry Andric     IsIncompleteFunction = true;
43500b57cec5SDimitry Andric   }
43510b57cec5SDimitry Andric 
43520b57cec5SDimitry Andric   llvm::Function *F =
43530b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
43540b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
43570b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
43580b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
43590b57cec5SDimitry Andric   //
43600b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
43610b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
43620b57cec5SDimitry Andric   if (Entry) {
43630b57cec5SDimitry Andric     F->takeName(Entry);
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
43660b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
43670b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
43680b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
43690b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
43700b57cec5SDimitry Andric     // dropping arguments.
43710b57cec5SDimitry Andric     if (!Entry->use_empty()) {
43720b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
43730b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
43740b57cec5SDimitry Andric     }
43750b57cec5SDimitry Andric 
43760b57cec5SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
4377bdd1243dSDimitry Andric         F, Entry->getValueType()->getPointerTo(Entry->getAddressSpace()));
43780b57cec5SDimitry Andric     addGlobalValReplacement(Entry, BC);
43790b57cec5SDimitry Andric   }
43800b57cec5SDimitry Andric 
43810b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
43820b57cec5SDimitry Andric   if (D)
43830b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4384349cc55cSDimitry Andric   if (ExtraAttrs.hasFnAttrs()) {
438504eeddc0SDimitry Andric     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4386349cc55cSDimitry Andric     F->addFnAttrs(B);
43870b57cec5SDimitry Andric   }
43880b57cec5SDimitry Andric 
43890b57cec5SDimitry Andric   if (!DontDefer) {
43900b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
43910b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
43920b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
4393bdd1243dSDimitry Andric     if (isa_and_nonnull<CXXDestructorDecl>(D) &&
43940b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
43950b57cec5SDimitry Andric                                            GD.getDtorType()))
43960b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
43970b57cec5SDimitry Andric 
43980b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
43990b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
44000b57cec5SDimitry Andric     // of the file.
44010b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
44020b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
44030b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
44040b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
44050b57cec5SDimitry Andric       // don't need it anymore).
44060b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
44070b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
44080b57cec5SDimitry Andric 
44090b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
44100b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
44110b57cec5SDimitry Andric       // we might not find a top-level definition:
44120b57cec5SDimitry Andric       //   - member functions defined inline in their classes
44130b57cec5SDimitry Andric       //   - friend functions defined inline in some class
44140b57cec5SDimitry Andric       //   - special member functions with implicit definitions
44150b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
44160b57cec5SDimitry Andric       // this will be unnecessary.
44170b57cec5SDimitry Andric       //
44180b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
44190b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
44200b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
44210b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
44220b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
44230b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
44240b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
44250b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
44260b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
44270b57cec5SDimitry Andric             break;
44280b57cec5SDimitry Andric           }
44290b57cec5SDimitry Andric         }
44300b57cec5SDimitry Andric       }
44310b57cec5SDimitry Andric     }
44320b57cec5SDimitry Andric   }
44330b57cec5SDimitry Andric 
44340b57cec5SDimitry Andric   // Make sure the result is of the requested type.
44350b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
44365ffd83dbSDimitry Andric     assert(F->getFunctionType() == Ty);
44370b57cec5SDimitry Andric     return F;
44380b57cec5SDimitry Andric   }
44390b57cec5SDimitry Andric 
4440bdd1243dSDimitry Andric   return llvm::ConstantExpr::getBitCast(F,
4441bdd1243dSDimitry Andric                                         Ty->getPointerTo(F->getAddressSpace()));
44420b57cec5SDimitry Andric }
44430b57cec5SDimitry Andric 
44440b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
44450b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
44460b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
444706c3fb27SDimitry Andric llvm::Constant *
444806c3fb27SDimitry Andric CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
44490b57cec5SDimitry Andric                                  bool DontDefer,
44500b57cec5SDimitry Andric                                  ForDefinition_t IsForDefinition) {
44510b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
44520b57cec5SDimitry Andric   if (!Ty) {
44530b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
44540b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
44550b57cec5SDimitry Andric   }
44560b57cec5SDimitry Andric 
44570b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
44580b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
44590b57cec5SDimitry Andric   // of the complete destructor when necessary.
44600b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
44610b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
44620b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
44630b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
44640b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
44650b57cec5SDimitry Andric   }
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
4468fe6060f1SDimitry Andric   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
44690b57cec5SDimitry Andric                                     /*IsThunk=*/false, llvm::AttributeList(),
44700b57cec5SDimitry Andric                                     IsForDefinition);
4471fe6060f1SDimitry Andric   // Returns kernel handle for HIP kernel stub function.
4472fe6060f1SDimitry Andric   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4473fe6060f1SDimitry Andric       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4474fe6060f1SDimitry Andric     auto *Handle = getCUDARuntime().getKernelHandle(
4475fe6060f1SDimitry Andric         cast<llvm::Function>(F->stripPointerCasts()), GD);
4476fe6060f1SDimitry Andric     if (IsForDefinition)
4477fe6060f1SDimitry Andric       return F;
4478fe6060f1SDimitry Andric     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
4479fe6060f1SDimitry Andric   }
4480fe6060f1SDimitry Andric   return F;
44810b57cec5SDimitry Andric }
44820b57cec5SDimitry Andric 
44830eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
44840eae32dcSDimitry Andric   llvm::GlobalValue *F =
44850eae32dcSDimitry Andric       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
44860eae32dcSDimitry Andric 
4487bdd1243dSDimitry Andric   return llvm::ConstantExpr::getBitCast(
4488bdd1243dSDimitry Andric       llvm::NoCFIValue::get(F),
4489bdd1243dSDimitry Andric       llvm::Type::getInt8PtrTy(VMContext, F->getAddressSpace()));
44900eae32dcSDimitry Andric }
44910eae32dcSDimitry Andric 
44920b57cec5SDimitry Andric static const FunctionDecl *
44930b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
44940b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
44950b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
44960b57cec5SDimitry Andric 
44970b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
4498fe6060f1SDimitry Andric   for (const auto *Result : DC->lookup(&CII))
4499fe6060f1SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
45000b57cec5SDimitry Andric       return FD;
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
45030b57cec5SDimitry Andric     return nullptr;
45040b57cec5SDimitry Andric 
45050b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
45060b57cec5SDimitry Andric   IdentifierInfo &CXXII =
45070b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
45080b57cec5SDimitry Andric           ? C.Idents.get("terminate")
45090b57cec5SDimitry Andric           : C.Idents.get(Name);
45100b57cec5SDimitry Andric 
45110b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
45120b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
4513fe6060f1SDimitry Andric     for (const auto *Result : DC->lookup(&NS)) {
4514fe6060f1SDimitry Andric       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4515fe6060f1SDimitry Andric       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4516fe6060f1SDimitry Andric         for (const auto *Result : LSD->lookup(&NS))
45170b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
45180b57cec5SDimitry Andric             break;
45190b57cec5SDimitry Andric 
45200b57cec5SDimitry Andric       if (ND)
4521fe6060f1SDimitry Andric         for (const auto *Result : ND->lookup(&CXXII))
45220b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
45230b57cec5SDimitry Andric             return FD;
45240b57cec5SDimitry Andric     }
45250b57cec5SDimitry Andric   }
45260b57cec5SDimitry Andric 
45270b57cec5SDimitry Andric   return nullptr;
45280b57cec5SDimitry Andric }
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
45310b57cec5SDimitry Andric /// type and name.
45320b57cec5SDimitry Andric llvm::FunctionCallee
45330b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4534480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
4535480093f4SDimitry Andric                                      bool AssumeConvergent) {
4536480093f4SDimitry Andric   if (AssumeConvergent) {
4537480093f4SDimitry Andric     ExtraAttrs =
4538349cc55cSDimitry Andric         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4539480093f4SDimitry Andric   }
4540480093f4SDimitry Andric 
45410b57cec5SDimitry Andric   llvm::Constant *C =
45420b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
45430b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
45440b57cec5SDimitry Andric                               ExtraAttrs);
45450b57cec5SDimitry Andric 
45460b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
45470b57cec5SDimitry Andric     if (F->empty()) {
45480b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
45490b57cec5SDimitry Andric 
45500b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
45510b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
45520b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
45530b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
45540b57cec5SDimitry Andric       // and warnings.
45550b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
45560b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
45570b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
45580b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
45590b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
45600b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
45610b57cec5SDimitry Andric         }
45620b57cec5SDimitry Andric       }
45630b57cec5SDimitry Andric       setDSOLocal(F);
45640b57cec5SDimitry Andric     }
45650b57cec5SDimitry Andric   }
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric   return {FTy, C};
45680b57cec5SDimitry Andric }
45690b57cec5SDimitry Andric 
45700b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
45710b57cec5SDimitry Andric /// as a constant.
45720b57cec5SDimitry Andric ///
45730b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
45740b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is
457506c3fb27SDimitry Andric /// not written to during its construction. ExcludeDtor works similarly.
457606c3fb27SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor,
457706c3fb27SDimitry Andric                                    bool ExcludeDtor) {
45780b57cec5SDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
45790b57cec5SDimitry Andric     return false;
45800b57cec5SDimitry Andric 
45810b57cec5SDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
45820b57cec5SDimitry Andric     if (const CXXRecordDecl *Record
45830b57cec5SDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
45840b57cec5SDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
458506c3fb27SDimitry Andric              (Record->hasTrivialDestructor() || ExcludeDtor);
45860b57cec5SDimitry Andric   }
45870b57cec5SDimitry Andric 
45880b57cec5SDimitry Andric   return true;
45890b57cec5SDimitry Andric }
45900b57cec5SDimitry Andric 
45910b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4592fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address
4593fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return
4594fe6060f1SDimitry Andric /// it potentially bitcasted to the right type.
45950b57cec5SDimitry Andric ///
45960b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
45970b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
45980b57cec5SDimitry Andric ///
45990b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
46000b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
46010b57cec5SDimitry Andric /// mangled name but some other type.
46020b57cec5SDimitry Andric llvm::Constant *
4603fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4604349cc55cSDimitry Andric                                      LangAS AddrSpace, const VarDecl *D,
46050b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
46060b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
46070b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4608349cc55cSDimitry Andric   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
46090b57cec5SDimitry Andric   if (Entry) {
46100b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
46110b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
46120b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
46130b57cec5SDimitry Andric     }
46140b57cec5SDimitry Andric 
46150b57cec5SDimitry Andric     // Handle dropped DLL attributes.
461681ad6265SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
461781ad6265SDimitry Andric         !shouldMapVisibilityToDLLExport(D))
46180b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
46190b57cec5SDimitry Andric 
46200b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
46210b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
46220b57cec5SDimitry Andric 
4623349cc55cSDimitry Andric     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
46240b57cec5SDimitry Andric       return Entry;
46250b57cec5SDimitry Andric 
46260b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
46270b57cec5SDimitry Andric     // error.
46280b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
46290b57cec5SDimitry Andric       GlobalDecl OtherGD;
46300b57cec5SDimitry Andric       const VarDecl *OtherD;
46310b57cec5SDimitry Andric 
46320b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
46330b57cec5SDimitry Andric       // to make sure that we issue an error only once.
46340b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
46350b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
46360b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
46370b57cec5SDimitry Andric           OtherD->hasInit() &&
46380b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
46390b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
46400b57cec5SDimitry Andric             << MangledName;
46410b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
46420b57cec5SDimitry Andric                           diag::note_previous_definition);
46430b57cec5SDimitry Andric       }
46440b57cec5SDimitry Andric     }
46450b57cec5SDimitry Andric 
46460b57cec5SDimitry Andric     // Make sure the result is of the correct type.
4647349cc55cSDimitry Andric     if (Entry->getType()->getAddressSpace() != TargetAS) {
4648fe6060f1SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4649349cc55cSDimitry Andric                                                   Ty->getPointerTo(TargetAS));
4650fe6060f1SDimitry Andric     }
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
46530b57cec5SDimitry Andric     // global, not just return a bitcast.)
46540b57cec5SDimitry Andric     if (!IsForDefinition)
4655349cc55cSDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
46560b57cec5SDimitry Andric   }
46570b57cec5SDimitry Andric 
4658fe6060f1SDimitry Andric   auto DAddrSpace = GetGlobalVarAddressSpace(D);
46590b57cec5SDimitry Andric 
46600b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
4661fe6060f1SDimitry Andric       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4662fe6060f1SDimitry Andric       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4663349cc55cSDimitry Andric       getContext().getTargetAddressSpace(DAddrSpace));
46640b57cec5SDimitry Andric 
46650b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
46660b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
46670b57cec5SDimitry Andric   if (Entry) {
46680b57cec5SDimitry Andric     GV->takeName(Entry);
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric     if (!Entry->use_empty()) {
46710b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
46720b57cec5SDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
46730b57cec5SDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
46740b57cec5SDimitry Andric     }
46750b57cec5SDimitry Andric 
46760b57cec5SDimitry Andric     Entry->eraseFromParent();
46770b57cec5SDimitry Andric   }
46780b57cec5SDimitry Andric 
46790b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
46800b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
46810b57cec5SDimitry Andric   // of the file.
46820b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
46830b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
46840b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
46850b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
46860b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
46870b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
46880b57cec5SDimitry Andric   }
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
46910b57cec5SDimitry Andric   if (D) {
46920b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
46930b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
46940b57cec5SDimitry Andric 
46950b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
46960b57cec5SDimitry Andric     // handling.
469706c3fb27SDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false, false));
46980b57cec5SDimitry Andric 
4699a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
47000b57cec5SDimitry Andric 
47010b57cec5SDimitry Andric     setLinkageForGV(GV, D);
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric     if (D->getTLSKind()) {
47040b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
47050b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
47060b57cec5SDimitry Andric       setTLSMode(GV, *D);
47070b57cec5SDimitry Andric     }
47080b57cec5SDimitry Andric 
47090b57cec5SDimitry Andric     setGVProperties(GV, D);
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
47120b57cec5SDimitry Andric     // inline initializers as definitions.
47130b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
47140b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
47150b57cec5SDimitry Andric     }
47160b57cec5SDimitry Andric 
47170b57cec5SDimitry Andric     // Emit section information for extern variables.
47180b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
47190b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
47200b57cec5SDimitry Andric         GV->setSection(SA->getName());
47210b57cec5SDimitry Andric     }
47220b57cec5SDimitry Andric 
47230b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
47240b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
47250b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
47260b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
47270b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
47280b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
47290b57cec5SDimitry Andric 
47300b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
47310b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
47320b57cec5SDimitry Andric     // optimizer.
47330b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
47340b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
47350b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
47360b57cec5SDimitry Andric       const auto *Record =
47370b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
47380b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
47390b57cec5SDimitry Andric       if (!HasMutableFields) {
47400b57cec5SDimitry Andric         const VarDecl *InitDecl;
47410b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
47420b57cec5SDimitry Andric         if (InitExpr) {
47430b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
47440b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
47450b57cec5SDimitry Andric           if (Init) {
47460b57cec5SDimitry Andric             auto *InitType = Init->getType();
47475ffd83dbSDimitry Andric             if (GV->getValueType() != InitType) {
47480b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
47490b57cec5SDimitry Andric               // This happens when an initializer has a different type from
47500b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
47510b57cec5SDimitry Andric               // structure for instance).
47520b57cec5SDimitry Andric               GV->setName(StringRef());
47530b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
47540b57cec5SDimitry Andric               // to work.
47550b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
4756a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4757a7dea167SDimitry Andric                       ->stripPointerCasts());
47580b57cec5SDimitry Andric 
47590b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
47600b57cec5SDimitry Andric               GV->eraseFromParent();
47610b57cec5SDimitry Andric               GV = NewGV;
47620b57cec5SDimitry Andric             } else {
47630b57cec5SDimitry Andric               GV->setInitializer(Init);
47640b57cec5SDimitry Andric               GV->setConstant(true);
47650b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
47660b57cec5SDimitry Andric             }
47670b57cec5SDimitry Andric             emitter.finalize(GV);
47680b57cec5SDimitry Andric           }
47690b57cec5SDimitry Andric         }
47700b57cec5SDimitry Andric       }
47710b57cec5SDimitry Andric     }
47720b57cec5SDimitry Andric   }
47730b57cec5SDimitry Andric 
477406c3fb27SDimitry Andric   if (D &&
477506c3fb27SDimitry Andric       D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
4776480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4777fe6060f1SDimitry Andric     // External HIP managed variables needed to be recorded for transformation
4778fe6060f1SDimitry Andric     // in both device and host compilations.
4779fe6060f1SDimitry Andric     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4780fe6060f1SDimitry Andric         D->hasExternalStorage())
4781fe6060f1SDimitry Andric       getCUDARuntime().handleVarRegistration(D, *GV);
4782fe6060f1SDimitry Andric   }
4783480093f4SDimitry Andric 
4784753f127fSDimitry Andric   if (D)
4785753f127fSDimitry Andric     SanitizerMD->reportGlobal(GV, *D);
4786753f127fSDimitry Andric 
47870b57cec5SDimitry Andric   LangAS ExpectedAS =
47880b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
47890b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4790349cc55cSDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4791fe6060f1SDimitry Andric   if (DAddrSpace != ExpectedAS) {
4792fe6060f1SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(
4793349cc55cSDimitry Andric         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4794fe6060f1SDimitry Andric   }
47950b57cec5SDimitry Andric 
47960b57cec5SDimitry Andric   return GV;
47970b57cec5SDimitry Andric }
47980b57cec5SDimitry Andric 
47990b57cec5SDimitry Andric llvm::Constant *
48005ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
48010b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
48025ffd83dbSDimitry Andric 
48030b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
48040b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
48050b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
48065ffd83dbSDimitry Andric 
48075ffd83dbSDimitry Andric   if (isa<CXXMethodDecl>(D)) {
48085ffd83dbSDimitry Andric     auto FInfo =
48095ffd83dbSDimitry Andric         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
48100b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
48110b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
48120b57cec5SDimitry Andric                              IsForDefinition);
48135ffd83dbSDimitry Andric   }
48145ffd83dbSDimitry Andric 
48155ffd83dbSDimitry Andric   if (isa<FunctionDecl>(D)) {
48160b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
48170b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
48180b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
48190b57cec5SDimitry Andric                              IsForDefinition);
48205ffd83dbSDimitry Andric   }
48215ffd83dbSDimitry Andric 
48225ffd83dbSDimitry Andric   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
48230b57cec5SDimitry Andric }
48240b57cec5SDimitry Andric 
48250b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
48260b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4827bdd1243dSDimitry Andric     llvm::Align Alignment) {
48280b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
48290b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
48300b57cec5SDimitry Andric 
48310b57cec5SDimitry Andric   if (GV) {
48320b57cec5SDimitry Andric     // Check if the variable has the right type.
48335ffd83dbSDimitry Andric     if (GV->getValueType() == Ty)
48340b57cec5SDimitry Andric       return GV;
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
48370b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
48380b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
48390b57cec5SDimitry Andric     OldGV = GV;
48400b57cec5SDimitry Andric   }
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric   // Create a new variable.
48430b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
48440b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
48450b57cec5SDimitry Andric 
48460b57cec5SDimitry Andric   if (OldGV) {
48470b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
48480b57cec5SDimitry Andric     GV->takeName(OldGV);
48490b57cec5SDimitry Andric 
48500b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
48510b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
48520b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
48530b57cec5SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
48540b57cec5SDimitry Andric     }
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric     OldGV->eraseFromParent();
48570b57cec5SDimitry Andric   }
48580b57cec5SDimitry Andric 
48590b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
48600b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
48610b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
48620b57cec5SDimitry Andric 
4863bdd1243dSDimitry Andric   GV->setAlignment(Alignment);
48640b57cec5SDimitry Andric 
48650b57cec5SDimitry Andric   return GV;
48660b57cec5SDimitry Andric }
48670b57cec5SDimitry Andric 
48680b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
48690b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
48700b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
48710b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
48720b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
48730b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
48740b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
48750b57cec5SDimitry Andric                                                   llvm::Type *Ty,
48760b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
48770b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
48780b57cec5SDimitry Andric   QualType ASTTy = D->getType();
48790b57cec5SDimitry Andric   if (!Ty)
48800b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
48810b57cec5SDimitry Andric 
48820b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
4883349cc55cSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4884fe6060f1SDimitry Andric                                IsForDefinition);
48850b57cec5SDimitry Andric }
48860b57cec5SDimitry Andric 
48870b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
48880b57cec5SDimitry Andric /// specified type and name.
48890b57cec5SDimitry Andric llvm::Constant *
48900b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
48910b57cec5SDimitry Andric                                      StringRef Name) {
4892349cc55cSDimitry Andric   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4893349cc55cSDimitry Andric                                                        : LangAS::Default;
4894fe6060f1SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
48950b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
48960b57cec5SDimitry Andric   return Ret;
48970b57cec5SDimitry Andric }
48980b57cec5SDimitry Andric 
48990b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
49000b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
49010b57cec5SDimitry Andric 
49020b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
49030b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
49040b57cec5SDimitry Andric 
49050b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
49060b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
49070b57cec5SDimitry Andric   // definition).
49080b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
49090b57cec5SDimitry Andric     return;
49100b57cec5SDimitry Andric 
49110b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
49120b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
49130b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
49140b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
49150b57cec5SDimitry Andric       return;
49160b57cec5SDimitry Andric   }
49170b57cec5SDimitry Andric 
49180b57cec5SDimitry Andric   // The tentative definition is the only definition.
49190b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
49200b57cec5SDimitry Andric }
49210b57cec5SDimitry Andric 
4922480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4923480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
4924480093f4SDimitry Andric }
4925480093f4SDimitry Andric 
49260b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
49270b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
49280b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
49290b57cec5SDimitry Andric }
49300b57cec5SDimitry Andric 
49310b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
49320b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
4933349cc55cSDimitry Andric     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4934349cc55cSDimitry Andric     assert(AS == LangAS::opencl_global ||
4935349cc55cSDimitry Andric            AS == LangAS::opencl_global_device ||
4936349cc55cSDimitry Andric            AS == LangAS::opencl_global_host ||
4937349cc55cSDimitry Andric            AS == LangAS::opencl_constant ||
4938349cc55cSDimitry Andric            AS == LangAS::opencl_local ||
4939349cc55cSDimitry Andric            AS >= LangAS::FirstTargetAddressSpace);
4940349cc55cSDimitry Andric     return AS;
49410b57cec5SDimitry Andric   }
49420b57cec5SDimitry Andric 
4943fe6060f1SDimitry Andric   if (LangOpts.SYCLIsDevice &&
4944fe6060f1SDimitry Andric       (!D || D->getType().getAddressSpace() == LangAS::Default))
4945fe6060f1SDimitry Andric     return LangAS::sycl_global;
4946fe6060f1SDimitry Andric 
49470b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
494806c3fb27SDimitry Andric     if (D) {
494906c3fb27SDimitry Andric       if (D->hasAttr<CUDAConstantAttr>())
49500b57cec5SDimitry Andric         return LangAS::cuda_constant;
495106c3fb27SDimitry Andric       if (D->hasAttr<CUDASharedAttr>())
49520b57cec5SDimitry Andric         return LangAS::cuda_shared;
495306c3fb27SDimitry Andric       if (D->hasAttr<CUDADeviceAttr>())
49540b57cec5SDimitry Andric         return LangAS::cuda_device;
495506c3fb27SDimitry Andric       if (D->getType().isConstQualified())
49560b57cec5SDimitry Andric         return LangAS::cuda_constant;
495706c3fb27SDimitry Andric     }
49580b57cec5SDimitry Andric     return LangAS::cuda_device;
49590b57cec5SDimitry Andric   }
49600b57cec5SDimitry Andric 
49610b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
49620b57cec5SDimitry Andric     LangAS AS;
49630b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
49640b57cec5SDimitry Andric       return AS;
49650b57cec5SDimitry Andric   }
49660b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
49670b57cec5SDimitry Andric }
49680b57cec5SDimitry Andric 
4969fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
49700b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
49710b57cec5SDimitry Andric   if (LangOpts.OpenCL)
49720b57cec5SDimitry Andric     return LangAS::opencl_constant;
4973fe6060f1SDimitry Andric   if (LangOpts.SYCLIsDevice)
4974fe6060f1SDimitry Andric     return LangAS::sycl_global;
4975d56accc7SDimitry Andric   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4976d56accc7SDimitry Andric     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4977d56accc7SDimitry Andric     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4978d56accc7SDimitry Andric     // with OpVariable instructions with Generic storage class which is not
4979d56accc7SDimitry Andric     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4980d56accc7SDimitry Andric     // UniformConstant storage class is not viable as pointers to it may not be
4981d56accc7SDimitry Andric     // casted to Generic pointers which are used to model HIP's "flat" pointers.
4982d56accc7SDimitry Andric     return LangAS::cuda_device;
49830b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
498481ad6265SDimitry Andric     return *AS;
49850b57cec5SDimitry Andric   return LangAS::Default;
49860b57cec5SDimitry Andric }
49870b57cec5SDimitry Andric 
49880b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
49890b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
49900b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
49910b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
49920b57cec5SDimitry Andric // need to be casted to default address space before being put into address
49930b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
49940b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
49950b57cec5SDimitry Andric // they should not be casted to default address space.
49960b57cec5SDimitry Andric static llvm::Constant *
49970b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
49980b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
49990b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
50000b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
5001fe6060f1SDimitry Andric     auto AS = CGM.GetGlobalConstantAddressSpace();
50020b57cec5SDimitry Andric     if (AS != LangAS::Default)
50030b57cec5SDimitry Andric       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
5004fe6060f1SDimitry Andric           CGM, GV, AS, LangAS::Default,
50050b57cec5SDimitry Andric           GV->getValueType()->getPointerTo(
50060b57cec5SDimitry Andric               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
50070b57cec5SDimitry Andric   }
50080b57cec5SDimitry Andric   return Cast;
50090b57cec5SDimitry Andric }
50100b57cec5SDimitry Andric 
50110b57cec5SDimitry Andric template<typename SomeDecl>
50120b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
50130b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
50140b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
50150b57cec5SDimitry Andric     return;
50160b57cec5SDimitry Andric 
50170b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
50180b57cec5SDimitry Andric   // the name existing.
50190b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
50200b57cec5SDimitry Andric     return;
50210b57cec5SDimitry Andric 
50220b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
50230b57cec5SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
50240b57cec5SDimitry Andric     return;
50250b57cec5SDimitry Andric 
50260b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
50270b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
50280b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
50290b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
50300b57cec5SDimitry Andric     return;
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
50330b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
50340b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
50350b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
50360b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
50370b57cec5SDimitry Andric 
50380b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
50390b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
50400b57cec5SDimitry Andric   if (!R.second)
50410b57cec5SDimitry Andric     R.first->second = nullptr;
50420b57cec5SDimitry Andric }
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
50450b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
50460b57cec5SDimitry Andric     return false;
50470b57cec5SDimitry Andric 
50480b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
50490b57cec5SDimitry Andric     return true;
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric   GVALinkage Linkage;
50520b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
50530b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
50540b57cec5SDimitry Andric   else
50550b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
50560b57cec5SDimitry Andric 
50570b57cec5SDimitry Andric   switch (Linkage) {
50580b57cec5SDimitry Andric   case GVA_Internal:
50590b57cec5SDimitry Andric   case GVA_AvailableExternally:
50600b57cec5SDimitry Andric   case GVA_StrongExternal:
50610b57cec5SDimitry Andric     return false;
50620b57cec5SDimitry Andric   case GVA_DiscardableODR:
50630b57cec5SDimitry Andric   case GVA_StrongODR:
50640b57cec5SDimitry Andric     return true;
50650b57cec5SDimitry Andric   }
50660b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
50670b57cec5SDimitry Andric }
50680b57cec5SDimitry Andric 
506906c3fb27SDimitry Andric bool CodeGenModule::supportsCOMDAT() const {
507006c3fb27SDimitry Andric   return getTriple().supportsCOMDAT();
507106c3fb27SDimitry Andric }
507206c3fb27SDimitry Andric 
50730b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
50740b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
50750b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
50760b57cec5SDimitry Andric     return;
50770b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
50780b57cec5SDimitry Andric }
50790b57cec5SDimitry Andric 
50800b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
50810b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
50820b57cec5SDimitry Andric                                             bool IsTentative) {
50830b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
50840b57cec5SDimitry Andric   // therefore no need to be translated.
50850b57cec5SDimitry Andric   QualType ASTTy = D->getType();
50860b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
50870b57cec5SDimitry Andric     return;
50880b57cec5SDimitry Andric 
50890b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
50900b57cec5SDimitry Andric   // normally.
509106c3fb27SDimitry Andric   if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
50920b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
50930b57cec5SDimitry Andric     return;
50940b57cec5SDimitry Andric 
5095fe6060f1SDimitry Andric   llvm::TrackingVH<llvm::Constant> Init;
50960b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
5097bdd1243dSDimitry Andric   // Whether the definition of the variable is available externally.
5098bdd1243dSDimitry Andric   // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5099bdd1243dSDimitry Andric   // since this is the job for its original source.
5100bdd1243dSDimitry Andric   bool IsDefinitionAvailableExternally =
5101bdd1243dSDimitry Andric       getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5102a7dea167SDimitry Andric   bool NeedsGlobalDtor =
5103bdd1243dSDimitry Andric       !IsDefinitionAvailableExternally &&
5104a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
51050b57cec5SDimitry Andric 
51060b57cec5SDimitry Andric   const VarDecl *InitDecl;
51070b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
51080b57cec5SDimitry Andric 
5109bdd1243dSDimitry Andric   std::optional<ConstantEmitter> emitter;
51100b57cec5SDimitry Andric 
51110b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
51120b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
51130b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
51140b57cec5SDimitry Andric   bool IsCUDASharedVar =
51150b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
51160b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
51170b57cec5SDimitry Andric   // undefined.
5118fe6060f1SDimitry Andric   // Managed Variables should be initialized on both host side and device side.
51190b57cec5SDimitry Andric   bool IsCUDAShadowVar =
5120e8d8bef9SDimitry Andric       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
51210b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
51220b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
51235ffd83dbSDimitry Andric   bool IsCUDADeviceShadowVar =
5124fe6060f1SDimitry Andric       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
51255ffd83dbSDimitry Andric       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5126fe6060f1SDimitry Andric        D->getType()->isCUDADeviceBuiltinTextureType());
51270b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
51285ffd83dbSDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5129fe6060f1SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
51305ffd83dbSDimitry Andric   else if (D->hasAttr<LoaderUninitializedAttr>())
5131fe6060f1SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
51320b57cec5SDimitry Andric   else if (!InitExpr) {
51330b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
51340b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
51350b57cec5SDimitry Andric     //
51360b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
51370b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
51380b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
51390b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
51400b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
51410b57cec5SDimitry Andric     // to do a RAUW.
51420b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
51430b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
51440b57cec5SDimitry Andric   } else {
51450b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
51460b57cec5SDimitry Andric     emitter.emplace(*this);
5147fe6060f1SDimitry Andric     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5148fe6060f1SDimitry Andric     if (!Initializer) {
51490b57cec5SDimitry Andric       QualType T = InitExpr->getType();
51500b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
51510b57cec5SDimitry Andric         T = D->getType();
51520b57cec5SDimitry Andric 
51530b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
515481ad6265SDimitry Andric         if (InitDecl->hasFlexibleArrayInit(getContext()))
515581ad6265SDimitry Andric           ErrorUnsupported(D, "flexible array initializer");
51560b57cec5SDimitry Andric         Init = EmitNullConstant(T);
5157bdd1243dSDimitry Andric 
5158bdd1243dSDimitry Andric         if (!IsDefinitionAvailableExternally)
51590b57cec5SDimitry Andric           NeedsGlobalCtor = true;
51600b57cec5SDimitry Andric       } else {
51610b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
51620b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
51630b57cec5SDimitry Andric       }
51640b57cec5SDimitry Andric     } else {
5165fe6060f1SDimitry Andric       Init = Initializer;
51660b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
51670b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
51680b57cec5SDimitry Andric       // also don't need to register a destructor.
51690b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
51700b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
517181ad6265SDimitry Andric 
517281ad6265SDimitry Andric #ifndef NDEBUG
517381ad6265SDimitry Andric       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
517481ad6265SDimitry Andric                           InitDecl->getFlexibleArrayInitChars(getContext());
517581ad6265SDimitry Andric       CharUnits CstSize = CharUnits::fromQuantity(
517681ad6265SDimitry Andric           getDataLayout().getTypeAllocSize(Init->getType()));
517781ad6265SDimitry Andric       assert(VarSize == CstSize && "Emitted constant has unexpected size");
517881ad6265SDimitry Andric #endif
51790b57cec5SDimitry Andric     }
51800b57cec5SDimitry Andric   }
51810b57cec5SDimitry Andric 
51820b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
51830b57cec5SDimitry Andric   llvm::Constant *Entry =
51840b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
51850b57cec5SDimitry Andric 
5186a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
5187a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
51880b57cec5SDimitry Andric 
51890b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
51900b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
51910b57cec5SDimitry Andric 
51920b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
51930b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
51940b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
51950b57cec5SDimitry Andric   // (which will be a definition).
51960b57cec5SDimitry Andric   //
51970b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
51980b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
51990b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
52000b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
52015ffd83dbSDimitry Andric   if (!GV || GV->getValueType() != InitType ||
52020b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
52030b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
52040b57cec5SDimitry Andric 
52050b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
52060b57cec5SDimitry Andric     Entry->setName(StringRef());
52070b57cec5SDimitry Andric 
52080b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
52090b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
5210a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5211a7dea167SDimitry Andric             ->stripPointerCasts());
52120b57cec5SDimitry Andric 
52130b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
52140b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
5215fe6060f1SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5216fe6060f1SDimitry Andric                                                              Entry->getType());
52170b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
52180b57cec5SDimitry Andric 
52190b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
52200b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
52210b57cec5SDimitry Andric   }
52220b57cec5SDimitry Andric 
52230b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
52240b57cec5SDimitry Andric 
52250b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
52260b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
52270b57cec5SDimitry Andric 
52280b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
5229*8a4dda33SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
52300b57cec5SDimitry Andric 
52310b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
52320b57cec5SDimitry Andric   // the device. [...]"
52330b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
52340b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
52350b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
52360b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
52370b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
523806c3fb27SDimitry Andric   if (LangOpts.CUDA) {
52390b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
52400b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
5241349cc55cSDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5242349cc55cSDimitry Andric            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5243349cc55cSDimitry Andric            D->getType()->isCUDADeviceBuiltinTextureType()))
52440b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
52450b57cec5SDimitry Andric     } else {
5246fe6060f1SDimitry Andric       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
52475ffd83dbSDimitry Andric     }
5248fe6060f1SDimitry Andric     getCUDARuntime().handleVarRegistration(D, *GV);
52490b57cec5SDimitry Andric   }
52500b57cec5SDimitry Andric 
52510b57cec5SDimitry Andric   GV->setInitializer(Init);
52525ffd83dbSDimitry Andric   if (emitter)
52535ffd83dbSDimitry Andric     emitter->finalize(GV);
52540b57cec5SDimitry Andric 
52550b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
52560b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
525706c3fb27SDimitry Andric                   isTypeConstant(D->getType(), true, true));
52580b57cec5SDimitry Andric 
52590b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
52600b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
52610b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
52620b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
52630b57cec5SDimitry Andric       GV->setConstant(true);
52640b57cec5SDimitry Andric   }
52650b57cec5SDimitry Andric 
526681ad6265SDimitry Andric   CharUnits AlignVal = getContext().getDeclAlign(D);
526781ad6265SDimitry Andric   // Check for alignment specifed in an 'omp allocate' directive.
5268bdd1243dSDimitry Andric   if (std::optional<CharUnits> AlignValFromAllocate =
526981ad6265SDimitry Andric           getOMPAllocateAlignment(D))
527081ad6265SDimitry Andric     AlignVal = *AlignValFromAllocate;
527181ad6265SDimitry Andric   GV->setAlignment(AlignVal.getAsAlign());
52720b57cec5SDimitry Andric 
52735ffd83dbSDimitry Andric   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
52745ffd83dbSDimitry Andric   // function is only defined alongside the variable, not also alongside
52755ffd83dbSDimitry Andric   // callers. Normally, all accesses to a thread_local go through the
52765ffd83dbSDimitry Andric   // thread-wrapper in order to ensure initialization has occurred, underlying
52775ffd83dbSDimitry Andric   // variable will never be used other than the thread-wrapper, so it can be
52785ffd83dbSDimitry Andric   // converted to internal linkage.
52795ffd83dbSDimitry Andric   //
52805ffd83dbSDimitry Andric   // However, if the variable has the 'constinit' attribute, it _can_ be
52815ffd83dbSDimitry Andric   // referenced directly, without calling the thread-wrapper, so the linkage
52825ffd83dbSDimitry Andric   // must not be changed.
52835ffd83dbSDimitry Andric   //
52845ffd83dbSDimitry Andric   // Additionally, if the variable isn't plain external linkage, e.g. if it's
52855ffd83dbSDimitry Andric   // weak or linkonce, the de-duplication semantics are important to preserve,
52865ffd83dbSDimitry Andric   // so we don't change the linkage.
52875ffd83dbSDimitry Andric   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
52885ffd83dbSDimitry Andric       Linkage == llvm::GlobalValue::ExternalLinkage &&
52890b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
52905ffd83dbSDimitry Andric       !D->hasAttr<ConstInitAttr>())
52910b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
52920b57cec5SDimitry Andric 
52930b57cec5SDimitry Andric   GV->setLinkage(Linkage);
52940b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
52950b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
52960b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
52970b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
52980b57cec5SDimitry Andric   else
52990b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
53000b57cec5SDimitry Andric 
53010b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
53020b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
53030b57cec5SDimitry Andric     GV->setConstant(false);
53040b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
53050b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
53060b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
53070b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
53080b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
53090b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
53100b57cec5SDimitry Andric   }
53110b57cec5SDimitry Andric 
53120b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
53130b57cec5SDimitry Andric 
53140b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
53150b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
53160b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
53170b57cec5SDimitry Andric     setTLSMode(GV, *D);
53180b57cec5SDimitry Andric   }
53190b57cec5SDimitry Andric 
53200b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
53210b57cec5SDimitry Andric 
53220b57cec5SDimitry Andric   // Emit the initializer function if necessary.
53230b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
53240b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
53250b57cec5SDimitry Andric 
532681ad6265SDimitry Andric   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
53270b57cec5SDimitry Andric 
53280b57cec5SDimitry Andric   // Emit global variable debug information.
53290b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
5330480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
53310b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
53320b57cec5SDimitry Andric }
53330b57cec5SDimitry Andric 
5334480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5335480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
5336480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
5337480093f4SDimitry Andric       QualType ASTTy = D->getType();
5338480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5339349cc55cSDimitry Andric       llvm::Constant *GV =
5340349cc55cSDimitry Andric           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5341480093f4SDimitry Andric       DI->EmitExternalVariable(
5342480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5343480093f4SDimitry Andric     }
5344480093f4SDimitry Andric }
5345480093f4SDimitry Andric 
53460b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
53470b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
53480b57cec5SDimitry Andric                                       bool NoCommon) {
53490b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
53500b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
53510b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
53520b57cec5SDimitry Andric     return true;
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric   // C11 6.9.2/2:
53550b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
53560b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
53570b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
53580b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
53590b57cec5SDimitry Andric     return true;
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
53620b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
53630b57cec5SDimitry Andric     return true;
53640b57cec5SDimitry Andric 
53650b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
53660b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
53670b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
53680b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
53690b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
5370a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
53710b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
53720b57cec5SDimitry Andric     return true;
53730b57cec5SDimitry Andric 
53740b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
53750b57cec5SDimitry Andric   if (D->getTLSKind())
53760b57cec5SDimitry Andric     return true;
53770b57cec5SDimitry Andric 
53780b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
53790b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
53800b57cec5SDimitry Andric     return true;
53810b57cec5SDimitry Andric 
53820b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
53830b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
53840b57cec5SDimitry Andric     return true;
53850b57cec5SDimitry Andric 
53860b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
53870b57cec5SDimitry Andric   // mode.
53880b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
53890b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
53900b57cec5SDimitry Andric       return true;
53910b57cec5SDimitry Andric     QualType VarType = D->getType();
53920b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
53930b57cec5SDimitry Andric       return true;
53940b57cec5SDimitry Andric 
53950b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
53960b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
53970b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
53980b57cec5SDimitry Andric         if (FD->isBitField())
53990b57cec5SDimitry Andric           continue;
54000b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
54010b57cec5SDimitry Andric           return true;
54020b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
54030b57cec5SDimitry Andric           return true;
54040b57cec5SDimitry Andric       }
54050b57cec5SDimitry Andric     }
54060b57cec5SDimitry Andric   }
54070b57cec5SDimitry Andric 
54080b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
54090b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
54100b57cec5SDimitry Andric   // common.
54110b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
54120b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
54130b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
54140b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
54150b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
54160b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
54170b57cec5SDimitry Andric     return true;
54180b57cec5SDimitry Andric 
54190b57cec5SDimitry Andric   return false;
54200b57cec5SDimitry Andric }
54210b57cec5SDimitry Andric 
5422*8a4dda33SDimitry Andric llvm::GlobalValue::LinkageTypes
5423*8a4dda33SDimitry Andric CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
5424*8a4dda33SDimitry Andric                                            GVALinkage Linkage) {
54250b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
54260b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
54270b57cec5SDimitry Andric 
542881ad6265SDimitry Andric   if (D->hasAttr<WeakAttr>())
54290b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakAnyLinkage;
54300b57cec5SDimitry Andric 
54310b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
54320b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
54330b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
54340b57cec5SDimitry Andric 
54350b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
54360b57cec5SDimitry Andric   // so we can use available_externally linkage.
54370b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
54380b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
54390b57cec5SDimitry Andric 
54400b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
54410b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
54420b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
54430b57cec5SDimitry Andric   // instantiations we'll map to external.
54440b57cec5SDimitry Andric 
54450b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
54460b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
54470b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
54480b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
54490b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
54500b57cec5SDimitry Andric   // definition is dependable.
54510b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
54520b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
54530b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
54560b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
54570b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
54580b57cec5SDimitry Andric   // throw away these explicit instantiations.
54590b57cec5SDimitry Andric   //
5460e8d8bef9SDimitry Andric   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
54610b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
5462e8d8bef9SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations. For
5463e8d8bef9SDimitry Andric   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5464e8d8bef9SDimitry Andric   // therefore we need to follow the normal linkage paradigm.
54650b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
5466e8d8bef9SDimitry Andric     if (getLangOpts().AppleKext)
54670b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
5468e8d8bef9SDimitry Andric     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5469e8d8bef9SDimitry Andric         !getLangOpts().GPURelocatableDeviceCode)
54700b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
54710b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
54720b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
54730b57cec5SDimitry Andric   }
54740b57cec5SDimitry Andric 
54750b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
54760b57cec5SDimitry Andric   // linkage.
54770b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
54780b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
54790b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
54800b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
54810b57cec5SDimitry Andric 
54820b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
54830b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
54840b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
54850b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
54860b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
54870b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
54900b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
54910b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
54920b57cec5SDimitry Andric }
54930b57cec5SDimitry Andric 
5494*8a4dda33SDimitry Andric llvm::GlobalValue::LinkageTypes
5495*8a4dda33SDimitry Andric CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
54960b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5497*8a4dda33SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage);
54980b57cec5SDimitry Andric }
54990b57cec5SDimitry Andric 
55000b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
55010b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
55020b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
55030b57cec5SDimitry Andric                                           llvm::Function *newFn) {
55040b57cec5SDimitry Andric   // Fast path.
55050b57cec5SDimitry Andric   if (old->use_empty()) return;
55060b57cec5SDimitry Andric 
55070b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
55080b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
55090b57cec5SDimitry Andric 
55100b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
55110b57cec5SDimitry Andric          ui != ue; ) {
55120b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
55130b57cec5SDimitry Andric     llvm::User *user = use->getUser();
55140b57cec5SDimitry Andric 
55150b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
55160b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
55170b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
55180b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
55190b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
55200b57cec5SDimitry Andric       continue;
55210b57cec5SDimitry Andric     }
55220b57cec5SDimitry Andric 
55230b57cec5SDimitry Andric     // Recognize calls to the function.
55240b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
55250b57cec5SDimitry Andric     if (!callSite) continue;
55260b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
55270b57cec5SDimitry Andric       continue;
55280b57cec5SDimitry Andric 
55290b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
55300b57cec5SDimitry Andric     // transform this call unless it's dead.
55310b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
55320b57cec5SDimitry Andric       continue;
55330b57cec5SDimitry Andric 
55340b57cec5SDimitry Andric     // Get the call site's attribute list.
55350b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
55360b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
55370b57cec5SDimitry Andric 
55380b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
55390b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
55400b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
55410b57cec5SDimitry Andric       continue;
55420b57cec5SDimitry Andric 
55430b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
55440b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
55450b57cec5SDimitry Andric     unsigned argNo = 0;
55460b57cec5SDimitry Andric     bool dontTransform = false;
55470b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
55480b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
55490b57cec5SDimitry Andric         dontTransform = true;
55500b57cec5SDimitry Andric         break;
55510b57cec5SDimitry Andric       }
55520b57cec5SDimitry Andric 
55530b57cec5SDimitry Andric       // Add any parameter attributes.
5554349cc55cSDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
55550b57cec5SDimitry Andric       argNo++;
55560b57cec5SDimitry Andric     }
55570b57cec5SDimitry Andric     if (dontTransform)
55580b57cec5SDimitry Andric       continue;
55590b57cec5SDimitry Andric 
55600b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
55610b57cec5SDimitry Andric     // over the required information.
55620b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
55630b57cec5SDimitry Andric 
55640b57cec5SDimitry Andric     // Copy over any operand bundles.
5565fe6060f1SDimitry Andric     SmallVector<llvm::OperandBundleDef, 1> newBundles;
55660b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
55670b57cec5SDimitry Andric 
55680b57cec5SDimitry Andric     llvm::CallBase *newCall;
5569349cc55cSDimitry Andric     if (isa<llvm::CallInst>(callSite)) {
55700b57cec5SDimitry Andric       newCall =
55710b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
55720b57cec5SDimitry Andric     } else {
55730b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
55740b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
55750b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
55760b57cec5SDimitry Andric                                          newBundles, "", callSite);
55770b57cec5SDimitry Andric     }
55780b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
55790b57cec5SDimitry Andric 
55800b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
55810b57cec5SDimitry Andric       newCall->takeName(callSite);
5582349cc55cSDimitry Andric     newCall->setAttributes(
5583349cc55cSDimitry Andric         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5584349cc55cSDimitry Andric                                  oldAttrs.getRetAttrs(), newArgAttrs));
55850b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
55860b57cec5SDimitry Andric 
55870b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
55880b57cec5SDimitry Andric     if (!callSite->use_empty())
55890b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
55900b57cec5SDimitry Andric 
55910b57cec5SDimitry Andric     // Copy debug location attached to CI.
55920b57cec5SDimitry Andric     if (callSite->getDebugLoc())
55930b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
55940b57cec5SDimitry Andric 
55950b57cec5SDimitry Andric     callSite->eraseFromParent();
55960b57cec5SDimitry Andric   }
55970b57cec5SDimitry Andric }
55980b57cec5SDimitry Andric 
55990b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
56000b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
56010b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
56020b57cec5SDimitry Andric /// call the new function directly.
56030b57cec5SDimitry Andric ///
56040b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
56050b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
56060b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
56070b57cec5SDimitry Andric /// run at -O0.
56080b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
56090b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
56100b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
56110b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
56120b57cec5SDimitry Andric 
56130b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
56140b57cec5SDimitry Andric }
56150b57cec5SDimitry Andric 
56160b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
56170b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
56180b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
56190b57cec5SDimitry Andric     return;
56200b57cec5SDimitry Andric 
56210b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
56220b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
56230b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
56240b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
56250b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
56260b57cec5SDimitry Andric 
56270b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
56280b57cec5SDimitry Andric }
56290b57cec5SDimitry Andric 
56300b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
56310b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
56320b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
56330b57cec5SDimitry Andric 
56340b57cec5SDimitry Andric   // Compute the function info and LLVM type.
56350b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
56360b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
56370b57cec5SDimitry Andric 
56380b57cec5SDimitry Andric   // Get or create the prototype for the function.
56395ffd83dbSDimitry Andric   if (!GV || (GV->getValueType() != Ty))
56400b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
56410b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
56420b57cec5SDimitry Andric                                                    ForDefinition));
56430b57cec5SDimitry Andric 
56440b57cec5SDimitry Andric   // Already emitted.
56450b57cec5SDimitry Andric   if (!GV->isDeclaration())
56460b57cec5SDimitry Andric     return;
56470b57cec5SDimitry Andric 
56480b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
56490b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
56500b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
56510b57cec5SDimitry Andric   // declarations).
56520b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
56530b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
56540b57cec5SDimitry Andric 
56550b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
56560b57cec5SDimitry Andric   setGVProperties(Fn, GD);
56570b57cec5SDimitry Andric 
56580b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
56590b57cec5SDimitry Andric 
56600b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
56610b57cec5SDimitry Andric 
56625ffd83dbSDimitry Andric   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
56630b57cec5SDimitry Andric 
56640b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
56650b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
56660b57cec5SDimitry Andric 
56670b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
56680b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
56690b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5670e8d8bef9SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority(), true);
56710b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
56720b57cec5SDimitry Andric     AddGlobalAnnotations(D, Fn);
56730b57cec5SDimitry Andric }
56740b57cec5SDimitry Andric 
56750b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
56760b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
56770b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
56780b57cec5SDimitry Andric   assert(AA && "Not an alias?");
56790b57cec5SDimitry Andric 
56800b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
56810b57cec5SDimitry Andric 
56820b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
56830b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
56840b57cec5SDimitry Andric     return;
56850b57cec5SDimitry Andric   }
56860b57cec5SDimitry Andric 
56870b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
56880b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
56890b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
56900b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
56910b57cec5SDimitry Andric     return;
56920b57cec5SDimitry Andric 
56930b57cec5SDimitry Andric   Aliases.push_back(GD);
56940b57cec5SDimitry Andric 
56950b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
56960b57cec5SDimitry Andric 
56970b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
56980b57cec5SDimitry Andric   // if a deferred decl.
56990b57cec5SDimitry Andric   llvm::Constant *Aliasee;
57000b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
57010b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
57020b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
57030b57cec5SDimitry Andric                                       /*ForVTable=*/false);
57040b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
57050b57cec5SDimitry Andric   } else {
5706349cc55cSDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
57070b57cec5SDimitry Andric                                     /*D=*/nullptr);
5708e8d8bef9SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5709*8a4dda33SDimitry Andric       LT = getLLVMLinkageVarDefinition(VD);
5710e8d8bef9SDimitry Andric     else
5711e8d8bef9SDimitry Andric       LT = getFunctionLinkage(GD);
57120b57cec5SDimitry Andric   }
57130b57cec5SDimitry Andric 
57140b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
57155ffd83dbSDimitry Andric   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
57160b57cec5SDimitry Andric   auto *GA =
57175ffd83dbSDimitry Andric       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
57180b57cec5SDimitry Andric 
57190b57cec5SDimitry Andric   if (Entry) {
57200b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
57210b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
57220b57cec5SDimitry Andric       return;
57230b57cec5SDimitry Andric     }
57240b57cec5SDimitry Andric 
57250b57cec5SDimitry Andric     assert(Entry->isDeclaration());
57260b57cec5SDimitry Andric 
57270b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
57280b57cec5SDimitry Andric     // by the alias, as in:
57290b57cec5SDimitry Andric     //   extern int test6();
57300b57cec5SDimitry Andric     //   ...
57310b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
57320b57cec5SDimitry Andric     //
57330b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
57340b57cec5SDimitry Andric     GA->takeName(Entry);
57350b57cec5SDimitry Andric 
57360b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
57370b57cec5SDimitry Andric                                                           Entry->getType()));
57380b57cec5SDimitry Andric     Entry->eraseFromParent();
57390b57cec5SDimitry Andric   } else {
57400b57cec5SDimitry Andric     GA->setName(MangledName);
57410b57cec5SDimitry Andric   }
57420b57cec5SDimitry Andric 
57430b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
57440b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
57450b57cec5SDimitry Andric   // variable/function.
57460b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
57470b57cec5SDimitry Andric       D->isWeakImported()) {
57480b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
57490b57cec5SDimitry Andric   }
57500b57cec5SDimitry Andric 
57510b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
57520b57cec5SDimitry Andric     if (VD->getTLSKind())
57530b57cec5SDimitry Andric       setTLSMode(GA, *VD);
57540b57cec5SDimitry Andric 
57550b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
575681ad6265SDimitry Andric 
575781ad6265SDimitry Andric   // Emit global alias debug information.
575881ad6265SDimitry Andric   if (isa<VarDecl>(D))
575981ad6265SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5760bdd1243dSDimitry Andric       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
57610b57cec5SDimitry Andric }
57620b57cec5SDimitry Andric 
57630b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
57640b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
57650b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
57660b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
57670b57cec5SDimitry Andric 
57680b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
57690b57cec5SDimitry Andric 
57700b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
57710b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
57720b57cec5SDimitry Andric     return;
57730b57cec5SDimitry Andric   }
57740b57cec5SDimitry Andric 
57750b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
57760b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
57770b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
57780b57cec5SDimitry Andric     GlobalDecl OtherGD;
57790b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
57800b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
57810b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
57820b57cec5SDimitry Andric           << MangledName;
57830b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
57840b57cec5SDimitry Andric                    diag::note_previous_definition);
57850b57cec5SDimitry Andric     }
57860b57cec5SDimitry Andric     return;
57870b57cec5SDimitry Andric   }
57880b57cec5SDimitry Andric 
57890b57cec5SDimitry Andric   Aliases.push_back(GD);
57900b57cec5SDimitry Andric 
57910b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5792349cc55cSDimitry Andric   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
57930b57cec5SDimitry Andric   llvm::Constant *Resolver =
5794349cc55cSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
57950b57cec5SDimitry Andric                               /*ForVTable=*/false);
57960b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
57970b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
57980b57cec5SDimitry Andric                                 "", Resolver, &getModule());
57990b57cec5SDimitry Andric   if (Entry) {
58000b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
58010b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
58020b57cec5SDimitry Andric       return;
58030b57cec5SDimitry Andric     }
58040b57cec5SDimitry Andric     assert(Entry->isDeclaration());
58050b57cec5SDimitry Andric 
58060b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
58070b57cec5SDimitry Andric     // by the ifunc, as in:
58080b57cec5SDimitry Andric     //   extern int test();
58090b57cec5SDimitry Andric     //   ...
58100b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
58110b57cec5SDimitry Andric     //
58120b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
58130b57cec5SDimitry Andric     GIF->takeName(Entry);
58140b57cec5SDimitry Andric 
58150b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
58160b57cec5SDimitry Andric                                                           Entry->getType()));
58170b57cec5SDimitry Andric     Entry->eraseFromParent();
58180b57cec5SDimitry Andric   } else
58190b57cec5SDimitry Andric     GIF->setName(MangledName);
58200b57cec5SDimitry Andric 
58210b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
58220b57cec5SDimitry Andric }
58230b57cec5SDimitry Andric 
58240b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
58250b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
58260b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
58270b57cec5SDimitry Andric                                          Tys);
58280b57cec5SDimitry Andric }
58290b57cec5SDimitry Andric 
58300b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
58310b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
58320b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
58330b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
58340b57cec5SDimitry Andric   StringRef String = Literal->getString();
58350b57cec5SDimitry Andric   unsigned NumBytes = String.size();
58360b57cec5SDimitry Andric 
58370b57cec5SDimitry Andric   // Check for simple case.
58380b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
58390b57cec5SDimitry Andric     StringLength = NumBytes;
58400b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
58410b57cec5SDimitry Andric   }
58420b57cec5SDimitry Andric 
58430b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
58440b57cec5SDimitry Andric   IsUTF16 = true;
58450b57cec5SDimitry Andric 
58460b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
58470b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
58480b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
58490b57cec5SDimitry Andric 
58500b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
58510b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
58520b57cec5SDimitry Andric 
58530b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
58540b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
58550b57cec5SDimitry Andric 
58560b57cec5SDimitry Andric   // Add an explicit null.
58570b57cec5SDimitry Andric   *ToPtr = 0;
58580b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
58590b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
58600b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
58610b57cec5SDimitry Andric                          nullptr)).first;
58620b57cec5SDimitry Andric }
58630b57cec5SDimitry Andric 
58640b57cec5SDimitry Andric ConstantAddress
58650b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
58660b57cec5SDimitry Andric   unsigned StringLength = 0;
58670b57cec5SDimitry Andric   bool isUTF16 = false;
58680b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
58690b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
58700b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
58710b57cec5SDimitry Andric                                StringLength);
58720b57cec5SDimitry Andric 
58730b57cec5SDimitry Andric   if (auto *C = Entry.second)
58740eae32dcSDimitry Andric     return ConstantAddress(
58750eae32dcSDimitry Andric         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
58760b57cec5SDimitry Andric 
58770b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
58780b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
58790b57cec5SDimitry Andric 
58800b57cec5SDimitry Andric   const ASTContext &Context = getContext();
58810b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
58820b57cec5SDimitry Andric 
58830b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
58840b57cec5SDimitry Andric   const bool IsSwiftABI =
58850b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
58860b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
58870b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
58880b57cec5SDimitry Andric 
58890b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
58900b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
58910b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
58920b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
58930b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
58940b57cec5SDimitry Andric 
58950b57cec5SDimitry Andric     switch (CFRuntime) {
58960b57cec5SDimitry Andric     default: break;
5897bdd1243dSDimitry Andric     case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
58980b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
58990b57cec5SDimitry Andric       CFConstantStringClassName =
59000b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
59010b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
59020b57cec5SDimitry Andric       Ty = IntPtrTy;
59030b57cec5SDimitry Andric       break;
59040b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
59050b57cec5SDimitry Andric       CFConstantStringClassName =
59060b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
59070b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
59080b57cec5SDimitry Andric       Ty = IntPtrTy;
59090b57cec5SDimitry Andric       break;
59100b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
59110b57cec5SDimitry Andric       CFConstantStringClassName =
59120b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
59130b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
59140b57cec5SDimitry Andric       Ty = IntPtrTy;
59150b57cec5SDimitry Andric       break;
59160b57cec5SDimitry Andric     }
59170b57cec5SDimitry Andric 
59180b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
59190b57cec5SDimitry Andric 
59200b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
59210b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
59220b57cec5SDimitry Andric 
59230b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
59240b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
59250b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
59260b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
59270b57cec5SDimitry Andric 
59280b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
5929fe6060f1SDimitry Andric         for (const auto *Result : DC->lookup(&II))
59300b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
59310b57cec5SDimitry Andric             break;
59320b57cec5SDimitry Andric 
59330b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
59340b57cec5SDimitry Andric           if (!VD)
59350b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
59360b57cec5SDimitry Andric         } else {
59370b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
59380b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
59390b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
59400b57cec5SDimitry Andric           else
59410b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
59420b57cec5SDimitry Andric         }
59430b57cec5SDimitry Andric 
59440b57cec5SDimitry Andric         setDSOLocal(GV);
59450b57cec5SDimitry Andric       }
59460b57cec5SDimitry Andric     }
59470b57cec5SDimitry Andric 
59480b57cec5SDimitry Andric     // Decay array -> ptr
59490b57cec5SDimitry Andric     CFConstantStringClassRef =
59500b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
59510b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
59520b57cec5SDimitry Andric   }
59530b57cec5SDimitry Andric 
59540b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
59550b57cec5SDimitry Andric 
59560b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
59570b57cec5SDimitry Andric 
59580b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
59590b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
59600b57cec5SDimitry Andric 
59610b57cec5SDimitry Andric   // Class pointer.
596281ad6265SDimitry Andric   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
59630b57cec5SDimitry Andric 
59640b57cec5SDimitry Andric   // Flags.
59650b57cec5SDimitry Andric   if (IsSwiftABI) {
59660b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
59670b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
59680b57cec5SDimitry Andric   } else {
59690b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
59700b57cec5SDimitry Andric   }
59710b57cec5SDimitry Andric 
59720b57cec5SDimitry Andric   // String pointer.
59730b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
59740b57cec5SDimitry Andric   if (isUTF16) {
5975bdd1243dSDimitry Andric     auto Arr = llvm::ArrayRef(
59760b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
59770b57cec5SDimitry Andric         Entry.first().size() / 2);
59780b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
59790b57cec5SDimitry Andric   } else {
59800b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
59810b57cec5SDimitry Andric   }
59820b57cec5SDimitry Andric 
59830b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
59840b57cec5SDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
59850b57cec5SDimitry Andric   auto *GV =
59860b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
59870b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
59880b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
59890b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
59900b57cec5SDimitry Andric   // of the string is via this class initializer.
59910b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
59920b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
5993a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
59940b57cec5SDimitry Andric 
59950b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
59960b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
59970b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
59980b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
59990b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
60000b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
60010b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
60020b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
60030b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
60040b57cec5SDimitry Andric     GV->setSection(".rodata");
60050b57cec5SDimitry Andric 
60060b57cec5SDimitry Andric   // String.
60070b57cec5SDimitry Andric   llvm::Constant *Str =
60080b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
60090b57cec5SDimitry Andric 
60100b57cec5SDimitry Andric   if (isUTF16)
60110b57cec5SDimitry Andric     // Cast the UTF16 string to the correct type.
60120b57cec5SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
60130b57cec5SDimitry Andric   Fields.add(Str);
60140b57cec5SDimitry Andric 
60150b57cec5SDimitry Andric   // String length.
60160b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
60170b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
60180b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
60190b57cec5SDimitry Andric   if (IsSwiftABI) {
60200b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
60210b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
60220b57cec5SDimitry Andric       LengthTy = Int32Ty;
60230b57cec5SDimitry Andric     else
60240b57cec5SDimitry Andric       LengthTy = IntPtrTy;
60250b57cec5SDimitry Andric   }
60260b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
60270b57cec5SDimitry Andric 
6028a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6029a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
6030a7dea167SDimitry Andric   CharUnits Alignment =
6031a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric   // The struct.
60340b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
60350b57cec5SDimitry Andric                                     /*isConstant=*/false,
60360b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
60370b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
60380b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
60390b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
60400b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
604181ad6265SDimitry Andric   case llvm::Triple::DXContainer:
6042e8d8bef9SDimitry Andric   case llvm::Triple::GOFF:
604381ad6265SDimitry Andric   case llvm::Triple::SPIRV:
60440b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
604581ad6265SDimitry Andric     llvm_unreachable("unimplemented");
60460b57cec5SDimitry Andric   case llvm::Triple::COFF:
60470b57cec5SDimitry Andric   case llvm::Triple::ELF:
60480b57cec5SDimitry Andric   case llvm::Triple::Wasm:
60490b57cec5SDimitry Andric     GV->setSection("cfstring");
60500b57cec5SDimitry Andric     break;
60510b57cec5SDimitry Andric   case llvm::Triple::MachO:
60520b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
60530b57cec5SDimitry Andric     break;
60540b57cec5SDimitry Andric   }
60550b57cec5SDimitry Andric   Entry.second = GV;
60560b57cec5SDimitry Andric 
60570eae32dcSDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
60580b57cec5SDimitry Andric }
60590b57cec5SDimitry Andric 
60600b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
60610b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
60620b57cec5SDimitry Andric }
60630b57cec5SDimitry Andric 
60640b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
60650b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
60660b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
60670b57cec5SDimitry Andric     D->startDefinition();
60680b57cec5SDimitry Andric 
60690b57cec5SDimitry Andric     QualType FieldTypes[] = {
60700b57cec5SDimitry Andric       Context.UnsignedLongTy,
60710b57cec5SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
60720b57cec5SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
60730b57cec5SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
6074a7dea167SDimitry Andric                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
60750b57cec5SDimitry Andric     };
60760b57cec5SDimitry Andric 
60770b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
60780b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
60790b57cec5SDimitry Andric                                            D,
60800b57cec5SDimitry Andric                                            SourceLocation(),
60810b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
60820b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
60830b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
60840b57cec5SDimitry Andric                                            /*Mutable=*/false,
60850b57cec5SDimitry Andric                                            ICIS_NoInit);
60860b57cec5SDimitry Andric       Field->setAccess(AS_public);
60870b57cec5SDimitry Andric       D->addDecl(Field);
60880b57cec5SDimitry Andric     }
60890b57cec5SDimitry Andric 
60900b57cec5SDimitry Andric     D->completeDefinition();
60910b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
60920b57cec5SDimitry Andric   }
60930b57cec5SDimitry Andric 
60940b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
60950b57cec5SDimitry Andric }
60960b57cec5SDimitry Andric 
60970b57cec5SDimitry Andric llvm::Constant *
60980b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
60990b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
61000b57cec5SDimitry Andric 
61010b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
61020b57cec5SDimitry Andric   // as an inline array.
61030b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
61040b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
61050b57cec5SDimitry Andric 
61060b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
61070b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
610806c3fb27SDimitry Andric     assert(CAT && "String literal not of constant array type!");
61090b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
61100b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
61110b57cec5SDimitry Andric   }
61120b57cec5SDimitry Andric 
61130b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
61140b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
61150b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
61160b57cec5SDimitry Andric 
61170b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
61180b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
61190b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
61200b57cec5SDimitry Andric     Elements.reserve(NumElements);
61210b57cec5SDimitry Andric 
61220b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
61230b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
61240b57cec5SDimitry Andric     Elements.resize(NumElements);
61250b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
61260b57cec5SDimitry Andric   }
61270b57cec5SDimitry Andric 
61280b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
61290b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
61300b57cec5SDimitry Andric   Elements.reserve(NumElements);
61310b57cec5SDimitry Andric 
61320b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
61330b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
61340b57cec5SDimitry Andric   Elements.resize(NumElements);
61350b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
61360b57cec5SDimitry Andric }
61370b57cec5SDimitry Andric 
61380b57cec5SDimitry Andric static llvm::GlobalVariable *
61390b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
61400b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
61410b57cec5SDimitry Andric                       CharUnits Alignment) {
61420b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6143fe6060f1SDimitry Andric       CGM.GetGlobalConstantAddressSpace());
61440b57cec5SDimitry Andric 
61450b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
61460b57cec5SDimitry Andric   // Create a global variable for this string
61470b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
61480b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
61490b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6150a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
61510b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
61520b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
61530b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
61540b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
61550b57cec5SDimitry Andric   }
61560b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
61570b57cec5SDimitry Andric 
61580b57cec5SDimitry Andric   return GV;
61590b57cec5SDimitry Andric }
61600b57cec5SDimitry Andric 
61610b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
61620b57cec5SDimitry Andric /// constant array for the given string literal.
61630b57cec5SDimitry Andric ConstantAddress
61640b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
61650b57cec5SDimitry Andric                                                   StringRef Name) {
61660b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
61670b57cec5SDimitry Andric 
61680b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
61690b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
61700b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
61710b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
61720b57cec5SDimitry Andric     if (auto GV = *Entry) {
6173349cc55cSDimitry Andric       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6174a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
61750b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
61760eae32dcSDimitry Andric                              GV->getValueType(), Alignment);
61770b57cec5SDimitry Andric     }
61780b57cec5SDimitry Andric   }
61790b57cec5SDimitry Andric 
61800b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
61810b57cec5SDimitry Andric   StringRef GlobalVariableName;
61820b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
61830b57cec5SDimitry Andric 
61840b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
61850b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
61860b57cec5SDimitry Andric   // affect strings in another.
61870b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
61880b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
61890b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
61900b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
61910b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
61920b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
61930b57cec5SDimitry Andric   } else {
61940b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
61950b57cec5SDimitry Andric     GlobalVariableName = Name;
61960b57cec5SDimitry Andric   }
61970b57cec5SDimitry Andric 
61980b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
619981ad6265SDimitry Andric 
620081ad6265SDimitry Andric   CGDebugInfo *DI = getModuleDebugInfo();
620181ad6265SDimitry Andric   if (DI && getCodeGenOpts().hasReducedDebugInfo())
620281ad6265SDimitry Andric     DI->AddStringLiteralDebugInfo(GV, S);
620381ad6265SDimitry Andric 
62040b57cec5SDimitry Andric   if (Entry)
62050b57cec5SDimitry Andric     *Entry = GV;
62060b57cec5SDimitry Andric 
620781ad6265SDimitry Andric   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
62080b57cec5SDimitry Andric 
62090b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
62100eae32dcSDimitry Andric                          GV->getValueType(), Alignment);
62110b57cec5SDimitry Andric }
62120b57cec5SDimitry Andric 
62130b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
62140b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
62150b57cec5SDimitry Andric ConstantAddress
62160b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
62170b57cec5SDimitry Andric   std::string Str;
62180b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
62190b57cec5SDimitry Andric 
62200b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
62210b57cec5SDimitry Andric }
62220b57cec5SDimitry Andric 
62230b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
62240b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
62250b57cec5SDimitry Andric /// The result has pointer to array type.
62260b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
62270b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
62280b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
62290b57cec5SDimitry Andric   CharUnits Alignment =
62300b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
62310b57cec5SDimitry Andric 
62320b57cec5SDimitry Andric   llvm::Constant *C =
62330b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
62340b57cec5SDimitry Andric 
62350b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
62360b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
62370b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
62380b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
62390b57cec5SDimitry Andric     if (auto GV = *Entry) {
6240349cc55cSDimitry Andric       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6241a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
62420b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
62430eae32dcSDimitry Andric                              GV->getValueType(), Alignment);
62440b57cec5SDimitry Andric     }
62450b57cec5SDimitry Andric   }
62460b57cec5SDimitry Andric 
62470b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
62480b57cec5SDimitry Andric   if (!GlobalName)
62490b57cec5SDimitry Andric     GlobalName = ".str";
62500b57cec5SDimitry Andric   // Create a global variable for this.
62510b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
62520b57cec5SDimitry Andric                                   GlobalName, Alignment);
62530b57cec5SDimitry Andric   if (Entry)
62540b57cec5SDimitry Andric     *Entry = GV;
62550b57cec5SDimitry Andric 
62560b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
62570eae32dcSDimitry Andric                          GV->getValueType(), Alignment);
62580b57cec5SDimitry Andric }
62590b57cec5SDimitry Andric 
62600b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
62610b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
62620b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
62630b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
62640b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
62650b57cec5SDimitry Andric 
62660b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
62670b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
62680b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
6269480093f4SDimitry Andric   if (Init == E->getSubExpr())
62700b57cec5SDimitry Andric     MaterializedType = E->getType();
62710b57cec5SDimitry Andric 
62720b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
62730b57cec5SDimitry Andric 
6274fe6060f1SDimitry Andric   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6275fe6060f1SDimitry Andric   if (!InsertResult.second) {
6276fe6060f1SDimitry Andric     // We've seen this before: either we already created it or we're in the
6277fe6060f1SDimitry Andric     // process of doing so.
6278fe6060f1SDimitry Andric     if (!InsertResult.first->second) {
6279fe6060f1SDimitry Andric       // We recursively re-entered this function, probably during emission of
6280fe6060f1SDimitry Andric       // the initializer. Create a placeholder. We'll clean this up in the
6281fe6060f1SDimitry Andric       // outer call, at the end of this function.
6282fe6060f1SDimitry Andric       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6283fe6060f1SDimitry Andric       InsertResult.first->second = new llvm::GlobalVariable(
6284fe6060f1SDimitry Andric           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6285fe6060f1SDimitry Andric           nullptr);
6286fe6060f1SDimitry Andric     }
628781ad6265SDimitry Andric     return ConstantAddress(InsertResult.first->second,
628881ad6265SDimitry Andric                            llvm::cast<llvm::GlobalVariable>(
628981ad6265SDimitry Andric                                InsertResult.first->second->stripPointerCasts())
629081ad6265SDimitry Andric                                ->getValueType(),
629181ad6265SDimitry Andric                            Align);
6292fe6060f1SDimitry Andric   }
62930b57cec5SDimitry Andric 
62940b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
62950b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
62960b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
62970b57cec5SDimitry Andric   SmallString<256> Name;
62980b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
62990b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
63000b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
63010b57cec5SDimitry Andric 
63020b57cec5SDimitry Andric   APValue *Value = nullptr;
6303a7dea167SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
6304a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
6305a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
6306a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
6307a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
6308a7dea167SDimitry Andric     // expression modifies the temporary.
6309480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
63100b57cec5SDimitry Andric   }
63110b57cec5SDimitry Andric 
63120b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
63130b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
63140b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
63150b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
63160b57cec5SDimitry Andric     Value = &EvalResult.Val;
63170b57cec5SDimitry Andric 
63180b57cec5SDimitry Andric   LangAS AddrSpace =
63190b57cec5SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
63200b57cec5SDimitry Andric 
6321bdd1243dSDimitry Andric   std::optional<ConstantEmitter> emitter;
63220b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
63230b57cec5SDimitry Andric   bool Constant = false;
63240b57cec5SDimitry Andric   llvm::Type *Type;
63250b57cec5SDimitry Andric   if (Value) {
63260b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
63270b57cec5SDimitry Andric     emitter.emplace(*this);
63280b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
63290b57cec5SDimitry Andric                                                MaterializedType);
633006c3fb27SDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/ Value,
633106c3fb27SDimitry Andric                               /*ExcludeDtor*/ false);
63320b57cec5SDimitry Andric     Type = InitialValue->getType();
63330b57cec5SDimitry Andric   } else {
63340b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
63350b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
63360b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
63370b57cec5SDimitry Andric   }
63380b57cec5SDimitry Andric 
63390b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
6340*8a4dda33SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
63410b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
63420b57cec5SDimitry Andric     const VarDecl *InitVD;
63430b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
63440b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
63450b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
63460b57cec5SDimitry Andric       // class can be defined in multiple translation units.
63470b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
63480b57cec5SDimitry Andric     } else {
63490b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
63500b57cec5SDimitry Andric       // VarDecl has external linkage.
63510b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
63520b57cec5SDimitry Andric     }
63530b57cec5SDimitry Andric   }
63540b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
63550b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
63560b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
63570b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
63580b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
6359bdd1243dSDimitry Andric   // Don't assign dllimport or dllexport to local linkage globals.
6360bdd1243dSDimitry Andric   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
63610b57cec5SDimitry Andric     setGVProperties(GV, VD);
636281ad6265SDimitry Andric     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
636381ad6265SDimitry Andric       // The reference temporary should never be dllexport.
636481ad6265SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6365bdd1243dSDimitry Andric   }
6366a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
63670b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
63680b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
63690b57cec5SDimitry Andric   if (VD->getTLSKind())
63700b57cec5SDimitry Andric     setTLSMode(GV, *VD);
63710b57cec5SDimitry Andric   llvm::Constant *CV = GV;
63720b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
63730b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
63740b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
63750b57cec5SDimitry Andric         Type->getPointerTo(
63760b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
6377fe6060f1SDimitry Andric 
6378fe6060f1SDimitry Andric   // Update the map with the new temporary. If we created a placeholder above,
6379fe6060f1SDimitry Andric   // replace it with the new global now.
6380fe6060f1SDimitry Andric   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6381fe6060f1SDimitry Andric   if (Entry) {
6382fe6060f1SDimitry Andric     Entry->replaceAllUsesWith(
6383fe6060f1SDimitry Andric         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
6384fe6060f1SDimitry Andric     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6385fe6060f1SDimitry Andric   }
6386fe6060f1SDimitry Andric   Entry = CV;
6387fe6060f1SDimitry Andric 
63880eae32dcSDimitry Andric   return ConstantAddress(CV, Type, Align);
63890b57cec5SDimitry Andric }
63900b57cec5SDimitry Andric 
63910b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
63920b57cec5SDimitry Andric /// properties for an implementation.
63930b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
63940b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
63950b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
63960b57cec5SDimitry Andric     // Dynamic is just for type-checking.
63970b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
63980b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
63990b57cec5SDimitry Andric 
64000b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
64010b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
64020b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
64030b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
64040b57cec5SDimitry Andric       // this implementation.
6405480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
6406480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
64070b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
64080b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
6409480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
6410480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
64110b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
64120b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
64130b57cec5SDimitry Andric     }
64140b57cec5SDimitry Andric   }
64150b57cec5SDimitry Andric }
64160b57cec5SDimitry Andric 
64170b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
64180b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
64190b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
64200b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
64210b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
64220b57cec5SDimitry Andric       return true;
64230b57cec5SDimitry Andric 
64240b57cec5SDimitry Andric   return false;
64250b57cec5SDimitry Andric }
64260b57cec5SDimitry Andric 
64270b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
64280b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
64290b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
64300b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
64310b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
64320b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
64330b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
64340b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
64350b57cec5SDimitry Andric       return false;
64360b57cec5SDimitry Andric   }
64370b57cec5SDimitry Andric   return true;
64380b57cec5SDimitry Andric }
64390b57cec5SDimitry Andric 
64400b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
64410b57cec5SDimitry Andric /// for an implementation.
64420b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
64430b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
64440b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
64450b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
64460b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6447480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6448480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6449480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
64500b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
6451480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6452480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
64530b57cec5SDimitry Andric         /*isDefined=*/false, ObjCMethodDecl::Required);
64540b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
64550b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
64560b57cec5SDimitry Andric     D->setHasDestructors(true);
64570b57cec5SDimitry Andric   }
64580b57cec5SDimitry Andric 
64590b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
64600b57cec5SDimitry Andric   // a .cxx_construct.
64610b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
64620b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
64630b57cec5SDimitry Andric     return;
64640b57cec5SDimitry Andric 
64650b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
64660b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
64670b57cec5SDimitry Andric   // The constructor returns 'self'.
6468480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6469480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6470480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
64710b57cec5SDimitry Andric       /*isVariadic=*/false,
6472480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
64730b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
6474480093f4SDimitry Andric       /*isDefined=*/false, ObjCMethodDecl::Required);
64750b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
64760b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
64770b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
64780b57cec5SDimitry Andric }
64790b57cec5SDimitry Andric 
64800b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
64810b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
64820b57cec5SDimitry Andric   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
6483480093f4SDimitry Andric       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
64840b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
64850b57cec5SDimitry Andric     return;
64860b57cec5SDimitry Andric   }
64870b57cec5SDimitry Andric 
64880b57cec5SDimitry Andric   EmitDeclContext(LSD);
64890b57cec5SDimitry Andric }
64900b57cec5SDimitry Andric 
6491bdd1243dSDimitry Andric void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
649206c3fb27SDimitry Andric   // Device code should not be at top level.
649306c3fb27SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
649406c3fb27SDimitry Andric     return;
649506c3fb27SDimitry Andric 
6496bdd1243dSDimitry Andric   std::unique_ptr<CodeGenFunction> &CurCGF =
6497bdd1243dSDimitry Andric       GlobalTopLevelStmtBlockInFlight.first;
6498bdd1243dSDimitry Andric 
6499bdd1243dSDimitry Andric   // We emitted a top-level stmt but after it there is initialization.
6500bdd1243dSDimitry Andric   // Stop squashing the top-level stmts into a single function.
6501bdd1243dSDimitry Andric   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6502bdd1243dSDimitry Andric     CurCGF->FinishFunction(D->getEndLoc());
6503bdd1243dSDimitry Andric     CurCGF = nullptr;
6504bdd1243dSDimitry Andric   }
6505bdd1243dSDimitry Andric 
6506bdd1243dSDimitry Andric   if (!CurCGF) {
6507bdd1243dSDimitry Andric     // void __stmts__N(void)
6508bdd1243dSDimitry Andric     // FIXME: Ask the ABI name mangler to pick a name.
6509bdd1243dSDimitry Andric     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6510bdd1243dSDimitry Andric     FunctionArgList Args;
6511bdd1243dSDimitry Andric     QualType RetTy = getContext().VoidTy;
6512bdd1243dSDimitry Andric     const CGFunctionInfo &FnInfo =
6513bdd1243dSDimitry Andric         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6514bdd1243dSDimitry Andric     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6515bdd1243dSDimitry Andric     llvm::Function *Fn = llvm::Function::Create(
6516bdd1243dSDimitry Andric         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6517bdd1243dSDimitry Andric 
6518bdd1243dSDimitry Andric     CurCGF.reset(new CodeGenFunction(*this));
6519bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight.second = D;
6520bdd1243dSDimitry Andric     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6521bdd1243dSDimitry Andric                           D->getBeginLoc(), D->getBeginLoc());
6522bdd1243dSDimitry Andric     CXXGlobalInits.push_back(Fn);
6523bdd1243dSDimitry Andric   }
6524bdd1243dSDimitry Andric 
6525bdd1243dSDimitry Andric   CurCGF->EmitStmt(D->getStmt());
6526bdd1243dSDimitry Andric }
6527bdd1243dSDimitry Andric 
65280b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
65290b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
65300b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
65310b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
65320b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
65330b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
65340b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
65350b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
65360b57cec5SDimitry Andric       for (auto *M : OID->methods())
65370b57cec5SDimitry Andric         EmitTopLevelDecl(M);
65380b57cec5SDimitry Andric     }
65390b57cec5SDimitry Andric 
65400b57cec5SDimitry Andric     EmitTopLevelDecl(I);
65410b57cec5SDimitry Andric   }
65420b57cec5SDimitry Andric }
65430b57cec5SDimitry Andric 
65440b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
65450b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
65460b57cec5SDimitry Andric   // Ignore dependent declarations.
65470b57cec5SDimitry Andric   if (D->isTemplated())
65480b57cec5SDimitry Andric     return;
65490b57cec5SDimitry Andric 
65505ffd83dbSDimitry Andric   // Consteval function shouldn't be emitted.
655106c3fb27SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
65525ffd83dbSDimitry Andric     return;
65535ffd83dbSDimitry Andric 
65540b57cec5SDimitry Andric   switch (D->getKind()) {
65550b57cec5SDimitry Andric   case Decl::CXXConversion:
65560b57cec5SDimitry Andric   case Decl::CXXMethod:
65570b57cec5SDimitry Andric   case Decl::Function:
65580b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
65590b57cec5SDimitry Andric     // Always provide some coverage mapping
65600b57cec5SDimitry Andric     // even for the functions that aren't emitted.
65610b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
65620b57cec5SDimitry Andric     break;
65630b57cec5SDimitry Andric 
65640b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
65650b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
65660b57cec5SDimitry Andric     break;
65670b57cec5SDimitry Andric 
65680b57cec5SDimitry Andric   case Decl::Var:
65690b57cec5SDimitry Andric   case Decl::Decomposition:
65700b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
65710b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
65720b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
65730b57cec5SDimitry Andric       for (auto *B : DD->bindings())
65740b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
65750b57cec5SDimitry Andric           EmitGlobal(HD);
65760b57cec5SDimitry Andric     break;
65770b57cec5SDimitry Andric 
65780b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
65790b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
65800b57cec5SDimitry Andric   case Decl::IndirectField:
65810b57cec5SDimitry Andric     break;
65820b57cec5SDimitry Andric 
65830b57cec5SDimitry Andric   // C++ Decls
65840b57cec5SDimitry Andric   case Decl::Namespace:
65850b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
65860b57cec5SDimitry Andric     break;
65870b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
65880b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
65895ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
65905ffd83dbSDimitry Andric       if (Spec->getSpecializationKind() ==
65915ffd83dbSDimitry Andric               TSK_ExplicitInstantiationDefinition &&
65920b57cec5SDimitry Andric           Spec->hasDefinition())
65935ffd83dbSDimitry Andric         DI->completeTemplateDefinition(*Spec);
6594bdd1243dSDimitry Andric   } [[fallthrough]];
6595e8d8bef9SDimitry Andric   case Decl::CXXRecord: {
6596e8d8bef9SDimitry Andric     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6597e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6598e8d8bef9SDimitry Andric       if (CRD->hasDefinition())
6599e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
66000b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
66010b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6602e8d8bef9SDimitry Andric           DI->completeUnusedClass(*CRD);
6603e8d8bef9SDimitry Andric     }
66040b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
6605e8d8bef9SDimitry Andric     for (auto *I : CRD->decls())
66060b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
66070b57cec5SDimitry Andric         EmitTopLevelDecl(I);
66080b57cec5SDimitry Andric     break;
6609e8d8bef9SDimitry Andric   }
66100b57cec5SDimitry Andric     // No code generation needed.
66110b57cec5SDimitry Andric   case Decl::UsingShadow:
66120b57cec5SDimitry Andric   case Decl::ClassTemplate:
66130b57cec5SDimitry Andric   case Decl::VarTemplate:
66140b57cec5SDimitry Andric   case Decl::Concept:
66150b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
66160b57cec5SDimitry Andric   case Decl::FunctionTemplate:
66170b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
66180b57cec5SDimitry Andric   case Decl::Block:
66190b57cec5SDimitry Andric   case Decl::Empty:
66200b57cec5SDimitry Andric   case Decl::Binding:
66210b57cec5SDimitry Andric     break;
66220b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
66230b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
66240b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
66255ffd83dbSDimitry Andric     break;
6626fe6060f1SDimitry Andric   case Decl::UsingEnum: // using enum X; [C++]
6627fe6060f1SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6628fe6060f1SDimitry Andric       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6629fe6060f1SDimitry Andric     break;
66300b57cec5SDimitry Andric   case Decl::NamespaceAlias:
66310b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
66320b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
66335ffd83dbSDimitry Andric     break;
66340b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
66350b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
66360b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
66375ffd83dbSDimitry Andric     break;
66380b57cec5SDimitry Andric   case Decl::CXXConstructor:
66390b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
66400b57cec5SDimitry Andric     break;
66410b57cec5SDimitry Andric   case Decl::CXXDestructor:
66420b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
66430b57cec5SDimitry Andric     break;
66440b57cec5SDimitry Andric 
66450b57cec5SDimitry Andric   case Decl::StaticAssert:
66460b57cec5SDimitry Andric     // Nothing to do.
66470b57cec5SDimitry Andric     break;
66480b57cec5SDimitry Andric 
66490b57cec5SDimitry Andric   // Objective-C Decls
66500b57cec5SDimitry Andric 
66510b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
66520b57cec5SDimitry Andric   case Decl::ObjCInterface:
66530b57cec5SDimitry Andric   case Decl::ObjCCategory:
66540b57cec5SDimitry Andric     break;
66550b57cec5SDimitry Andric 
66560b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
66570b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
66580b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
66590b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
66600b57cec5SDimitry Andric     break;
66610b57cec5SDimitry Andric   }
66620b57cec5SDimitry Andric 
66630b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
66640b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
66650b57cec5SDimitry Andric     // can ignore them here.
66660b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
66670b57cec5SDimitry Andric     break;
66680b57cec5SDimitry Andric 
66690b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
66700b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
66710b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
66720b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
66730b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
66740b57cec5SDimitry Andric     // Emit global variable debug information.
66750b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6676480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
66770b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
66780b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
66790b57cec5SDimitry Andric     break;
66800b57cec5SDimitry Andric   }
66810b57cec5SDimitry Andric   case Decl::ObjCMethod: {
66820b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
66830b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
66840b57cec5SDimitry Andric     if (OMD->getBody())
66850b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
66860b57cec5SDimitry Andric     break;
66870b57cec5SDimitry Andric   }
66880b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
66890b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
66900b57cec5SDimitry Andric     break;
66910b57cec5SDimitry Andric 
66920b57cec5SDimitry Andric   case Decl::PragmaComment: {
66930b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
66940b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
66950b57cec5SDimitry Andric     case PCK_Unknown:
66960b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
66970b57cec5SDimitry Andric     case PCK_Linker:
66980b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
66990b57cec5SDimitry Andric       break;
67000b57cec5SDimitry Andric     case PCK_Lib:
67010b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
67020b57cec5SDimitry Andric       break;
67030b57cec5SDimitry Andric     case PCK_Compiler:
67040b57cec5SDimitry Andric     case PCK_ExeStr:
67050b57cec5SDimitry Andric     case PCK_User:
67060b57cec5SDimitry Andric       break; // We ignore all of these.
67070b57cec5SDimitry Andric     }
67080b57cec5SDimitry Andric     break;
67090b57cec5SDimitry Andric   }
67100b57cec5SDimitry Andric 
67110b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
67120b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
67130b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
67140b57cec5SDimitry Andric     break;
67150b57cec5SDimitry Andric   }
67160b57cec5SDimitry Andric 
67170b57cec5SDimitry Andric   case Decl::LinkageSpec:
67180b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
67190b57cec5SDimitry Andric     break;
67200b57cec5SDimitry Andric 
67210b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
67220b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
67230b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
67240b57cec5SDimitry Andric       break;
67250b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
672606c3fb27SDimitry Andric     if (LangOpts.OpenMPIsTargetDevice)
67270b57cec5SDimitry Andric       break;
6728fe6060f1SDimitry Andric     // File-scope asm is ignored during device-side SYCL compilation.
6729fe6060f1SDimitry Andric     if (LangOpts.SYCLIsDevice)
6730fe6060f1SDimitry Andric       break;
67310b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
67320b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
67330b57cec5SDimitry Andric     break;
67340b57cec5SDimitry Andric   }
67350b57cec5SDimitry Andric 
6736bdd1243dSDimitry Andric   case Decl::TopLevelStmt:
6737bdd1243dSDimitry Andric     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6738bdd1243dSDimitry Andric     break;
6739bdd1243dSDimitry Andric 
67400b57cec5SDimitry Andric   case Decl::Import: {
67410b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
67420b57cec5SDimitry Andric 
67430b57cec5SDimitry Andric     // If we've already imported this module, we're done.
67440b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
67450b57cec5SDimitry Andric       break;
67460b57cec5SDimitry Andric 
67470b57cec5SDimitry Andric     // Emit debug information for direct imports.
67480b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
67490b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
67500b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
67510b57cec5SDimitry Andric     }
67520b57cec5SDimitry Andric 
6753fcaf7f86SDimitry Andric     // For C++ standard modules we are done - we will call the module
6754fcaf7f86SDimitry Andric     // initializer for imported modules, and that will likewise call those for
6755fcaf7f86SDimitry Andric     // any imports it has.
6756fcaf7f86SDimitry Andric     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6757fcaf7f86SDimitry Andric         !Import->getImportedOwningModule()->isModuleMapModule())
6758fcaf7f86SDimitry Andric       break;
6759fcaf7f86SDimitry Andric 
6760fcaf7f86SDimitry Andric     // For clang C++ module map modules the initializers for sub-modules are
6761fcaf7f86SDimitry Andric     // emitted here.
6762fcaf7f86SDimitry Andric 
67630b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
67640b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
67650b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
67660b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
67670b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
67680b57cec5SDimitry Andric 
67690b57cec5SDimitry Andric     while (!Stack.empty()) {
67700b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
67710b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
67720b57cec5SDimitry Andric         continue;
67730b57cec5SDimitry Andric 
67740b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
67750b57cec5SDimitry Andric         EmitTopLevelDecl(D);
67760b57cec5SDimitry Andric 
67770b57cec5SDimitry Andric       // Visit the submodules of this module.
677806c3fb27SDimitry Andric       for (auto *Submodule : Mod->submodules()) {
67790b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
67800b57cec5SDimitry Andric         // the initializers.
678106c3fb27SDimitry Andric         if (Submodule->IsExplicit)
67820b57cec5SDimitry Andric           continue;
67830b57cec5SDimitry Andric 
678406c3fb27SDimitry Andric         if (Visited.insert(Submodule).second)
678506c3fb27SDimitry Andric           Stack.push_back(Submodule);
67860b57cec5SDimitry Andric       }
67870b57cec5SDimitry Andric     }
67880b57cec5SDimitry Andric     break;
67890b57cec5SDimitry Andric   }
67900b57cec5SDimitry Andric 
67910b57cec5SDimitry Andric   case Decl::Export:
67920b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
67930b57cec5SDimitry Andric     break;
67940b57cec5SDimitry Andric 
67950b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
67960b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
67970b57cec5SDimitry Andric     break;
67980b57cec5SDimitry Andric 
67990b57cec5SDimitry Andric   case Decl::OMPAllocate:
6800fe6060f1SDimitry Andric     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
68010b57cec5SDimitry Andric     break;
68020b57cec5SDimitry Andric 
68030b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
68040b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
68050b57cec5SDimitry Andric     break;
68060b57cec5SDimitry Andric 
68070b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
68080b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
68090b57cec5SDimitry Andric     break;
68100b57cec5SDimitry Andric 
68110b57cec5SDimitry Andric   case Decl::OMPRequires:
68120b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
68130b57cec5SDimitry Andric     break;
68140b57cec5SDimitry Andric 
6815e8d8bef9SDimitry Andric   case Decl::Typedef:
6816e8d8bef9SDimitry Andric   case Decl::TypeAlias: // using foo = bar; [C++11]
6817e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6818e8d8bef9SDimitry Andric       DI->EmitAndRetainType(
6819e8d8bef9SDimitry Andric           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6820e8d8bef9SDimitry Andric     break;
6821e8d8bef9SDimitry Andric 
6822e8d8bef9SDimitry Andric   case Decl::Record:
6823e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6824e8d8bef9SDimitry Andric       if (cast<RecordDecl>(D)->getDefinition())
6825e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6826e8d8bef9SDimitry Andric     break;
6827e8d8bef9SDimitry Andric 
6828e8d8bef9SDimitry Andric   case Decl::Enum:
6829e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6830e8d8bef9SDimitry Andric       if (cast<EnumDecl>(D)->getDefinition())
6831e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6832e8d8bef9SDimitry Andric     break;
6833e8d8bef9SDimitry Andric 
6834bdd1243dSDimitry Andric   case Decl::HLSLBuffer:
6835bdd1243dSDimitry Andric     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
6836bdd1243dSDimitry Andric     break;
6837bdd1243dSDimitry Andric 
68380b57cec5SDimitry Andric   default:
68390b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
68400b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
68410b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
68420b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
68430b57cec5SDimitry Andric     break;
68440b57cec5SDimitry Andric   }
68450b57cec5SDimitry Andric }
68460b57cec5SDimitry Andric 
68470b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
68480b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
68490b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
68500b57cec5SDimitry Andric     return;
68510b57cec5SDimitry Andric   switch (D->getKind()) {
68520b57cec5SDimitry Andric   case Decl::CXXConversion:
68530b57cec5SDimitry Andric   case Decl::CXXMethod:
68540b57cec5SDimitry Andric   case Decl::Function:
68550b57cec5SDimitry Andric   case Decl::ObjCMethod:
68560b57cec5SDimitry Andric   case Decl::CXXConstructor:
68570b57cec5SDimitry Andric   case Decl::CXXDestructor: {
68580b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
68595ffd83dbSDimitry Andric       break;
68600b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
68610b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
68625ffd83dbSDimitry Andric       break;
68630b57cec5SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
68640b57cec5SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
68650b57cec5SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
68660b57cec5SDimitry Andric     break;
68670b57cec5SDimitry Andric   }
68680b57cec5SDimitry Andric   default:
68690b57cec5SDimitry Andric     break;
68700b57cec5SDimitry Andric   };
68710b57cec5SDimitry Andric }
68720b57cec5SDimitry Andric 
68730b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
68740b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
68750b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
68760b57cec5SDimitry Andric     return;
68770b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
68780b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
68790b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
68800b57cec5SDimitry Andric   }
68810b57cec5SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
68820b57cec5SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
68830b57cec5SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
68840b57cec5SDimitry Andric   else
68850b57cec5SDimitry Andric     I->second = false;
68860b57cec5SDimitry Andric }
68870b57cec5SDimitry Andric 
68880b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
68890b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
68900b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
68910b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
68920b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
68930b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
68940b57cec5SDimitry Andric     if (!Entry.second)
68950b57cec5SDimitry Andric       continue;
68960b57cec5SDimitry Andric     const Decl *D = Entry.first;
68970b57cec5SDimitry Andric     switch (D->getKind()) {
68980b57cec5SDimitry Andric     case Decl::CXXConversion:
68990b57cec5SDimitry Andric     case Decl::CXXMethod:
69000b57cec5SDimitry Andric     case Decl::Function:
69010b57cec5SDimitry Andric     case Decl::ObjCMethod: {
69020b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
69030b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
69040b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
69050b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
69060b57cec5SDimitry Andric       break;
69070b57cec5SDimitry Andric     }
69080b57cec5SDimitry Andric     case Decl::CXXConstructor: {
69090b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
69100b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
69110b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
69120b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
69130b57cec5SDimitry Andric       break;
69140b57cec5SDimitry Andric     }
69150b57cec5SDimitry Andric     case Decl::CXXDestructor: {
69160b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
69170b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
69180b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
69190b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
69200b57cec5SDimitry Andric       break;
69210b57cec5SDimitry Andric     }
69220b57cec5SDimitry Andric     default:
69230b57cec5SDimitry Andric       break;
69240b57cec5SDimitry Andric     };
69250b57cec5SDimitry Andric   }
69260b57cec5SDimitry Andric }
69270b57cec5SDimitry Andric 
69285ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() {
69295ffd83dbSDimitry Andric   // In order to transition away from "__original_main" gracefully, emit an
69305ffd83dbSDimitry Andric   // alias for "main" in the no-argument case so that libc can detect when
69315ffd83dbSDimitry Andric   // new-style no-argument main is in used.
69325ffd83dbSDimitry Andric   if (llvm::Function *F = getModule().getFunction("main")) {
69335ffd83dbSDimitry Andric     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
693481ad6265SDimitry Andric         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
693581ad6265SDimitry Andric       auto *GA = llvm::GlobalAlias::create("__main_void", F);
693681ad6265SDimitry Andric       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
693781ad6265SDimitry Andric     }
69385ffd83dbSDimitry Andric   }
69395ffd83dbSDimitry Andric }
69405ffd83dbSDimitry Andric 
69410b57cec5SDimitry Andric /// Turns the given pointer into a constant.
69420b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
69430b57cec5SDimitry Andric                                           const void *Ptr) {
69440b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
69450b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
69460b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
69470b57cec5SDimitry Andric }
69480b57cec5SDimitry Andric 
69490b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
69500b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
69510b57cec5SDimitry Andric                                    GlobalDecl D,
69520b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
69530b57cec5SDimitry Andric   if (!GlobalMetadata)
69540b57cec5SDimitry Andric     GlobalMetadata =
69550b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
69560b57cec5SDimitry Andric 
69570b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
69580b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
69590b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
69600b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
69610b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
69620b57cec5SDimitry Andric }
69630b57cec5SDimitry Andric 
696481ad6265SDimitry Andric bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
696581ad6265SDimitry Andric                                                  llvm::GlobalValue *CppFunc) {
696681ad6265SDimitry Andric   // Store the list of ifuncs we need to replace uses in.
696781ad6265SDimitry Andric   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
696881ad6265SDimitry Andric   // List of ConstantExprs that we should be able to delete when we're done
696981ad6265SDimitry Andric   // here.
697081ad6265SDimitry Andric   llvm::SmallVector<llvm::ConstantExpr *> CEs;
697181ad6265SDimitry Andric 
697281ad6265SDimitry Andric   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
697381ad6265SDimitry Andric   if (Elem == CppFunc)
697481ad6265SDimitry Andric     return false;
697581ad6265SDimitry Andric 
697681ad6265SDimitry Andric   // First make sure that all users of this are ifuncs (or ifuncs via a
697781ad6265SDimitry Andric   // bitcast), and collect the list of ifuncs and CEs so we can work on them
697881ad6265SDimitry Andric   // later.
697981ad6265SDimitry Andric   for (llvm::User *User : Elem->users()) {
698081ad6265SDimitry Andric     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
698181ad6265SDimitry Andric     // ifunc directly. In any other case, just give up, as we don't know what we
698281ad6265SDimitry Andric     // could break by changing those.
698381ad6265SDimitry Andric     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
698481ad6265SDimitry Andric       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
698581ad6265SDimitry Andric         return false;
698681ad6265SDimitry Andric 
698781ad6265SDimitry Andric       for (llvm::User *CEUser : ConstExpr->users()) {
698881ad6265SDimitry Andric         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
698981ad6265SDimitry Andric           IFuncs.push_back(IFunc);
699081ad6265SDimitry Andric         } else {
699181ad6265SDimitry Andric           return false;
699281ad6265SDimitry Andric         }
699381ad6265SDimitry Andric       }
699481ad6265SDimitry Andric       CEs.push_back(ConstExpr);
699581ad6265SDimitry Andric     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
699681ad6265SDimitry Andric       IFuncs.push_back(IFunc);
699781ad6265SDimitry Andric     } else {
699881ad6265SDimitry Andric       // This user is one we don't know how to handle, so fail redirection. This
699981ad6265SDimitry Andric       // will result in an ifunc retaining a resolver name that will ultimately
700081ad6265SDimitry Andric       // fail to be resolved to a defined function.
700181ad6265SDimitry Andric       return false;
700281ad6265SDimitry Andric     }
700381ad6265SDimitry Andric   }
700481ad6265SDimitry Andric 
700581ad6265SDimitry Andric   // Now we know this is a valid case where we can do this alias replacement, we
700681ad6265SDimitry Andric   // need to remove all of the references to Elem (and the bitcasts!) so we can
700781ad6265SDimitry Andric   // delete it.
700881ad6265SDimitry Andric   for (llvm::GlobalIFunc *IFunc : IFuncs)
700981ad6265SDimitry Andric     IFunc->setResolver(nullptr);
701081ad6265SDimitry Andric   for (llvm::ConstantExpr *ConstExpr : CEs)
701181ad6265SDimitry Andric     ConstExpr->destroyConstant();
701281ad6265SDimitry Andric 
701381ad6265SDimitry Andric   // We should now be out of uses for the 'old' version of this function, so we
701481ad6265SDimitry Andric   // can erase it as well.
701581ad6265SDimitry Andric   Elem->eraseFromParent();
701681ad6265SDimitry Andric 
701781ad6265SDimitry Andric   for (llvm::GlobalIFunc *IFunc : IFuncs) {
701881ad6265SDimitry Andric     // The type of the resolver is always just a function-type that returns the
701981ad6265SDimitry Andric     // type of the IFunc, so create that here. If the type of the actual
702081ad6265SDimitry Andric     // resolver doesn't match, it just gets bitcast to the right thing.
702181ad6265SDimitry Andric     auto *ResolverTy =
702281ad6265SDimitry Andric         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
702381ad6265SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
702481ad6265SDimitry Andric         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
702581ad6265SDimitry Andric     IFunc->setResolver(Resolver);
702681ad6265SDimitry Andric   }
702781ad6265SDimitry Andric   return true;
702881ad6265SDimitry Andric }
702981ad6265SDimitry Andric 
70300b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
70310b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
70320b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
70330b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
70340b57cec5SDimitry Andric /// same translation unit.
70350b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
70360b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
70370b57cec5SDimitry Andric     return;
70380b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
70390b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
70400b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
704181ad6265SDimitry Andric 
704281ad6265SDimitry Andric     // If Val is null, that implies there were multiple declarations that each
704381ad6265SDimitry Andric     // had a claim to the unmangled name. In this case, generation of the alias
704481ad6265SDimitry Andric     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
704581ad6265SDimitry Andric     if (!Val)
704681ad6265SDimitry Andric       break;
704781ad6265SDimitry Andric 
704881ad6265SDimitry Andric     llvm::GlobalValue *ExistingElem =
704981ad6265SDimitry Andric         getModule().getNamedValue(Name->getName());
705081ad6265SDimitry Andric 
705181ad6265SDimitry Andric     // If there is either not something already by this name, or we were able to
705281ad6265SDimitry Andric     // replace all uses from IFuncs, create the alias.
705381ad6265SDimitry Andric     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7054fe6060f1SDimitry Andric       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
70550b57cec5SDimitry Andric   }
70560b57cec5SDimitry Andric }
70570b57cec5SDimitry Andric 
70580b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
70590b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
70600b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
70610b57cec5SDimitry Andric   if (Res == Manglings.end())
70620b57cec5SDimitry Andric     return false;
70630b57cec5SDimitry Andric   Result = Res->getValue();
70640b57cec5SDimitry Andric   return true;
70650b57cec5SDimitry Andric }
70660b57cec5SDimitry Andric 
70670b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
70680b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
70690b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
70700b57cec5SDimitry Andric ///
70710b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
70720b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
70730b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
70740b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
70750b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
70760b57cec5SDimitry Andric 
70770b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
70780b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
70790b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
70800b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
70810b57cec5SDimitry Andric     if (Addr)
70820b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
70830b57cec5SDimitry Andric   }
70840b57cec5SDimitry Andric }
70850b57cec5SDimitry Andric 
70860b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
70870b57cec5SDimitry Andric /// function.
70880b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
70890b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
70900b57cec5SDimitry Andric 
70910b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
70920b57cec5SDimitry Andric 
70930b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
70940b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
70950b57cec5SDimitry Andric 
70960b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
70970b57cec5SDimitry Andric 
70980b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
70990b57cec5SDimitry Andric     const Decl *D = I.first;
71000b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
71010b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
71020b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
71030b57cec5SDimitry Andric       Alloca->setMetadata(
71040b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
71050b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
71060b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
71070b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
71080b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
71090b57cec5SDimitry Andric     }
71100b57cec5SDimitry Andric   }
71110b57cec5SDimitry Andric }
71120b57cec5SDimitry Andric 
71130b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
71140b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
71150b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
71160b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
71170b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
71180b57cec5SDimitry Andric 
71190b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
71200b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
71210b57cec5SDimitry Andric }
71220b57cec5SDimitry Andric 
71230b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
71240b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
71250b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
71260b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
71270b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
71280b57cec5SDimitry Andric 
71290b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
71300b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
71310b57cec5SDimitry Andric }
71320b57cec5SDimitry Andric 
71330b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
71340b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
71350b57cec5SDimitry Andric   if (!CUNode)
71360b57cec5SDimitry Andric     return;
71370b57cec5SDimitry Andric 
71380b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
71390b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
71400b57cec5SDimitry Andric   auto *CoverageDataFile =
71410b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
71420b57cec5SDimitry Andric   auto *CoverageNotesFile =
71430b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
71440b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
71450b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
71460b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
71470b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
71480b57cec5SDimitry Andric   }
71490b57cec5SDimitry Andric }
71500b57cec5SDimitry Andric 
71510b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
71520b57cec5SDimitry Andric                                                        bool ForEH) {
71530b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
71540b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
71550b57cec5SDimitry Andric   // and it's not for EH?
715606c3fb27SDimitry Andric   if (!shouldEmitRTTI(ForEH))
715706c3fb27SDimitry Andric     return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
71580b57cec5SDimitry Andric 
71590b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
71600b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
71610b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
71620b57cec5SDimitry Andric 
71630b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
71640b57cec5SDimitry Andric }
71650b57cec5SDimitry Andric 
71660b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
71670b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
71680b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
71690b57cec5SDimitry Andric     return;
71700b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
71710b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
71720b57cec5SDimitry Andric     bool PerformInit =
71730b57cec5SDimitry Andric         VD->getAnyInitializer() &&
71740b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
71750b57cec5SDimitry Andric                                                         /*ForRef=*/false);
71760b57cec5SDimitry Andric 
717781ad6265SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD),
717881ad6265SDimitry Andric                  getTypes().ConvertTypeForMem(VD->getType()),
717981ad6265SDimitry Andric                  getContext().getDeclAlign(VD));
71800b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
71810b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
71820b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
71830b57cec5SDimitry Andric   }
71840b57cec5SDimitry Andric }
71850b57cec5SDimitry Andric 
71860b57cec5SDimitry Andric llvm::Metadata *
71870b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
71880b57cec5SDimitry Andric                                             StringRef Suffix) {
71890eae32dcSDimitry Andric   if (auto *FnType = T->getAs<FunctionProtoType>())
71900eae32dcSDimitry Andric     T = getContext().getFunctionType(
71910eae32dcSDimitry Andric         FnType->getReturnType(), FnType->getParamTypes(),
71920eae32dcSDimitry Andric         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
71930eae32dcSDimitry Andric 
71940b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
71950b57cec5SDimitry Andric   if (InternalId)
71960b57cec5SDimitry Andric     return InternalId;
71970b57cec5SDimitry Andric 
71980b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
71990b57cec5SDimitry Andric     std::string OutName;
72000b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
720106c3fb27SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(
720206c3fb27SDimitry Andric         T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
720306c3fb27SDimitry Andric 
720406c3fb27SDimitry Andric     if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
720506c3fb27SDimitry Andric       Out << ".normalized";
720606c3fb27SDimitry Andric 
72070b57cec5SDimitry Andric     Out << Suffix;
72080b57cec5SDimitry Andric 
72090b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
72100b57cec5SDimitry Andric   } else {
72110b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
72120b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
72130b57cec5SDimitry Andric   }
72140b57cec5SDimitry Andric 
72150b57cec5SDimitry Andric   return InternalId;
72160b57cec5SDimitry Andric }
72170b57cec5SDimitry Andric 
72180b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
72190b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
72200b57cec5SDimitry Andric }
72210b57cec5SDimitry Andric 
72220b57cec5SDimitry Andric llvm::Metadata *
72230b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
72240b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
72250b57cec5SDimitry Andric }
72260b57cec5SDimitry Andric 
72270b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
72280b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
72290b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
72300b57cec5SDimitry Andric // 'void *'.
72310b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
72320b57cec5SDimitry Andric   if (!Ty->isPointerType())
72330b57cec5SDimitry Andric     return Ty;
72340b57cec5SDimitry Andric 
72350b57cec5SDimitry Andric   return Ctx.getPointerType(
72360b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
72370b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
72380b57cec5SDimitry Andric }
72390b57cec5SDimitry Andric 
72400b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
72410b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
72420b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
72430b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
72440b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
72450b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
72460b57cec5SDimitry Andric 
72470b57cec5SDimitry Andric     return Ctx.getFunctionType(
72480b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
72490b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
72500b57cec5SDimitry Andric   }
72510b57cec5SDimitry Andric 
72520b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
72530b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
72540b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
72550b57cec5SDimitry Andric 
72560b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
72570b57cec5SDimitry Andric }
72580b57cec5SDimitry Andric 
72590b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
72600b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
72610b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
72620b57cec5SDimitry Andric }
72630b57cec5SDimitry Andric 
72640b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
72650b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
72660b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
72670b57cec5SDimitry Andric   // is not in the trapping mode.
72680b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
72690b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
72700b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
72710b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
72720b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
72730b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
72740b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
72750b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
72760b57cec5SDimitry Andric }
72770b57cec5SDimitry Andric 
72780b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
72790b57cec5SDimitry Andric                                           CharUnits Offset,
72800b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
72810b57cec5SDimitry Andric   llvm::Metadata *MD =
72820b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
72830b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
72840b57cec5SDimitry Andric 
72850b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
72860b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
72870b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
72880b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
72890b57cec5SDimitry Andric 
72900b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
72910b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
72920b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
72930b57cec5SDimitry Andric   }
72940b57cec5SDimitry Andric }
72950b57cec5SDimitry Andric 
72960b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
72970b57cec5SDimitry Andric   if (!SanStats)
7298a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
72990b57cec5SDimitry Andric 
73000b57cec5SDimitry Andric   return *SanStats;
73010b57cec5SDimitry Andric }
730223408297SDimitry Andric 
73030b57cec5SDimitry Andric llvm::Value *
73040b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
73050b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
73060b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
730723408297SDimitry Andric   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
730823408297SDimitry Andric   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7309fe6060f1SDimitry Andric   auto *Call = CGF.EmitRuntimeCall(
731023408297SDimitry Andric       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
731123408297SDimitry Andric   return Call;
73120b57cec5SDimitry Andric }
73135ffd83dbSDimitry Andric 
73145ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
73155ffd83dbSDimitry Andric     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
73165ffd83dbSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
73175ffd83dbSDimitry Andric                                  /* forPointeeType= */ true);
73185ffd83dbSDimitry Andric }
73195ffd83dbSDimitry Andric 
73205ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
73215ffd83dbSDimitry Andric                                                  LValueBaseInfo *BaseInfo,
73225ffd83dbSDimitry Andric                                                  TBAAAccessInfo *TBAAInfo,
73235ffd83dbSDimitry Andric                                                  bool forPointeeType) {
73245ffd83dbSDimitry Andric   if (TBAAInfo)
73255ffd83dbSDimitry Andric     *TBAAInfo = getTBAAAccessInfo(T);
73265ffd83dbSDimitry Andric 
73275ffd83dbSDimitry Andric   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
73285ffd83dbSDimitry Andric   // that doesn't return the information we need to compute BaseInfo.
73295ffd83dbSDimitry Andric 
73305ffd83dbSDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
73315ffd83dbSDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
73325ffd83dbSDimitry Andric   // there's an expressivity gap here.
73335ffd83dbSDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
73345ffd83dbSDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
73355ffd83dbSDimitry Andric       if (BaseInfo)
73365ffd83dbSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
73375ffd83dbSDimitry Andric       return getContext().toCharUnitsFromBits(Align);
73385ffd83dbSDimitry Andric     }
73395ffd83dbSDimitry Andric   }
73405ffd83dbSDimitry Andric 
73415ffd83dbSDimitry Andric   bool AlignForArray = T->isArrayType();
73425ffd83dbSDimitry Andric 
73435ffd83dbSDimitry Andric   // Analyze the base element type, so we don't get confused by incomplete
73445ffd83dbSDimitry Andric   // array types.
73455ffd83dbSDimitry Andric   T = getContext().getBaseElementType(T);
73465ffd83dbSDimitry Andric 
73475ffd83dbSDimitry Andric   if (T->isIncompleteType()) {
73485ffd83dbSDimitry Andric     // We could try to replicate the logic from
73495ffd83dbSDimitry Andric     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
73505ffd83dbSDimitry Andric     // type is incomplete, so it's impossible to test. We could try to reuse
73515ffd83dbSDimitry Andric     // getTypeAlignIfKnown, but that doesn't return the information we need
73525ffd83dbSDimitry Andric     // to set BaseInfo.  So just ignore the possibility that the alignment is
73535ffd83dbSDimitry Andric     // greater than one.
73545ffd83dbSDimitry Andric     if (BaseInfo)
73555ffd83dbSDimitry Andric       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
73565ffd83dbSDimitry Andric     return CharUnits::One();
73575ffd83dbSDimitry Andric   }
73585ffd83dbSDimitry Andric 
73595ffd83dbSDimitry Andric   if (BaseInfo)
73605ffd83dbSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
73615ffd83dbSDimitry Andric 
73625ffd83dbSDimitry Andric   CharUnits Alignment;
7363e8d8bef9SDimitry Andric   const CXXRecordDecl *RD;
7364e8d8bef9SDimitry Andric   if (T.getQualifiers().hasUnaligned()) {
7365e8d8bef9SDimitry Andric     Alignment = CharUnits::One();
7366e8d8bef9SDimitry Andric   } else if (forPointeeType && !AlignForArray &&
7367e8d8bef9SDimitry Andric              (RD = T->getAsCXXRecordDecl())) {
73685ffd83dbSDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
73695ffd83dbSDimitry Andric     // base or a complete object, so we generally need to use the
73705ffd83dbSDimitry Andric     // non-virtual alignment.
73715ffd83dbSDimitry Andric     Alignment = getClassPointerAlignment(RD);
73725ffd83dbSDimitry Andric   } else {
73735ffd83dbSDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
73745ffd83dbSDimitry Andric   }
73755ffd83dbSDimitry Andric 
73765ffd83dbSDimitry Andric   // Cap to the global maximum type alignment unless the alignment
73775ffd83dbSDimitry Andric   // was somehow explicit on the type.
73785ffd83dbSDimitry Andric   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
73795ffd83dbSDimitry Andric     if (Alignment.getQuantity() > MaxAlign &&
73805ffd83dbSDimitry Andric         !getContext().isAlignmentRequired(T))
73815ffd83dbSDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
73825ffd83dbSDimitry Andric   }
73835ffd83dbSDimitry Andric   return Alignment;
73845ffd83dbSDimitry Andric }
73855ffd83dbSDimitry Andric 
73865ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() {
73875ffd83dbSDimitry Andric   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
73885ffd83dbSDimitry Andric   if (StopAfter) {
73895ffd83dbSDimitry Andric     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
73905ffd83dbSDimitry Andric     // used
73915ffd83dbSDimitry Andric     if (NumAutoVarInit >= StopAfter) {
73925ffd83dbSDimitry Andric       return true;
73935ffd83dbSDimitry Andric     }
73945ffd83dbSDimitry Andric     if (!NumAutoVarInit) {
73955ffd83dbSDimitry Andric       unsigned DiagID = getDiags().getCustomDiagID(
73965ffd83dbSDimitry Andric           DiagnosticsEngine::Warning,
73975ffd83dbSDimitry Andric           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
73985ffd83dbSDimitry Andric           "number of times ftrivial-auto-var-init=%1 gets applied.");
73995ffd83dbSDimitry Andric       getDiags().Report(DiagID)
74005ffd83dbSDimitry Andric           << StopAfter
74015ffd83dbSDimitry Andric           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
74025ffd83dbSDimitry Andric                       LangOptions::TrivialAutoVarInitKind::Zero
74035ffd83dbSDimitry Andric                   ? "zero"
74045ffd83dbSDimitry Andric                   : "pattern");
74055ffd83dbSDimitry Andric     }
74065ffd83dbSDimitry Andric     ++NumAutoVarInit;
74075ffd83dbSDimitry Andric   }
74085ffd83dbSDimitry Andric   return false;
74095ffd83dbSDimitry Andric }
7410fe6060f1SDimitry Andric 
74112a66634dSDimitry Andric void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
74122a66634dSDimitry Andric                                                     const Decl *D) const {
74132a66634dSDimitry Andric   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
74142a66634dSDimitry Andric   // postfix beginning with '.' since the symbol name can be demangled.
74152a66634dSDimitry Andric   if (LangOpts.HIP)
741681ad6265SDimitry Andric     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
74172a66634dSDimitry Andric   else
741881ad6265SDimitry Andric     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
741981ad6265SDimitry Andric 
742081ad6265SDimitry Andric   // If the CUID is not specified we try to generate a unique postfix.
742181ad6265SDimitry Andric   if (getLangOpts().CUID.empty()) {
742281ad6265SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
742381ad6265SDimitry Andric     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
742481ad6265SDimitry Andric     assert(PLoc.isValid() && "Source location is expected to be valid.");
742581ad6265SDimitry Andric 
742681ad6265SDimitry Andric     // Get the hash of the user defined macros.
742781ad6265SDimitry Andric     llvm::MD5 Hash;
742881ad6265SDimitry Andric     llvm::MD5::MD5Result Result;
742981ad6265SDimitry Andric     for (const auto &Arg : PreprocessorOpts.Macros)
743081ad6265SDimitry Andric       Hash.update(Arg.first);
743181ad6265SDimitry Andric     Hash.final(Result);
743281ad6265SDimitry Andric 
743381ad6265SDimitry Andric     // Get the UniqueID for the file containing the decl.
743481ad6265SDimitry Andric     llvm::sys::fs::UniqueID ID;
743581ad6265SDimitry Andric     if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
743681ad6265SDimitry Andric       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
743781ad6265SDimitry Andric       assert(PLoc.isValid() && "Source location is expected to be valid.");
743881ad6265SDimitry Andric       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
743981ad6265SDimitry Andric         SM.getDiagnostics().Report(diag::err_cannot_open_file)
744081ad6265SDimitry Andric             << PLoc.getFilename() << EC.message();
744181ad6265SDimitry Andric     }
744281ad6265SDimitry Andric     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
744381ad6265SDimitry Andric        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
744481ad6265SDimitry Andric   } else {
744581ad6265SDimitry Andric     OS << getContext().getCUIDHash();
744681ad6265SDimitry Andric   }
7447fe6060f1SDimitry Andric }
7448fcaf7f86SDimitry Andric 
7449fcaf7f86SDimitry Andric void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7450fcaf7f86SDimitry Andric   assert(DeferredDeclsToEmit.empty() &&
7451fcaf7f86SDimitry Andric          "Should have emitted all decls deferred to emit.");
7452fcaf7f86SDimitry Andric   assert(NewBuilder->DeferredDecls.empty() &&
7453fcaf7f86SDimitry Andric          "Newly created module should not have deferred decls");
7454fcaf7f86SDimitry Andric   NewBuilder->DeferredDecls = std::move(DeferredDecls);
7455fcaf7f86SDimitry Andric 
7456fcaf7f86SDimitry Andric   assert(NewBuilder->DeferredVTables.empty() &&
7457fcaf7f86SDimitry Andric          "Newly created module should not have deferred vtables");
7458fcaf7f86SDimitry Andric   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7459fcaf7f86SDimitry Andric 
7460fcaf7f86SDimitry Andric   assert(NewBuilder->MangledDeclNames.empty() &&
7461fcaf7f86SDimitry Andric          "Newly created module should not have mangled decl names");
7462fcaf7f86SDimitry Andric   assert(NewBuilder->Manglings.empty() &&
7463fcaf7f86SDimitry Andric          "Newly created module should not have manglings");
7464fcaf7f86SDimitry Andric   NewBuilder->Manglings = std::move(Manglings);
7465fcaf7f86SDimitry Andric 
7466fcaf7f86SDimitry Andric   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7467fcaf7f86SDimitry Andric 
7468fcaf7f86SDimitry Andric   NewBuilder->TBAA = std::move(TBAA);
7469fcaf7f86SDimitry Andric 
7470fcaf7f86SDimitry Andric   assert(NewBuilder->EmittedDeferredDecls.empty() &&
7471fcaf7f86SDimitry Andric          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7472fcaf7f86SDimitry Andric 
7473fcaf7f86SDimitry Andric   NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
7474972a253aSDimitry Andric 
7475972a253aSDimitry Andric   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7476fcaf7f86SDimitry Andric }
7477