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"
31c9157d92SDimitry Andric #include "clang/AST/ASTLambda.h"
320b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
330b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
340b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
350b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
360b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
370b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
380b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
390b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
400b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
410b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
420b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
435ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
440b57cec5SDimitry Andric #include "clang/Basic/Module.h"
450b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
460b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
470b57cec5SDimitry Andric #include "clang/Basic/Version.h"
4881ad6265SDimitry Andric #include "clang/CodeGen/BackendUtil.h"
490b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
500b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
51bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h"
52bdd1243dSDimitry Andric #include "llvm/ADT/StringExtras.h"
530b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
540b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
55480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
56fe013be4SDimitry Andric #include "llvm/IR/AttributeMask.h"
570b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
580b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
590b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
600b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
610b57cec5SDimitry Andric #include "llvm/IR/Module.h"
620b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
630b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
64bdd1243dSDimitry Andric #include "llvm/ProfileData/SampleProf.h"
65fcaf7f86SDimitry Andric #include "llvm/Support/CRC.h"
660b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
67480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
680b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
690b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
70*f1e32799SDimitry Andric #include "llvm/Support/RISCVISAInfo.h"
710b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
72bdd1243dSDimitry Andric #include "llvm/Support/xxhash.h"
73fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h"
74fe013be4SDimitry Andric #include "llvm/TargetParser/X86TargetParser.h"
75bdd1243dSDimitry Andric #include <optional>
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric using namespace clang;
780b57cec5SDimitry Andric using namespace CodeGen;
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
8181ad6265SDimitry Andric     "limited-coverage-experimental", llvm::cl::Hidden,
8281ad6265SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
850b57cec5SDimitry Andric 
createCXXABI(CodeGenModule & CGM)860b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
87fe6060f1SDimitry Andric   switch (CGM.getContext().getCXXABIKind()) {
88e8d8bef9SDimitry Andric   case TargetCXXABI::AppleARM64:
89480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
900b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
910b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
920b57cec5SDimitry Andric   case TargetCXXABI::iOS:
930b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
940b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
950b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
960b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
975ffd83dbSDimitry Andric   case TargetCXXABI::XL:
980b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
990b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
1000b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric 
106fe013be4SDimitry Andric static std::unique_ptr<TargetCodeGenInfo>
createTargetCodeGenInfo(CodeGenModule & CGM)107fe013be4SDimitry Andric createTargetCodeGenInfo(CodeGenModule &CGM) {
108fe013be4SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
109fe013be4SDimitry Andric   const llvm::Triple &Triple = Target.getTriple();
110fe013be4SDimitry Andric   const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
111fe013be4SDimitry Andric 
112fe013be4SDimitry Andric   switch (Triple.getArch()) {
113fe013be4SDimitry Andric   default:
114fe013be4SDimitry Andric     return createDefaultTargetCodeGenInfo(CGM);
115fe013be4SDimitry Andric 
116fe013be4SDimitry Andric   case llvm::Triple::le32:
117fe013be4SDimitry Andric     return createPNaClTargetCodeGenInfo(CGM);
118fe013be4SDimitry Andric   case llvm::Triple::m68k:
119fe013be4SDimitry Andric     return createM68kTargetCodeGenInfo(CGM);
120fe013be4SDimitry Andric   case llvm::Triple::mips:
121fe013be4SDimitry Andric   case llvm::Triple::mipsel:
122fe013be4SDimitry Andric     if (Triple.getOS() == llvm::Triple::NaCl)
123fe013be4SDimitry Andric       return createPNaClTargetCodeGenInfo(CGM);
124fe013be4SDimitry Andric     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
125fe013be4SDimitry Andric 
126fe013be4SDimitry Andric   case llvm::Triple::mips64:
127fe013be4SDimitry Andric   case llvm::Triple::mips64el:
128fe013be4SDimitry Andric     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
129fe013be4SDimitry Andric 
130fe013be4SDimitry Andric   case llvm::Triple::avr: {
131fe013be4SDimitry Andric     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
132fe013be4SDimitry Andric     // on avrtiny. For passing return value, R18~R25 are used on avr, and
133fe013be4SDimitry Andric     // R22~R25 are used on avrtiny.
134fe013be4SDimitry Andric     unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
135fe013be4SDimitry Andric     unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
136fe013be4SDimitry Andric     return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
137fe013be4SDimitry Andric   }
138fe013be4SDimitry Andric 
139fe013be4SDimitry Andric   case llvm::Triple::aarch64:
140fe013be4SDimitry Andric   case llvm::Triple::aarch64_32:
141fe013be4SDimitry Andric   case llvm::Triple::aarch64_be: {
142fe013be4SDimitry Andric     AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
143fe013be4SDimitry Andric     if (Target.getABI() == "darwinpcs")
144fe013be4SDimitry Andric       Kind = AArch64ABIKind::DarwinPCS;
145fe013be4SDimitry Andric     else if (Triple.isOSWindows())
146fe013be4SDimitry Andric       return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
147fe013be4SDimitry Andric 
148fe013be4SDimitry Andric     return createAArch64TargetCodeGenInfo(CGM, Kind);
149fe013be4SDimitry Andric   }
150fe013be4SDimitry Andric 
151fe013be4SDimitry Andric   case llvm::Triple::wasm32:
152fe013be4SDimitry Andric   case llvm::Triple::wasm64: {
153fe013be4SDimitry Andric     WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
154fe013be4SDimitry Andric     if (Target.getABI() == "experimental-mv")
155fe013be4SDimitry Andric       Kind = WebAssemblyABIKind::ExperimentalMV;
156fe013be4SDimitry Andric     return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
157fe013be4SDimitry Andric   }
158fe013be4SDimitry Andric 
159fe013be4SDimitry Andric   case llvm::Triple::arm:
160fe013be4SDimitry Andric   case llvm::Triple::armeb:
161fe013be4SDimitry Andric   case llvm::Triple::thumb:
162fe013be4SDimitry Andric   case llvm::Triple::thumbeb: {
163fe013be4SDimitry Andric     if (Triple.getOS() == llvm::Triple::Win32)
164fe013be4SDimitry Andric       return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
165fe013be4SDimitry Andric 
166fe013be4SDimitry Andric     ARMABIKind Kind = ARMABIKind::AAPCS;
167fe013be4SDimitry Andric     StringRef ABIStr = Target.getABI();
168fe013be4SDimitry Andric     if (ABIStr == "apcs-gnu")
169fe013be4SDimitry Andric       Kind = ARMABIKind::APCS;
170fe013be4SDimitry Andric     else if (ABIStr == "aapcs16")
171fe013be4SDimitry Andric       Kind = ARMABIKind::AAPCS16_VFP;
172fe013be4SDimitry Andric     else if (CodeGenOpts.FloatABI == "hard" ||
173fe013be4SDimitry Andric              (CodeGenOpts.FloatABI != "soft" &&
174fe013be4SDimitry Andric               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
175fe013be4SDimitry Andric                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
176fe013be4SDimitry Andric                Triple.getEnvironment() == llvm::Triple::EABIHF)))
177fe013be4SDimitry Andric       Kind = ARMABIKind::AAPCS_VFP;
178fe013be4SDimitry Andric 
179fe013be4SDimitry Andric     return createARMTargetCodeGenInfo(CGM, Kind);
180fe013be4SDimitry Andric   }
181fe013be4SDimitry Andric 
182fe013be4SDimitry Andric   case llvm::Triple::ppc: {
183fe013be4SDimitry Andric     if (Triple.isOSAIX())
184fe013be4SDimitry Andric       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
185fe013be4SDimitry Andric 
186fe013be4SDimitry Andric     bool IsSoftFloat =
187fe013be4SDimitry Andric         CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
188fe013be4SDimitry Andric     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
189fe013be4SDimitry Andric   }
190fe013be4SDimitry Andric   case llvm::Triple::ppcle: {
191fe013be4SDimitry Andric     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
192fe013be4SDimitry Andric     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
193fe013be4SDimitry Andric   }
194fe013be4SDimitry Andric   case llvm::Triple::ppc64:
195fe013be4SDimitry Andric     if (Triple.isOSAIX())
196fe013be4SDimitry Andric       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
197fe013be4SDimitry Andric 
198fe013be4SDimitry Andric     if (Triple.isOSBinFormatELF()) {
199fe013be4SDimitry Andric       PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
200fe013be4SDimitry Andric       if (Target.getABI() == "elfv2")
201fe013be4SDimitry Andric         Kind = PPC64_SVR4_ABIKind::ELFv2;
202fe013be4SDimitry Andric       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
203fe013be4SDimitry Andric 
204fe013be4SDimitry Andric       return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
205fe013be4SDimitry Andric     }
206fe013be4SDimitry Andric     return createPPC64TargetCodeGenInfo(CGM);
207fe013be4SDimitry Andric   case llvm::Triple::ppc64le: {
208fe013be4SDimitry Andric     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
209fe013be4SDimitry Andric     PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
210fe013be4SDimitry Andric     if (Target.getABI() == "elfv1")
211fe013be4SDimitry Andric       Kind = PPC64_SVR4_ABIKind::ELFv1;
212fe013be4SDimitry Andric     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
213fe013be4SDimitry Andric 
214fe013be4SDimitry Andric     return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
215fe013be4SDimitry Andric   }
216fe013be4SDimitry Andric 
217fe013be4SDimitry Andric   case llvm::Triple::nvptx:
218fe013be4SDimitry Andric   case llvm::Triple::nvptx64:
219fe013be4SDimitry Andric     return createNVPTXTargetCodeGenInfo(CGM);
220fe013be4SDimitry Andric 
221fe013be4SDimitry Andric   case llvm::Triple::msp430:
222fe013be4SDimitry Andric     return createMSP430TargetCodeGenInfo(CGM);
223fe013be4SDimitry Andric 
224fe013be4SDimitry Andric   case llvm::Triple::riscv32:
225fe013be4SDimitry Andric   case llvm::Triple::riscv64: {
226fe013be4SDimitry Andric     StringRef ABIStr = Target.getABI();
227fe013be4SDimitry Andric     unsigned XLen = Target.getPointerWidth(LangAS::Default);
228fe013be4SDimitry Andric     unsigned ABIFLen = 0;
229c9157d92SDimitry Andric     if (ABIStr.ends_with("f"))
230fe013be4SDimitry Andric       ABIFLen = 32;
231c9157d92SDimitry Andric     else if (ABIStr.ends_with("d"))
232fe013be4SDimitry Andric       ABIFLen = 64;
233a58f00eaSDimitry Andric     bool EABI = ABIStr.ends_with("e");
234a58f00eaSDimitry Andric     return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI);
235fe013be4SDimitry Andric   }
236fe013be4SDimitry Andric 
237fe013be4SDimitry Andric   case llvm::Triple::systemz: {
238fe013be4SDimitry Andric     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
239fe013be4SDimitry Andric     bool HasVector = !SoftFloat && Target.getABI() == "vector";
240fe013be4SDimitry Andric     return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
241fe013be4SDimitry Andric   }
242fe013be4SDimitry Andric 
243fe013be4SDimitry Andric   case llvm::Triple::tce:
244fe013be4SDimitry Andric   case llvm::Triple::tcele:
245fe013be4SDimitry Andric     return createTCETargetCodeGenInfo(CGM);
246fe013be4SDimitry Andric 
247fe013be4SDimitry Andric   case llvm::Triple::x86: {
248fe013be4SDimitry Andric     bool IsDarwinVectorABI = Triple.isOSDarwin();
249fe013be4SDimitry Andric     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
250fe013be4SDimitry Andric 
251fe013be4SDimitry Andric     if (Triple.getOS() == llvm::Triple::Win32) {
252fe013be4SDimitry Andric       return createWinX86_32TargetCodeGenInfo(
253fe013be4SDimitry Andric           CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
254fe013be4SDimitry Andric           CodeGenOpts.NumRegisterParameters);
255fe013be4SDimitry Andric     }
256fe013be4SDimitry Andric     return createX86_32TargetCodeGenInfo(
257fe013be4SDimitry Andric         CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
258fe013be4SDimitry Andric         CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
259fe013be4SDimitry Andric   }
260fe013be4SDimitry Andric 
261fe013be4SDimitry Andric   case llvm::Triple::x86_64: {
262fe013be4SDimitry Andric     StringRef ABI = Target.getABI();
263fe013be4SDimitry Andric     X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
264fe013be4SDimitry Andric                                : ABI == "avx"  ? X86AVXABILevel::AVX
265fe013be4SDimitry Andric                                                : X86AVXABILevel::None);
266fe013be4SDimitry Andric 
267fe013be4SDimitry Andric     switch (Triple.getOS()) {
268fe013be4SDimitry Andric     case llvm::Triple::Win32:
269fe013be4SDimitry Andric       return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
270fe013be4SDimitry Andric     default:
271fe013be4SDimitry Andric       return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
272fe013be4SDimitry Andric     }
273fe013be4SDimitry Andric   }
274fe013be4SDimitry Andric   case llvm::Triple::hexagon:
275fe013be4SDimitry Andric     return createHexagonTargetCodeGenInfo(CGM);
276fe013be4SDimitry Andric   case llvm::Triple::lanai:
277fe013be4SDimitry Andric     return createLanaiTargetCodeGenInfo(CGM);
278fe013be4SDimitry Andric   case llvm::Triple::r600:
279fe013be4SDimitry Andric     return createAMDGPUTargetCodeGenInfo(CGM);
280fe013be4SDimitry Andric   case llvm::Triple::amdgcn:
281fe013be4SDimitry Andric     return createAMDGPUTargetCodeGenInfo(CGM);
282fe013be4SDimitry Andric   case llvm::Triple::sparc:
283fe013be4SDimitry Andric     return createSparcV8TargetCodeGenInfo(CGM);
284fe013be4SDimitry Andric   case llvm::Triple::sparcv9:
285fe013be4SDimitry Andric     return createSparcV9TargetCodeGenInfo(CGM);
286fe013be4SDimitry Andric   case llvm::Triple::xcore:
287fe013be4SDimitry Andric     return createXCoreTargetCodeGenInfo(CGM);
288fe013be4SDimitry Andric   case llvm::Triple::arc:
289fe013be4SDimitry Andric     return createARCTargetCodeGenInfo(CGM);
290fe013be4SDimitry Andric   case llvm::Triple::spir:
291fe013be4SDimitry Andric   case llvm::Triple::spir64:
292fe013be4SDimitry Andric     return createCommonSPIRTargetCodeGenInfo(CGM);
293fe013be4SDimitry Andric   case llvm::Triple::spirv32:
294fe013be4SDimitry Andric   case llvm::Triple::spirv64:
295fe013be4SDimitry Andric     return createSPIRVTargetCodeGenInfo(CGM);
296fe013be4SDimitry Andric   case llvm::Triple::ve:
297fe013be4SDimitry Andric     return createVETargetCodeGenInfo(CGM);
298fe013be4SDimitry Andric   case llvm::Triple::csky: {
299fe013be4SDimitry Andric     bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
300fe013be4SDimitry Andric     bool hasFP64 =
301fe013be4SDimitry Andric         Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
302fe013be4SDimitry Andric     return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
303fe013be4SDimitry Andric                                             : hasFP64   ? 64
304fe013be4SDimitry Andric                                                         : 32);
305fe013be4SDimitry Andric   }
306fe013be4SDimitry Andric   case llvm::Triple::bpfeb:
307fe013be4SDimitry Andric   case llvm::Triple::bpfel:
308fe013be4SDimitry Andric     return createBPFTargetCodeGenInfo(CGM);
309fe013be4SDimitry Andric   case llvm::Triple::loongarch32:
310fe013be4SDimitry Andric   case llvm::Triple::loongarch64: {
311fe013be4SDimitry Andric     StringRef ABIStr = Target.getABI();
312fe013be4SDimitry Andric     unsigned ABIFRLen = 0;
313c9157d92SDimitry Andric     if (ABIStr.ends_with("f"))
314fe013be4SDimitry Andric       ABIFRLen = 32;
315c9157d92SDimitry Andric     else if (ABIStr.ends_with("d"))
316fe013be4SDimitry Andric       ABIFRLen = 64;
317fe013be4SDimitry Andric     return createLoongArchTargetCodeGenInfo(
318fe013be4SDimitry Andric         CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
319fe013be4SDimitry Andric   }
320fe013be4SDimitry Andric   }
321fe013be4SDimitry Andric }
322fe013be4SDimitry Andric 
getTargetCodeGenInfo()323fe013be4SDimitry Andric const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
324fe013be4SDimitry Andric   if (!TheTargetCodeGenInfo)
325fe013be4SDimitry Andric     TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
326fe013be4SDimitry Andric   return *TheTargetCodeGenInfo;
327fe013be4SDimitry Andric }
328fe013be4SDimitry Andric 
CodeGenModule(ASTContext & C,IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::Module & M,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)329972a253aSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C,
330972a253aSDimitry Andric                              IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
331972a253aSDimitry Andric                              const HeaderSearchOptions &HSO,
3320b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
3330b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
3340b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
3350b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
336fe013be4SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
337fe013be4SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
338fe013be4SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
339fe013be4SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
340fe013be4SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   // Initialize the type cache.
3430b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
3440b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
3450b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
3460b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
3470b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
3480b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
3490b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
3505ffd83dbSDimitry Andric   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
3510b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
3520b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
353bdd1243dSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
3540b57cec5SDimitry Andric   PointerAlignInBytes =
355bdd1243dSDimitry Andric       C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
356bdd1243dSDimitry Andric           .getQuantity();
3570b57cec5SDimitry Andric   SizeSizeInBytes =
3580b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
3590b57cec5SDimitry Andric   IntAlignInBytes =
3600b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
361e8d8bef9SDimitry Andric   CharTy =
362e8d8bef9SDimitry Andric     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
3630b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
3640b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
3650b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
366c9157d92SDimitry Andric   Int8PtrTy = llvm::PointerType::get(LLVMContext, 0);
367349cc55cSDimitry Andric   const llvm::DataLayout &DL = M.getDataLayout();
368c9157d92SDimitry Andric   AllocaInt8PtrTy =
369c9157d92SDimitry Andric       llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
370c9157d92SDimitry Andric   GlobalsInt8PtrTy =
371c9157d92SDimitry Andric       llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
372c9157d92SDimitry Andric   ConstGlobalsPtrTy = llvm::PointerType::get(
373c9157d92SDimitry Andric       LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
3740b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
3750b57cec5SDimitry Andric 
376fcaf7f86SDimitry Andric   // Build C++20 Module initializers.
377fcaf7f86SDimitry Andric   // TODO: Add Microsoft here once we know the mangling required for the
378fcaf7f86SDimitry Andric   // initializers.
379fcaf7f86SDimitry Andric   CXX20ModuleInits =
380fcaf7f86SDimitry Andric       LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
381fcaf7f86SDimitry Andric                                        ItaniumMangleContext::MK_Itanium;
382fcaf7f86SDimitry Andric 
3830b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   if (LangOpts.ObjC)
3860b57cec5SDimitry Andric     createObjCRuntime();
3870b57cec5SDimitry Andric   if (LangOpts.OpenCL)
3880b57cec5SDimitry Andric     createOpenCLRuntime();
3890b57cec5SDimitry Andric   if (LangOpts.OpenMP)
3900b57cec5SDimitry Andric     createOpenMPRuntime();
3910b57cec5SDimitry Andric   if (LangOpts.CUDA)
3920b57cec5SDimitry Andric     createCUDARuntime();
39381ad6265SDimitry Andric   if (LangOpts.HLSL)
39481ad6265SDimitry Andric     createHLSLRuntime();
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
3970b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
3980b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
3990b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
4000b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
4030b57cec5SDimitry Andric   // object.
404fe013be4SDimitry Andric   if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
405fe013be4SDimitry Andric       CodeGenOpts.CoverageNotesFile.size() ||
406fe013be4SDimitry Andric       CodeGenOpts.CoverageDataFile.size())
4070b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
4120b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
4150b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
416fe013be4SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, *FS,
417fe013be4SDimitry Andric         CodeGenOpts.ProfileRemappingFile);
418bdd1243dSDimitry Andric     // We're checking for profile read errors in CompilerInvocation, so if
419bdd1243dSDimitry Andric     // there was an error it should've already been caught. If it hasn't been
420bdd1243dSDimitry Andric     // somehow, trip an assertion.
421bdd1243dSDimitry Andric     assert(ReaderOrErr);
4220b57cec5SDimitry Andric     PGOReader = std::move(ReaderOrErr.get());
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
4260b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
4270b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
4280b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
429fe6060f1SDimitry Andric 
430fe6060f1SDimitry Andric   // Generate the module name hash here if needed.
431fe6060f1SDimitry Andric   if (CodeGenOpts.UniqueInternalLinkageNames &&
432fe6060f1SDimitry Andric       !getModule().getSourceFileName().empty()) {
433fe6060f1SDimitry Andric     std::string Path = getModule().getSourceFileName();
434fe6060f1SDimitry Andric     // Check if a path substitution is needed from the MacroPrefixMap.
4356e75b2fbSDimitry Andric     for (const auto &Entry : LangOpts.MacroPrefixMap)
436fe6060f1SDimitry Andric       if (Path.rfind(Entry.first, 0) != std::string::npos) {
437fe6060f1SDimitry Andric         Path = Entry.second + Path.substr(Entry.first.size());
438fe6060f1SDimitry Andric         break;
439fe6060f1SDimitry Andric       }
440bdd1243dSDimitry Andric     ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
441fe6060f1SDimitry Andric   }
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
~CodeGenModule()4440b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
4450b57cec5SDimitry Andric 
createObjCRuntime()4460b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
4470b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
4480b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
4490b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
4500b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
4510b57cec5SDimitry Andric   case ObjCRuntime::GCC:
4520b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
4530b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
4540b57cec5SDimitry Andric     return;
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
4570b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
4580b57cec5SDimitry Andric   case ObjCRuntime::iOS:
4590b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
4600b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
4610b57cec5SDimitry Andric     return;
4620b57cec5SDimitry Andric   }
4630b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
createOpenCLRuntime()4660b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
4670b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
createOpenMPRuntime()4700b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
4710b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
4720b57cec5SDimitry Andric   // If it does not exist use the default implementation.
4730b57cec5SDimitry Andric   switch (getTriple().getArch()) {
4740b57cec5SDimitry Andric   case llvm::Triple::nvptx:
4750b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
476e8d8bef9SDimitry Andric   case llvm::Triple::amdgcn:
477fe013be4SDimitry Andric     assert(getLangOpts().OpenMPIsTargetDevice &&
478349cc55cSDimitry Andric            "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
479349cc55cSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
480e8d8bef9SDimitry Andric     break;
4810b57cec5SDimitry Andric   default:
4820b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
4830b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
4840b57cec5SDimitry Andric     else
4850b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
4860b57cec5SDimitry Andric     break;
4870b57cec5SDimitry Andric   }
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric 
createCUDARuntime()4900b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
4910b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric 
createHLSLRuntime()49481ad6265SDimitry Andric void CodeGenModule::createHLSLRuntime() {
49581ad6265SDimitry Andric   HLSLRuntime.reset(new CGHLSLRuntime(*this));
49681ad6265SDimitry Andric }
49781ad6265SDimitry Andric 
addReplacement(StringRef Name,llvm::Constant * C)4980b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
4990b57cec5SDimitry Andric   Replacements[Name] = C;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
applyReplacements()5020b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
5030b57cec5SDimitry Andric   for (auto &I : Replacements) {
504fe013be4SDimitry Andric     StringRef MangledName = I.first;
5050b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
5060b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5070b57cec5SDimitry Andric     if (!Entry)
5080b57cec5SDimitry Andric       continue;
5090b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
5100b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
5110b57cec5SDimitry Andric     if (!NewF) {
5120b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
5130b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
5140b57cec5SDimitry Andric       } else {
5150b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
5160b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
5170b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
5180b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
5190b57cec5SDimitry Andric       }
5200b57cec5SDimitry Andric     }
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
5230b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
5240b57cec5SDimitry Andric     if (NewF) {
5250b57cec5SDimitry Andric       NewF->removeFromParent();
5260b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
5270b57cec5SDimitry Andric                                                        NewF);
5280b57cec5SDimitry Andric     }
5290b57cec5SDimitry Andric     OldF->eraseFromParent();
5300b57cec5SDimitry Andric   }
5310b57cec5SDimitry Andric }
5320b57cec5SDimitry Andric 
addGlobalValReplacement(llvm::GlobalValue * GV,llvm::Constant * C)5330b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
5340b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
applyGlobalValReplacements()5370b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
5380b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
5390b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
5400b57cec5SDimitry Andric     llvm::Constant *C = I.second;
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
5430b57cec5SDimitry Andric     GV->eraseFromParent();
5440b57cec5SDimitry Andric   }
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
5480b57cec5SDimitry Andric // linear structure.
getAliasedGlobal(const llvm::GlobalValue * GV)549349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
550349cc55cSDimitry Andric   const llvm::Constant *C;
551349cc55cSDimitry Andric   if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
552349cc55cSDimitry Andric     C = GA->getAliasee();
553349cc55cSDimitry Andric   else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
554349cc55cSDimitry Andric     C = GI->getResolver();
555349cc55cSDimitry Andric   else
556349cc55cSDimitry Andric     return GV;
557349cc55cSDimitry Andric 
558349cc55cSDimitry Andric   const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
559349cc55cSDimitry Andric   if (!AliaseeGV)
5600b57cec5SDimitry Andric     return nullptr;
561349cc55cSDimitry Andric 
562349cc55cSDimitry Andric   const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
563349cc55cSDimitry Andric   if (FinalGV == GV)
5640b57cec5SDimitry Andric     return nullptr;
565349cc55cSDimitry Andric 
566349cc55cSDimitry Andric   return FinalGV;
5670b57cec5SDimitry Andric }
568349cc55cSDimitry Andric 
checkAliasedGlobal(const ASTContext & Context,DiagnosticsEngine & Diags,SourceLocation Location,bool IsIFunc,const llvm::GlobalValue * Alias,const llvm::GlobalValue * & GV,const llvm::MapVector<GlobalDecl,StringRef> & MangledDeclNames,SourceRange AliasRange)569fe013be4SDimitry Andric static bool checkAliasedGlobal(
570c9157d92SDimitry Andric     const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
571c9157d92SDimitry Andric     bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
572fe013be4SDimitry Andric     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
573fe013be4SDimitry Andric     SourceRange AliasRange) {
574349cc55cSDimitry Andric   GV = getAliasedGlobal(Alias);
575349cc55cSDimitry Andric   if (!GV) {
576349cc55cSDimitry Andric     Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
577349cc55cSDimitry Andric     return false;
578349cc55cSDimitry Andric   }
579349cc55cSDimitry Andric 
580c9157d92SDimitry Andric   if (GV->hasCommonLinkage()) {
581c9157d92SDimitry Andric     const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
582c9157d92SDimitry Andric     if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
583c9157d92SDimitry Andric       Diags.Report(Location, diag::err_alias_to_common);
584c9157d92SDimitry Andric       return false;
585c9157d92SDimitry Andric     }
586c9157d92SDimitry Andric   }
587c9157d92SDimitry Andric 
588349cc55cSDimitry Andric   if (GV->isDeclaration()) {
589349cc55cSDimitry Andric     Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
590fe013be4SDimitry Andric     Diags.Report(Location, diag::note_alias_requires_mangled_name)
591fe013be4SDimitry Andric         << IsIFunc << IsIFunc;
592fe013be4SDimitry Andric     // Provide a note if the given function is not found and exists as a
593fe013be4SDimitry Andric     // mangled name.
594fe013be4SDimitry Andric     for (const auto &[Decl, Name] : MangledDeclNames) {
595fe013be4SDimitry Andric       if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
596fe013be4SDimitry Andric         if (ND->getName() == GV->getName()) {
597fe013be4SDimitry Andric           Diags.Report(Location, diag::note_alias_mangled_name_alternative)
598fe013be4SDimitry Andric               << Name
599fe013be4SDimitry Andric               << FixItHint::CreateReplacement(
600fe013be4SDimitry Andric                      AliasRange,
601fe013be4SDimitry Andric                      (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
602fe013be4SDimitry Andric                          .str());
603fe013be4SDimitry Andric         }
604fe013be4SDimitry Andric       }
605fe013be4SDimitry Andric     }
606349cc55cSDimitry Andric     return false;
607349cc55cSDimitry Andric   }
608349cc55cSDimitry Andric 
609349cc55cSDimitry Andric   if (IsIFunc) {
610349cc55cSDimitry Andric     // Check resolver function type.
611349cc55cSDimitry Andric     const auto *F = dyn_cast<llvm::Function>(GV);
612349cc55cSDimitry Andric     if (!F) {
613349cc55cSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
614349cc55cSDimitry Andric           << IsIFunc << IsIFunc;
615349cc55cSDimitry Andric       return false;
616349cc55cSDimitry Andric     }
617349cc55cSDimitry Andric 
618349cc55cSDimitry Andric     llvm::FunctionType *FTy = F->getFunctionType();
619349cc55cSDimitry Andric     if (!FTy->getReturnType()->isPointerTy()) {
620349cc55cSDimitry Andric       Diags.Report(Location, diag::err_ifunc_resolver_return);
621349cc55cSDimitry Andric       return false;
622349cc55cSDimitry Andric     }
623349cc55cSDimitry Andric   }
624349cc55cSDimitry Andric 
625349cc55cSDimitry Andric   return true;
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric 
checkAliases()6280b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
6290b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
6300b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
6310b57cec5SDimitry Andric   // and aliases during codegen.
6320b57cec5SDimitry Andric   bool Error = false;
6330b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
6340b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
6350b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
6360b57cec5SDimitry Andric     SourceLocation Location;
637fe013be4SDimitry Andric     SourceRange Range;
6380b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
639fe013be4SDimitry Andric     if (const Attr *A = D->getDefiningAttr()) {
6400b57cec5SDimitry Andric       Location = A->getLocation();
641fe013be4SDimitry Andric       Range = A->getRange();
642fe013be4SDimitry Andric     } else
6430b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
644349cc55cSDimitry Andric 
6450b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
646349cc55cSDimitry Andric     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
647349cc55cSDimitry Andric     const llvm::GlobalValue *GV = nullptr;
648c9157d92SDimitry Andric     if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
649fe013be4SDimitry Andric                             MangledDeclNames, Range)) {
6500b57cec5SDimitry Andric       Error = true;
651349cc55cSDimitry Andric       continue;
6520b57cec5SDimitry Andric     }
6530b57cec5SDimitry Andric 
654349cc55cSDimitry Andric     llvm::Constant *Aliasee =
655349cc55cSDimitry Andric         IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
656349cc55cSDimitry Andric                 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
657349cc55cSDimitry Andric 
6580b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
6590b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
6600b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
6610b57cec5SDimitry Andric     else
6620b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
6650b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
6660b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
6670b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
6680b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
6690b57cec5SDimitry Andric     }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
6720b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
6730b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
6740b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
6750b57cec5SDimitry Andric     // expecting the link to be weak.
676349cc55cSDimitry Andric     if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
6770b57cec5SDimitry Andric       if (GA->isInterposable()) {
6780b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
6790b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
6800b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
681349cc55cSDimitry Andric             GA->getAliasee(), Alias->getType());
682349cc55cSDimitry Andric 
683349cc55cSDimitry Andric         if (IsIFunc)
684349cc55cSDimitry Andric           cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
685349cc55cSDimitry Andric         else
686349cc55cSDimitry Andric           cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
6870b57cec5SDimitry Andric       }
6880b57cec5SDimitry Andric     }
6890b57cec5SDimitry Andric   }
6900b57cec5SDimitry Andric   if (!Error)
6910b57cec5SDimitry Andric     return;
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
6940b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
695349cc55cSDimitry Andric     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
6960b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
6970b57cec5SDimitry Andric     Alias->eraseFromParent();
6980b57cec5SDimitry Andric   }
6990b57cec5SDimitry Andric }
7000b57cec5SDimitry Andric 
clear()7010b57cec5SDimitry Andric void CodeGenModule::clear() {
7020b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
703753f127fSDimitry Andric   EmittedDeferredDecls.clear();
704c9157d92SDimitry Andric   DeferredAnnotations.clear();
7050b57cec5SDimitry Andric   if (OpenMPRuntime)
7060b57cec5SDimitry Andric     OpenMPRuntime->clear();
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)7090b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
7100b57cec5SDimitry Andric                                        StringRef MainFile) {
7110b57cec5SDimitry Andric   if (!hasDiagnostics())
7120b57cec5SDimitry Andric     return;
7130b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
7140b57cec5SDimitry Andric     if (MainFile.empty())
7150b57cec5SDimitry Andric       MainFile = "<stdin>";
7160b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
7170b57cec5SDimitry Andric   } else {
7180b57cec5SDimitry Andric     if (Mismatched > 0)
7190b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric     if (Missing > 0)
7220b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
7230b57cec5SDimitry Andric   }
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
726a58f00eaSDimitry Andric static std::optional<llvm::GlobalValue::VisibilityTypes>
getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)727a58f00eaSDimitry Andric getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) {
728a58f00eaSDimitry Andric   // Map to LLVM visibility.
729a58f00eaSDimitry Andric   switch (K) {
730a58f00eaSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep:
731a58f00eaSDimitry Andric     return std::nullopt;
732a58f00eaSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default:
733a58f00eaSDimitry Andric     return llvm::GlobalValue::DefaultVisibility;
734a58f00eaSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden:
735a58f00eaSDimitry Andric     return llvm::GlobalValue::HiddenVisibility;
736a58f00eaSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected:
737a58f00eaSDimitry Andric     return llvm::GlobalValue::ProtectedVisibility;
738a58f00eaSDimitry Andric   }
739a58f00eaSDimitry Andric   llvm_unreachable("unknown option value!");
740a58f00eaSDimitry Andric }
741a58f00eaSDimitry Andric 
setLLVMVisibility(llvm::GlobalValue & GV,std::optional<llvm::GlobalValue::VisibilityTypes> V)742a58f00eaSDimitry Andric void setLLVMVisibility(llvm::GlobalValue &GV,
743a58f00eaSDimitry Andric                        std::optional<llvm::GlobalValue::VisibilityTypes> V) {
744a58f00eaSDimitry Andric   if (!V)
745e8d8bef9SDimitry Andric     return;
746e8d8bef9SDimitry Andric 
747e8d8bef9SDimitry Andric   // Reset DSO locality before setting the visibility. This removes
748e8d8bef9SDimitry Andric   // any effects that visibility options and annotations may have
749e8d8bef9SDimitry Andric   // had on the DSO locality. Setting the visibility will implicitly set
750e8d8bef9SDimitry Andric   // appropriate globals to DSO Local; however, this will be pessimistic
751e8d8bef9SDimitry Andric   // w.r.t. to the normal compiler IRGen.
752e8d8bef9SDimitry Andric   GV.setDSOLocal(false);
753a58f00eaSDimitry Andric   GV.setVisibility(*V);
754a58f00eaSDimitry Andric }
755e8d8bef9SDimitry Andric 
setVisibilityFromDLLStorageClass(const clang::LangOptions & LO,llvm::Module & M)756a58f00eaSDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
757a58f00eaSDimitry Andric                                              llvm::Module &M) {
758a58f00eaSDimitry Andric   if (!LO.VisibilityFromDLLStorageClass)
759a58f00eaSDimitry Andric     return;
760a58f00eaSDimitry Andric 
761a58f00eaSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
762a58f00eaSDimitry Andric       getLLVMVisibility(LO.getDLLExportVisibility());
763a58f00eaSDimitry Andric 
764a58f00eaSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes>
765a58f00eaSDimitry Andric       NoDLLStorageClassVisibility =
766a58f00eaSDimitry Andric           getLLVMVisibility(LO.getNoDLLStorageClassVisibility());
767a58f00eaSDimitry Andric 
768a58f00eaSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes>
769a58f00eaSDimitry Andric       ExternDeclDLLImportVisibility =
770a58f00eaSDimitry Andric           getLLVMVisibility(LO.getExternDeclDLLImportVisibility());
771a58f00eaSDimitry Andric 
772a58f00eaSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes>
773a58f00eaSDimitry Andric       ExternDeclNoDLLStorageClassVisibility =
774a58f00eaSDimitry Andric           getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility());
775a58f00eaSDimitry Andric 
776a58f00eaSDimitry Andric   for (llvm::GlobalValue &GV : M.global_values()) {
777a58f00eaSDimitry Andric     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
778a58f00eaSDimitry Andric       continue;
779a58f00eaSDimitry Andric 
780a58f00eaSDimitry Andric     if (GV.isDeclarationForLinker())
781a58f00eaSDimitry Andric       setLLVMVisibility(GV, GV.getDLLStorageClass() ==
782e8d8bef9SDimitry Andric                                     llvm::GlobalValue::DLLImportStorageClass
783e8d8bef9SDimitry Andric                                 ? ExternDeclDLLImportVisibility
784e8d8bef9SDimitry Andric                                 : ExternDeclNoDLLStorageClassVisibility);
785a58f00eaSDimitry Andric     else
786a58f00eaSDimitry Andric       setLLVMVisibility(GV, GV.getDLLStorageClass() ==
787e8d8bef9SDimitry Andric                                     llvm::GlobalValue::DLLExportStorageClass
788e8d8bef9SDimitry Andric                                 ? DLLExportVisibility
789e8d8bef9SDimitry Andric                                 : NoDLLStorageClassVisibility);
790e8d8bef9SDimitry Andric 
791e8d8bef9SDimitry Andric     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
792e8d8bef9SDimitry Andric   }
793e8d8bef9SDimitry Andric }
794e8d8bef9SDimitry Andric 
isStackProtectorOn(const LangOptions & LangOpts,const llvm::Triple & Triple,clang::LangOptions::StackProtectorMode Mode)795c9157d92SDimitry Andric static bool isStackProtectorOn(const LangOptions &LangOpts,
796c9157d92SDimitry Andric                                const llvm::Triple &Triple,
797c9157d92SDimitry Andric                                clang::LangOptions::StackProtectorMode Mode) {
798c9157d92SDimitry Andric   if (Triple.isAMDGPU() || Triple.isNVPTX())
799c9157d92SDimitry Andric     return false;
800c9157d92SDimitry Andric   return LangOpts.getStackProtector() == Mode;
801c9157d92SDimitry Andric }
802c9157d92SDimitry Andric 
Release()8030b57cec5SDimitry Andric void CodeGenModule::Release() {
804fe013be4SDimitry Andric   Module *Primary = getContext().getCurrentNamedModule();
80561cfbce3SDimitry Andric   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
806fcaf7f86SDimitry Andric     EmitModuleInitializers(Primary);
8070b57cec5SDimitry Andric   EmitDeferred();
808753f127fSDimitry Andric   DeferredDecls.insert(EmittedDeferredDecls.begin(),
809753f127fSDimitry Andric                        EmittedDeferredDecls.end());
810753f127fSDimitry Andric   EmittedDeferredDecls.clear();
8110b57cec5SDimitry Andric   EmitVTablesOpportunistically();
8120b57cec5SDimitry Andric   applyGlobalValReplacements();
8130b57cec5SDimitry Andric   applyReplacements();
8140b57cec5SDimitry Andric   emitMultiVersionFunctions();
815bdd1243dSDimitry Andric 
816bdd1243dSDimitry Andric   if (Context.getLangOpts().IncrementalExtensions &&
817bdd1243dSDimitry Andric       GlobalTopLevelStmtBlockInFlight.first) {
818bdd1243dSDimitry Andric     const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
819bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
820bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
821bdd1243dSDimitry Andric   }
822bdd1243dSDimitry Andric 
823fe013be4SDimitry Andric   // Module implementations are initialized the same way as a regular TU that
824fe013be4SDimitry Andric   // imports one or more modules.
825fcaf7f86SDimitry Andric   if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
826fcaf7f86SDimitry Andric     EmitCXXModuleInitFunc(Primary);
827fcaf7f86SDimitry Andric   else
8280b57cec5SDimitry Andric     EmitCXXGlobalInitFunc();
8295ffd83dbSDimitry Andric   EmitCXXGlobalCleanUpFunc();
8300b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
8310b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
8320b57cec5SDimitry Andric   if (ObjCRuntime)
8330b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
8340b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
835fe6060f1SDimitry Andric   if (Context.getLangOpts().CUDA && CUDARuntime) {
836fe6060f1SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
8370b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
8380b57cec5SDimitry Andric   }
8390b57cec5SDimitry Andric   if (OpenMPRuntime) {
8400b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
8410b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
8420b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
8430b57cec5SDimitry Andric     }
844a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
8450b57cec5SDimitry Andric     OpenMPRuntime->clear();
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric   if (PGOReader) {
8480b57cec5SDimitry Andric     getModule().setProfileSummary(
8490b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
8500b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
8510b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
8520b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
8530b57cec5SDimitry Andric   }
854bdd1243dSDimitry Andric   llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
855bdd1243dSDimitry Andric     return L.LexOrder < R.LexOrder;
856bdd1243dSDimitry Andric   });
8570b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
8580b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
8590b57cec5SDimitry Andric   EmitGlobalAnnotations();
8600b57cec5SDimitry Andric   EmitStaticExternCAliases();
86181ad6265SDimitry Andric   checkAliases();
8620b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
863fe6060f1SDimitry Andric   CodeGenPGO(*this).setValueProfilingFlag(getModule());
8640b57cec5SDimitry Andric   if (CoverageMapping)
8650b57cec5SDimitry Andric     CoverageMapping->emit();
8660b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
8670b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
8680b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
8690b57cec5SDimitry Andric   }
870bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
871bdd1243dSDimitry Andric     finalizeKCFITypes();
8720b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
87381ad6265SDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm())
8745ffd83dbSDimitry Andric     EmitMainVoidAlias();
875fe6060f1SDimitry Andric 
87681ad6265SDimitry Andric   if (getTriple().isAMDGPU()) {
87781ad6265SDimitry Andric     // Emit amdgpu_code_object_version module flag, which is code object version
87881ad6265SDimitry Andric     // times 100.
879bdd1243dSDimitry Andric     if (getTarget().getTargetOpts().CodeObjectVersion !=
880c9157d92SDimitry Andric         llvm::CodeObjectVersionKind::COV_None) {
88181ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Error,
88281ad6265SDimitry Andric                                 "amdgpu_code_object_version",
88381ad6265SDimitry Andric                                 getTarget().getTargetOpts().CodeObjectVersion);
88481ad6265SDimitry Andric     }
885fe013be4SDimitry Andric 
886fe013be4SDimitry Andric     // Currently, "-mprintf-kind" option is only supported for HIP
887fe013be4SDimitry Andric     if (LangOpts.HIP) {
888fe013be4SDimitry Andric       auto *MDStr = llvm::MDString::get(
889fe013be4SDimitry Andric           getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
890fe013be4SDimitry Andric                              TargetOptions::AMDGPUPrintfKind::Hostcall)
891fe013be4SDimitry Andric                                 ? "hostcall"
892fe013be4SDimitry Andric                                 : "buffered");
893fe013be4SDimitry Andric       getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
894fe013be4SDimitry Andric                                 MDStr);
895fe013be4SDimitry Andric     }
89681ad6265SDimitry Andric   }
89781ad6265SDimitry Andric 
89881ad6265SDimitry Andric   // Emit a global array containing all external kernels or device variables
89981ad6265SDimitry Andric   // used by host functions and mark it as used for CUDA/HIP. This is necessary
90081ad6265SDimitry Andric   // to get kernels or device variables in archives linked in even if these
90181ad6265SDimitry Andric   // kernels or device variables are only used in host functions.
90281ad6265SDimitry Andric   if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
90381ad6265SDimitry Andric     SmallVector<llvm::Constant *, 8> UsedArray;
90481ad6265SDimitry Andric     for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
90581ad6265SDimitry Andric       GlobalDecl GD;
90681ad6265SDimitry Andric       if (auto *FD = dyn_cast<FunctionDecl>(D))
90781ad6265SDimitry Andric         GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
90881ad6265SDimitry Andric       else
90981ad6265SDimitry Andric         GD = GlobalDecl(D);
91081ad6265SDimitry Andric       UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
91181ad6265SDimitry Andric           GetAddrOfGlobal(GD), Int8PtrTy));
91281ad6265SDimitry Andric     }
91381ad6265SDimitry Andric 
91481ad6265SDimitry Andric     llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
91581ad6265SDimitry Andric 
91681ad6265SDimitry Andric     auto *GV = new llvm::GlobalVariable(
91781ad6265SDimitry Andric         getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
91881ad6265SDimitry Andric         llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
91981ad6265SDimitry Andric     addCompilerUsedGlobal(GV);
92004eeddc0SDimitry Andric   }
921fe6060f1SDimitry Andric 
9220b57cec5SDimitry Andric   emitLLVMUsed();
9230b57cec5SDimitry Andric   if (SanStats)
9240b57cec5SDimitry Andric     SanStats->finish();
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
9270b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
9280b57cec5SDimitry Andric     EmitModuleLinkOptions();
9290b57cec5SDimitry Andric   }
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
9320b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
9330b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
9340b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
9350b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
9360b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
9370b57cec5SDimitry Andric   // libs to the linker.
9380b57cec5SDimitry Andric   //
9390b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
9400b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
9410b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
9420b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
9430b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
9440b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
9450b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
9460b57cec5SDimitry Andric       NMD->addOperand(MD);
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
9500b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
9510b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
9520b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
955480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
9560b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
9570b57cec5SDimitry Andric   }
9585ffd83dbSDimitry Andric 
959fe6060f1SDimitry Andric   if (CodeGenOpts.Dwarf64)
960fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
961fe6060f1SDimitry Andric 
9625ffd83dbSDimitry Andric   if (Context.getLangOpts().SemanticInterposition)
9635ffd83dbSDimitry Andric     // Require various optimization to respect semantic interposition.
96404eeddc0SDimitry Andric     getModule().setSemanticInterposition(true);
9655ffd83dbSDimitry Andric 
9660b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
9670b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
9680b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
9690b57cec5SDimitry Andric   }
9700b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
9710b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
9720b57cec5SDimitry Andric   }
9730b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
974480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
975480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
976480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
977480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
978480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
9790b57cec5SDimitry Andric   }
980fe6060f1SDimitry Andric   if (CodeGenOpts.EHContGuard) {
981fe6060f1SDimitry Andric     // Function ID tables for EH Continuation Guard.
982fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
983fe6060f1SDimitry Andric   }
984bdd1243dSDimitry Andric   if (Context.getLangOpts().Kernel) {
985bdd1243dSDimitry Andric     // Note if we are compiling with /kernel.
986bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
987bdd1243dSDimitry Andric   }
9880b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
9890b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
9900b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
9910b57cec5SDimitry Andric     // by StrictVTablePointers.
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
9960b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
9970b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
9980b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
10010b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
10020b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
10030b57cec5SDimitry Andric   }
10045ffd83dbSDimitry Andric   if (getModuleDebugInfo())
10050b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
10060b57cec5SDimitry Andric     // parser will drop debug info with a different version number
10070b57cec5SDimitry Andric     // (and warn about it, too).
10080b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
10090b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
10120b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
10130b57cec5SDimitry Andric   // TargetLibraryInfo.
10140b57cec5SDimitry Andric   uint64_t WCharWidth =
10150b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
10160b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
10170b57cec5SDimitry Andric 
1018c9157d92SDimitry Andric   if (getTriple().isOSzOS()) {
1019c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning,
1020c9157d92SDimitry Andric                               "zos_product_major_version",
1021c9157d92SDimitry Andric                               uint32_t(CLANG_VERSION_MAJOR));
1022c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning,
1023c9157d92SDimitry Andric                               "zos_product_minor_version",
1024c9157d92SDimitry Andric                               uint32_t(CLANG_VERSION_MINOR));
1025c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel",
1026c9157d92SDimitry Andric                               uint32_t(CLANG_VERSION_PATCHLEVEL));
1027e710425bSDimitry Andric     std::string ProductId = getClangVendor() + "clang";
1028c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "zos_product_id",
1029c9157d92SDimitry Andric                               llvm::MDString::get(VMContext, ProductId));
1030c9157d92SDimitry Andric 
1031c9157d92SDimitry Andric     // Record the language because we need it for the PPA2.
1032c9157d92SDimitry Andric     StringRef lang_str = languageToString(
1033c9157d92SDimitry Andric         LangStandard::getLangStandardForKind(LangOpts.LangStd).Language);
1034c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language",
1035c9157d92SDimitry Andric                               llvm::MDString::get(VMContext, lang_str));
1036c9157d92SDimitry Andric 
1037c9157d92SDimitry Andric     time_t TT = PreprocessorOpts.SourceDateEpoch
1038c9157d92SDimitry Andric                     ? *PreprocessorOpts.SourceDateEpoch
1039c9157d92SDimitry Andric                     : std::time(nullptr);
1040c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time",
1041c9157d92SDimitry Andric                               static_cast<uint64_t>(TT));
1042c9157d92SDimitry Andric 
1043c9157d92SDimitry Andric     // Multiple modes will be supported here.
1044c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
1045c9157d92SDimitry Andric                               llvm::MDString::get(VMContext, "ascii"));
1046c9157d92SDimitry Andric   }
1047c9157d92SDimitry Andric 
10480b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
10490b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
10500b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
10510b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
10520b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
10530b57cec5SDimitry Andric     // The minimum width of an enum in bytes
10540b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
10550b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
10560b57cec5SDimitry Andric   }
10570b57cec5SDimitry Andric 
105813138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
105913138422SDimitry Andric     StringRef ABIStr = Target.getABI();
106013138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
106113138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
106213138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
1063*f1e32799SDimitry Andric 
1064*f1e32799SDimitry Andric     // Add the canonical ISA string as metadata so the backend can set the ELF
1065*f1e32799SDimitry Andric     // attributes correctly. We use AppendUnique so LTO will keep all of the
1066*f1e32799SDimitry Andric     // unique ISA strings that were linked together.
1067*f1e32799SDimitry Andric     const std::vector<std::string> &Features =
1068*f1e32799SDimitry Andric         getTarget().getTargetOpts().Features;
1069*f1e32799SDimitry Andric     auto ParseResult = llvm::RISCVISAInfo::parseFeatures(
1070*f1e32799SDimitry Andric         Arch == llvm::Triple::riscv64 ? 64 : 32, Features);
1071*f1e32799SDimitry Andric     if (!errorToBool(ParseResult.takeError()))
1072*f1e32799SDimitry Andric       getModule().addModuleFlag(
1073*f1e32799SDimitry Andric           llvm::Module::AppendUnique, "riscv-isa",
1074*f1e32799SDimitry Andric           llvm::MDNode::get(
1075*f1e32799SDimitry Andric               Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
107613138422SDimitry Andric   }
107713138422SDimitry Andric 
10780b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10790b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
10800b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
10810b57cec5SDimitry Andric   }
10820b57cec5SDimitry Andric 
10835ffd83dbSDimitry Andric   if (CodeGenOpts.WholeProgramVTables) {
10845ffd83dbSDimitry Andric     // Indicate whether VFE was enabled for this module, so that the
10855ffd83dbSDimitry Andric     // vcall_visibility metadata added under whole program vtables is handled
10865ffd83dbSDimitry Andric     // appropriately in the optimizer.
10875ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
10885ffd83dbSDimitry Andric                               CodeGenOpts.VirtualFunctionElimination);
10895ffd83dbSDimitry Andric   }
10905ffd83dbSDimitry Andric 
1091a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1092a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
1093a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
1094a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1095a7dea167SDimitry Andric   }
1096a7dea167SDimitry Andric 
1097bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1098bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1099bdd1243dSDimitry Andric     // KCFI assumes patchable-function-prefix is the same for all indirectly
1100bdd1243dSDimitry Andric     // called functions. Store the expected offset for code generation.
1101bdd1243dSDimitry Andric     if (CodeGenOpts.PatchableFunctionEntryOffset)
1102bdd1243dSDimitry Andric       getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1103bdd1243dSDimitry Andric                                 CodeGenOpts.PatchableFunctionEntryOffset);
1104bdd1243dSDimitry Andric   }
1105bdd1243dSDimitry Andric 
11060b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
11070b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
11080b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
1109fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
11100b57cec5SDimitry Andric                               1);
11110b57cec5SDimitry Andric   }
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
11140b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
11150b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
1116fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
11170b57cec5SDimitry Andric                               1);
11180b57cec5SDimitry Andric   }
11190b57cec5SDimitry Andric 
1120fcaf7f86SDimitry Andric   if (CodeGenOpts.FunctionReturnThunks)
1121fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
112204eeddc0SDimitry Andric 
1123bdd1243dSDimitry Andric   if (CodeGenOpts.IndirectBranchCSPrefix)
1124bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1125bdd1243dSDimitry Andric 
11264824e7fdSDimitry Andric   // Add module metadata for return address signing (ignoring
11274824e7fdSDimitry Andric   // non-leaf/all) and stack tagging. These are actually turned on by function
11284824e7fdSDimitry Andric   // attributes, but we use module metadata to emit build attributes. This is
11294824e7fdSDimitry Andric   // needed for LTO, where the function attributes are inside bitcode
11304824e7fdSDimitry Andric   // serialised into a global variable by the time build attributes are
113181ad6265SDimitry Andric   // emitted, so we can't access them. LTO objects could be compiled with
113281ad6265SDimitry Andric   // different flags therefore module flags are set to "Min" behavior to achieve
113381ad6265SDimitry Andric   // the same end result of the normal build where e.g BTI is off if any object
113481ad6265SDimitry Andric   // doesn't support it.
11354824e7fdSDimitry Andric   if (Context.getTargetInfo().hasFeature("ptrauth") &&
11364824e7fdSDimitry Andric       LangOpts.getSignReturnAddressScope() !=
11374824e7fdSDimitry Andric           LangOptions::SignReturnAddressScopeKind::None)
11384824e7fdSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
11394824e7fdSDimitry Andric                               "sign-return-address-buildattr", 1);
114081ad6265SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
11414824e7fdSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
11424824e7fdSDimitry Andric                               "tag-stack-memory-buildattr", 1);
11434824e7fdSDimitry Andric 
11444824e7fdSDimitry Andric   if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
11451fd87a68SDimitry Andric       Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
11464824e7fdSDimitry Andric       Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
1147e8d8bef9SDimitry Andric       Arch == llvm::Triple::aarch64_be) {
1148972a253aSDimitry Andric     if (LangOpts.BranchTargetEnforcement)
114981ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1150972a253aSDimitry Andric                                 1);
1151e710425bSDimitry Andric     if (LangOpts.BranchProtectionPAuthLR)
1152e710425bSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr",
1153e710425bSDimitry Andric                                 1);
11546c20abcdSDimitry Andric     if (LangOpts.GuardedControlStack)
11556c20abcdSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1);
1156972a253aSDimitry Andric     if (LangOpts.hasSignReturnAddress())
1157972a253aSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1158972a253aSDimitry Andric     if (LangOpts.isSignReturnAddressScopeAll())
115981ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1160972a253aSDimitry Andric                                 1);
1161972a253aSDimitry Andric     if (!LangOpts.isSignReturnAddressWithAKey())
116281ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min,
1163972a253aSDimitry Andric                                 "sign-return-address-with-bkey", 1);
1164e8d8bef9SDimitry Andric   }
1165e8d8bef9SDimitry Andric 
1166c9157d92SDimitry Andric   if (CodeGenOpts.StackClashProtector)
1167c9157d92SDimitry Andric     getModule().addModuleFlag(
1168c9157d92SDimitry Andric         llvm::Module::Override, "probe-stack",
1169c9157d92SDimitry Andric         llvm::MDString::get(TheModule.getContext(), "inline-asm"));
1170c9157d92SDimitry Andric 
1171c9157d92SDimitry Andric   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1172c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
1173c9157d92SDimitry Andric                               CodeGenOpts.StackProbeSize);
1174c9157d92SDimitry Andric 
1175e8d8bef9SDimitry Andric   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1176e8d8bef9SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
1177e8d8bef9SDimitry Andric     getModule().addModuleFlag(
1178e8d8bef9SDimitry Andric         llvm::Module::Error, "MemProfProfileFilename",
1179e8d8bef9SDimitry Andric         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1180e8d8bef9SDimitry Andric   }
1181e8d8bef9SDimitry Andric 
11820b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
11830b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
11840b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
11850b57cec5SDimitry Andric     // property.)
11860b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
11875ffd83dbSDimitry Andric                               CodeGenOpts.FP32DenormalMode.Output !=
11885ffd83dbSDimitry Andric                                   llvm::DenormalMode::IEEE);
11890b57cec5SDimitry Andric   }
11900b57cec5SDimitry Andric 
1191fe6060f1SDimitry Andric   if (LangOpts.EHAsynch)
1192fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1193fe6060f1SDimitry Andric 
1194fe6060f1SDimitry Andric   // Indicate whether this Module was compiled with -fopenmp
1195fe6060f1SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1196fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
1197fe013be4SDimitry Andric   if (getLangOpts().OpenMPIsTargetDevice)
1198fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1199fe6060f1SDimitry Andric                               LangOpts.OpenMP);
1200fe6060f1SDimitry Andric 
12010b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
120281ad6265SDimitry Andric   if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
12030b57cec5SDimitry Andric     EmitOpenCLMetadata();
12040b57cec5SDimitry Andric     // Emit SPIR version.
12050b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
12060b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
12070b57cec5SDimitry Andric       // opencl.spir.version named metadata.
1208349cc55cSDimitry Andric       // C++ for OpenCL has a distinct mapping for version compatibility with
1209349cc55cSDimitry Andric       // OpenCL.
1210349cc55cSDimitry Andric       auto Version = LangOpts.getOpenCLCompatibleVersion();
12110b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
12120b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
12130b57cec5SDimitry Andric               Int32Ty, Version / 100)),
12140b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
12150b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
12160b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
12170b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
12180b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
12190b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
12200b57cec5SDimitry Andric     }
12210b57cec5SDimitry Andric   }
12220b57cec5SDimitry Andric 
122381ad6265SDimitry Andric   // HLSL related end of code gen work items.
122481ad6265SDimitry Andric   if (LangOpts.HLSL)
122581ad6265SDimitry Andric     getHLSLRuntime().finishCodeGen();
122681ad6265SDimitry Andric 
12270b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
12280b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
12290b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
12300b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
12310b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
12320b57cec5SDimitry Andric   }
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
12350b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
12360b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
12370b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
12380b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
12390b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
12400b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
12410b57cec5SDimitry Andric                   .Default(~0u);
12420b57cec5SDimitry Andric     if (CM != ~0u) {
12430b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
12440b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
1245c9157d92SDimitry Andric 
1246a58f00eaSDimitry Andric       if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1247c9157d92SDimitry Andric           Context.getTargetInfo().getTriple().getArch() ==
1248c9157d92SDimitry Andric               llvm::Triple::x86_64) {
1249c9157d92SDimitry Andric         getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold);
1250c9157d92SDimitry Andric       }
12510b57cec5SDimitry Andric     }
12520b57cec5SDimitry Andric   }
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
12550b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
1256fe013be4SDimitry Andric   if (getTriple().isOSBinFormatELF() &&
1257fe013be4SDimitry Andric       CodeGenOpts.DirectAccessExternalData !=
1258fe013be4SDimitry Andric           getModule().getDirectAccessExternalData()) {
1259fe013be4SDimitry Andric     getModule().setDirectAccessExternalData(
1260fe013be4SDimitry Andric         CodeGenOpts.DirectAccessExternalData);
1261fe013be4SDimitry Andric   }
1262fe6060f1SDimitry Andric   if (CodeGenOpts.UnwindTables)
126381ad6265SDimitry Andric     getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1264fe6060f1SDimitry Andric 
1265fe6060f1SDimitry Andric   switch (CodeGenOpts.getFramePointer()) {
1266fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
1267fe6060f1SDimitry Andric     // 0 ("none") is the default.
1268fe6060f1SDimitry Andric     break;
1269fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
1270fe6060f1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1271fe6060f1SDimitry Andric     break;
1272fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
1273fe6060f1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::All);
1274fe6060f1SDimitry Andric     break;
1275fe6060f1SDimitry Andric   }
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric   SimplifyPersonality();
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
12800b57cec5SDimitry Andric     EmitDeclMetadata();
12810b57cec5SDimitry Andric 
1282fe013be4SDimitry Andric   if (getCodeGenOpts().CoverageNotesFile.size() ||
1283fe013be4SDimitry Andric       getCodeGenOpts().CoverageDataFile.size())
12840b57cec5SDimitry Andric     EmitCoverageFile();
12850b57cec5SDimitry Andric 
12865ffd83dbSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
12875ffd83dbSDimitry Andric     DI->finalize();
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
12900b57cec5SDimitry Andric     EmitVersionIdentMetadata();
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
12930b57cec5SDimitry Andric     EmitCommandLineMetadata();
12940b57cec5SDimitry Andric 
1295fe6060f1SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuard.empty())
1296fe6060f1SDimitry Andric     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1297fe6060f1SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1298fe6060f1SDimitry Andric     getModule().setStackProtectorGuardReg(
1299fe6060f1SDimitry Andric         getCodeGenOpts().StackProtectorGuardReg);
1300753f127fSDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1301753f127fSDimitry Andric     getModule().setStackProtectorGuardSymbol(
1302753f127fSDimitry Andric         getCodeGenOpts().StackProtectorGuardSymbol);
1303fe6060f1SDimitry Andric   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1304fe6060f1SDimitry Andric     getModule().setStackProtectorGuardOffset(
1305fe6060f1SDimitry Andric         getCodeGenOpts().StackProtectorGuardOffset);
1306fe6060f1SDimitry Andric   if (getCodeGenOpts().StackAlignment)
1307fe6060f1SDimitry Andric     getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1308349cc55cSDimitry Andric   if (getCodeGenOpts().SkipRaxSetup)
1309349cc55cSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1310c9157d92SDimitry Andric   if (getLangOpts().RegCall4)
1311c9157d92SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1312fe6060f1SDimitry Andric 
1313fe013be4SDimitry Andric   if (getContext().getTargetInfo().getMaxTLSAlign())
1314fe013be4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1315fe013be4SDimitry Andric                               getContext().getTargetInfo().getMaxTLSAlign());
1316fe013be4SDimitry Andric 
1317c9157d92SDimitry Andric   getTargetCodeGenInfo().emitTargetGlobals(*this);
1318c9157d92SDimitry Andric 
13195ffd83dbSDimitry Andric   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
13205ffd83dbSDimitry Andric 
13215ffd83dbSDimitry Andric   EmitBackendOptionsMetadata(getCodeGenOpts());
1322e8d8bef9SDimitry Andric 
132381ad6265SDimitry Andric   // If there is device offloading code embed it in the host now.
132481ad6265SDimitry Andric   EmbedObject(&getModule(), CodeGenOpts, getDiags());
132581ad6265SDimitry Andric 
1326e8d8bef9SDimitry Andric   // Set visibility from DLL storage class
1327e8d8bef9SDimitry Andric   // We do this at the end of LLVM IR generation; after any operation
1328e8d8bef9SDimitry Andric   // that might affect the DLL storage class or the visibility, and
1329e8d8bef9SDimitry Andric   // before anything that might act on these.
1330e8d8bef9SDimitry Andric   setVisibilityFromDLLStorageClass(LangOpts, getModule());
13310b57cec5SDimitry Andric }
13320b57cec5SDimitry Andric 
EmitOpenCLMetadata()13330b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
13340b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
13350b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
1336349cc55cSDimitry Andric   // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
1337349cc55cSDimitry Andric   auto Version = LangOpts.getOpenCLCompatibleVersion();
13380b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
13390b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
13400b57cec5SDimitry Andric           Int32Ty, Version / 100)),
13410b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
13420b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
13430b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
13440b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
13450b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
13460b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
13470b57cec5SDimitry Andric }
13480b57cec5SDimitry Andric 
EmitBackendOptionsMetadata(const CodeGenOptions & CodeGenOpts)13495ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata(
1350fe013be4SDimitry Andric     const CodeGenOptions &CodeGenOpts) {
1351bdd1243dSDimitry Andric   if (getTriple().isRISCV()) {
1352fe013be4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
13535ffd83dbSDimitry Andric                               CodeGenOpts.SmallDataLimit);
13545ffd83dbSDimitry Andric   }
13555ffd83dbSDimitry Andric }
13565ffd83dbSDimitry Andric 
UpdateCompletedType(const TagDecl * TD)13570b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
13580b57cec5SDimitry Andric   // Make sure that this type is translated.
13590b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
13600b57cec5SDimitry Andric }
13610b57cec5SDimitry Andric 
RefreshTypeCacheForClass(const CXXRecordDecl * RD)13620b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
13630b57cec5SDimitry Andric   // Make sure that this type is translated.
13640b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
13650b57cec5SDimitry Andric }
13660b57cec5SDimitry Andric 
getTBAATypeInfo(QualType QTy)13670b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
13680b57cec5SDimitry Andric   if (!TBAA)
13690b57cec5SDimitry Andric     return nullptr;
13700b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
13710b57cec5SDimitry Andric }
13720b57cec5SDimitry Andric 
getTBAAAccessInfo(QualType AccessType)13730b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
13740b57cec5SDimitry Andric   if (!TBAA)
13750b57cec5SDimitry Andric     return TBAAAccessInfo();
13765ffd83dbSDimitry Andric   if (getLangOpts().CUDAIsDevice) {
13775ffd83dbSDimitry Andric     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
13785ffd83dbSDimitry Andric     // access info.
13795ffd83dbSDimitry Andric     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
13805ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
13815ffd83dbSDimitry Andric           nullptr)
13825ffd83dbSDimitry Andric         return TBAAAccessInfo();
13835ffd83dbSDimitry Andric     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
13845ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
13855ffd83dbSDimitry Andric           nullptr)
13865ffd83dbSDimitry Andric         return TBAAAccessInfo();
13875ffd83dbSDimitry Andric     }
13885ffd83dbSDimitry Andric   }
13890b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
13900b57cec5SDimitry Andric }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type * VTablePtrType)13930b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
13940b57cec5SDimitry Andric   if (!TBAA)
13950b57cec5SDimitry Andric     return TBAAAccessInfo();
13960b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric 
getTBAAStructInfo(QualType QTy)13990b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
14000b57cec5SDimitry Andric   if (!TBAA)
14010b57cec5SDimitry Andric     return nullptr;
14020b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
14030b57cec5SDimitry Andric }
14040b57cec5SDimitry Andric 
getTBAABaseTypeInfo(QualType QTy)14050b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
14060b57cec5SDimitry Andric   if (!TBAA)
14070b57cec5SDimitry Andric     return nullptr;
14080b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
14090b57cec5SDimitry Andric }
14100b57cec5SDimitry Andric 
getTBAAAccessTagInfo(TBAAAccessInfo Info)14110b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
14120b57cec5SDimitry Andric   if (!TBAA)
14130b57cec5SDimitry Andric     return nullptr;
14140b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
14150b57cec5SDimitry Andric }
14160b57cec5SDimitry Andric 
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,TBAAAccessInfo TargetInfo)14170b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
14180b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
14190b57cec5SDimitry Andric   if (!TBAA)
14200b57cec5SDimitry Andric     return TBAAAccessInfo();
14210b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
14220b57cec5SDimitry Andric }
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,TBAAAccessInfo InfoB)14250b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
14260b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
14270b57cec5SDimitry Andric   if (!TBAA)
14280b57cec5SDimitry Andric     return TBAAAccessInfo();
14290b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
14300b57cec5SDimitry Andric }
14310b57cec5SDimitry Andric 
14320b57cec5SDimitry Andric TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,TBAAAccessInfo SrcInfo)14330b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
14340b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
14350b57cec5SDimitry Andric   if (!TBAA)
14360b57cec5SDimitry Andric     return TBAAAccessInfo();
14370b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
14380b57cec5SDimitry Andric }
14390b57cec5SDimitry Andric 
DecorateInstructionWithTBAA(llvm::Instruction * Inst,TBAAAccessInfo TBAAInfo)14400b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
14410b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
14420b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
14430b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
14440b57cec5SDimitry Andric }
14450b57cec5SDimitry Andric 
DecorateInstructionWithInvariantGroup(llvm::Instruction * I,const CXXRecordDecl * RD)14460b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
14470b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
14480b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
14490b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
14500b57cec5SDimitry Andric }
14510b57cec5SDimitry Andric 
Error(SourceLocation loc,StringRef message)14520b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
14530b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
14540b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
14550b57cec5SDimitry Andric }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
14580b57cec5SDimitry Andric /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)14590b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
14600b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
14610b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
14620b57cec5SDimitry Andric   std::string Msg = Type;
14630b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
14640b57cec5SDimitry Andric       << Msg << S->getSourceRange();
14650b57cec5SDimitry Andric }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
14680b57cec5SDimitry Andric /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)14690b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
14700b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
14710b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
14720b57cec5SDimitry Andric   std::string Msg = Type;
14730b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric 
getSize(CharUnits size)14760b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
14770b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
14780b57cec5SDimitry Andric }
14790b57cec5SDimitry Andric 
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const14800b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
14810b57cec5SDimitry Andric                                         const NamedDecl *D) const {
14820b57cec5SDimitry Andric   // Internal definitions always have default visibility.
14830b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
14840b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
14850b57cec5SDimitry Andric     return;
14860b57cec5SDimitry Andric   }
14870b57cec5SDimitry Andric   if (!D)
14880b57cec5SDimitry Andric     return;
1489c9157d92SDimitry Andric 
14900b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
14910b57cec5SDimitry Andric   // or set explicitly.
14920b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
1493c9157d92SDimitry Andric 
1494c9157d92SDimitry Andric   // OpenMP declare target variables must be visible to the host so they can
1495c9157d92SDimitry Andric   // be registered. We require protected visibility unless the variable has
1496c9157d92SDimitry Andric   // the DT_nohost modifier and does not need to be registered.
1497c9157d92SDimitry Andric   if (Context.getLangOpts().OpenMP &&
1498c9157d92SDimitry Andric       Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1499c9157d92SDimitry Andric       D->hasAttr<OMPDeclareTargetDeclAttr>() &&
1500c9157d92SDimitry Andric       D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1501c9157d92SDimitry Andric           OMPDeclareTargetDeclAttr::DT_NoHost &&
1502c9157d92SDimitry Andric       LV.getVisibility() == HiddenVisibility) {
1503c9157d92SDimitry Andric     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1504c9157d92SDimitry Andric     return;
1505c9157d92SDimitry Andric   }
1506c9157d92SDimitry Andric 
1507bdd1243dSDimitry Andric   if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1508bdd1243dSDimitry Andric     // Reject incompatible dlllstorage and visibility annotations.
1509bdd1243dSDimitry Andric     if (!LV.isVisibilityExplicit())
1510bdd1243dSDimitry Andric       return;
1511bdd1243dSDimitry Andric     if (GV->hasDLLExportStorageClass()) {
1512bdd1243dSDimitry Andric       if (LV.getVisibility() == HiddenVisibility)
1513bdd1243dSDimitry Andric         getDiags().Report(D->getLocation(),
1514bdd1243dSDimitry Andric                           diag::err_hidden_visibility_dllexport);
1515bdd1243dSDimitry Andric     } else if (LV.getVisibility() != DefaultVisibility) {
1516bdd1243dSDimitry Andric       getDiags().Report(D->getLocation(),
1517bdd1243dSDimitry Andric                         diag::err_non_default_visibility_dllimport);
1518bdd1243dSDimitry Andric     }
1519bdd1243dSDimitry Andric     return;
1520bdd1243dSDimitry Andric   }
1521bdd1243dSDimitry Andric 
15220b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
15230b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
15240b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
15250b57cec5SDimitry Andric }
15260b57cec5SDimitry Andric 
shouldAssumeDSOLocal(const CodeGenModule & CGM,llvm::GlobalValue * GV)15270b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
15280b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
15290b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
15300b57cec5SDimitry Andric     return true;
15310b57cec5SDimitry Andric 
15320b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
15330b57cec5SDimitry Andric     return true;
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
15360b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
15370b57cec5SDimitry Andric     return false;
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
1540c9157d92SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
15410b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
15420b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
15430b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
15440b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
1545fe6060f1SDimitry Andric 
1546fe6060f1SDimitry Andric     // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1547fe6060f1SDimitry Andric     // (and this actually happens in the public interface of libstdc++), so
1548fe6060f1SDimitry Andric     // such variables can't be marked as DSO local. (Native TLS variables
1549fe6060f1SDimitry Andric     // can't be dllimported at all, though.)
15500b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1551c9157d92SDimitry Andric         (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
1552c9157d92SDimitry Andric         CGOpts.AutoImport)
15530b57cec5SDimitry Andric       return false;
15540b57cec5SDimitry Andric   }
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
15570b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
15580b57cec5SDimitry Andric   // outside the current DSO.
15590b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
15600b57cec5SDimitry Andric     return false;
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   // Every other GV is local on COFF.
15630b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
15640b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
15650b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
15660b57cec5SDimitry Andric   // FIXME: even thread local variables?
15670b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
15680b57cec5SDimitry Andric     return true;
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
15710b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
15720b57cec5SDimitry Andric     return false;
15730b57cec5SDimitry Andric 
1574fe6060f1SDimitry Andric   // If this is not an executable, don't assume anything is local.
1575fe6060f1SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
1576fe6060f1SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
1577e8d8bef9SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1578e8d8bef9SDimitry Andric     // On ELF, if -fno-semantic-interposition is specified and the target
1579e8d8bef9SDimitry Andric     // supports local aliases, there will be neither CC1
1580e8d8bef9SDimitry Andric     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1581fe6060f1SDimitry Andric     // dso_local on the function if using a local alias is preferable (can avoid
1582fe6060f1SDimitry Andric     // PLT indirection).
1583fe6060f1SDimitry Andric     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
15840b57cec5SDimitry Andric       return false;
1585e8d8bef9SDimitry Andric     return !(CGM.getLangOpts().SemanticInterposition ||
1586e8d8bef9SDimitry Andric              CGM.getLangOpts().HalfNoSemanticInterposition);
1587e8d8bef9SDimitry Andric   }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
15900b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
15910b57cec5SDimitry Andric     return true;
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
15940b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
15950b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
15960b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
15970b57cec5SDimitry Andric     return false;
15980b57cec5SDimitry Andric 
1599e8d8bef9SDimitry Andric   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1600e8d8bef9SDimitry Andric   if (TT.isPPC64())
16010b57cec5SDimitry Andric     return false;
16020b57cec5SDimitry Andric 
1603e8d8bef9SDimitry Andric   if (CGOpts.DirectAccessExternalData) {
1604e8d8bef9SDimitry Andric     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1605e8d8bef9SDimitry Andric     // for non-thread-local variables. If the symbol is not defined in the
1606e8d8bef9SDimitry Andric     // executable, a copy relocation will be needed at link time. dso_local is
1607e8d8bef9SDimitry Andric     // excluded for thread-local variables because they generally don't support
1608e8d8bef9SDimitry Andric     // copy relocations.
16090b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1610e8d8bef9SDimitry Andric       if (!Var->isThreadLocal())
16110b57cec5SDimitry Andric         return true;
16120b57cec5SDimitry Andric 
1613e8d8bef9SDimitry Andric     // -fno-pic sets dso_local on a function declaration to allow direct
1614e8d8bef9SDimitry Andric     // accesses when taking its address (similar to a data symbol). If the
1615e8d8bef9SDimitry Andric     // function is not defined in the executable, a canonical PLT entry will be
1616e8d8bef9SDimitry Andric     // needed at link time. -fno-direct-access-external-data can avoid the
1617e8d8bef9SDimitry Andric     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1618e8d8bef9SDimitry Andric     // it could just cause trouble without providing perceptible benefits.
16190b57cec5SDimitry Andric     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
16200b57cec5SDimitry Andric       return true;
1621e8d8bef9SDimitry Andric   }
1622e8d8bef9SDimitry Andric 
1623e8d8bef9SDimitry Andric   // If we can use copy relocations we can assume it is local.
16240b57cec5SDimitry Andric 
16255ffd83dbSDimitry Andric   // Otherwise don't assume it is local.
16260b57cec5SDimitry Andric   return false;
16270b57cec5SDimitry Andric }
16280b57cec5SDimitry Andric 
setDSOLocal(llvm::GlobalValue * GV) const16290b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
16300b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
16310b57cec5SDimitry Andric }
16320b57cec5SDimitry Andric 
setDLLImportDLLExport(llvm::GlobalValue * GV,GlobalDecl GD) const16330b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
16340b57cec5SDimitry Andric                                           GlobalDecl GD) const {
16350b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
16360b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
16370b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
16380b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
16390b57cec5SDimitry Andric     return;
16400b57cec5SDimitry Andric   }
16410b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
16420b57cec5SDimitry Andric }
16430b57cec5SDimitry Andric 
setDLLImportDLLExport(llvm::GlobalValue * GV,const NamedDecl * D) const16440b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
16450b57cec5SDimitry Andric                                           const NamedDecl *D) const {
16460b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
16470b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
16480b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
164981ad6265SDimitry Andric     else if ((D->hasAttr<DLLExportAttr>() ||
165081ad6265SDimitry Andric               shouldMapVisibilityToDLLExport(D)) &&
165181ad6265SDimitry Andric              !GV->isDeclarationForLinker())
16520b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
16530b57cec5SDimitry Andric   }
16540b57cec5SDimitry Andric }
16550b57cec5SDimitry Andric 
setGVProperties(llvm::GlobalValue * GV,GlobalDecl GD) const16560b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
16570b57cec5SDimitry Andric                                     GlobalDecl GD) const {
16580b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
16590b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
16600b57cec5SDimitry Andric }
16610b57cec5SDimitry Andric 
setGVProperties(llvm::GlobalValue * GV,const NamedDecl * D) const16620b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
16630b57cec5SDimitry Andric                                     const NamedDecl *D) const {
16640b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
16650b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
16660b57cec5SDimitry Andric }
16670b57cec5SDimitry Andric 
setGVPropertiesAux(llvm::GlobalValue * GV,const NamedDecl * D) const16680b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
16690b57cec5SDimitry Andric                                        const NamedDecl *D) const {
16700b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
16710b57cec5SDimitry Andric   setDSOLocal(GV);
16720b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
16730b57cec5SDimitry Andric }
16740b57cec5SDimitry Andric 
GetLLVMTLSModel(StringRef S)16750b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
16760b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
16770b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
16780b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
16790b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
16800b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
16810b57cec5SDimitry Andric }
16820b57cec5SDimitry Andric 
16835ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode
GetDefaultLLVMTLSModel() const16845ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const {
16855ffd83dbSDimitry Andric   switch (CodeGenOpts.getDefaultTLSModel()) {
16860b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
16870b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
16880b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
16890b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
16900b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
16910b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
16920b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
16930b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
16940b57cec5SDimitry Andric   }
16950b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
16960b57cec5SDimitry Andric }
16970b57cec5SDimitry Andric 
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const16980b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
16990b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
17025ffd83dbSDimitry Andric   TLM = GetDefaultLLVMTLSModel();
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
17050b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
17060b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
17070b57cec5SDimitry Andric   }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric 
getCPUSpecificMangling(const CodeGenModule & CGM,StringRef Name)17120b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
17130b57cec5SDimitry Andric                                           StringRef Name) {
17140b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
17150b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
17160b57cec5SDimitry Andric }
17170b57cec5SDimitry Andric 
AppendCPUSpecificCPUDispatchMangling(const CodeGenModule & CGM,const CPUSpecificAttr * Attr,unsigned CPUIndex,raw_ostream & Out)17180b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
17190b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
17200b57cec5SDimitry Andric                                                  unsigned CPUIndex,
17210b57cec5SDimitry Andric                                                  raw_ostream &Out) {
17220b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
17230b57cec5SDimitry Andric   // supported.
17240b57cec5SDimitry Andric   if (Attr)
17250b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
17260b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
17270b57cec5SDimitry Andric     Out << ".resolver";
17280b57cec5SDimitry Andric }
17290b57cec5SDimitry Andric 
AppendTargetVersionMangling(const CodeGenModule & CGM,const TargetVersionAttr * Attr,raw_ostream & Out)1730bdd1243dSDimitry Andric static void AppendTargetVersionMangling(const CodeGenModule &CGM,
1731bdd1243dSDimitry Andric                                         const TargetVersionAttr *Attr,
1732bdd1243dSDimitry Andric                                         raw_ostream &Out) {
1733a58f00eaSDimitry Andric   if (Attr->isDefaultVersion()) {
1734a58f00eaSDimitry Andric     Out << ".default";
1735bdd1243dSDimitry Andric     return;
1736a58f00eaSDimitry Andric   }
1737bdd1243dSDimitry Andric   Out << "._";
1738fe013be4SDimitry Andric   const TargetInfo &TI = CGM.getTarget();
1739bdd1243dSDimitry Andric   llvm::SmallVector<StringRef, 8> Feats;
1740bdd1243dSDimitry Andric   Attr->getFeatures(Feats);
1741fe013be4SDimitry Andric   llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) {
1742fe013be4SDimitry Andric     return TI.multiVersionSortPriority(FeatL) <
1743fe013be4SDimitry Andric            TI.multiVersionSortPriority(FeatR);
1744fe013be4SDimitry Andric   });
1745bdd1243dSDimitry Andric   for (const auto &Feat : Feats) {
1746bdd1243dSDimitry Andric     Out << 'M';
1747bdd1243dSDimitry Andric     Out << Feat;
1748bdd1243dSDimitry Andric   }
1749bdd1243dSDimitry Andric }
1750bdd1243dSDimitry Andric 
AppendTargetMangling(const CodeGenModule & CGM,const TargetAttr * Attr,raw_ostream & Out)17510b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
17520b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
17530b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
17540b57cec5SDimitry Andric     return;
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   Out << '.';
17570b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
1758bdd1243dSDimitry Andric   ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr());
1759bdd1243dSDimitry Andric   llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) {
17600b57cec5SDimitry Andric     // Multiversioning doesn't allow "no-${feature}", so we can
17610b57cec5SDimitry Andric     // only have "+" prefixes here.
1762c9157d92SDimitry Andric     assert(LHS.starts_with("+") && RHS.starts_with("+") &&
17630b57cec5SDimitry Andric            "Features should always have a prefix.");
17640b57cec5SDimitry Andric     return Target.multiVersionSortPriority(LHS.substr(1)) >
17650b57cec5SDimitry Andric            Target.multiVersionSortPriority(RHS.substr(1));
17660b57cec5SDimitry Andric   });
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric   bool IsFirst = true;
17690b57cec5SDimitry Andric 
1770bdd1243dSDimitry Andric   if (!Info.CPU.empty()) {
17710b57cec5SDimitry Andric     IsFirst = false;
1772bdd1243dSDimitry Andric     Out << "arch_" << Info.CPU;
17730b57cec5SDimitry Andric   }
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
17760b57cec5SDimitry Andric     if (!IsFirst)
17770b57cec5SDimitry Andric       Out << '_';
17780b57cec5SDimitry Andric     IsFirst = false;
17790b57cec5SDimitry Andric     Out << Feat.substr(1);
17800b57cec5SDimitry Andric   }
17810b57cec5SDimitry Andric }
17820b57cec5SDimitry Andric 
1783fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and
1784fe6060f1SDimitry Andric // needs a unique suffix after the mangled name.
isUniqueInternalLinkageDecl(GlobalDecl GD,CodeGenModule & CGM)1785fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1786fe6060f1SDimitry Andric                                         CodeGenModule &CGM) {
1787fe6060f1SDimitry Andric   const Decl *D = GD.getDecl();
1788fe6060f1SDimitry Andric   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1789fe6060f1SDimitry Andric          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1790fe6060f1SDimitry Andric }
1791fe6060f1SDimitry Andric 
AppendTargetClonesMangling(const CodeGenModule & CGM,const TargetClonesAttr * Attr,unsigned VersionIndex,raw_ostream & Out)17924824e7fdSDimitry Andric static void AppendTargetClonesMangling(const CodeGenModule &CGM,
17934824e7fdSDimitry Andric                                        const TargetClonesAttr *Attr,
17944824e7fdSDimitry Andric                                        unsigned VersionIndex,
17954824e7fdSDimitry Andric                                        raw_ostream &Out) {
1796fe013be4SDimitry Andric   const TargetInfo &TI = CGM.getTarget();
1797fe013be4SDimitry Andric   if (TI.getTriple().isAArch64()) {
1798bdd1243dSDimitry Andric     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1799a58f00eaSDimitry Andric     if (FeatureStr == "default") {
1800a58f00eaSDimitry Andric       Out << ".default";
1801bdd1243dSDimitry Andric       return;
1802a58f00eaSDimitry Andric     }
1803bdd1243dSDimitry Andric     Out << "._";
1804bdd1243dSDimitry Andric     SmallVector<StringRef, 8> Features;
1805bdd1243dSDimitry Andric     FeatureStr.split(Features, "+");
1806fe013be4SDimitry Andric     llvm::stable_sort(Features,
1807fe013be4SDimitry Andric                       [&TI](const StringRef FeatL, const StringRef FeatR) {
1808fe013be4SDimitry Andric                         return TI.multiVersionSortPriority(FeatL) <
1809fe013be4SDimitry Andric                                TI.multiVersionSortPriority(FeatR);
1810fe013be4SDimitry Andric                       });
1811bdd1243dSDimitry Andric     for (auto &Feat : Features) {
1812bdd1243dSDimitry Andric       Out << 'M';
1813bdd1243dSDimitry Andric       Out << Feat;
1814bdd1243dSDimitry Andric     }
1815bdd1243dSDimitry Andric   } else {
18164824e7fdSDimitry Andric     Out << '.';
18174824e7fdSDimitry Andric     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1818c9157d92SDimitry Andric     if (FeatureStr.starts_with("arch="))
18194824e7fdSDimitry Andric       Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
18204824e7fdSDimitry Andric     else
18214824e7fdSDimitry Andric       Out << FeatureStr;
18224824e7fdSDimitry Andric 
18234824e7fdSDimitry Andric     Out << '.' << Attr->getMangledIndex(VersionIndex);
18244824e7fdSDimitry Andric   }
1825bdd1243dSDimitry Andric }
18264824e7fdSDimitry Andric 
getMangledNameImpl(CodeGenModule & CGM,GlobalDecl GD,const NamedDecl * ND,bool OmitMultiVersionMangling=false)1827fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
18280b57cec5SDimitry Andric                                       const NamedDecl *ND,
18290b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
18300b57cec5SDimitry Andric   SmallString<256> Buffer;
18310b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
18320b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
1833fe6060f1SDimitry Andric   if (!CGM.getModuleNameHash().empty())
1834fe6060f1SDimitry Andric     MC.needsUniqueInternalLinkageNames();
1835fe6060f1SDimitry Andric   bool ShouldMangle = MC.shouldMangleDeclName(ND);
1836fe6060f1SDimitry Andric   if (ShouldMangle)
18375ffd83dbSDimitry Andric     MC.mangleName(GD.getWithDecl(ND), Out);
18385ffd83dbSDimitry Andric   else {
18390b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
18400b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
18410b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
18420b57cec5SDimitry Andric 
18430b57cec5SDimitry Andric     if (FD &&
18440b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1845c9157d92SDimitry Andric       if (CGM.getLangOpts().RegCall4)
1846c9157d92SDimitry Andric         Out << "__regcall4__" << II->getName();
1847c9157d92SDimitry Andric       else
18480b57cec5SDimitry Andric         Out << "__regcall3__" << II->getName();
18495ffd83dbSDimitry Andric     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
18505ffd83dbSDimitry Andric                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
18515ffd83dbSDimitry Andric       Out << "__device_stub__" << II->getName();
18520b57cec5SDimitry Andric     } else {
18530b57cec5SDimitry Andric       Out << II->getName();
18540b57cec5SDimitry Andric     }
18550b57cec5SDimitry Andric   }
18560b57cec5SDimitry Andric 
1857fe6060f1SDimitry Andric   // Check if the module name hash should be appended for internal linkage
1858fe6060f1SDimitry Andric   // symbols.   This should come before multi-version target suffixes are
1859fe6060f1SDimitry Andric   // appended. This is to keep the name and module hash suffix of the
1860fe6060f1SDimitry Andric   // internal linkage function together.  The unique suffix should only be
1861fe6060f1SDimitry Andric   // added when name mangling is done to make sure that the final name can
1862fe6060f1SDimitry Andric   // be properly demangled.  For example, for C functions without prototypes,
1863fe6060f1SDimitry Andric   // name mangling is not done and the unique suffix should not be appeneded
1864fe6060f1SDimitry Andric   // then.
1865fe6060f1SDimitry Andric   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1866fe6060f1SDimitry Andric     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1867fe6060f1SDimitry Andric            "Hash computed when not explicitly requested");
1868fe6060f1SDimitry Andric     Out << CGM.getModuleNameHash();
1869fe6060f1SDimitry Andric   }
1870fe6060f1SDimitry Andric 
18710b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
18720b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
18730b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
18740b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
18750b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
18760b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
18770b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
18780b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
18790b57cec5SDimitry Andric         break;
18800b57cec5SDimitry Andric       case MultiVersionKind::Target:
18810b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
18820b57cec5SDimitry Andric         break;
1883bdd1243dSDimitry Andric       case MultiVersionKind::TargetVersion:
1884bdd1243dSDimitry Andric         AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out);
1885bdd1243dSDimitry Andric         break;
18864824e7fdSDimitry Andric       case MultiVersionKind::TargetClones:
18874824e7fdSDimitry Andric         AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
18884824e7fdSDimitry Andric                                    GD.getMultiVersionIndex(), Out);
18894824e7fdSDimitry Andric         break;
18900b57cec5SDimitry Andric       case MultiVersionKind::None:
18910b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
18920b57cec5SDimitry Andric       }
18930b57cec5SDimitry Andric     }
18940b57cec5SDimitry Andric 
1895fe6060f1SDimitry Andric   // Make unique name for device side static file-scope variable for HIP.
189681ad6265SDimitry Andric   if (CGM.getContext().shouldExternalize(ND) &&
1897fe6060f1SDimitry Andric       CGM.getLangOpts().GPURelocatableDeviceCode &&
189881ad6265SDimitry Andric       CGM.getLangOpts().CUDAIsDevice)
18992a66634dSDimitry Andric     CGM.printPostfixForExternalizedDecl(Out, ND);
190081ad6265SDimitry Andric 
19015ffd83dbSDimitry Andric   return std::string(Out.str());
19020b57cec5SDimitry Andric }
19030b57cec5SDimitry Andric 
UpdateMultiVersionNames(GlobalDecl GD,const FunctionDecl * FD,StringRef & CurName)19040b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
190504eeddc0SDimitry Andric                                             const FunctionDecl *FD,
190604eeddc0SDimitry Andric                                             StringRef &CurName) {
19070b57cec5SDimitry Andric   if (!FD->isMultiVersion())
19080b57cec5SDimitry Andric     return;
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
19110b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
19120b57cec5SDimitry Andric   // multiversion function.
19130b57cec5SDimitry Andric   std::string NonTargetName =
19140b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
19150b57cec5SDimitry Andric   GlobalDecl OtherGD;
19160b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
19170b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
19180b57cec5SDimitry Andric                .getDecl()
19190b57cec5SDimitry Andric                ->getAsFunction()
19200b57cec5SDimitry Andric                ->isMultiVersion() &&
19210b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
19220b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
19230b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
19240b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
19250b57cec5SDimitry Andric                                       .getDecl()
19260b57cec5SDimitry Andric                                       ->getAsFunction()
19270b57cec5SDimitry Andric                                       ->getMostRecentDecl();
19280b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
19290b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
19300b57cec5SDimitry Andric     // version, we don't try to update it.
19310b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
19320b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
19330b57cec5SDimitry Andric       // to this.
19340b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
19350b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
19360b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
19370b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
193804eeddc0SDimitry Andric       StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
193904eeddc0SDimitry Andric           Result.first->first();
194004eeddc0SDimitry Andric       // If this is the current decl is being created, make sure we update the name.
194104eeddc0SDimitry Andric       if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
194204eeddc0SDimitry Andric         CurName = OtherNameRef;
19430b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
19440b57cec5SDimitry Andric         Entry->setName(OtherName);
19450b57cec5SDimitry Andric     }
19460b57cec5SDimitry Andric   }
19470b57cec5SDimitry Andric }
19480b57cec5SDimitry Andric 
getMangledName(GlobalDecl GD)19490b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
19500b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
19530b57cec5SDimitry Andric   // complete constructors get mangled the same.
19540b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
19550b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
19560b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
19570b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
19580b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
19590b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
19600b57cec5SDimitry Andric     }
19610b57cec5SDimitry Andric   }
19620b57cec5SDimitry Andric 
1963fe6060f1SDimitry Andric   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1964fe6060f1SDimitry Andric   // static device variable depends on whether the variable is referenced by
1965fe6060f1SDimitry Andric   // a host or device host function. Therefore the mangled name cannot be
1966fe6060f1SDimitry Andric   // cached.
196781ad6265SDimitry Andric   if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
19680b57cec5SDimitry Andric     auto FoundName = MangledDeclNames.find(CanonicalGD);
19690b57cec5SDimitry Andric     if (FoundName != MangledDeclNames.end())
19700b57cec5SDimitry Andric       return FoundName->second;
1971fe6060f1SDimitry Andric   }
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
19740b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
19750b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
19760b57cec5SDimitry Andric 
19775ffd83dbSDimitry Andric   // Ensure either we have different ABIs between host and device compilations,
19785ffd83dbSDimitry Andric   // says host compilation following MSVC ABI but device compilation follows
19795ffd83dbSDimitry Andric   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
19805ffd83dbSDimitry Andric   // mangling should be the same after name stubbing. The later checking is
19815ffd83dbSDimitry Andric   // very important as the device kernel name being mangled in host-compilation
19825ffd83dbSDimitry Andric   // is used to resolve the device binaries to be executed. Inconsistent naming
19835ffd83dbSDimitry Andric   // result in undefined behavior. Even though we cannot check that naming
19845ffd83dbSDimitry Andric   // directly between host- and device-compilations, the host- and
19855ffd83dbSDimitry Andric   // device-mangling in host compilation could help catching certain ones.
19865ffd83dbSDimitry Andric   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
198781ad6265SDimitry Andric          getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
19885ffd83dbSDimitry Andric          (getContext().getAuxTargetInfo() &&
19895ffd83dbSDimitry Andric           (getContext().getAuxTargetInfo()->getCXXABI() !=
19905ffd83dbSDimitry Andric            getContext().getTargetInfo().getCXXABI())) ||
19915ffd83dbSDimitry Andric          getCUDARuntime().getDeviceSideName(ND) ==
19925ffd83dbSDimitry Andric              getMangledNameImpl(
19935ffd83dbSDimitry Andric                  *this,
19945ffd83dbSDimitry Andric                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
19955ffd83dbSDimitry Andric                  ND));
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
19980b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric 
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)20010b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
20020b57cec5SDimitry Andric                                              const BlockDecl *BD) {
20030b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
20040b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric   SmallString<256> Buffer;
20070b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
20080b57cec5SDimitry Andric   if (!D)
20090b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
20100b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
20110b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
20120b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
20130b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
20140b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
20150b57cec5SDimitry Andric   else
20160b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
20190b57cec5SDimitry Andric   return Result.first->first();
20200b57cec5SDimitry Andric }
20210b57cec5SDimitry Andric 
getMangledNameDecl(StringRef Name)202281ad6265SDimitry Andric const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
202381ad6265SDimitry Andric   auto it = MangledDeclNames.begin();
202481ad6265SDimitry Andric   while (it != MangledDeclNames.end()) {
202581ad6265SDimitry Andric     if (it->second == Name)
202681ad6265SDimitry Andric       return it->first;
202781ad6265SDimitry Andric     it++;
202881ad6265SDimitry Andric   }
202981ad6265SDimitry Andric   return GlobalDecl();
203081ad6265SDimitry Andric }
203181ad6265SDimitry Andric 
GetGlobalValue(StringRef Name)20320b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
20330b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
20340b57cec5SDimitry Andric }
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
20370b57cec5SDimitry Andric /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,unsigned LexOrder,llvm::Constant * AssociatedData)20380b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2039bdd1243dSDimitry Andric                                   unsigned LexOrder,
20400b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
20410b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
2042bdd1243dSDimitry Andric   GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
20430b57cec5SDimitry Andric }
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
20460b57cec5SDimitry Andric /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority,bool IsDtorAttrFunc)2047e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2048e8d8bef9SDimitry Andric                                   bool IsDtorAttrFunc) {
2049e8d8bef9SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2050e8d8bef9SDimitry Andric       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
20510b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
20520b57cec5SDimitry Andric     return;
20530b57cec5SDimitry Andric   }
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
2056bdd1243dSDimitry Andric   GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
20570b57cec5SDimitry Andric }
20580b57cec5SDimitry Andric 
EmitCtorList(CtorList & Fns,const char * GlobalName)20590b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
20600b57cec5SDimitry Andric   if (Fns.empty()) return;
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric   // Ctor function type is void()*.
20630b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
20640b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
20650b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
20680b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
20690b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
20720b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
20730b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
20740b57cec5SDimitry Andric   for (const auto &I : Fns) {
20750b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
20760b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
2077c9157d92SDimitry Andric     ctor.add(I.Initializer);
20780b57cec5SDimitry Andric     if (I.AssociatedData)
2079c9157d92SDimitry Andric       ctor.add(I.AssociatedData);
20800b57cec5SDimitry Andric     else
20810b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
20820b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
20830b57cec5SDimitry Andric   }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   auto list =
20860b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
20870b57cec5SDimitry Andric                                 /*constant*/ false,
20880b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
20910b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
2092bdd1243dSDimitry Andric   list->setAlignment(std::nullopt);
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric   Fns.clear();
20950b57cec5SDimitry Andric }
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)20980b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
20990b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
21040b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
21050b57cec5SDimitry Andric 
2106271697daSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage);
21070b57cec5SDimitry Andric }
21080b57cec5SDimitry Andric 
CreateCrossDsoCfiTypeId(llvm::Metadata * MD)21090b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
21100b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
21110b57cec5SDimitry Andric   if (!MDS) return nullptr;
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
21140b57cec5SDimitry Andric }
21150b57cec5SDimitry Andric 
CreateKCFITypeId(QualType T)2116bdd1243dSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
2117bdd1243dSDimitry Andric   if (auto *FnType = T->getAs<FunctionProtoType>())
2118bdd1243dSDimitry Andric     T = getContext().getFunctionType(
2119bdd1243dSDimitry Andric         FnType->getReturnType(), FnType->getParamTypes(),
2120bdd1243dSDimitry Andric         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2121bdd1243dSDimitry Andric 
2122bdd1243dSDimitry Andric   std::string OutName;
2123bdd1243dSDimitry Andric   llvm::raw_string_ostream Out(OutName);
2124c9157d92SDimitry Andric   getCXXABI().getMangleContext().mangleCanonicalTypeName(
2125fe013be4SDimitry Andric       T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2126fe013be4SDimitry Andric 
2127fe013be4SDimitry Andric   if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2128fe013be4SDimitry Andric     Out << ".normalized";
2129bdd1243dSDimitry Andric 
2130bdd1243dSDimitry Andric   return llvm::ConstantInt::get(Int32Ty,
2131bdd1243dSDimitry Andric                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2132bdd1243dSDimitry Andric }
2133bdd1243dSDimitry Andric 
SetLLVMFunctionAttributes(GlobalDecl GD,const CGFunctionInfo & Info,llvm::Function * F,bool IsThunk)21340b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
21350b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
2136fe6060f1SDimitry Andric                                               llvm::Function *F, bool IsThunk) {
21370b57cec5SDimitry Andric   unsigned CallingConv;
21380b57cec5SDimitry Andric   llvm::AttributeList PAL;
2139fe6060f1SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2140fe6060f1SDimitry Andric                          /*AttrOnCallSite=*/false, IsThunk);
21410b57cec5SDimitry Andric   F->setAttributes(PAL);
21420b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
21430b57cec5SDimitry Andric }
21440b57cec5SDimitry Andric 
removeImageAccessQualifier(std::string & TyName)21450b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
21460b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
21470b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
21480b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
21490b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
21500b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
21510b57cec5SDimitry Andric   else {
21520b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
21530b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
21540b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
21550b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
21560b57cec5SDimitry Andric     else {
21570b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
21580b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
21590b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
21600b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
21610b57cec5SDimitry Andric     }
21620b57cec5SDimitry Andric   }
21630b57cec5SDimitry Andric }
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric // Returns the address space id that should be produced to the
21660b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
21670b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
21680b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
21690b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
21700b57cec5SDimitry Andric // (basically all single AS CPUs).
ArgInfoAddressSpace(LangAS AS)21710b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
21720b57cec5SDimitry Andric   switch (AS) {
2173e8d8bef9SDimitry Andric   case LangAS::opencl_global:
2174e8d8bef9SDimitry Andric     return 1;
2175e8d8bef9SDimitry Andric   case LangAS::opencl_constant:
2176e8d8bef9SDimitry Andric     return 2;
2177e8d8bef9SDimitry Andric   case LangAS::opencl_local:
2178e8d8bef9SDimitry Andric     return 3;
2179e8d8bef9SDimitry Andric   case LangAS::opencl_generic:
2180e8d8bef9SDimitry Andric     return 4; // Not in SPIR 2.0 specs.
2181e8d8bef9SDimitry Andric   case LangAS::opencl_global_device:
2182e8d8bef9SDimitry Andric     return 5;
2183e8d8bef9SDimitry Andric   case LangAS::opencl_global_host:
2184e8d8bef9SDimitry Andric     return 6;
21850b57cec5SDimitry Andric   default:
21860b57cec5SDimitry Andric     return 0; // Assume private.
21870b57cec5SDimitry Andric   }
21880b57cec5SDimitry Andric }
21890b57cec5SDimitry Andric 
GenKernelArgMetadata(llvm::Function * Fn,const FunctionDecl * FD,CodeGenFunction * CGF)219081ad6265SDimitry Andric void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
21910b57cec5SDimitry Andric                                          const FunctionDecl *FD,
21920b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
21930b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
21940b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
21950b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
21960b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
21970b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
22020b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
22050b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
22080b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
22110b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
22140b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric   // MDNode for the kernel argument names.
22170b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric   if (FD && CGF)
22200b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
22210b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
222281ad6265SDimitry Andric       // Get argument name.
222381ad6265SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
222481ad6265SDimitry Andric 
222581ad6265SDimitry Andric       if (!getLangOpts().OpenCL)
222681ad6265SDimitry Andric         continue;
22270b57cec5SDimitry Andric       QualType ty = parm->getType();
22280b57cec5SDimitry Andric       std::string typeQuals;
22290b57cec5SDimitry Andric 
2230fe6060f1SDimitry Andric       // Get image and pipe access qualifier:
2231fe6060f1SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
2232fe6060f1SDimitry Andric         const Decl *PDecl = parm;
2233bdd1243dSDimitry Andric         if (const auto *TD = ty->getAs<TypedefType>())
2234fe6060f1SDimitry Andric           PDecl = TD->getDecl();
2235fe6060f1SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2236fe6060f1SDimitry Andric         if (A && A->isWriteOnly())
2237fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2238fe6060f1SDimitry Andric         else if (A && A->isReadWrite())
2239fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2240fe6060f1SDimitry Andric         else
2241fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2242fe6060f1SDimitry Andric       } else
2243fe6060f1SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2244fe6060f1SDimitry Andric 
2245fe6060f1SDimitry Andric       auto getTypeSpelling = [&](QualType Ty) {
2246fe6060f1SDimitry Andric         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2247fe6060f1SDimitry Andric 
2248fe6060f1SDimitry Andric         if (Ty.isCanonical()) {
2249fe6060f1SDimitry Andric           StringRef typeNameRef = typeName;
2250fe6060f1SDimitry Andric           // Turn "unsigned type" to "utype"
2251fe6060f1SDimitry Andric           if (typeNameRef.consume_front("unsigned "))
2252fe6060f1SDimitry Andric             return std::string("u") + typeNameRef.str();
2253fe6060f1SDimitry Andric           if (typeNameRef.consume_front("signed "))
2254fe6060f1SDimitry Andric             return typeNameRef.str();
2255fe6060f1SDimitry Andric         }
2256fe6060f1SDimitry Andric 
2257fe6060f1SDimitry Andric         return typeName;
2258fe6060f1SDimitry Andric       };
2259fe6060f1SDimitry Andric 
22600b57cec5SDimitry Andric       if (ty->isPointerType()) {
22610b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric         // Get address qualifier.
22640b57cec5SDimitry Andric         addressQuals.push_back(
22650b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
22660b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric         // Get argument type name.
2269fe6060f1SDimitry Andric         std::string typeName = getTypeSpelling(pointeeTy) + "*";
22700b57cec5SDimitry Andric         std::string baseTypeName =
2271fe6060f1SDimitry Andric             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2272fe6060f1SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
22730b57cec5SDimitry Andric         argBaseTypeNames.push_back(
22740b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric         // Get argument type qualifiers:
22770b57cec5SDimitry Andric         if (ty.isRestrictQualified())
22780b57cec5SDimitry Andric           typeQuals = "restrict";
22790b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
22800b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
22810b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
22820b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
22830b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
22840b57cec5SDimitry Andric       } else {
22850b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
22860b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
22870b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
22880b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric         addressQuals.push_back(
22910b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric         // Get argument type name.
2294fe6060f1SDimitry Andric         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2295fe6060f1SDimitry Andric         std::string typeName = getTypeSpelling(ty);
2296fe6060f1SDimitry Andric         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric         // Remove access qualifiers on images
22990b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
23000b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
23010b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
23020b57cec5SDimitry Andric         if (ty->isImageType()) {
23030b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
23040b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
23050b57cec5SDimitry Andric         }
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
23080b57cec5SDimitry Andric         argBaseTypeNames.push_back(
23090b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric         if (isPipe)
23120b57cec5SDimitry Andric           typeQuals = "pipe";
23130b57cec5SDimitry Andric       }
23140b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
23150b57cec5SDimitry Andric     }
23160b57cec5SDimitry Andric 
231781ad6265SDimitry Andric   if (getLangOpts().OpenCL) {
23180b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_addr_space",
23190b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, addressQuals));
23200b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_access_qual",
23210b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, accessQuals));
23220b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_type",
23230b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argTypeNames));
23240b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_base_type",
23250b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argBaseTypeNames));
23260b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_type_qual",
23270b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argTypeQuals));
232881ad6265SDimitry Andric   }
232981ad6265SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
233081ad6265SDimitry Andric       getCodeGenOpts().HIPSaveKernelArgName)
23310b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
23320b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
23330b57cec5SDimitry Andric }
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric /// Determines whether the language options require us to model
23360b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
23370b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
23380b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
23390b57cec5SDimitry Andric /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)23400b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
23410b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
23420b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
23450b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
23480b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
23490b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
23500b57cec5SDimitry Andric   }
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric   return true;
23530b57cec5SDimitry Andric }
23540b57cec5SDimitry Andric 
requiresMemberFunctionPointerTypeMetadata(CodeGenModule & CGM,const CXXMethodDecl * MD)23550b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
23560b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
23570b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
23580b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
23590b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
23600b57cec5SDimitry Andric     return false;
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
23630b57cec5SDimitry Andric   // need this sort of type metadata.
2364c9157d92SDimitry Andric   return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2365c9157d92SDimitry Andric          !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
23660b57cec5SDimitry Andric }
23670b57cec5SDimitry Andric 
2368c9157d92SDimitry Andric SmallVector<const CXXRecordDecl *, 0>
getMostBaseClasses(const CXXRecordDecl * RD)23690b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
23700b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
23730b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
23740b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
23750b57cec5SDimitry Andric       MostBases.insert(RD);
23760b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
23770b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
23780b57cec5SDimitry Andric   };
23790b57cec5SDimitry Andric   CollectMostBases(RD);
23800b57cec5SDimitry Andric   return MostBases.takeVector();
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric 
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)23830b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
23840b57cec5SDimitry Andric                                                            llvm::Function *F) {
238504eeddc0SDimitry Andric   llvm::AttrBuilder B(F->getContext());
23860b57cec5SDimitry Andric 
2387bdd1243dSDimitry Andric   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
238881ad6265SDimitry Andric     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
23890b57cec5SDimitry Andric 
23905ffd83dbSDimitry Andric   if (CodeGenOpts.StackClashProtector)
23915ffd83dbSDimitry Andric     B.addAttribute("probe-stack", "inline-asm");
23925ffd83dbSDimitry Andric 
2393c9157d92SDimitry Andric   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2394c9157d92SDimitry Andric     B.addAttribute("stack-probe-size",
2395c9157d92SDimitry Andric                    std::to_string(CodeGenOpts.StackProbeSize));
2396c9157d92SDimitry Andric 
23970b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
23980b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
23990b57cec5SDimitry Andric 
2400bdd1243dSDimitry Andric   if (D && D->hasAttr<NoStackProtectorAttr>())
2401bdd1243dSDimitry Andric     ; // Do nothing.
2402bdd1243dSDimitry Andric   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2403c9157d92SDimitry Andric            isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2404bdd1243dSDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
2405c9157d92SDimitry Andric   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
24060b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
2407c9157d92SDimitry Andric   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong))
24080b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
2409c9157d92SDimitry Andric   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
24100b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric   if (!D) {
24130b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
24140b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
24150b57cec5SDimitry Andric     // disabled, mark the function as noinline.
24160b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
24170b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
24180b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
24190b57cec5SDimitry Andric 
2420349cc55cSDimitry Andric     F->addFnAttrs(B);
24210b57cec5SDimitry Andric     return;
24220b57cec5SDimitry Andric   }
24230b57cec5SDimitry Andric 
2424c9157d92SDimitry Andric   // Handle SME attributes that apply to function definitions,
2425c9157d92SDimitry Andric   // rather than to function prototypes.
2426c9157d92SDimitry Andric   if (D->hasAttr<ArmLocallyStreamingAttr>())
2427c9157d92SDimitry Andric     B.addAttribute("aarch64_pstate_sm_body");
2428c9157d92SDimitry Andric 
2429a58f00eaSDimitry Andric   if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2430a58f00eaSDimitry Andric     if (Attr->isNewZA())
2431c9157d92SDimitry Andric       B.addAttribute("aarch64_pstate_za_new");
2432a58f00eaSDimitry Andric     if (Attr->isNewZT0())
2433a58f00eaSDimitry Andric       B.addAttribute("aarch64_new_zt0");
2434a58f00eaSDimitry Andric   }
2435c9157d92SDimitry Andric 
24360b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
24370b57cec5SDimitry Andric   // starting with the default for this optimization level.
24380b57cec5SDimitry Andric   bool ShouldAddOptNone =
24390b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
24400b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
24410b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
24420b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
24430b57cec5SDimitry Andric 
2444480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
2445480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2446480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
24470b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
24500b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
24530b57cec5SDimitry Andric     // much of their semantics.
24540b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
24550b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
24580b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
24590b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
24600b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
24610b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
24620b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
24630b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
24640b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
24650b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
2466480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2467480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
24680b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
24690b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
24700b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
24710b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
24720b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
24730b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
24740b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
24750b57cec5SDimitry Andric     // carry an explicit noinline attribute.
24760b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
24770b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
24780b57cec5SDimitry Andric   } else {
24790b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
24800b57cec5SDimitry Andric     // absence to mark things as noinline.
24810b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
24820b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
24830b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
24840b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
24850b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
24860b57cec5SDimitry Andric         };
24870b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
24880b57cec5SDimitry Andric           return true;
24890b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
24900b57cec5SDimitry Andric         if (!Pattern)
24910b57cec5SDimitry Andric           return false;
24920b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
24930b57cec5SDimitry Andric       };
24940b57cec5SDimitry Andric       if (CheckForInline(FD)) {
24950b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
24960b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
24970b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
24980b57cec5SDimitry Andric                  !FD->isInlined() &&
24990b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
25000b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
25010b57cec5SDimitry Andric       }
25020b57cec5SDimitry Andric     }
25030b57cec5SDimitry Andric   }
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
25060b57cec5SDimitry Andric   // function.
25070b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
25080b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
25090b57cec5SDimitry Andric       if (!ShouldAddOptNone)
25100b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
25110b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
25120b57cec5SDimitry Andric     }
2513e8d8bef9SDimitry Andric     if (D->hasAttr<HotAttr>())
2514e8d8bef9SDimitry Andric       B.addAttribute(llvm::Attribute::Hot);
25150b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
25160b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
25170b57cec5SDimitry Andric   }
25180b57cec5SDimitry Andric 
2519349cc55cSDimitry Andric   F->addFnAttrs(B);
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
25220b57cec5SDimitry Andric   if (alignment)
2523a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
25260b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
2527a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
25300b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
25310b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
25320b57cec5SDimitry Andric   // member function, set its alignment accordingly.
25330b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2534271697daSDimitry Andric     if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2535fe013be4SDimitry Andric       F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
25360b57cec5SDimitry Andric   }
25370b57cec5SDimitry Andric 
2538a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
2539a7dea167SDimitry Andric   // attributes on definitions only.
2540a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
2541a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2542a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2543a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
2544a7dea167SDimitry Andric       // current module anyway.
2545a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
25460b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
2547a7dea167SDimitry Andric     }
2548a7dea167SDimitry Andric   }
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
25510b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
25520b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
25530b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
25540b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
25550b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
25560b57cec5SDimitry Andric       llvm::Metadata *Id =
25570b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
25580b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
25590b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
25600b57cec5SDimitry Andric     }
25610b57cec5SDimitry Andric   }
25620b57cec5SDimitry Andric }
25630b57cec5SDimitry Andric 
SetCommonAttributes(GlobalDecl GD,llvm::GlobalValue * GV)25640b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
25650b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
2566349cc55cSDimitry Andric   if (isa_and_nonnull<NamedDecl>(D))
25670b57cec5SDimitry Andric     setGVProperties(GV, GD);
25680b57cec5SDimitry Andric   else
25690b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
2572fe6060f1SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
25730b57cec5SDimitry Andric 
2574fe013be4SDimitry Andric   if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2575fe013be4SDimitry Andric       VD &&
2576fe013be4SDimitry Andric       ((CodeGenOpts.KeepPersistentStorageVariables &&
2577fe013be4SDimitry Andric         (VD->getStorageDuration() == SD_Static ||
2578fe013be4SDimitry Andric          VD->getStorageDuration() == SD_Thread)) ||
2579fe013be4SDimitry Andric        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2580fe013be4SDimitry Andric         VD->getType().isConstQualified())))
2581fe6060f1SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
25820b57cec5SDimitry Andric }
25830b57cec5SDimitry Andric 
GetCPUAndFeaturesAttributes(GlobalDecl GD,llvm::AttrBuilder & Attrs,bool SetTargetFeatures)25840b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2585fe013be4SDimitry Andric                                                 llvm::AttrBuilder &Attrs,
2586fe013be4SDimitry Andric                                                 bool SetTargetFeatures) {
25870b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
25880b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
25890b57cec5SDimitry Andric   // parse that and add it to the feature set.
25900b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2591e8d8bef9SDimitry Andric   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
25920b57cec5SDimitry Andric   std::vector<std::string> Features;
25930b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
25940b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
25950b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2596bdd1243dSDimitry Andric   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2597bdd1243dSDimitry Andric   assert((!TD || !TV) && "both target_version and target specified");
25980b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
25994824e7fdSDimitry Andric   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
26000b57cec5SDimitry Andric   bool AddedAttr = false;
2601bdd1243dSDimitry Andric   if (TD || TV || SD || TC) {
26020b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
2603480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
26060b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
26070b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
26100b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
26110b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
26120b57cec5SDimitry Andric     // the function.
26130b57cec5SDimitry Andric     if (TD) {
2614bdd1243dSDimitry Andric       ParsedTargetAttr ParsedAttr =
2615bdd1243dSDimitry Andric           Target.parseTargetAttr(TD->getFeaturesStr());
2616bdd1243dSDimitry Andric       if (!ParsedAttr.CPU.empty() &&
2617bdd1243dSDimitry Andric           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2618bdd1243dSDimitry Andric         TargetCPU = ParsedAttr.CPU;
2619e8d8bef9SDimitry Andric         TuneCPU = ""; // Clear the tune CPU.
2620e8d8bef9SDimitry Andric       }
2621e8d8bef9SDimitry Andric       if (!ParsedAttr.Tune.empty() &&
2622e8d8bef9SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Tune))
2623e8d8bef9SDimitry Andric         TuneCPU = ParsedAttr.Tune;
26240b57cec5SDimitry Andric     }
262581ad6265SDimitry Andric 
262681ad6265SDimitry Andric     if (SD) {
262781ad6265SDimitry Andric       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
262881ad6265SDimitry Andric       // favor this processor.
2629fe013be4SDimitry Andric       TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
263081ad6265SDimitry Andric     }
26310b57cec5SDimitry Andric   } else {
26320b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
26330b57cec5SDimitry Andric     // function.
26340b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
26350b57cec5SDimitry Andric   }
26360b57cec5SDimitry Andric 
2637e8d8bef9SDimitry Andric   if (!TargetCPU.empty()) {
26380b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
26390b57cec5SDimitry Andric     AddedAttr = true;
26400b57cec5SDimitry Andric   }
2641e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
2642e8d8bef9SDimitry Andric     Attrs.addAttribute("tune-cpu", TuneCPU);
2643e8d8bef9SDimitry Andric     AddedAttr = true;
2644e8d8bef9SDimitry Andric   }
2645fe013be4SDimitry Andric   if (!Features.empty() && SetTargetFeatures) {
2646fe013be4SDimitry Andric     llvm::erase_if(Features, [&](const std::string& F) {
2647fe013be4SDimitry Andric        return getTarget().isReadOnlyFeature(F.substr(1));
2648fe013be4SDimitry Andric     });
26490b57cec5SDimitry Andric     llvm::sort(Features);
26500b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
26510b57cec5SDimitry Andric     AddedAttr = true;
26520b57cec5SDimitry Andric   }
26530b57cec5SDimitry Andric 
26540b57cec5SDimitry Andric   return AddedAttr;
26550b57cec5SDimitry Andric }
26560b57cec5SDimitry Andric 
setNonAliasAttributes(GlobalDecl GD,llvm::GlobalObject * GO)26570b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
26580b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
26590b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
26600b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric   if (D) {
26630b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2664fe6060f1SDimitry Andric       if (D->hasAttr<RetainAttr>())
2665fe6060f1SDimitry Andric         addUsedGlobal(GV);
26660b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
26670b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
26680b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
26690b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
26700b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
26710b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
2672a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2673a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
26740b57cec5SDimitry Andric     }
26750b57cec5SDimitry Andric 
26760b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2677fe6060f1SDimitry Andric       if (D->hasAttr<RetainAttr>())
2678fe6060f1SDimitry Andric         addUsedGlobal(F);
26790b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
26800b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
26810b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
26820b57cec5SDimitry Andric 
268304eeddc0SDimitry Andric       llvm::AttrBuilder Attrs(F->getContext());
26840b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
26850b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
26860b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
26870b57cec5SDimitry Andric         // new ones should replace the old.
268804eeddc0SDimitry Andric         llvm::AttributeMask RemoveAttrs;
2689e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-cpu");
2690e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-features");
2691e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("tune-cpu");
2692349cc55cSDimitry Andric         F->removeFnAttrs(RemoveAttrs);
2693349cc55cSDimitry Andric         F->addFnAttrs(Attrs);
26940b57cec5SDimitry Andric       }
26950b57cec5SDimitry Andric     }
26960b57cec5SDimitry Andric 
26970b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
26980b57cec5SDimitry Andric       GO->setSection(CSA->getName());
26990b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
27000b57cec5SDimitry Andric       GO->setSection(SA->getName());
27010b57cec5SDimitry Andric   }
27020b57cec5SDimitry Andric 
27030b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
27040b57cec5SDimitry Andric }
27050b57cec5SDimitry Andric 
SetInternalFunctionAttributes(GlobalDecl GD,llvm::Function * F,const CGFunctionInfo & FI)27060b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
27070b57cec5SDimitry Andric                                                   llvm::Function *F,
27080b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
27090b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
2710fe6060f1SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
27110b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
27160b57cec5SDimitry Andric }
27170b57cec5SDimitry Andric 
setLinkageForGV(llvm::GlobalValue * GV,const NamedDecl * ND)27180b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
27190b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
27200b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
27210b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
27220b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
27230b57cec5SDimitry Andric   // separate linkage types for this.
27240b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
27250b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
27260b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
27270b57cec5SDimitry Andric }
27280b57cec5SDimitry Andric 
CreateFunctionTypeMetadataForIcall(const FunctionDecl * FD,llvm::Function * F)27290b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
27300b57cec5SDimitry Andric                                                        llvm::Function *F) {
27310b57cec5SDimitry Andric   // Only if we are checking indirect calls.
27320b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
27330b57cec5SDimitry Andric     return;
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
27360b57cec5SDimitry Andric   // checks elsewhere.
27370b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
27380b57cec5SDimitry Andric     return;
27390b57cec5SDimitry Andric 
27400b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
27410b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
27420b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
27450b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
27460b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
27470b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
27480b57cec5SDimitry Andric }
27490b57cec5SDimitry Andric 
setKCFIType(const FunctionDecl * FD,llvm::Function * F)2750bdd1243dSDimitry Andric void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2751bdd1243dSDimitry Andric   llvm::LLVMContext &Ctx = F->getContext();
2752bdd1243dSDimitry Andric   llvm::MDBuilder MDB(Ctx);
2753bdd1243dSDimitry Andric   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2754bdd1243dSDimitry Andric                  llvm::MDNode::get(
2755bdd1243dSDimitry Andric                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2756bdd1243dSDimitry Andric }
2757bdd1243dSDimitry Andric 
allowKCFIIdentifier(StringRef Name)2758bdd1243dSDimitry Andric static bool allowKCFIIdentifier(StringRef Name) {
2759bdd1243dSDimitry Andric   // KCFI type identifier constants are only necessary for external assembly
2760bdd1243dSDimitry Andric   // functions, which means it's safe to skip unusual names. Subset of
2761bdd1243dSDimitry Andric   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2762bdd1243dSDimitry Andric   return llvm::all_of(Name, [](const char &C) {
2763bdd1243dSDimitry Andric     return llvm::isAlnum(C) || C == '_' || C == '.';
2764bdd1243dSDimitry Andric   });
2765bdd1243dSDimitry Andric }
2766bdd1243dSDimitry Andric 
finalizeKCFITypes()2767bdd1243dSDimitry Andric void CodeGenModule::finalizeKCFITypes() {
2768bdd1243dSDimitry Andric   llvm::Module &M = getModule();
2769bdd1243dSDimitry Andric   for (auto &F : M.functions()) {
2770bdd1243dSDimitry Andric     // Remove KCFI type metadata from non-address-taken local functions.
2771bdd1243dSDimitry Andric     bool AddressTaken = F.hasAddressTaken();
2772bdd1243dSDimitry Andric     if (!AddressTaken && F.hasLocalLinkage())
2773bdd1243dSDimitry Andric       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2774bdd1243dSDimitry Andric 
2775bdd1243dSDimitry Andric     // Generate a constant with the expected KCFI type identifier for all
2776bdd1243dSDimitry Andric     // address-taken function declarations to support annotating indirectly
2777bdd1243dSDimitry Andric     // called assembly functions.
2778bdd1243dSDimitry Andric     if (!AddressTaken || !F.isDeclaration())
2779bdd1243dSDimitry Andric       continue;
2780bdd1243dSDimitry Andric 
2781bdd1243dSDimitry Andric     const llvm::ConstantInt *Type;
2782bdd1243dSDimitry Andric     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2783bdd1243dSDimitry Andric       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2784bdd1243dSDimitry Andric     else
2785bdd1243dSDimitry Andric       continue;
2786bdd1243dSDimitry Andric 
2787bdd1243dSDimitry Andric     StringRef Name = F.getName();
2788bdd1243dSDimitry Andric     if (!allowKCFIIdentifier(Name))
2789bdd1243dSDimitry Andric       continue;
2790bdd1243dSDimitry Andric 
2791bdd1243dSDimitry Andric     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2792bdd1243dSDimitry Andric                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2793bdd1243dSDimitry Andric                           .str();
2794bdd1243dSDimitry Andric     M.appendModuleInlineAsm(Asm);
2795bdd1243dSDimitry Andric   }
2796bdd1243dSDimitry Andric }
2797bdd1243dSDimitry Andric 
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)27980b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
27990b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
28000b57cec5SDimitry Andric                                           bool IsThunk) {
28010b57cec5SDimitry Andric 
28020b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
28030b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
28040b57cec5SDimitry Andric     // to the intrinsic's attributes.
28050b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
28060b57cec5SDimitry Andric     return;
28070b57cec5SDimitry Andric   }
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric   if (!IsIncompleteFunction)
2812fe6060f1SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2813fe6060f1SDimitry Andric                               IsThunk);
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
28160b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
28170b57cec5SDimitry Andric   // GCC and does not actually return "this".
28180b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
28190b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
28200b57cec5SDimitry Andric     assert(!F->arg_empty() &&
28210b57cec5SDimitry Andric            F->arg_begin()->getType()
28220b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
28230b57cec5SDimitry Andric            "unexpected this return");
2824349cc55cSDimitry Andric     F->addParamAttr(0, llvm::Attribute::Returned);
28250b57cec5SDimitry Andric   }
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
28280b57cec5SDimitry Andric   // overridden by a definition.
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric   setLinkageForGV(F, FD);
28310b57cec5SDimitry Andric   setGVProperties(F, FD);
28320b57cec5SDimitry Andric 
28330b57cec5SDimitry Andric   // Setup target-specific attributes.
28340b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
28350b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
28360b57cec5SDimitry Andric 
28370b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
28380b57cec5SDimitry Andric     F->setSection(CSA->getName());
28390b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
28400b57cec5SDimitry Andric      F->setSection(SA->getName());
28410b57cec5SDimitry Andric 
2842349cc55cSDimitry Andric   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2843349cc55cSDimitry Andric     if (EA->isError())
2844349cc55cSDimitry Andric       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2845349cc55cSDimitry Andric     else if (EA->isWarning())
2846349cc55cSDimitry Andric       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2847349cc55cSDimitry Andric   }
2848349cc55cSDimitry Andric 
2849d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2850480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
2851d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
2852d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
2853d65cd7a5SDimitry Andric     (void)HasBody;
2854d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
2855d65cd7a5SDimitry Andric                       "available body!");
2856d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
2857349cc55cSDimitry Andric       F->addFnAttr(llvm::Attribute::NoBuiltin);
2858480093f4SDimitry Andric   }
2859480093f4SDimitry Andric 
28600b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
28610b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
28620b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
2863349cc55cSDimitry Andric     F->addFnAttr(llvm::Attribute::NoBuiltin);
28640b57cec5SDimitry Andric   }
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
28670b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
28680b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
28690b57cec5SDimitry Andric     if (MD->isVirtual())
28700b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
28710b57cec5SDimitry Andric 
28720b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
2873a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
2874a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
2875a7dea167SDimitry Andric   // jump table.
2876a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2877a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
28780b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
28790b57cec5SDimitry Andric 
2880bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2881bdd1243dSDimitry Andric     setKCFIType(FD, F);
2882bdd1243dSDimitry Andric 
28830b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
28840b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
28850b57cec5SDimitry Andric 
2886bdd1243dSDimitry Andric   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2887bdd1243dSDimitry Andric     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2888bdd1243dSDimitry Andric 
28890b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
28900b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
28910b57cec5SDimitry Andric     //  - The callback callee (as argument number).
28920b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
28930b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
28940b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
28970b57cec5SDimitry Andric     // identifies the callback callee.
28980b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
28990b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
29000b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
29010b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
29020b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
29030b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
29040b57cec5SDimitry Andric   }
29050b57cec5SDimitry Andric }
29060b57cec5SDimitry Andric 
addUsedGlobal(llvm::GlobalValue * GV)29070b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2908e8d8bef9SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
29090b57cec5SDimitry Andric          "Only globals with definition can force usage.");
29100b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
29110b57cec5SDimitry Andric }
29120b57cec5SDimitry Andric 
addCompilerUsedGlobal(llvm::GlobalValue * GV)29130b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
29140b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
29150b57cec5SDimitry Andric          "Only globals with definition can force usage.");
29160b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
29170b57cec5SDimitry Andric }
29180b57cec5SDimitry Andric 
addUsedOrCompilerUsedGlobal(llvm::GlobalValue * GV)2919fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2920fe6060f1SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2921fe6060f1SDimitry Andric          "Only globals with definition can force usage.");
2922fe6060f1SDimitry Andric   if (getTriple().isOSBinFormatELF())
2923fe6060f1SDimitry Andric     LLVMCompilerUsed.emplace_back(GV);
2924fe6060f1SDimitry Andric   else
2925fe6060f1SDimitry Andric     LLVMUsed.emplace_back(GV);
2926fe6060f1SDimitry Andric }
2927fe6060f1SDimitry Andric 
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakTrackingVH> & List)29280b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
29290b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
29300b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
29310b57cec5SDimitry Andric   if (List.empty())
29320b57cec5SDimitry Andric     return;
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
29350b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
29360b57cec5SDimitry Andric   UsedArray.resize(List.size());
29370b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
29380b57cec5SDimitry Andric     UsedArray[i] =
29390b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
29400b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
29410b57cec5SDimitry Andric   }
29420b57cec5SDimitry Andric 
29430b57cec5SDimitry Andric   if (UsedArray.empty())
29440b57cec5SDimitry Andric     return;
29450b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
29460b57cec5SDimitry Andric 
29470b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
29480b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
29490b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
29520b57cec5SDimitry Andric }
29530b57cec5SDimitry Andric 
emitLLVMUsed()29540b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
29550b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
29560b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
29570b57cec5SDimitry Andric }
29580b57cec5SDimitry Andric 
AppendLinkerOptions(StringRef Opts)29590b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
29600b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
29610b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
29620b57cec5SDimitry Andric }
29630b57cec5SDimitry Andric 
AddDetectMismatch(StringRef Name,StringRef Value)29640b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
29650b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
29660b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2967480093f4SDimitry Andric   if (Opt.empty())
2968480093f4SDimitry Andric     return;
29690b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
29700b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
29710b57cec5SDimitry Andric }
29720b57cec5SDimitry Andric 
AddDependentLib(StringRef Lib)29730b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
29740b57cec5SDimitry Andric   auto &C = getLLVMContext();
29750b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
29760b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
29770b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
29780b57cec5SDimitry Andric     return;
29790b57cec5SDimitry Andric   }
29800b57cec5SDimitry Andric 
29810b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
29820b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
29830b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
29840b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
29850b57cec5SDimitry Andric }
29860b57cec5SDimitry Andric 
29870b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
29880b57cec5SDimitry Andric /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::MDNode * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)29890b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
29900b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
29910b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
29920b57cec5SDimitry Andric   // Import this module's parent.
29930b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
29940b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
29950b57cec5SDimitry Andric   }
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric   // Import this module's dependencies.
2998349cc55cSDimitry Andric   for (Module *Import : llvm::reverse(Mod->Imports)) {
2999349cc55cSDimitry Andric     if (Visited.insert(Import).second)
3000349cc55cSDimitry Andric       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
30010b57cec5SDimitry Andric   }
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
30040b57cec5SDimitry Andric   // described by this module.
30050b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
30060b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
30070b57cec5SDimitry Andric 
30080b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
30090b57cec5SDimitry Andric   // name instead.
30100b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
30110b57cec5SDimitry Andric     return;
30120b57cec5SDimitry Andric 
3013349cc55cSDimitry Andric   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
30140b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
30150b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3016349cc55cSDimitry Andric     if (LL.IsFramework) {
3017349cc55cSDimitry Andric       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3018349cc55cSDimitry Andric                                  llvm::MDString::get(Context, LL.Library)};
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
30210b57cec5SDimitry Andric       continue;
30220b57cec5SDimitry Andric     }
30230b57cec5SDimitry Andric 
30240b57cec5SDimitry Andric     // Link against a library.
30250b57cec5SDimitry Andric     if (IsELF) {
30260b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
30270b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
3028349cc55cSDimitry Andric           llvm::MDString::get(Context, LL.Library),
30290b57cec5SDimitry Andric       };
30300b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
30310b57cec5SDimitry Andric     } else {
30320b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
3033349cc55cSDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
30340b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
30350b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
30360b57cec5SDimitry Andric     }
30370b57cec5SDimitry Andric   }
30380b57cec5SDimitry Andric }
30390b57cec5SDimitry Andric 
EmitModuleInitializers(clang::Module * Primary)3040fcaf7f86SDimitry Andric void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3041c9157d92SDimitry Andric   assert(Primary->isNamedModuleUnit() &&
3042c9157d92SDimitry Andric          "We should only emit module initializers for named modules.");
3043c9157d92SDimitry Andric 
3044fcaf7f86SDimitry Andric   // Emit the initializers in the order that sub-modules appear in the
3045fcaf7f86SDimitry Andric   // source, first Global Module Fragments, if present.
3046fcaf7f86SDimitry Andric   if (auto GMF = Primary->getGlobalModuleFragment()) {
3047fcaf7f86SDimitry Andric     for (Decl *D : getContext().getModuleInitializers(GMF)) {
304861cfbce3SDimitry Andric       if (isa<ImportDecl>(D))
304961cfbce3SDimitry Andric         continue;
305061cfbce3SDimitry Andric       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3051fcaf7f86SDimitry Andric       EmitTopLevelDecl(D);
3052fcaf7f86SDimitry Andric     }
3053fcaf7f86SDimitry Andric   }
3054fcaf7f86SDimitry Andric   // Second any associated with the module, itself.
3055fcaf7f86SDimitry Andric   for (Decl *D : getContext().getModuleInitializers(Primary)) {
3056fcaf7f86SDimitry Andric     // Skip import decls, the inits for those are called explicitly.
305761cfbce3SDimitry Andric     if (isa<ImportDecl>(D))
3058fcaf7f86SDimitry Andric       continue;
3059fcaf7f86SDimitry Andric     EmitTopLevelDecl(D);
3060fcaf7f86SDimitry Andric   }
3061fcaf7f86SDimitry Andric   // Third any associated with the Privat eMOdule Fragment, if present.
3062fcaf7f86SDimitry Andric   if (auto PMF = Primary->getPrivateModuleFragment()) {
3063fcaf7f86SDimitry Andric     for (Decl *D : getContext().getModuleInitializers(PMF)) {
3064c9157d92SDimitry Andric       // Skip import decls, the inits for those are called explicitly.
3065c9157d92SDimitry Andric       if (isa<ImportDecl>(D))
3066c9157d92SDimitry Andric         continue;
306761cfbce3SDimitry Andric       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3068fcaf7f86SDimitry Andric       EmitTopLevelDecl(D);
3069fcaf7f86SDimitry Andric     }
3070fcaf7f86SDimitry Andric   }
3071fcaf7f86SDimitry Andric }
3072fcaf7f86SDimitry Andric 
EmitModuleLinkOptions()30730b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
30740b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
30750b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
30760b57cec5SDimitry Andric   // non-explicit child modules.
30770b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
30780b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
30790b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   // Seed the stack with imported modules.
30820b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
30830b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
30840b57cec5SDimitry Andric     // a header of that same module.
30850b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
30860b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
30870b57cec5SDimitry Andric       continue;
30880b57cec5SDimitry Andric     if (Visited.insert(M).second)
30890b57cec5SDimitry Andric       Stack.push_back(M);
30900b57cec5SDimitry Andric   }
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
30930b57cec5SDimitry Andric   // non-leaf modules.
30940b57cec5SDimitry Andric   while (!Stack.empty()) {
30950b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
30960b57cec5SDimitry Andric 
30970b57cec5SDimitry Andric     bool AnyChildren = false;
30980b57cec5SDimitry Andric 
30990b57cec5SDimitry Andric     // Visit the submodules of this module.
31000b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
31010b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
31020b57cec5SDimitry Andric       // linked against.
31030b57cec5SDimitry Andric       if (SM->IsExplicit)
31040b57cec5SDimitry Andric         continue;
31050b57cec5SDimitry Andric 
31060b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
31070b57cec5SDimitry Andric         Stack.push_back(SM);
31080b57cec5SDimitry Andric         AnyChildren = true;
31090b57cec5SDimitry Andric       }
31100b57cec5SDimitry Andric     }
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
31130b57cec5SDimitry Andric     // modules to link against.
31140b57cec5SDimitry Andric     if (!AnyChildren) {
31150b57cec5SDimitry Andric       LinkModules.insert(Mod);
31160b57cec5SDimitry Andric     }
31170b57cec5SDimitry Andric   }
31180b57cec5SDimitry Andric 
31190b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
31200b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
31210b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
31220b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
31230b57cec5SDimitry Andric   Visited.clear();
31240b57cec5SDimitry Andric   for (Module *M : LinkModules)
31250b57cec5SDimitry Andric     if (Visited.insert(M).second)
31260b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
31270b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
31280b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
31290b57cec5SDimitry Andric 
31300b57cec5SDimitry Andric   // Add the linker options metadata flag.
31310b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
31320b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
31330b57cec5SDimitry Andric     NMD->addOperand(MD);
31340b57cec5SDimitry Andric }
31350b57cec5SDimitry Andric 
EmitDeferred()31360b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
31370b57cec5SDimitry Andric   // Emit deferred declare target declarations.
31380b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
31390b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
31400b57cec5SDimitry Andric 
31410b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
31420b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
31430b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
31440b57cec5SDimitry Andric 
31450b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
31460b57cec5SDimitry Andric     EmitDeferredVTables();
31470b57cec5SDimitry Andric 
31480b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
31490b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
31500b57cec5SDimitry Andric     // emitted that then need those vtables.
31510b57cec5SDimitry Andric     assert(DeferredVTables.empty());
31520b57cec5SDimitry Andric   }
31530b57cec5SDimitry Andric 
3154e8d8bef9SDimitry Andric   // Emit CUDA/HIP static device variables referenced by host code only.
3155fe6060f1SDimitry Andric   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3156fe6060f1SDimitry Andric   // needed for further handling.
3157fe6060f1SDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
315881ad6265SDimitry Andric     llvm::append_range(DeferredDeclsToEmit,
315981ad6265SDimitry Andric                        getContext().CUDADeviceVarODRUsedByHost);
3160e8d8bef9SDimitry Andric 
31610b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
31620b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
31630b57cec5SDimitry Andric     return;
31640b57cec5SDimitry Andric 
31650b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
31660b57cec5SDimitry Andric   // work, it will not interfere with this.
31670b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
31680b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
31710b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
31720b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
31730b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
31740b57cec5SDimitry Andric     // different type.
31750b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
31760b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
31770b57cec5SDimitry Andric 
31780b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
31790b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
31800b57cec5SDimitry Andric     // GlobalValue.
31810b57cec5SDimitry Andric     if (!GV)
31820b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
31850b57cec5SDimitry Andric     assert(GV);
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
31880b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
31890b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
31900b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
31910b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
31920b57cec5SDimitry Andric     // ignore these cases.
31930b57cec5SDimitry Andric     if (!GV->isDeclaration())
31940b57cec5SDimitry Andric       continue;
31950b57cec5SDimitry Andric 
3196a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
3197a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3198a7dea167SDimitry Andric       continue;
3199a7dea167SDimitry Andric 
32000b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
32010b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
32020b57cec5SDimitry Andric 
32030b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
32040b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
32050b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
32060b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
32070b57cec5SDimitry Andric       EmitDeferred();
32080b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
32090b57cec5SDimitry Andric     }
32100b57cec5SDimitry Andric   }
32110b57cec5SDimitry Andric }
32120b57cec5SDimitry Andric 
EmitVTablesOpportunistically()32130b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
32140b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
32150b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
32160b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
32170b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
32180b57cec5SDimitry Andric 
32190b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
32200b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
32210b57cec5SDimitry Andric 
32220b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
32230b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
32240b57cec5SDimitry Andric            "This queue should only contain external vtables");
32250b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
32260b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
32270b57cec5SDimitry Andric   }
32280b57cec5SDimitry Andric   OpportunisticVTables.clear();
32290b57cec5SDimitry Andric }
32300b57cec5SDimitry Andric 
EmitGlobalAnnotations()32310b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
3232c9157d92SDimitry Andric   for (const auto& [MangledName, VD] : DeferredAnnotations) {
3233c9157d92SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3234c9157d92SDimitry Andric     if (GV)
3235c9157d92SDimitry Andric       AddGlobalAnnotations(VD, GV);
3236c9157d92SDimitry Andric   }
3237c9157d92SDimitry Andric   DeferredAnnotations.clear();
3238c9157d92SDimitry Andric 
32390b57cec5SDimitry Andric   if (Annotations.empty())
32400b57cec5SDimitry Andric     return;
32410b57cec5SDimitry Andric 
32420b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
32430b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
32440b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
32450b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
32460b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
32470b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
32480b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
32490b57cec5SDimitry Andric }
32500b57cec5SDimitry Andric 
EmitAnnotationString(StringRef Str)32510b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
32520b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
32530b57cec5SDimitry Andric   if (AStr)
32540b57cec5SDimitry Andric     return AStr;
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric   // Not found yet, create a new global.
32570b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3258bdd1243dSDimitry Andric   auto *gv = new llvm::GlobalVariable(
3259bdd1243dSDimitry Andric       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3260bdd1243dSDimitry Andric       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3261bdd1243dSDimitry Andric       ConstGlobalsPtrTy->getAddressSpace());
32620b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
32630b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
32640b57cec5SDimitry Andric   AStr = gv;
32650b57cec5SDimitry Andric   return gv;
32660b57cec5SDimitry Andric }
32670b57cec5SDimitry Andric 
EmitAnnotationUnit(SourceLocation Loc)32680b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
32690b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
32700b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
32710b57cec5SDimitry Andric   if (PLoc.isValid())
32720b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
32730b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
32740b57cec5SDimitry Andric }
32750b57cec5SDimitry Andric 
EmitAnnotationLineNo(SourceLocation L)32760b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
32770b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
32780b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
32790b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
32800b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
32810b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
32820b57cec5SDimitry Andric }
32830b57cec5SDimitry Andric 
EmitAnnotationArgs(const AnnotateAttr * Attr)3284e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3285e8d8bef9SDimitry Andric   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3286e8d8bef9SDimitry Andric   if (Exprs.empty())
3287bdd1243dSDimitry Andric     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3288e8d8bef9SDimitry Andric 
3289e8d8bef9SDimitry Andric   llvm::FoldingSetNodeID ID;
3290e8d8bef9SDimitry Andric   for (Expr *E : Exprs) {
3291e8d8bef9SDimitry Andric     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3292e8d8bef9SDimitry Andric   }
3293e8d8bef9SDimitry Andric   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3294e8d8bef9SDimitry Andric   if (Lookup)
3295e8d8bef9SDimitry Andric     return Lookup;
3296e8d8bef9SDimitry Andric 
3297e8d8bef9SDimitry Andric   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3298e8d8bef9SDimitry Andric   LLVMArgs.reserve(Exprs.size());
3299e8d8bef9SDimitry Andric   ConstantEmitter ConstEmiter(*this);
3300e8d8bef9SDimitry Andric   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3301e8d8bef9SDimitry Andric     const auto *CE = cast<clang::ConstantExpr>(E);
3302e8d8bef9SDimitry Andric     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3303e8d8bef9SDimitry Andric                                     CE->getType());
3304e8d8bef9SDimitry Andric   });
3305e8d8bef9SDimitry Andric   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3306e8d8bef9SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3307e8d8bef9SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Struct,
3308e8d8bef9SDimitry Andric                                       ".args");
3309e8d8bef9SDimitry Andric   GV->setSection(AnnotationSection);
3310e8d8bef9SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3311e8d8bef9SDimitry Andric 
3312c9157d92SDimitry Andric   Lookup = GV;
3313c9157d92SDimitry Andric   return GV;
3314e8d8bef9SDimitry Andric }
3315e8d8bef9SDimitry Andric 
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)33160b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
33170b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
33180b57cec5SDimitry Andric                                                 SourceLocation L) {
33190b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
33200b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
33210b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
3322e8d8bef9SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L),
3323e8d8bef9SDimitry Andric                  *Args = EmitAnnotationArgs(AA);
33240b57cec5SDimitry Andric 
3325349cc55cSDimitry Andric   llvm::Constant *GVInGlobalsAS = GV;
3326349cc55cSDimitry Andric   if (GV->getAddressSpace() !=
3327349cc55cSDimitry Andric       getDataLayout().getDefaultGlobalsAddressSpace()) {
3328349cc55cSDimitry Andric     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3329c9157d92SDimitry Andric         GV,
3330c9157d92SDimitry Andric         llvm::PointerType::get(
3331c9157d92SDimitry Andric             GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3332480093f4SDimitry Andric   }
3333480093f4SDimitry Andric 
33340b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
3335e8d8bef9SDimitry Andric   llvm::Constant *Fields[] = {
3336c9157d92SDimitry Andric       GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
33370b57cec5SDimitry Andric   };
33380b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
33390b57cec5SDimitry Andric }
33400b57cec5SDimitry Andric 
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)33410b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
33420b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
33430b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
33440b57cec5SDimitry Andric   // Get the struct elements for these annotations.
33450b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
33460b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
33470b57cec5SDimitry Andric }
33480b57cec5SDimitry Andric 
isInNoSanitizeList(SanitizerMask Kind,llvm::Function * Fn,SourceLocation Loc) const3349fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
33500b57cec5SDimitry Andric                                        SourceLocation Loc) const {
3351fe6060f1SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3352fe6060f1SDimitry Andric   // NoSanitize by function name.
3353fe6060f1SDimitry Andric   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
33540b57cec5SDimitry Andric     return true;
3355fcaf7f86SDimitry Andric   // NoSanitize by location. Check "mainfile" prefix.
3356fcaf7f86SDimitry Andric   auto &SM = Context.getSourceManager();
3357c9157d92SDimitry Andric   FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3358fcaf7f86SDimitry Andric   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3359fcaf7f86SDimitry Andric     return true;
3360fcaf7f86SDimitry Andric 
3361fcaf7f86SDimitry Andric   // Check "src" prefix.
33620b57cec5SDimitry Andric   if (Loc.isValid())
3363fe6060f1SDimitry Andric     return NoSanitizeL.containsLocation(Kind, Loc);
33640b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
33650b57cec5SDimitry Andric   // it's located in the main file.
3366fcaf7f86SDimitry Andric   return NoSanitizeL.containsFile(Kind, MainFile.getName());
33670b57cec5SDimitry Andric }
33680b57cec5SDimitry Andric 
isInNoSanitizeList(SanitizerMask Kind,llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const336981ad6265SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
337081ad6265SDimitry Andric                                        llvm::GlobalVariable *GV,
33710b57cec5SDimitry Andric                                        SourceLocation Loc, QualType Ty,
33720b57cec5SDimitry Andric                                        StringRef Category) const {
3373fe6060f1SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
337481ad6265SDimitry Andric   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
33750b57cec5SDimitry Andric     return true;
3376fcaf7f86SDimitry Andric   auto &SM = Context.getSourceManager();
3377fcaf7f86SDimitry Andric   if (NoSanitizeL.containsMainFile(
3378c9157d92SDimitry Andric           Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3379c9157d92SDimitry Andric           Category))
3380fcaf7f86SDimitry Andric     return true;
338181ad6265SDimitry Andric   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
33820b57cec5SDimitry Andric     return true;
3383fcaf7f86SDimitry Andric 
33840b57cec5SDimitry Andric   // Check global type.
33850b57cec5SDimitry Andric   if (!Ty.isNull()) {
33860b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
3387fe6060f1SDimitry Andric     // not sanitized, we also don't instrument arrays of them.
33880b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
33890b57cec5SDimitry Andric       Ty = AT->getElementType();
33900b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
3391fe6060f1SDimitry Andric     // Only record types (classes, structs etc.) are ignored.
33920b57cec5SDimitry Andric     if (Ty->isRecordType()) {
33930b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
339481ad6265SDimitry Andric       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
33950b57cec5SDimitry Andric         return true;
33960b57cec5SDimitry Andric     }
33970b57cec5SDimitry Andric   }
33980b57cec5SDimitry Andric   return false;
33990b57cec5SDimitry Andric }
34000b57cec5SDimitry Andric 
imbueXRayAttrs(llvm::Function * Fn,SourceLocation Loc,StringRef Category) const34010b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
34020b57cec5SDimitry Andric                                    StringRef Category) const {
34030b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
34040b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
34050b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
34060b57cec5SDimitry Andric   if (Loc.isValid())
34070b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
34080b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
34090b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
34100b57cec5SDimitry Andric   switch (Attr) {
34110b57cec5SDimitry Andric   case ImbueAttr::NONE:
34120b57cec5SDimitry Andric     return false;
34130b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
34140b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
34150b57cec5SDimitry Andric     break;
34160b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
34170b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
34180b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
34190b57cec5SDimitry Andric     break;
34200b57cec5SDimitry Andric   case ImbueAttr::NEVER:
34210b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
34220b57cec5SDimitry Andric     break;
34230b57cec5SDimitry Andric   }
34240b57cec5SDimitry Andric   return true;
34250b57cec5SDimitry Andric }
34260b57cec5SDimitry Andric 
3427bdd1243dSDimitry Andric ProfileList::ExclusionType
isFunctionBlockedByProfileList(llvm::Function * Fn,SourceLocation Loc) const3428bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3429e8d8bef9SDimitry Andric                                               SourceLocation Loc) const {
3430e8d8bef9SDimitry Andric   const auto &ProfileList = getContext().getProfileList();
3431e8d8bef9SDimitry Andric   // If the profile list is empty, then instrument everything.
3432e8d8bef9SDimitry Andric   if (ProfileList.isEmpty())
3433bdd1243dSDimitry Andric     return ProfileList::Allow;
3434e8d8bef9SDimitry Andric   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3435e8d8bef9SDimitry Andric   // First, check the function name.
3436bdd1243dSDimitry Andric   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3437e8d8bef9SDimitry Andric     return *V;
3438e8d8bef9SDimitry Andric   // Next, check the source location.
3439bdd1243dSDimitry Andric   if (Loc.isValid())
3440bdd1243dSDimitry Andric     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3441e8d8bef9SDimitry Andric       return *V;
3442e8d8bef9SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
3443e8d8bef9SDimitry Andric   // it's located in the main file.
3444e8d8bef9SDimitry Andric   auto &SM = Context.getSourceManager();
3445c9157d92SDimitry Andric   if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3446bdd1243dSDimitry Andric     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3447e8d8bef9SDimitry Andric       return *V;
3448bdd1243dSDimitry Andric   return ProfileList.getDefault(Kind);
3449e8d8bef9SDimitry Andric }
3450e8d8bef9SDimitry Andric 
3451bdd1243dSDimitry Andric ProfileList::ExclusionType
isFunctionBlockedFromProfileInstr(llvm::Function * Fn,SourceLocation Loc) const3452bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3453bdd1243dSDimitry Andric                                                  SourceLocation Loc) const {
3454bdd1243dSDimitry Andric   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3455bdd1243dSDimitry Andric   if (V != ProfileList::Allow)
3456bdd1243dSDimitry Andric     return V;
3457fcaf7f86SDimitry Andric 
3458fcaf7f86SDimitry Andric   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3459fcaf7f86SDimitry Andric   if (NumGroups > 1) {
3460fcaf7f86SDimitry Andric     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3461fcaf7f86SDimitry Andric     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3462bdd1243dSDimitry Andric       return ProfileList::Skip;
3463fcaf7f86SDimitry Andric   }
3464bdd1243dSDimitry Andric   return ProfileList::Allow;
3465fcaf7f86SDimitry Andric }
3466fcaf7f86SDimitry Andric 
MustBeEmitted(const ValueDecl * Global)34670b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
34680b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
34690b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
34700b57cec5SDimitry Andric     return true;
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric   const auto *VD = dyn_cast<VarDecl>(Global);
3473fe013be4SDimitry Andric   if (VD &&
3474fe013be4SDimitry Andric       ((CodeGenOpts.KeepPersistentStorageVariables &&
3475fe013be4SDimitry Andric         (VD->getStorageDuration() == SD_Static ||
3476fe013be4SDimitry Andric          VD->getStorageDuration() == SD_Thread)) ||
3477fe013be4SDimitry Andric        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3478fe013be4SDimitry Andric         VD->getType().isConstQualified())))
34790b57cec5SDimitry Andric     return true;
34800b57cec5SDimitry Andric 
34810b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
34820b57cec5SDimitry Andric }
34830b57cec5SDimitry Andric 
MayBeEmittedEagerly(const ValueDecl * Global)34840b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3485fe6060f1SDimitry Andric   // In OpenMP 5.0 variables and function may be marked as
3486fe6060f1SDimitry Andric   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3487fe6060f1SDimitry Andric   // that they must be emitted on the host/device. To be sure we need to have
3488fe6060f1SDimitry Andric   // seen a declare target with an explicit mentioning of the function, we know
3489fe6060f1SDimitry Andric   // we have if the level of the declare target attribute is -1. Note that we
3490fe6060f1SDimitry Andric   // check somewhere else if we should emit this at all.
3491fe6060f1SDimitry Andric   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3492bdd1243dSDimitry Andric     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3493fe6060f1SDimitry Andric         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3494fe6060f1SDimitry Andric     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3495fe6060f1SDimitry Andric       return false;
3496fe6060f1SDimitry Andric   }
3497fe6060f1SDimitry Andric 
3498a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
34990b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
35000b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
35010b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
35020b57cec5SDimitry Andric       return false;
3503a7dea167SDimitry Andric   }
3504fcaf7f86SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
35050b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
35060b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
35070b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
35080b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
35090b57cec5SDimitry Andric       return false;
3510fcaf7f86SDimitry Andric     if (CXX20ModuleInits && VD->getOwningModule() &&
3511fcaf7f86SDimitry Andric         !VD->getOwningModule()->isModuleMapModule()) {
3512fcaf7f86SDimitry Andric       // For CXX20, module-owned initializers need to be deferred, since it is
3513fcaf7f86SDimitry Andric       // not known at this point if they will be run for the current module or
3514fcaf7f86SDimitry Andric       // as part of the initializer for an imported one.
3515fcaf7f86SDimitry Andric       return false;
3516fcaf7f86SDimitry Andric     }
3517fcaf7f86SDimitry Andric   }
35180b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
35190b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
35200b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
35210b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3522c9157d92SDimitry Andric       !Global->getType().isConstantStorage(getContext(), false, false) &&
35230b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
35240b57cec5SDimitry Andric     return false;
35250b57cec5SDimitry Andric 
35260b57cec5SDimitry Andric   return true;
35270b57cec5SDimitry Andric }
35280b57cec5SDimitry Andric 
GetAddrOfMSGuidDecl(const MSGuidDecl * GD)35295ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
35305ffd83dbSDimitry Andric   StringRef Name = getMangledName(GD);
35310b57cec5SDimitry Andric 
35320b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
35330b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   // Look for an existing global.
35360b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
35370eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
35380b57cec5SDimitry Andric 
35395ffd83dbSDimitry Andric   ConstantEmitter Emitter(*this);
35405ffd83dbSDimitry Andric   llvm::Constant *Init;
35415ffd83dbSDimitry Andric 
35425ffd83dbSDimitry Andric   APValue &V = GD->getAsAPValue();
35435ffd83dbSDimitry Andric   if (!V.isAbsent()) {
35445ffd83dbSDimitry Andric     // If possible, emit the APValue version of the initializer. In particular,
35455ffd83dbSDimitry Andric     // this gets the type of the constant right.
35465ffd83dbSDimitry Andric     Init = Emitter.emitForInitializer(
35475ffd83dbSDimitry Andric         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
35485ffd83dbSDimitry Andric   } else {
35495ffd83dbSDimitry Andric     // As a fallback, directly construct the constant.
35505ffd83dbSDimitry Andric     // FIXME: This may get padding wrong under esoteric struct layout rules.
35515ffd83dbSDimitry Andric     // MSVC appears to create a complete type 'struct __s_GUID' that it
35525ffd83dbSDimitry Andric     // presumably uses to represent these constants.
35535ffd83dbSDimitry Andric     MSGuidDecl::Parts Parts = GD->getParts();
35545ffd83dbSDimitry Andric     llvm::Constant *Fields[4] = {
35555ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
35565ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
35575ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
35585ffd83dbSDimitry Andric         llvm::ConstantDataArray::getRaw(
35595ffd83dbSDimitry Andric             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
35605ffd83dbSDimitry Andric             Int8Ty)};
35615ffd83dbSDimitry Andric     Init = llvm::ConstantStruct::getAnon(Fields);
35625ffd83dbSDimitry Andric   }
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
35650b57cec5SDimitry Andric       getModule(), Init->getType(),
35660b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
35670b57cec5SDimitry Andric   if (supportsCOMDAT())
35680b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
35690b57cec5SDimitry Andric   setDSOLocal(GV);
35705ffd83dbSDimitry Andric 
35715ffd83dbSDimitry Andric   if (!V.isAbsent()) {
35725ffd83dbSDimitry Andric     Emitter.finalize(GV);
35730eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
35745ffd83dbSDimitry Andric   }
35750eae32dcSDimitry Andric 
35760eae32dcSDimitry Andric   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3577c9157d92SDimitry Andric   return ConstantAddress(GV, Ty, Alignment);
35780b57cec5SDimitry Andric }
35790b57cec5SDimitry Andric 
GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl * GCD)358081ad6265SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
358181ad6265SDimitry Andric     const UnnamedGlobalConstantDecl *GCD) {
358281ad6265SDimitry Andric   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
358381ad6265SDimitry Andric 
358481ad6265SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
358581ad6265SDimitry Andric   Entry = &UnnamedGlobalConstantDeclMap[GCD];
358681ad6265SDimitry Andric   if (*Entry)
358781ad6265SDimitry Andric     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
358881ad6265SDimitry Andric 
358981ad6265SDimitry Andric   ConstantEmitter Emitter(*this);
359081ad6265SDimitry Andric   llvm::Constant *Init;
359181ad6265SDimitry Andric 
359281ad6265SDimitry Andric   const APValue &V = GCD->getValue();
359381ad6265SDimitry Andric 
359481ad6265SDimitry Andric   assert(!V.isAbsent());
359581ad6265SDimitry Andric   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
359681ad6265SDimitry Andric                                     GCD->getType());
359781ad6265SDimitry Andric 
359881ad6265SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
359981ad6265SDimitry Andric                                       /*isConstant=*/true,
360081ad6265SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Init,
360181ad6265SDimitry Andric                                       ".constant");
360281ad6265SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
360381ad6265SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
360481ad6265SDimitry Andric 
360581ad6265SDimitry Andric   Emitter.finalize(GV);
360681ad6265SDimitry Andric 
360781ad6265SDimitry Andric   *Entry = GV;
360881ad6265SDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
360981ad6265SDimitry Andric }
361081ad6265SDimitry Andric 
GetAddrOfTemplateParamObject(const TemplateParamObjectDecl * TPO)3611e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3612e8d8bef9SDimitry Andric     const TemplateParamObjectDecl *TPO) {
3613e8d8bef9SDimitry Andric   StringRef Name = getMangledName(TPO);
3614e8d8bef9SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3615e8d8bef9SDimitry Andric 
3616e8d8bef9SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
36170eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
3618e8d8bef9SDimitry Andric 
3619e8d8bef9SDimitry Andric   ConstantEmitter Emitter(*this);
3620e8d8bef9SDimitry Andric   llvm::Constant *Init = Emitter.emitForInitializer(
3621e8d8bef9SDimitry Andric         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3622e8d8bef9SDimitry Andric 
3623e8d8bef9SDimitry Andric   if (!Init) {
3624e8d8bef9SDimitry Andric     ErrorUnsupported(TPO, "template parameter object");
3625e8d8bef9SDimitry Andric     return ConstantAddress::invalid();
3626e8d8bef9SDimitry Andric   }
3627e8d8bef9SDimitry Andric 
3628fe013be4SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
3629fe013be4SDimitry Andric       isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
3630fe013be4SDimitry Andric           ? llvm::GlobalValue::LinkOnceODRLinkage
3631fe013be4SDimitry Andric           : llvm::GlobalValue::InternalLinkage;
3632fe013be4SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3633fe013be4SDimitry Andric                                       /*isConstant=*/true, Linkage, Init, Name);
3634fe013be4SDimitry Andric   setGVProperties(GV, TPO);
3635e8d8bef9SDimitry Andric   if (supportsCOMDAT())
3636e8d8bef9SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3637e8d8bef9SDimitry Andric   Emitter.finalize(GV);
3638e8d8bef9SDimitry Andric 
36390eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
3640e8d8bef9SDimitry Andric }
3641e8d8bef9SDimitry Andric 
GetWeakRefReference(const ValueDecl * VD)36420b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
36430b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
36440b57cec5SDimitry Andric   assert(AA && "No alias?");
36450b57cec5SDimitry Andric 
36460b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
36470b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
36480b57cec5SDimitry Andric 
36490b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
36500b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3651c9157d92SDimitry Andric   if (Entry)
3652c9157d92SDimitry Andric     return ConstantAddress(Entry, DeclTy, Alignment);
36530b57cec5SDimitry Andric 
36540b57cec5SDimitry Andric   llvm::Constant *Aliasee;
36550b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
36560b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
36570b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
36580b57cec5SDimitry Andric                                       /*ForVTable=*/false);
36590b57cec5SDimitry Andric   else
3660349cc55cSDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3661349cc55cSDimitry Andric                                     nullptr);
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
36640b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
36650b57cec5SDimitry Andric   WeakRefReferences.insert(F);
36660b57cec5SDimitry Andric 
36670eae32dcSDimitry Andric   return ConstantAddress(Aliasee, DeclTy, Alignment);
36680b57cec5SDimitry Andric }
36690b57cec5SDimitry Andric 
hasImplicitAttr(const ValueDecl * D)3670c9157d92SDimitry Andric template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
3671c9157d92SDimitry Andric   if (!D)
3672c9157d92SDimitry Andric     return false;
3673c9157d92SDimitry Andric   if (auto *A = D->getAttr<AttrT>())
3674c9157d92SDimitry Andric     return A->isImplicit();
3675c9157d92SDimitry Andric   return D->isImplicit();
3676c9157d92SDimitry Andric }
3677c9157d92SDimitry Andric 
EmitGlobal(GlobalDecl GD)36780b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
36790b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
36800b57cec5SDimitry Andric 
36810b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
36820b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
36830b57cec5SDimitry Andric     return;
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
36860b57cec5SDimitry Andric   // emit it now.
36870b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
36880b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
36890b57cec5SDimitry Andric 
36900b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
36910b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
36920b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
36950b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
36960b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
36970b57cec5SDimitry Andric 
36980b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
3699c9157d92SDimitry Andric   // Non-constexpr non-lambda implicit host device functions are not emitted
3700c9157d92SDimitry Andric   // unless they are used on device side.
37010b57cec5SDimitry Andric   if (LangOpts.CUDA) {
37020b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
3703c9157d92SDimitry Andric       const auto *FD = dyn_cast<FunctionDecl>(Global);
3704c9157d92SDimitry Andric       if ((!Global->hasAttr<CUDADeviceAttr>() ||
3705c9157d92SDimitry Andric            (LangOpts.OffloadImplicitHostDeviceTemplates && FD &&
3706c9157d92SDimitry Andric             hasImplicitAttr<CUDAHostAttr>(FD) &&
3707c9157d92SDimitry Andric             hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
3708c9157d92SDimitry Andric             !isLambdaCallOperator(FD) &&
3709c9157d92SDimitry Andric             !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
37100b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
37110b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
37120b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
37135ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3714c9157d92SDimitry Andric           !Global->getType()->isCUDADeviceBuiltinTextureType() &&
3715c9157d92SDimitry Andric           !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
3716c9157d92SDimitry Andric             !Global->hasAttr<CUDAHostAttr>()))
37170b57cec5SDimitry Andric         return;
37180b57cec5SDimitry Andric     } else {
37190b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
37200b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
37210b57cec5SDimitry Andric       // size and host-side address in order to provide access to
37220b57cec5SDimitry Andric       // their device-side incarnations.
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
37250b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
37260b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
37270b57cec5SDimitry Andric         return;
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
37300b57cec5SDimitry Andric              "Expected Variable or Function");
37310b57cec5SDimitry Andric     }
37320b57cec5SDimitry Andric   }
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
3735a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
37360b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
37370b57cec5SDimitry Andric       return;
37380b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
37390b57cec5SDimitry Andric       if (MustBeEmitted(Global))
37400b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
37410b57cec5SDimitry Andric       return;
3742fe013be4SDimitry Andric     }
3743fe013be4SDimitry Andric     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
37440b57cec5SDimitry Andric       if (MustBeEmitted(Global))
37450b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
37460b57cec5SDimitry Andric       return;
37470b57cec5SDimitry Andric     }
37480b57cec5SDimitry Andric   }
37490b57cec5SDimitry Andric 
37500b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
37510b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3752c9157d92SDimitry Andric     // Update deferred annotations with the latest declaration if the function
3753c9157d92SDimitry Andric     // function was already used or defined.
3754c9157d92SDimitry Andric     if (FD->hasAttr<AnnotateAttr>()) {
3755c9157d92SDimitry Andric       StringRef MangledName = getMangledName(GD);
3756c9157d92SDimitry Andric       if (GetGlobalValue(MangledName))
3757c9157d92SDimitry Andric         DeferredAnnotations[MangledName] = FD;
3758c9157d92SDimitry Andric     }
3759c9157d92SDimitry Andric 
37600b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
37610b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
37620b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
37630b57cec5SDimitry Andric         return;
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
37660b57cec5SDimitry Andric 
37670b57cec5SDimitry Andric       // Compute the function info and LLVM type.
37680b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
37690b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
37700b57cec5SDimitry Andric 
37710b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
37720b57cec5SDimitry Andric                               /*DontDefer=*/false);
37730b57cec5SDimitry Andric       return;
37740b57cec5SDimitry Andric     }
37750b57cec5SDimitry Andric   } else {
37760b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
37770b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
37780b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
37790b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
37800b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
37810b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
3782bdd1243dSDimitry Andric         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
37830b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3784271697daSDimitry Andric 
3785271697daSDimitry Andric           // If this variable has external storage and doesn't require special
3786271697daSDimitry Andric           // link handling we defer to its canonical definition.
3787271697daSDimitry Andric           if (VD->hasExternalStorage() &&
3788271697daSDimitry Andric               Res != OMPDeclareTargetDeclAttr::MT_Link)
3789271697daSDimitry Andric             return;
3790271697daSDimitry Andric 
37910b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
37920b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3793bdd1243dSDimitry Andric           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3794bdd1243dSDimitry Andric                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
37950b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
37960b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
37970b57cec5SDimitry Andric           } else {
37980b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3799bdd1243dSDimitry Andric                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3800bdd1243dSDimitry Andric                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
38010b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
38020b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
38030b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
38040b57cec5SDimitry Andric           }
38050b57cec5SDimitry Andric 
38060b57cec5SDimitry Andric           return;
38070b57cec5SDimitry Andric         }
38080b57cec5SDimitry Andric       }
38090b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
38100b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
38110b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
38120b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
38130b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
38140b57cec5SDimitry Andric       return;
38150b57cec5SDimitry Andric     }
38160b57cec5SDimitry Andric   }
38170b57cec5SDimitry Andric 
38180b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
38190b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
38200b57cec5SDimitry Andric   // to benefit from cache locality.
38210b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
38220b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
38230b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
3824271697daSDimitry Andric     addEmittedDeferredDecl(GD);
38250b57cec5SDimitry Andric     return;
38260b57cec5SDimitry Andric   }
38270b57cec5SDimitry Andric 
38280b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
38290b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
38300b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
38310b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
38320b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
38330b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
38340b57cec5SDimitry Andric   }
38350b57cec5SDimitry Andric 
38360b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
38370b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
38380b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
38390b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
38400b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
38410b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
38420b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
38430b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
38440b57cec5SDimitry Andric   } else {
38450b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
38460b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
38470b57cec5SDimitry Andric     // DeferredDeclsToEmit.
38480b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
38490b57cec5SDimitry Andric   }
38500b57cec5SDimitry Andric }
38510b57cec5SDimitry Andric 
38520b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
HasNonDllImportDtor(QualType T)38530b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
38540b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
38550b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
38560b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
38570b57cec5SDimitry Andric         return true;
38580b57cec5SDimitry Andric 
38590b57cec5SDimitry Andric   return false;
38600b57cec5SDimitry Andric }
38610b57cec5SDimitry Andric 
38620b57cec5SDimitry Andric namespace {
38630b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
38640b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
38650b57cec5SDimitry Andric     const StringRef Name;
38660b57cec5SDimitry Andric     const Builtin::Context &BI;
FunctionIsDirectlyRecursive__anon8930a1af0c11::FunctionIsDirectlyRecursive38670b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
38680b57cec5SDimitry Andric         : Name(N), BI(C) {}
38690b57cec5SDimitry Andric 
VisitCallExpr__anon8930a1af0c11::FunctionIsDirectlyRecursive38700b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
38710b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
38720b57cec5SDimitry Andric       if (!FD)
38730b57cec5SDimitry Andric         return false;
38740b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
38750b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
38760b57cec5SDimitry Andric         return true;
38770b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
38780b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
38790b57cec5SDimitry Andric         return false;
38800b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
3881c9157d92SDimitry Andric       if (BuiltinName.starts_with("__builtin_") &&
38820b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
38830b57cec5SDimitry Andric         return true;
38840b57cec5SDimitry Andric       }
38850b57cec5SDimitry Andric       return false;
38860b57cec5SDimitry Andric     }
38870b57cec5SDimitry Andric 
VisitStmt__anon8930a1af0c11::FunctionIsDirectlyRecursive38880b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
38890b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
38900b57cec5SDimitry Andric         if (Child && this->Visit(Child))
38910b57cec5SDimitry Andric           return true;
38920b57cec5SDimitry Andric       return false;
38930b57cec5SDimitry Andric     }
38940b57cec5SDimitry Andric   };
38950b57cec5SDimitry Andric 
38960b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
38970b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
38980b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
38990b57cec5SDimitry Andric     bool SafeToInline = true;
39000b57cec5SDimitry Andric 
shouldVisitImplicitCode__anon8930a1af0c11::DLLImportFunctionVisitor39010b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
39020b57cec5SDimitry Andric 
VisitVarDecl__anon8930a1af0c11::DLLImportFunctionVisitor39030b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
39040b57cec5SDimitry Andric       if (VD->getTLSKind()) {
39050b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
39060b57cec5SDimitry Andric         SafeToInline = false;
39070b57cec5SDimitry Andric         return SafeToInline;
39080b57cec5SDimitry Andric       }
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
39110b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
39120b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric       return SafeToInline;
39150b57cec5SDimitry Andric     }
39160b57cec5SDimitry Andric 
VisitCXXBindTemporaryExpr__anon8930a1af0c11::DLLImportFunctionVisitor39170b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
39180b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
39190b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
39200b57cec5SDimitry Andric       return SafeToInline;
39210b57cec5SDimitry Andric     }
39220b57cec5SDimitry Andric 
VisitDeclRefExpr__anon8930a1af0c11::DLLImportFunctionVisitor39230b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
39240b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
39250b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
39260b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
39270b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
39280b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
39290b57cec5SDimitry Andric       return SafeToInline;
39300b57cec5SDimitry Andric     }
39310b57cec5SDimitry Andric 
VisitCXXConstructExpr__anon8930a1af0c11::DLLImportFunctionVisitor39320b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
39330b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
39340b57cec5SDimitry Andric       return SafeToInline;
39350b57cec5SDimitry Andric     }
39360b57cec5SDimitry Andric 
VisitCXXMemberCallExpr__anon8930a1af0c11::DLLImportFunctionVisitor39370b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
39380b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
39390b57cec5SDimitry Andric       if (!M) {
39400b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
39410b57cec5SDimitry Andric         SafeToInline = true;
39420b57cec5SDimitry Andric       } else {
39430b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
39440b57cec5SDimitry Andric       }
39450b57cec5SDimitry Andric       return SafeToInline;
39460b57cec5SDimitry Andric     }
39470b57cec5SDimitry Andric 
VisitCXXDeleteExpr__anon8930a1af0c11::DLLImportFunctionVisitor39480b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
39490b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
39500b57cec5SDimitry Andric       return SafeToInline;
39510b57cec5SDimitry Andric     }
39520b57cec5SDimitry Andric 
VisitCXXNewExpr__anon8930a1af0c11::DLLImportFunctionVisitor39530b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
39540b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
39550b57cec5SDimitry Andric       return SafeToInline;
39560b57cec5SDimitry Andric     }
39570b57cec5SDimitry Andric   };
39580b57cec5SDimitry Andric }
39590b57cec5SDimitry Andric 
39600b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
39610b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
39620b57cec5SDimitry Andric // ends up pointing to itself.
39630b57cec5SDimitry Andric bool
isTriviallyRecursive(const FunctionDecl * FD)39640b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
39650b57cec5SDimitry Andric   StringRef Name;
39660b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
39670b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
39680b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
39690b57cec5SDimitry Andric     if (!Attr)
39700b57cec5SDimitry Andric       return false;
39710b57cec5SDimitry Andric     Name = Attr->getLabel();
39720b57cec5SDimitry Andric   } else {
39730b57cec5SDimitry Andric     Name = FD->getName();
39740b57cec5SDimitry Andric   }
39750b57cec5SDimitry Andric 
39760b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
39770b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
39780b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
39790b57cec5SDimitry Andric }
39800b57cec5SDimitry Andric 
shouldEmitFunction(GlobalDecl GD)39810b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
39820b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
39830b57cec5SDimitry Andric     return true;
3984c9157d92SDimitry Andric 
39850b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
39860b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
39870b57cec5SDimitry Andric     return false;
39880b57cec5SDimitry Andric 
3989c9157d92SDimitry Andric   // We don't import function bodies from other named module units since that
3990c9157d92SDimitry Andric   // behavior may break ABI compatibility of the current unit.
3991c9157d92SDimitry Andric   if (const Module *M = F->getOwningModule();
3992c9157d92SDimitry Andric       M && M->getTopLevelModule()->isNamedModule() &&
3993c9157d92SDimitry Andric       getContext().getCurrentNamedModule() != M->getTopLevelModule() &&
3994c9157d92SDimitry Andric       !F->hasAttr<AlwaysInlineAttr>())
3995c9157d92SDimitry Andric     return false;
3996c9157d92SDimitry Andric 
3997c9157d92SDimitry Andric   if (F->hasAttr<NoInlineAttr>())
3998c9157d92SDimitry Andric     return false;
3999c9157d92SDimitry Andric 
4000fe6060f1SDimitry Andric   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
40010b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
40020b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
40030b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
40040b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
40050b57cec5SDimitry Andric       return false;
40060b57cec5SDimitry Andric 
40070b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
40080b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
40090b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
40100b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
40110b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
40120b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
40130b57cec5SDimitry Andric             return false;
40140b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
40150b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
40160b57cec5SDimitry Andric           return false;
40170b57cec5SDimitry Andric     }
40180b57cec5SDimitry Andric   }
40190b57cec5SDimitry Andric 
4020349cc55cSDimitry Andric   // Inline builtins declaration must be emitted. They often are fortified
4021349cc55cSDimitry Andric   // functions.
4022349cc55cSDimitry Andric   if (F->isInlineBuiltinDeclaration())
4023349cc55cSDimitry Andric     return true;
4024349cc55cSDimitry Andric 
40250b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
40260b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
40275ffd83dbSDimitry Andric   // but a function that calls itself through asm label/`__builtin_` trickery is
40285ffd83dbSDimitry Andric   // clearly not equivalent to the real implementation.
40290b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
40300b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
40310b57cec5SDimitry Andric }
40320b57cec5SDimitry Andric 
shouldOpportunisticallyEmitVTables()40330b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
40340b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
40350b57cec5SDimitry Andric }
40360b57cec5SDimitry Andric 
EmitMultiVersionFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)40370b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
40380b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
40390b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
40400b57cec5SDimitry Andric 
40410b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
40420b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
40430b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
40440b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
40454824e7fdSDimitry Andric   } else if (FD->isTargetClonesMultiVersion()) {
40464824e7fdSDimitry Andric     auto *Clone = FD->getAttr<TargetClonesAttr>();
40474824e7fdSDimitry Andric     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
40484824e7fdSDimitry Andric       if (Clone->isFirstOfVersion(I))
40494824e7fdSDimitry Andric         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
405081ad6265SDimitry Andric     // Ensure that the resolver function is also emitted.
405181ad6265SDimitry Andric     GetOrCreateMultiVersionResolver(GD);
4052a58f00eaSDimitry Andric   } else if (FD->hasAttr<TargetVersionAttr>()) {
4053a58f00eaSDimitry Andric     GetOrCreateMultiVersionResolver(GD);
40540b57cec5SDimitry Andric   } else
40550b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
40560b57cec5SDimitry Andric }
40570b57cec5SDimitry Andric 
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)40580b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
40590b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
40600b57cec5SDimitry Andric 
40610b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
40620b57cec5SDimitry Andric                                  Context.getSourceManager(),
40630b57cec5SDimitry Andric                                  "Generating code for declaration");
40640b57cec5SDimitry Andric 
40650b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
40660b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
40670b57cec5SDimitry Andric     // linkage.
40680b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
40690b57cec5SDimitry Andric       return;
40700b57cec5SDimitry Andric 
40710b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
40720b57cec5SDimitry Andric       std::string Name;
40730b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
40740b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
40750b57cec5SDimitry Andric                                /*Qualified=*/true);
40760b57cec5SDimitry Andric       return Name;
40770b57cec5SDimitry Andric     });
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
40800b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
40810b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
40820b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
40830b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
40840b57cec5SDimitry Andric       else if (FD->isMultiVersion())
40850b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
40860b57cec5SDimitry Andric       else
40870b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric       if (Method->isVirtual())
40900b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric       return;
40930b57cec5SDimitry Andric     }
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric     if (FD->isMultiVersion())
40960b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
40970b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
40980b57cec5SDimitry Andric   }
40990b57cec5SDimitry Andric 
41000b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
41010b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
41040b57cec5SDimitry Andric }
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
41070b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric static unsigned
TargetMVPriority(const TargetInfo & TI,const CodeGenFunction::MultiVersionResolverOption & RO)41100b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
41110b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
41120b57cec5SDimitry Andric   unsigned Priority = 0;
4113bdd1243dSDimitry Andric   unsigned NumFeatures = 0;
4114bdd1243dSDimitry Andric   for (StringRef Feat : RO.Conditions.Features) {
41150b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
4116bdd1243dSDimitry Andric     NumFeatures++;
4117bdd1243dSDimitry Andric   }
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
41200b57cec5SDimitry Andric     Priority = std::max(
41210b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
4122bdd1243dSDimitry Andric 
4123bdd1243dSDimitry Andric   Priority += TI.multiVersionFeatureCost() * NumFeatures;
4124bdd1243dSDimitry Andric 
41250b57cec5SDimitry Andric   return Priority;
41260b57cec5SDimitry Andric }
41270b57cec5SDimitry Andric 
4128349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4129349cc55cSDimitry Andric // TU can forward declare the function without causing problems.  Particularly
4130349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we
4131349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be
4132349cc55cSDimitry Andric // used with internal linkage in multiple TUs.
getMultiversionLinkage(CodeGenModule & CGM,GlobalDecl GD)4133349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
4134349cc55cSDimitry Andric                                                        GlobalDecl GD) {
4135349cc55cSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4136c9157d92SDimitry Andric   if (FD->getFormalLinkage() == Linkage::Internal)
4137349cc55cSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
4138349cc55cSDimitry Andric   return llvm::GlobalValue::WeakODRLinkage;
4139349cc55cSDimitry Andric }
4140349cc55cSDimitry Andric 
emitMultiVersionFunctions()41410b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
4142fe6060f1SDimitry Andric   std::vector<GlobalDecl> MVFuncsToEmit;
4143fe6060f1SDimitry Andric   MultiVersionFuncs.swap(MVFuncsToEmit);
4144fe6060f1SDimitry Andric   for (GlobalDecl GD : MVFuncsToEmit) {
414581ad6265SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
414681ad6265SDimitry Andric     assert(FD && "Expected a FunctionDecl");
414781ad6265SDimitry Andric 
41480b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
414981ad6265SDimitry Andric     if (FD->isTargetMultiVersion()) {
41500b57cec5SDimitry Andric       getContext().forEachMultiversionedFunctionVersion(
41510b57cec5SDimitry Andric           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
41520b57cec5SDimitry Andric             GlobalDecl CurGD{
41530b57cec5SDimitry Andric                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
41540b57cec5SDimitry Andric             StringRef MangledName = getMangledName(CurGD);
41550b57cec5SDimitry Andric             llvm::Constant *Func = GetGlobalValue(MangledName);
41560b57cec5SDimitry Andric             if (!Func) {
41570b57cec5SDimitry Andric               if (CurFD->isDefined()) {
41580b57cec5SDimitry Andric                 EmitGlobalFunctionDefinition(CurGD, nullptr);
41590b57cec5SDimitry Andric                 Func = GetGlobalValue(MangledName);
41600b57cec5SDimitry Andric               } else {
41610b57cec5SDimitry Andric                 const CGFunctionInfo &FI =
41620b57cec5SDimitry Andric                     getTypes().arrangeGlobalDeclaration(GD);
41630b57cec5SDimitry Andric                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
41640b57cec5SDimitry Andric                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
41650b57cec5SDimitry Andric                                          /*DontDefer=*/false, ForDefinition);
41660b57cec5SDimitry Andric               }
41670b57cec5SDimitry Andric               assert(Func && "This should have just been created");
41680b57cec5SDimitry Andric             }
4169bdd1243dSDimitry Andric             if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
41700b57cec5SDimitry Andric               const auto *TA = CurFD->getAttr<TargetAttr>();
41710b57cec5SDimitry Andric               llvm::SmallVector<StringRef, 8> Feats;
41720b57cec5SDimitry Andric               TA->getAddedFeatures(Feats);
41730b57cec5SDimitry Andric               Options.emplace_back(cast<llvm::Function>(Func),
41740b57cec5SDimitry Andric                                    TA->getArchitecture(), Feats);
4175bdd1243dSDimitry Andric             } else {
4176bdd1243dSDimitry Andric               const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
4177bdd1243dSDimitry Andric               llvm::SmallVector<StringRef, 8> Feats;
4178bdd1243dSDimitry Andric               TVA->getFeatures(Feats);
4179bdd1243dSDimitry Andric               Options.emplace_back(cast<llvm::Function>(Func),
4180bdd1243dSDimitry Andric                                    /*Architecture*/ "", Feats);
4181bdd1243dSDimitry Andric             }
41820b57cec5SDimitry Andric           });
418381ad6265SDimitry Andric     } else if (FD->isTargetClonesMultiVersion()) {
418481ad6265SDimitry Andric       const auto *TC = FD->getAttr<TargetClonesAttr>();
418581ad6265SDimitry Andric       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
418681ad6265SDimitry Andric            ++VersionIndex) {
418781ad6265SDimitry Andric         if (!TC->isFirstOfVersion(VersionIndex))
418881ad6265SDimitry Andric           continue;
418981ad6265SDimitry Andric         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
419081ad6265SDimitry Andric                          VersionIndex};
419181ad6265SDimitry Andric         StringRef Version = TC->getFeatureStr(VersionIndex);
419281ad6265SDimitry Andric         StringRef MangledName = getMangledName(CurGD);
419381ad6265SDimitry Andric         llvm::Constant *Func = GetGlobalValue(MangledName);
419481ad6265SDimitry Andric         if (!Func) {
419581ad6265SDimitry Andric           if (FD->isDefined()) {
419681ad6265SDimitry Andric             EmitGlobalFunctionDefinition(CurGD, nullptr);
419781ad6265SDimitry Andric             Func = GetGlobalValue(MangledName);
4198a7dea167SDimitry Andric           } else {
419981ad6265SDimitry Andric             const CGFunctionInfo &FI =
420081ad6265SDimitry Andric                 getTypes().arrangeGlobalDeclaration(CurGD);
420181ad6265SDimitry Andric             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
420281ad6265SDimitry Andric             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
420381ad6265SDimitry Andric                                      /*DontDefer=*/false, ForDefinition);
4204a7dea167SDimitry Andric           }
420581ad6265SDimitry Andric           assert(Func && "This should have just been created");
420681ad6265SDimitry Andric         }
420781ad6265SDimitry Andric 
420881ad6265SDimitry Andric         StringRef Architecture;
420981ad6265SDimitry Andric         llvm::SmallVector<StringRef, 1> Feature;
421081ad6265SDimitry Andric 
4211bdd1243dSDimitry Andric         if (getTarget().getTriple().isAArch64()) {
4212bdd1243dSDimitry Andric           if (Version != "default") {
4213bdd1243dSDimitry Andric             llvm::SmallVector<StringRef, 8> VerFeats;
4214bdd1243dSDimitry Andric             Version.split(VerFeats, "+");
4215bdd1243dSDimitry Andric             for (auto &CurFeat : VerFeats)
4216bdd1243dSDimitry Andric               Feature.push_back(CurFeat.trim());
4217bdd1243dSDimitry Andric           }
4218bdd1243dSDimitry Andric         } else {
4219c9157d92SDimitry Andric           if (Version.starts_with("arch="))
422081ad6265SDimitry Andric             Architecture = Version.drop_front(sizeof("arch=") - 1);
422181ad6265SDimitry Andric           else if (Version != "default")
422281ad6265SDimitry Andric             Feature.push_back(Version);
4223bdd1243dSDimitry Andric         }
422481ad6265SDimitry Andric 
422581ad6265SDimitry Andric         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
422681ad6265SDimitry Andric       }
422781ad6265SDimitry Andric     } else {
422881ad6265SDimitry Andric       assert(0 && "Expected a target or target_clones multiversion function");
422981ad6265SDimitry Andric       continue;
423081ad6265SDimitry Andric     }
423181ad6265SDimitry Andric 
423281ad6265SDimitry Andric     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4233c9157d92SDimitry Andric     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
423481ad6265SDimitry Andric       ResolverConstant = IFunc->getResolver();
4235a58f00eaSDimitry Andric       if (FD->isTargetClonesMultiVersion()) {
4236c9157d92SDimitry Andric         const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4237c9157d92SDimitry Andric         llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4238c9157d92SDimitry Andric         std::string MangledName = getMangledNameImpl(
4239c9157d92SDimitry Andric             *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4240c9157d92SDimitry Andric         // In prior versions of Clang, the mangling for ifuncs incorrectly
4241c9157d92SDimitry Andric         // included an .ifunc suffix. This alias is generated for backward
4242c9157d92SDimitry Andric         // compatibility. It is deprecated, and may be removed in the future.
4243c9157d92SDimitry Andric         auto *Alias = llvm::GlobalAlias::create(
4244c9157d92SDimitry Andric             DeclTy, 0, getMultiversionLinkage(*this, GD),
4245c9157d92SDimitry Andric             MangledName + ".ifunc", IFunc, &getModule());
4246c9157d92SDimitry Andric         SetCommonAttributes(FD, Alias);
4247c9157d92SDimitry Andric       }
4248c9157d92SDimitry Andric     }
424981ad6265SDimitry Andric     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
425081ad6265SDimitry Andric 
425181ad6265SDimitry Andric     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
42520b57cec5SDimitry Andric 
4253c9157d92SDimitry Andric     if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
42540b57cec5SDimitry Andric       ResolverFunc->setComdat(
42550b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
42560b57cec5SDimitry Andric 
425781ad6265SDimitry Andric     const TargetInfo &TI = getTarget();
42580b57cec5SDimitry Andric     llvm::stable_sort(
42590b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
42600b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
42610b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
42620b57cec5SDimitry Andric         });
42630b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
42640b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
42650b57cec5SDimitry Andric   }
4266fe6060f1SDimitry Andric 
4267fe6060f1SDimitry Andric   // Ensure that any additions to the deferred decls list caused by emitting a
4268fe6060f1SDimitry Andric   // variant are emitted.  This can happen when the variant itself is inline and
4269fe6060f1SDimitry Andric   // calls a function without linkage.
4270fe6060f1SDimitry Andric   if (!MVFuncsToEmit.empty())
4271fe6060f1SDimitry Andric     EmitDeferred();
4272fe6060f1SDimitry Andric 
4273fe6060f1SDimitry Andric   // Ensure that any additions to the multiversion funcs list from either the
4274fe6060f1SDimitry Andric   // deferred decls or the multiversion functions themselves are emitted.
4275fe6060f1SDimitry Andric   if (!MultiVersionFuncs.empty())
4276fe6060f1SDimitry Andric     emitMultiVersionFunctions();
42770b57cec5SDimitry Andric }
42780b57cec5SDimitry Andric 
emitCPUDispatchDefinition(GlobalDecl GD)42790b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
42800b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
42810b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
428204eeddc0SDimitry Andric   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
42830b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
42840b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
42850b57cec5SDimitry Andric 
428681ad6265SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
428781ad6265SDimitry Andric   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
42880b57cec5SDimitry Andric 
42890b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
429004eeddc0SDimitry Andric   UpdateMultiVersionNames(GD, FD, ResolverName);
42910b57cec5SDimitry Andric 
42920b57cec5SDimitry Andric   llvm::Type *ResolverType;
42930b57cec5SDimitry Andric   GlobalDecl ResolverGD;
429404eeddc0SDimitry Andric   if (getTarget().supportsIFunc()) {
42950b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
42960b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
4297bdd1243dSDimitry Andric                                getTypes().getTargetAddressSpace(FD->getType())),
42980b57cec5SDimitry Andric         false);
429904eeddc0SDimitry Andric   }
43000b57cec5SDimitry Andric   else {
43010b57cec5SDimitry Andric     ResolverType = DeclTy;
43020b57cec5SDimitry Andric     ResolverGD = GD;
43030b57cec5SDimitry Andric   }
43040b57cec5SDimitry Andric 
43050b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
43060b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4307349cc55cSDimitry Andric   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4308a7dea167SDimitry Andric   if (supportsCOMDAT())
4309a7dea167SDimitry Andric     ResolverFunc->setComdat(
4310a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
43110b57cec5SDimitry Andric 
43120b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
43130b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
43140b57cec5SDimitry Andric   unsigned Index = 0;
43150b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
43160b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
43170b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
43180b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric     if (!Func) {
43230b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
43240b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
43250b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
43260b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
43270b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
43280b57cec5SDimitry Andric       } else {
43290b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
43300b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
43310b57cec5SDimitry Andric 
43320b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
43330b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
43340b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
43350b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
43360b57cec5SDimitry Andric       }
43370b57cec5SDimitry Andric     }
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
43400b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
43410b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
43420b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
4343349cc55cSDimitry Andric     llvm::erase_if(Features, [&Target](StringRef Feat) {
43440b57cec5SDimitry Andric       return !Target.validateCpuSupports(Feat);
4345349cc55cSDimitry Andric     });
43460b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
43470b57cec5SDimitry Andric     ++Index;
43480b57cec5SDimitry Andric   }
43490b57cec5SDimitry Andric 
4350fe6060f1SDimitry Andric   llvm::stable_sort(
43510b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
43520b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
4353349cc55cSDimitry Andric         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4354349cc55cSDimitry Andric                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
43550b57cec5SDimitry Andric       });
43560b57cec5SDimitry Andric 
43570b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
43580b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
43590b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
43600b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
43610b57cec5SDimitry Andric   while (Options.size() > 1 &&
4362c9157d92SDimitry Andric          llvm::all_of(llvm::X86::getCpuSupportsMask(
4363c9157d92SDimitry Andric                           (Options.end() - 2)->Conditions.Features),
4364c9157d92SDimitry Andric                       [](auto X) { return X == 0; })) {
43650b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
43660b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
43670b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
43680b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
43690b57cec5SDimitry Andric     else
43700b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
43710b57cec5SDimitry Andric   }
43720b57cec5SDimitry Andric 
43730b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
43740b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4375a7dea167SDimitry Andric 
4376a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
437781ad6265SDimitry Andric     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
437881ad6265SDimitry Andric     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
437981ad6265SDimitry Andric 
438081ad6265SDimitry Andric     // Fix up function declarations that were created for cpu_specific before
438181ad6265SDimitry Andric     // cpu_dispatch was known
438281ad6265SDimitry Andric     if (!isa<llvm::GlobalIFunc>(IFunc)) {
438381ad6265SDimitry Andric       assert(cast<llvm::Function>(IFunc)->isDeclaration());
438481ad6265SDimitry Andric       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
438581ad6265SDimitry Andric                                            &getModule());
438681ad6265SDimitry Andric       GI->takeName(IFunc);
438781ad6265SDimitry Andric       IFunc->replaceAllUsesWith(GI);
438881ad6265SDimitry Andric       IFunc->eraseFromParent();
438981ad6265SDimitry Andric       IFunc = GI;
439081ad6265SDimitry Andric     }
439181ad6265SDimitry Andric 
4392a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
4393a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4394a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4395a7dea167SDimitry Andric     if (!AliasFunc) {
439681ad6265SDimitry Andric       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
439781ad6265SDimitry Andric                                            &getModule());
4398a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
4399a7dea167SDimitry Andric     }
4400a7dea167SDimitry Andric   }
44010b57cec5SDimitry Andric }
44020b57cec5SDimitry Andric 
44030b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
44040b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
GetOrCreateMultiVersionResolver(GlobalDecl GD)440581ad6265SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
440681ad6265SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
440781ad6265SDimitry Andric   assert(FD && "Not a FunctionDecl?");
440881ad6265SDimitry Andric 
44090b57cec5SDimitry Andric   std::string MangledName =
44100b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
44110b57cec5SDimitry Andric 
44120b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
44130b57cec5SDimitry Andric   // a separate resolver).
44140b57cec5SDimitry Andric   std::string ResolverName = MangledName;
4415c9157d92SDimitry Andric   if (getTarget().supportsIFunc()) {
4416a58f00eaSDimitry Andric     if (!FD->isTargetClonesMultiVersion())
44170b57cec5SDimitry Andric       ResolverName += ".ifunc";
4418c9157d92SDimitry Andric   } else if (FD->isTargetMultiVersion()) {
44190b57cec5SDimitry Andric     ResolverName += ".resolver";
4420c9157d92SDimitry Andric   }
44210b57cec5SDimitry Andric 
442281ad6265SDimitry Andric   // If the resolver has already been created, just return it.
44230b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
44240b57cec5SDimitry Andric     return ResolverGV;
44250b57cec5SDimitry Andric 
442681ad6265SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
442781ad6265SDimitry Andric   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
44280b57cec5SDimitry Andric 
442981ad6265SDimitry Andric   // The resolver needs to be created. For target and target_clones, defer
443081ad6265SDimitry Andric   // creation until the end of the TU.
443181ad6265SDimitry Andric   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
443281ad6265SDimitry Andric     MultiVersionFuncs.push_back(GD);
443381ad6265SDimitry Andric 
443481ad6265SDimitry Andric   // For cpu_specific, don't create an ifunc yet because we don't know if the
443581ad6265SDimitry Andric   // cpu_dispatch will be emitted in this translation unit.
443681ad6265SDimitry Andric   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
44370b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
4438bdd1243dSDimitry Andric         llvm::PointerType::get(DeclTy,
4439bdd1243dSDimitry Andric                                getTypes().getTargetAddressSpace(FD->getType())),
44400b57cec5SDimitry Andric         false);
44410b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
44420b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
44430b57cec5SDimitry Andric         /*ForVTable=*/false);
4444349cc55cSDimitry Andric     llvm::GlobalIFunc *GIF =
4445349cc55cSDimitry Andric         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4446349cc55cSDimitry Andric                                   "", Resolver, &getModule());
44470b57cec5SDimitry Andric     GIF->setName(ResolverName);
44480b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
44490b57cec5SDimitry Andric 
44500b57cec5SDimitry Andric     return GIF;
44510b57cec5SDimitry Andric   }
44520b57cec5SDimitry Andric 
44530b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
44540b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
44550b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
44560b57cec5SDimitry Andric          "Resolver should be created for the first time");
44570b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
44580b57cec5SDimitry Andric   return Resolver;
44590b57cec5SDimitry Andric }
44600b57cec5SDimitry Andric 
44610b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
44620b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
44630b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
44640b57cec5SDimitry Andric /// bitcasted to the right type.
44650b57cec5SDimitry Andric ///
44660b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
44670b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeList ExtraAttrs,ForDefinition_t IsForDefinition)44680b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
44690b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
44700b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
44710b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
44720b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
44730b57cec5SDimitry Andric 
44740b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
44750b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
44760b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
44770b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
4478fe013be4SDimitry Andric     if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
44790b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
44800b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
44810b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
44820b57cec5SDimitry Andric         GlobalDecl GDDef;
44830b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
44840b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
44850b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
44860b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
44870b57cec5SDimitry Andric         else
44880b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
44890b57cec5SDimitry Andric         EmitGlobal(GDDef);
44900b57cec5SDimitry Andric       }
44910b57cec5SDimitry Andric     }
44920b57cec5SDimitry Andric 
44930b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
449404eeddc0SDimitry Andric       UpdateMultiVersionNames(GD, FD, MangledName);
44950b57cec5SDimitry Andric       if (!IsForDefinition)
449681ad6265SDimitry Andric         return GetOrCreateMultiVersionResolver(GD);
44970b57cec5SDimitry Andric     }
44980b57cec5SDimitry Andric   }
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
45010b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
45020b57cec5SDimitry Andric   if (Entry) {
45030b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
45040b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
45050b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
45060b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
45070b57cec5SDimitry Andric     }
45080b57cec5SDimitry Andric 
45090b57cec5SDimitry Andric     // Handle dropped DLL attributes.
451081ad6265SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
451181ad6265SDimitry Andric         !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
45120b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
45130b57cec5SDimitry Andric       setDSOLocal(Entry);
45140b57cec5SDimitry Andric     }
45150b57cec5SDimitry Andric 
45160b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
45170b57cec5SDimitry Andric     // error.
45180b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
45190b57cec5SDimitry Andric       GlobalDecl OtherGD;
45200b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
45210b57cec5SDimitry Andric       // to make sure that we issue an error only once.
45220b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
45230b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
45240b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
45250b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
45260b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
45270b57cec5SDimitry Andric             << MangledName;
45280b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
45290b57cec5SDimitry Andric                           diag::note_previous_definition);
45300b57cec5SDimitry Andric       }
45310b57cec5SDimitry Andric     }
45320b57cec5SDimitry Andric 
45330b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
45345ffd83dbSDimitry Andric         (Entry->getValueType() == Ty)) {
45350b57cec5SDimitry Andric       return Entry;
45360b57cec5SDimitry Andric     }
45370b57cec5SDimitry Andric 
45380b57cec5SDimitry Andric     // Make sure the result is of the correct type.
45390b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
45400b57cec5SDimitry Andric     // function, not just return a bitcast.)
45410b57cec5SDimitry Andric     if (!IsForDefinition)
4542c9157d92SDimitry Andric       return Entry;
45430b57cec5SDimitry Andric   }
45440b57cec5SDimitry Andric 
45450b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
45460b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
45470b57cec5SDimitry Andric   // sure not to try to set attributes.
45480b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
45490b57cec5SDimitry Andric 
45500b57cec5SDimitry Andric   llvm::FunctionType *FTy;
45510b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
45520b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
45530b57cec5SDimitry Andric   } else {
45540b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
45550b57cec5SDimitry Andric     IsIncompleteFunction = true;
45560b57cec5SDimitry Andric   }
45570b57cec5SDimitry Andric 
45580b57cec5SDimitry Andric   llvm::Function *F =
45590b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
45600b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
45610b57cec5SDimitry Andric 
4562c9157d92SDimitry Andric   // Store the declaration associated with this function so it is potentially
4563c9157d92SDimitry Andric   // updated by further declarations or definitions and emitted at the end.
4564c9157d92SDimitry Andric   if (D && D->hasAttr<AnnotateAttr>())
4565c9157d92SDimitry Andric     DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
4566c9157d92SDimitry Andric 
45670b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
45680b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
45690b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
45700b57cec5SDimitry Andric   //
45710b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
45720b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
45730b57cec5SDimitry Andric   if (Entry) {
45740b57cec5SDimitry Andric     F->takeName(Entry);
45750b57cec5SDimitry Andric 
45760b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
45770b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
45780b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
45790b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
45800b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
45810b57cec5SDimitry Andric     // dropping arguments.
45820b57cec5SDimitry Andric     if (!Entry->use_empty()) {
45830b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
45840b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
45850b57cec5SDimitry Andric     }
45860b57cec5SDimitry Andric 
4587c9157d92SDimitry Andric     addGlobalValReplacement(Entry, F);
45880b57cec5SDimitry Andric   }
45890b57cec5SDimitry Andric 
45900b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
45910b57cec5SDimitry Andric   if (D)
45920b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4593349cc55cSDimitry Andric   if (ExtraAttrs.hasFnAttrs()) {
459404eeddc0SDimitry Andric     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4595349cc55cSDimitry Andric     F->addFnAttrs(B);
45960b57cec5SDimitry Andric   }
45970b57cec5SDimitry Andric 
45980b57cec5SDimitry Andric   if (!DontDefer) {
45990b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
46000b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
46010b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
4602bdd1243dSDimitry Andric     if (isa_and_nonnull<CXXDestructorDecl>(D) &&
46030b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
46040b57cec5SDimitry Andric                                            GD.getDtorType()))
46050b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
46080b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
46090b57cec5SDimitry Andric     // of the file.
46100b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
46110b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
46120b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
46130b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
46140b57cec5SDimitry Andric       // don't need it anymore).
46150b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
46160b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
46170b57cec5SDimitry Andric 
46180b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
46190b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
46200b57cec5SDimitry Andric       // we might not find a top-level definition:
46210b57cec5SDimitry Andric       //   - member functions defined inline in their classes
46220b57cec5SDimitry Andric       //   - friend functions defined inline in some class
46230b57cec5SDimitry Andric       //   - special member functions with implicit definitions
46240b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
46250b57cec5SDimitry Andric       // this will be unnecessary.
46260b57cec5SDimitry Andric       //
46270b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
46280b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
46290b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
46300b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
46310b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
46320b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
46330b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
46340b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
46350b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
46360b57cec5SDimitry Andric             break;
46370b57cec5SDimitry Andric           }
46380b57cec5SDimitry Andric         }
46390b57cec5SDimitry Andric       }
46400b57cec5SDimitry Andric     }
46410b57cec5SDimitry Andric   }
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric   // Make sure the result is of the requested type.
46440b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
46455ffd83dbSDimitry Andric     assert(F->getFunctionType() == Ty);
46460b57cec5SDimitry Andric     return F;
46470b57cec5SDimitry Andric   }
46480b57cec5SDimitry Andric 
4649c9157d92SDimitry Andric   return F;
46500b57cec5SDimitry Andric }
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
46530b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
46540b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
4655fe013be4SDimitry Andric llvm::Constant *
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer,ForDefinition_t IsForDefinition)4656fe013be4SDimitry Andric CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
46570b57cec5SDimitry Andric                                  bool DontDefer,
46580b57cec5SDimitry Andric                                  ForDefinition_t IsForDefinition) {
46590b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
46600b57cec5SDimitry Andric   if (!Ty) {
46610b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
46620b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
46630b57cec5SDimitry Andric   }
46640b57cec5SDimitry Andric 
46650b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
46660b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
46670b57cec5SDimitry Andric   // of the complete destructor when necessary.
46680b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
46690b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
46700b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
46710b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
46720b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
46730b57cec5SDimitry Andric   }
46740b57cec5SDimitry Andric 
46750b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
4676fe6060f1SDimitry Andric   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
46770b57cec5SDimitry Andric                                     /*IsThunk=*/false, llvm::AttributeList(),
46780b57cec5SDimitry Andric                                     IsForDefinition);
4679fe6060f1SDimitry Andric   // Returns kernel handle for HIP kernel stub function.
4680fe6060f1SDimitry Andric   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4681fe6060f1SDimitry Andric       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4682fe6060f1SDimitry Andric     auto *Handle = getCUDARuntime().getKernelHandle(
4683fe6060f1SDimitry Andric         cast<llvm::Function>(F->stripPointerCasts()), GD);
4684fe6060f1SDimitry Andric     if (IsForDefinition)
4685fe6060f1SDimitry Andric       return F;
4686c9157d92SDimitry Andric     return Handle;
4687fe6060f1SDimitry Andric   }
4688fe6060f1SDimitry Andric   return F;
46890b57cec5SDimitry Andric }
46900b57cec5SDimitry Andric 
GetFunctionStart(const ValueDecl * Decl)46910eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
46920eae32dcSDimitry Andric   llvm::GlobalValue *F =
46930eae32dcSDimitry Andric       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
46940eae32dcSDimitry Andric 
4695c9157d92SDimitry Andric   return llvm::NoCFIValue::get(F);
46960eae32dcSDimitry Andric }
46970eae32dcSDimitry Andric 
46980b57cec5SDimitry Andric static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext & C,StringRef Name)46990b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
47000b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
47010b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
4704fe6060f1SDimitry Andric   for (const auto *Result : DC->lookup(&CII))
4705fe6060f1SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
47060b57cec5SDimitry Andric       return FD;
47070b57cec5SDimitry Andric 
47080b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
47090b57cec5SDimitry Andric     return nullptr;
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
47120b57cec5SDimitry Andric   IdentifierInfo &CXXII =
47130b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
47140b57cec5SDimitry Andric           ? C.Idents.get("terminate")
47150b57cec5SDimitry Andric           : C.Idents.get(Name);
47160b57cec5SDimitry Andric 
47170b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
47180b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
4719fe6060f1SDimitry Andric     for (const auto *Result : DC->lookup(&NS)) {
4720fe6060f1SDimitry Andric       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4721fe6060f1SDimitry Andric       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4722fe6060f1SDimitry Andric         for (const auto *Result : LSD->lookup(&NS))
47230b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
47240b57cec5SDimitry Andric             break;
47250b57cec5SDimitry Andric 
47260b57cec5SDimitry Andric       if (ND)
4727fe6060f1SDimitry Andric         for (const auto *Result : ND->lookup(&CXXII))
47280b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
47290b57cec5SDimitry Andric             return FD;
47300b57cec5SDimitry Andric     }
47310b57cec5SDimitry Andric   }
47320b57cec5SDimitry Andric 
47330b57cec5SDimitry Andric   return nullptr;
47340b57cec5SDimitry Andric }
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
47370b57cec5SDimitry Andric /// type and name.
47380b57cec5SDimitry Andric llvm::FunctionCallee
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeList ExtraAttrs,bool Local,bool AssumeConvergent)47390b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4740480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
4741480093f4SDimitry Andric                                      bool AssumeConvergent) {
4742480093f4SDimitry Andric   if (AssumeConvergent) {
4743480093f4SDimitry Andric     ExtraAttrs =
4744349cc55cSDimitry Andric         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4745480093f4SDimitry Andric   }
4746480093f4SDimitry Andric 
47470b57cec5SDimitry Andric   llvm::Constant *C =
47480b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
47490b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
47500b57cec5SDimitry Andric                               ExtraAttrs);
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
47530b57cec5SDimitry Andric     if (F->empty()) {
47540b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
47550b57cec5SDimitry Andric 
47560b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
47570b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
47580b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
47590b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
47600b57cec5SDimitry Andric       // and warnings.
47610b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
47620b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
47630b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
47640b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
47650b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
47660b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
47670b57cec5SDimitry Andric         }
47680b57cec5SDimitry Andric       }
47690b57cec5SDimitry Andric       setDSOLocal(F);
47700b57cec5SDimitry Andric     }
47710b57cec5SDimitry Andric   }
47720b57cec5SDimitry Andric 
47730b57cec5SDimitry Andric   return {FTy, C};
47740b57cec5SDimitry Andric }
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4777fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address
4778fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return
4779fe6060f1SDimitry Andric /// it potentially bitcasted to the right type.
47800b57cec5SDimitry Andric ///
47810b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
47820b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
47830b57cec5SDimitry Andric ///
47840b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
47850b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
47860b57cec5SDimitry Andric /// mangled name but some other type.
47870b57cec5SDimitry Andric llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::Type * Ty,LangAS AddrSpace,const VarDecl * D,ForDefinition_t IsForDefinition)4788fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4789349cc55cSDimitry Andric                                      LangAS AddrSpace, const VarDecl *D,
47900b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
47910b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
47920b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4793349cc55cSDimitry Andric   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
47940b57cec5SDimitry Andric   if (Entry) {
47950b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
47960b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
47970b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
47980b57cec5SDimitry Andric     }
47990b57cec5SDimitry Andric 
48000b57cec5SDimitry Andric     // Handle dropped DLL attributes.
480181ad6265SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
480281ad6265SDimitry Andric         !shouldMapVisibilityToDLLExport(D))
48030b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
48040b57cec5SDimitry Andric 
48050b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
48060b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
48070b57cec5SDimitry Andric 
4808349cc55cSDimitry Andric     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
48090b57cec5SDimitry Andric       return Entry;
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
48120b57cec5SDimitry Andric     // error.
48130b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
48140b57cec5SDimitry Andric       GlobalDecl OtherGD;
48150b57cec5SDimitry Andric       const VarDecl *OtherD;
48160b57cec5SDimitry Andric 
48170b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
48180b57cec5SDimitry Andric       // to make sure that we issue an error only once.
48190b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
48200b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
48210b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
48220b57cec5SDimitry Andric           OtherD->hasInit() &&
48230b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
48240b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
48250b57cec5SDimitry Andric             << MangledName;
48260b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
48270b57cec5SDimitry Andric                           diag::note_previous_definition);
48280b57cec5SDimitry Andric       }
48290b57cec5SDimitry Andric     }
48300b57cec5SDimitry Andric 
48310b57cec5SDimitry Andric     // Make sure the result is of the correct type.
4832c9157d92SDimitry Andric     if (Entry->getType()->getAddressSpace() != TargetAS)
4833c9157d92SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(
4834c9157d92SDimitry Andric           Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
48370b57cec5SDimitry Andric     // global, not just return a bitcast.)
48380b57cec5SDimitry Andric     if (!IsForDefinition)
4839c9157d92SDimitry Andric       return Entry;
48400b57cec5SDimitry Andric   }
48410b57cec5SDimitry Andric 
4842fe6060f1SDimitry Andric   auto DAddrSpace = GetGlobalVarAddressSpace(D);
48430b57cec5SDimitry Andric 
48440b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
4845fe6060f1SDimitry Andric       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4846fe6060f1SDimitry Andric       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4847349cc55cSDimitry Andric       getContext().getTargetAddressSpace(DAddrSpace));
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
48500b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
48510b57cec5SDimitry Andric   if (Entry) {
48520b57cec5SDimitry Andric     GV->takeName(Entry);
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric     if (!Entry->use_empty()) {
4855c9157d92SDimitry Andric       Entry->replaceAllUsesWith(GV);
48560b57cec5SDimitry Andric     }
48570b57cec5SDimitry Andric 
48580b57cec5SDimitry Andric     Entry->eraseFromParent();
48590b57cec5SDimitry Andric   }
48600b57cec5SDimitry Andric 
48610b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
48620b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
48630b57cec5SDimitry Andric   // of the file.
48640b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
48650b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
48660b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
48670b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
48680b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
48690b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
48700b57cec5SDimitry Andric   }
48710b57cec5SDimitry Andric 
48720b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
48730b57cec5SDimitry Andric   if (D) {
48740b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
48750b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
48760b57cec5SDimitry Andric 
48770b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
48780b57cec5SDimitry Andric     // handling.
4879c9157d92SDimitry Andric     GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
48800b57cec5SDimitry Andric 
4881a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric     setLinkageForGV(GV, D);
48840b57cec5SDimitry Andric 
48850b57cec5SDimitry Andric     if (D->getTLSKind()) {
48860b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
48870b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
48880b57cec5SDimitry Andric       setTLSMode(GV, *D);
48890b57cec5SDimitry Andric     }
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric     setGVProperties(GV, D);
48920b57cec5SDimitry Andric 
48930b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
48940b57cec5SDimitry Andric     // inline initializers as definitions.
48950b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
48960b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
48970b57cec5SDimitry Andric     }
48980b57cec5SDimitry Andric 
48990b57cec5SDimitry Andric     // Emit section information for extern variables.
49000b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
49010b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
49020b57cec5SDimitry Andric         GV->setSection(SA->getName());
49030b57cec5SDimitry Andric     }
49040b57cec5SDimitry Andric 
49050b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
49060b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
49070b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
49080b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
49090b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
49100b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
49110b57cec5SDimitry Andric 
4912cdc20ff6SDimitry Andric     // Handle code model attribute
4913cdc20ff6SDimitry Andric     if (const auto *CMA = D->getAttr<CodeModelAttr>())
4914cdc20ff6SDimitry Andric       GV->setCodeModel(CMA->getModel());
4915cdc20ff6SDimitry Andric 
49160b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
49170b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
49180b57cec5SDimitry Andric     // optimizer.
49190b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
49200b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
49210b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
49220b57cec5SDimitry Andric       const auto *Record =
49230b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
49240b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
49250b57cec5SDimitry Andric       if (!HasMutableFields) {
49260b57cec5SDimitry Andric         const VarDecl *InitDecl;
49270b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
49280b57cec5SDimitry Andric         if (InitExpr) {
49290b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
49300b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
49310b57cec5SDimitry Andric           if (Init) {
49320b57cec5SDimitry Andric             auto *InitType = Init->getType();
49335ffd83dbSDimitry Andric             if (GV->getValueType() != InitType) {
49340b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
49350b57cec5SDimitry Andric               // This happens when an initializer has a different type from
49360b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
49370b57cec5SDimitry Andric               // structure for instance).
49380b57cec5SDimitry Andric               GV->setName(StringRef());
49390b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
49400b57cec5SDimitry Andric               // to work.
49410b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
4942a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4943a7dea167SDimitry Andric                       ->stripPointerCasts());
49440b57cec5SDimitry Andric 
49450b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
49460b57cec5SDimitry Andric               GV->eraseFromParent();
49470b57cec5SDimitry Andric               GV = NewGV;
49480b57cec5SDimitry Andric             } else {
49490b57cec5SDimitry Andric               GV->setInitializer(Init);
49500b57cec5SDimitry Andric               GV->setConstant(true);
49510b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
49520b57cec5SDimitry Andric             }
49530b57cec5SDimitry Andric             emitter.finalize(GV);
49540b57cec5SDimitry Andric           }
49550b57cec5SDimitry Andric         }
49560b57cec5SDimitry Andric       }
49570b57cec5SDimitry Andric     }
49580b57cec5SDimitry Andric   }
49590b57cec5SDimitry Andric 
4960fe013be4SDimitry Andric   if (D &&
4961fe013be4SDimitry Andric       D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
4962480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4963fe6060f1SDimitry Andric     // External HIP managed variables needed to be recorded for transformation
4964fe6060f1SDimitry Andric     // in both device and host compilations.
4965fe6060f1SDimitry Andric     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4966fe6060f1SDimitry Andric         D->hasExternalStorage())
4967fe6060f1SDimitry Andric       getCUDARuntime().handleVarRegistration(D, *GV);
4968fe6060f1SDimitry Andric   }
4969480093f4SDimitry Andric 
4970753f127fSDimitry Andric   if (D)
4971753f127fSDimitry Andric     SanitizerMD->reportGlobal(GV, *D);
4972753f127fSDimitry Andric 
49730b57cec5SDimitry Andric   LangAS ExpectedAS =
49740b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
49750b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4976349cc55cSDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4977fe6060f1SDimitry Andric   if (DAddrSpace != ExpectedAS) {
4978fe6060f1SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(
4979c9157d92SDimitry Andric         *this, GV, DAddrSpace, ExpectedAS,
4980c9157d92SDimitry Andric         llvm::PointerType::get(getLLVMContext(), TargetAS));
4981fe6060f1SDimitry Andric   }
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric   return GV;
49840b57cec5SDimitry Andric }
49850b57cec5SDimitry Andric 
49860b57cec5SDimitry Andric llvm::Constant *
GetAddrOfGlobal(GlobalDecl GD,ForDefinition_t IsForDefinition)49875ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
49880b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
49895ffd83dbSDimitry Andric 
49900b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
49910b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
49920b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
49935ffd83dbSDimitry Andric 
49945ffd83dbSDimitry Andric   if (isa<CXXMethodDecl>(D)) {
49955ffd83dbSDimitry Andric     auto FInfo =
49965ffd83dbSDimitry Andric         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
49970b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
49980b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
49990b57cec5SDimitry Andric                              IsForDefinition);
50005ffd83dbSDimitry Andric   }
50015ffd83dbSDimitry Andric 
50025ffd83dbSDimitry Andric   if (isa<FunctionDecl>(D)) {
50030b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
50040b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
50050b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
50060b57cec5SDimitry Andric                              IsForDefinition);
50075ffd83dbSDimitry Andric   }
50085ffd83dbSDimitry Andric 
50095ffd83dbSDimitry Andric   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
50100b57cec5SDimitry Andric }
50110b57cec5SDimitry Andric 
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage,llvm::Align Alignment)50120b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
50130b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
5014bdd1243dSDimitry Andric     llvm::Align Alignment) {
50150b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
50160b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
50170b57cec5SDimitry Andric 
50180b57cec5SDimitry Andric   if (GV) {
50190b57cec5SDimitry Andric     // Check if the variable has the right type.
50205ffd83dbSDimitry Andric     if (GV->getValueType() == Ty)
50210b57cec5SDimitry Andric       return GV;
50220b57cec5SDimitry Andric 
50230b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
50240b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
50250b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
50260b57cec5SDimitry Andric     OldGV = GV;
50270b57cec5SDimitry Andric   }
50280b57cec5SDimitry Andric 
50290b57cec5SDimitry Andric   // Create a new variable.
50300b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
50310b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
50320b57cec5SDimitry Andric 
50330b57cec5SDimitry Andric   if (OldGV) {
50340b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
50350b57cec5SDimitry Andric     GV->takeName(OldGV);
50360b57cec5SDimitry Andric 
50370b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
5038c9157d92SDimitry Andric       OldGV->replaceAllUsesWith(GV);
50390b57cec5SDimitry Andric     }
50400b57cec5SDimitry Andric 
50410b57cec5SDimitry Andric     OldGV->eraseFromParent();
50420b57cec5SDimitry Andric   }
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
50450b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
50460b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
50470b57cec5SDimitry Andric 
5048bdd1243dSDimitry Andric   GV->setAlignment(Alignment);
50490b57cec5SDimitry Andric 
50500b57cec5SDimitry Andric   return GV;
50510b57cec5SDimitry Andric }
50520b57cec5SDimitry Andric 
50530b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
50540b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
50550b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
50560b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
50570b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
50580b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty,ForDefinition_t IsForDefinition)50590b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
50600b57cec5SDimitry Andric                                                   llvm::Type *Ty,
50610b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
50620b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
50630b57cec5SDimitry Andric   QualType ASTTy = D->getType();
50640b57cec5SDimitry Andric   if (!Ty)
50650b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
5068349cc55cSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
5069fe6060f1SDimitry Andric                                IsForDefinition);
50700b57cec5SDimitry Andric }
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
50730b57cec5SDimitry Andric /// specified type and name.
50740b57cec5SDimitry Andric llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)50750b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
50760b57cec5SDimitry Andric                                      StringRef Name) {
5077349cc55cSDimitry Andric   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
5078349cc55cSDimitry Andric                                                        : LangAS::Default;
5079fe6060f1SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
50800b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
50810b57cec5SDimitry Andric   return Ret;
50820b57cec5SDimitry Andric }
50830b57cec5SDimitry Andric 
EmitTentativeDefinition(const VarDecl * D)50840b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
50850b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
50860b57cec5SDimitry Andric 
50870b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
50880b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
50890b57cec5SDimitry Andric 
50900b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
50910b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
50920b57cec5SDimitry Andric   // definition).
50930b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
50940b57cec5SDimitry Andric     return;
50950b57cec5SDimitry Andric 
50960b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
50970b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
50980b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
50990b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
51000b57cec5SDimitry Andric       return;
51010b57cec5SDimitry Andric   }
51020b57cec5SDimitry Andric 
51030b57cec5SDimitry Andric   // The tentative definition is the only definition.
51040b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
51050b57cec5SDimitry Andric }
51060b57cec5SDimitry Andric 
EmitExternalDeclaration(const VarDecl * D)5107480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
5108480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
5109480093f4SDimitry Andric }
5110480093f4SDimitry Andric 
GetTargetTypeStoreSize(llvm::Type * Ty) const51110b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
51120b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
51130b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
51140b57cec5SDimitry Andric }
51150b57cec5SDimitry Andric 
GetGlobalVarAddressSpace(const VarDecl * D)51160b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
51170b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
5118349cc55cSDimitry Andric     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
5119349cc55cSDimitry Andric     assert(AS == LangAS::opencl_global ||
5120349cc55cSDimitry Andric            AS == LangAS::opencl_global_device ||
5121349cc55cSDimitry Andric            AS == LangAS::opencl_global_host ||
5122349cc55cSDimitry Andric            AS == LangAS::opencl_constant ||
5123349cc55cSDimitry Andric            AS == LangAS::opencl_local ||
5124349cc55cSDimitry Andric            AS >= LangAS::FirstTargetAddressSpace);
5125349cc55cSDimitry Andric     return AS;
51260b57cec5SDimitry Andric   }
51270b57cec5SDimitry Andric 
5128fe6060f1SDimitry Andric   if (LangOpts.SYCLIsDevice &&
5129fe6060f1SDimitry Andric       (!D || D->getType().getAddressSpace() == LangAS::Default))
5130fe6060f1SDimitry Andric     return LangAS::sycl_global;
5131fe6060f1SDimitry Andric 
51320b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5133fe013be4SDimitry Andric     if (D) {
5134fe013be4SDimitry Andric       if (D->hasAttr<CUDAConstantAttr>())
51350b57cec5SDimitry Andric         return LangAS::cuda_constant;
5136fe013be4SDimitry Andric       if (D->hasAttr<CUDASharedAttr>())
51370b57cec5SDimitry Andric         return LangAS::cuda_shared;
5138fe013be4SDimitry Andric       if (D->hasAttr<CUDADeviceAttr>())
51390b57cec5SDimitry Andric         return LangAS::cuda_device;
5140fe013be4SDimitry Andric       if (D->getType().isConstQualified())
51410b57cec5SDimitry Andric         return LangAS::cuda_constant;
5142fe013be4SDimitry Andric     }
51430b57cec5SDimitry Andric     return LangAS::cuda_device;
51440b57cec5SDimitry Andric   }
51450b57cec5SDimitry Andric 
51460b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
51470b57cec5SDimitry Andric     LangAS AS;
51480b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
51490b57cec5SDimitry Andric       return AS;
51500b57cec5SDimitry Andric   }
51510b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
51520b57cec5SDimitry Andric }
51530b57cec5SDimitry Andric 
GetGlobalConstantAddressSpace() const5154fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
51550b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
51560b57cec5SDimitry Andric   if (LangOpts.OpenCL)
51570b57cec5SDimitry Andric     return LangAS::opencl_constant;
5158fe6060f1SDimitry Andric   if (LangOpts.SYCLIsDevice)
5159fe6060f1SDimitry Andric     return LangAS::sycl_global;
5160d56accc7SDimitry Andric   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
5161d56accc7SDimitry Andric     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5162d56accc7SDimitry Andric     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5163d56accc7SDimitry Andric     // with OpVariable instructions with Generic storage class which is not
5164d56accc7SDimitry Andric     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5165d56accc7SDimitry Andric     // UniformConstant storage class is not viable as pointers to it may not be
5166d56accc7SDimitry Andric     // casted to Generic pointers which are used to model HIP's "flat" pointers.
5167d56accc7SDimitry Andric     return LangAS::cuda_device;
51680b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
516981ad6265SDimitry Andric     return *AS;
51700b57cec5SDimitry Andric   return LangAS::Default;
51710b57cec5SDimitry Andric }
51720b57cec5SDimitry Andric 
51730b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
51740b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
51750b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
51760b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
51770b57cec5SDimitry Andric // need to be casted to default address space before being put into address
51780b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
51790b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
51800b57cec5SDimitry Andric // they should not be casted to default address space.
51810b57cec5SDimitry Andric static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule & CGM,llvm::GlobalVariable * GV)51820b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
51830b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
51840b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
51850b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
5186fe6060f1SDimitry Andric     auto AS = CGM.GetGlobalConstantAddressSpace();
51870b57cec5SDimitry Andric     if (AS != LangAS::Default)
51880b57cec5SDimitry Andric       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
5189fe6060f1SDimitry Andric           CGM, GV, AS, LangAS::Default,
5190c9157d92SDimitry Andric           llvm::PointerType::get(
5191c9157d92SDimitry Andric               CGM.getLLVMContext(),
51920b57cec5SDimitry Andric               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
51930b57cec5SDimitry Andric   }
51940b57cec5SDimitry Andric   return Cast;
51950b57cec5SDimitry Andric }
51960b57cec5SDimitry Andric 
51970b57cec5SDimitry Andric template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)51980b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
51990b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
52000b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
52010b57cec5SDimitry Andric     return;
52020b57cec5SDimitry Andric 
52030b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
52040b57cec5SDimitry Andric   // the name existing.
52050b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
52060b57cec5SDimitry Andric     return;
52070b57cec5SDimitry Andric 
52080b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
5209c9157d92SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal)
52100b57cec5SDimitry Andric     return;
52110b57cec5SDimitry Andric 
52120b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
52130b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
52140b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
52150b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
52160b57cec5SDimitry Andric     return;
52170b57cec5SDimitry Andric 
52180b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
52190b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
52200b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
52210b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
52220b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
52230b57cec5SDimitry Andric 
52240b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
52250b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
52260b57cec5SDimitry Andric   if (!R.second)
52270b57cec5SDimitry Andric     R.first->second = nullptr;
52280b57cec5SDimitry Andric }
52290b57cec5SDimitry Andric 
shouldBeInCOMDAT(CodeGenModule & CGM,const Decl & D)52300b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
52310b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
52320b57cec5SDimitry Andric     return false;
52330b57cec5SDimitry Andric 
52340b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
52350b57cec5SDimitry Andric     return true;
52360b57cec5SDimitry Andric 
52370b57cec5SDimitry Andric   GVALinkage Linkage;
52380b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
52390b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
52400b57cec5SDimitry Andric   else
52410b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
52420b57cec5SDimitry Andric 
52430b57cec5SDimitry Andric   switch (Linkage) {
52440b57cec5SDimitry Andric   case GVA_Internal:
52450b57cec5SDimitry Andric   case GVA_AvailableExternally:
52460b57cec5SDimitry Andric   case GVA_StrongExternal:
52470b57cec5SDimitry Andric     return false;
52480b57cec5SDimitry Andric   case GVA_DiscardableODR:
52490b57cec5SDimitry Andric   case GVA_StrongODR:
52500b57cec5SDimitry Andric     return true;
52510b57cec5SDimitry Andric   }
52520b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
52530b57cec5SDimitry Andric }
52540b57cec5SDimitry Andric 
supportsCOMDAT() const5255fe013be4SDimitry Andric bool CodeGenModule::supportsCOMDAT() const {
5256fe013be4SDimitry Andric   return getTriple().supportsCOMDAT();
5257fe013be4SDimitry Andric }
5258fe013be4SDimitry Andric 
maybeSetTrivialComdat(const Decl & D,llvm::GlobalObject & GO)52590b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
52600b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
52610b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
52620b57cec5SDimitry Andric     return;
52630b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
52640b57cec5SDimitry Andric }
52650b57cec5SDimitry Andric 
52660b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
EmitGlobalVarDefinition(const VarDecl * D,bool IsTentative)52670b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
52680b57cec5SDimitry Andric                                             bool IsTentative) {
52690b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
52700b57cec5SDimitry Andric   // therefore no need to be translated.
52710b57cec5SDimitry Andric   QualType ASTTy = D->getType();
52720b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
52730b57cec5SDimitry Andric     return;
52740b57cec5SDimitry Andric 
52750b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
52760b57cec5SDimitry Andric   // normally.
5277fe013be4SDimitry Andric   if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
52780b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
52790b57cec5SDimitry Andric     return;
52800b57cec5SDimitry Andric 
5281fe6060f1SDimitry Andric   llvm::TrackingVH<llvm::Constant> Init;
52820b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
5283bdd1243dSDimitry Andric   // Whether the definition of the variable is available externally.
5284bdd1243dSDimitry Andric   // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5285bdd1243dSDimitry Andric   // since this is the job for its original source.
5286bdd1243dSDimitry Andric   bool IsDefinitionAvailableExternally =
5287bdd1243dSDimitry Andric       getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5288a7dea167SDimitry Andric   bool NeedsGlobalDtor =
5289bdd1243dSDimitry Andric       !IsDefinitionAvailableExternally &&
5290a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric   const VarDecl *InitDecl;
52930b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
52940b57cec5SDimitry Andric 
5295bdd1243dSDimitry Andric   std::optional<ConstantEmitter> emitter;
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
52980b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
52990b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
53000b57cec5SDimitry Andric   bool IsCUDASharedVar =
53010b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
53020b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
53030b57cec5SDimitry Andric   // undefined.
5304fe6060f1SDimitry Andric   // Managed Variables should be initialized on both host side and device side.
53050b57cec5SDimitry Andric   bool IsCUDAShadowVar =
5306e8d8bef9SDimitry Andric       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
53070b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
53080b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
53095ffd83dbSDimitry Andric   bool IsCUDADeviceShadowVar =
5310fe6060f1SDimitry Andric       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
53115ffd83dbSDimitry Andric       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5312fe6060f1SDimitry Andric        D->getType()->isCUDADeviceBuiltinTextureType());
53130b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
53145ffd83dbSDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5315fe6060f1SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
53165ffd83dbSDimitry Andric   else if (D->hasAttr<LoaderUninitializedAttr>())
5317fe6060f1SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
53180b57cec5SDimitry Andric   else if (!InitExpr) {
53190b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
53200b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
53210b57cec5SDimitry Andric     //
53220b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
53230b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
53240b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
53250b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
53260b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
53270b57cec5SDimitry Andric     // to do a RAUW.
53280b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
53290b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
53300b57cec5SDimitry Andric   } else {
53310b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
53320b57cec5SDimitry Andric     emitter.emplace(*this);
5333fe6060f1SDimitry Andric     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5334fe6060f1SDimitry Andric     if (!Initializer) {
53350b57cec5SDimitry Andric       QualType T = InitExpr->getType();
53360b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
53370b57cec5SDimitry Andric         T = D->getType();
53380b57cec5SDimitry Andric 
53390b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
534081ad6265SDimitry Andric         if (InitDecl->hasFlexibleArrayInit(getContext()))
534181ad6265SDimitry Andric           ErrorUnsupported(D, "flexible array initializer");
53420b57cec5SDimitry Andric         Init = EmitNullConstant(T);
5343bdd1243dSDimitry Andric 
5344bdd1243dSDimitry Andric         if (!IsDefinitionAvailableExternally)
53450b57cec5SDimitry Andric           NeedsGlobalCtor = true;
53460b57cec5SDimitry Andric       } else {
53470b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
53480b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
53490b57cec5SDimitry Andric       }
53500b57cec5SDimitry Andric     } else {
5351fe6060f1SDimitry Andric       Init = Initializer;
53520b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
53530b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
53540b57cec5SDimitry Andric       // also don't need to register a destructor.
53550b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
53560b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
535781ad6265SDimitry Andric 
535881ad6265SDimitry Andric #ifndef NDEBUG
535981ad6265SDimitry Andric       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
536081ad6265SDimitry Andric                           InitDecl->getFlexibleArrayInitChars(getContext());
536181ad6265SDimitry Andric       CharUnits CstSize = CharUnits::fromQuantity(
536281ad6265SDimitry Andric           getDataLayout().getTypeAllocSize(Init->getType()));
536381ad6265SDimitry Andric       assert(VarSize == CstSize && "Emitted constant has unexpected size");
536481ad6265SDimitry Andric #endif
53650b57cec5SDimitry Andric     }
53660b57cec5SDimitry Andric   }
53670b57cec5SDimitry Andric 
53680b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
53690b57cec5SDimitry Andric   llvm::Constant *Entry =
53700b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
53710b57cec5SDimitry Andric 
5372a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
5373a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
53740b57cec5SDimitry Andric 
53750b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
53760b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
53770b57cec5SDimitry Andric 
53780b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
53790b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
53800b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
53810b57cec5SDimitry Andric   // (which will be a definition).
53820b57cec5SDimitry Andric   //
53830b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
53840b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
53850b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
53860b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
53875ffd83dbSDimitry Andric   if (!GV || GV->getValueType() != InitType ||
53880b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
53890b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
53900b57cec5SDimitry Andric 
53910b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
53920b57cec5SDimitry Andric     Entry->setName(StringRef());
53930b57cec5SDimitry Andric 
53940b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
53950b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
5396a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5397a7dea167SDimitry Andric             ->stripPointerCasts());
53980b57cec5SDimitry Andric 
53990b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
54000b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
5401fe6060f1SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5402fe6060f1SDimitry Andric                                                              Entry->getType());
54030b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
54040b57cec5SDimitry Andric 
54050b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
54060b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
54070b57cec5SDimitry Andric   }
54080b57cec5SDimitry Andric 
54090b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
54100b57cec5SDimitry Andric 
54110b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
54120b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
5415271697daSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
54160b57cec5SDimitry Andric 
54170b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
54180b57cec5SDimitry Andric   // the device. [...]"
54190b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
54200b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
54210b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
54220b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
54230b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
5424fe013be4SDimitry Andric   if (LangOpts.CUDA) {
54250b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
54260b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
5427349cc55cSDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5428349cc55cSDimitry Andric            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5429349cc55cSDimitry Andric            D->getType()->isCUDADeviceBuiltinTextureType()))
54300b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
54310b57cec5SDimitry Andric     } else {
5432fe6060f1SDimitry Andric       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
54335ffd83dbSDimitry Andric     }
5434fe6060f1SDimitry Andric     getCUDARuntime().handleVarRegistration(D, *GV);
54350b57cec5SDimitry Andric   }
54360b57cec5SDimitry Andric 
54370b57cec5SDimitry Andric   GV->setInitializer(Init);
54385ffd83dbSDimitry Andric   if (emitter)
54395ffd83dbSDimitry Andric     emitter->finalize(GV);
54400b57cec5SDimitry Andric 
54410b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
54420b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5443c9157d92SDimitry Andric                   D->getType().isConstantStorage(getContext(), true, true));
54440b57cec5SDimitry Andric 
54450b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
54460b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
54470b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
54480b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
54490b57cec5SDimitry Andric       GV->setConstant(true);
54500b57cec5SDimitry Andric   }
54510b57cec5SDimitry Andric 
545281ad6265SDimitry Andric   CharUnits AlignVal = getContext().getDeclAlign(D);
545381ad6265SDimitry Andric   // Check for alignment specifed in an 'omp allocate' directive.
5454bdd1243dSDimitry Andric   if (std::optional<CharUnits> AlignValFromAllocate =
545581ad6265SDimitry Andric           getOMPAllocateAlignment(D))
545681ad6265SDimitry Andric     AlignVal = *AlignValFromAllocate;
545781ad6265SDimitry Andric   GV->setAlignment(AlignVal.getAsAlign());
54580b57cec5SDimitry Andric 
54595ffd83dbSDimitry Andric   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
54605ffd83dbSDimitry Andric   // function is only defined alongside the variable, not also alongside
54615ffd83dbSDimitry Andric   // callers. Normally, all accesses to a thread_local go through the
54625ffd83dbSDimitry Andric   // thread-wrapper in order to ensure initialization has occurred, underlying
54635ffd83dbSDimitry Andric   // variable will never be used other than the thread-wrapper, so it can be
54645ffd83dbSDimitry Andric   // converted to internal linkage.
54655ffd83dbSDimitry Andric   //
54665ffd83dbSDimitry Andric   // However, if the variable has the 'constinit' attribute, it _can_ be
54675ffd83dbSDimitry Andric   // referenced directly, without calling the thread-wrapper, so the linkage
54685ffd83dbSDimitry Andric   // must not be changed.
54695ffd83dbSDimitry Andric   //
54705ffd83dbSDimitry Andric   // Additionally, if the variable isn't plain external linkage, e.g. if it's
54715ffd83dbSDimitry Andric   // weak or linkonce, the de-duplication semantics are important to preserve,
54725ffd83dbSDimitry Andric   // so we don't change the linkage.
54735ffd83dbSDimitry Andric   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
54745ffd83dbSDimitry Andric       Linkage == llvm::GlobalValue::ExternalLinkage &&
54750b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
54765ffd83dbSDimitry Andric       !D->hasAttr<ConstInitAttr>())
54770b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
54780b57cec5SDimitry Andric 
54790b57cec5SDimitry Andric   GV->setLinkage(Linkage);
54800b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
54810b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
54820b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
54830b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
54840b57cec5SDimitry Andric   else
54850b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
54860b57cec5SDimitry Andric 
54870b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
54880b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
54890b57cec5SDimitry Andric     GV->setConstant(false);
54900b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
54910b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
54920b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
54930b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
54940b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
54950b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
54960b57cec5SDimitry Andric   }
54970b57cec5SDimitry Andric 
54980b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
54990b57cec5SDimitry Andric 
55000b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
55010b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
55020b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
55030b57cec5SDimitry Andric     setTLSMode(GV, *D);
55040b57cec5SDimitry Andric   }
55050b57cec5SDimitry Andric 
55060b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
55070b57cec5SDimitry Andric 
55080b57cec5SDimitry Andric   // Emit the initializer function if necessary.
55090b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
55100b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
55110b57cec5SDimitry Andric 
551281ad6265SDimitry Andric   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
55130b57cec5SDimitry Andric 
55140b57cec5SDimitry Andric   // Emit global variable debug information.
55150b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
5516480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
55170b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
55180b57cec5SDimitry Andric }
55190b57cec5SDimitry Andric 
EmitExternalVarDeclaration(const VarDecl * D)5520480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5521480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
5522480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
5523480093f4SDimitry Andric       QualType ASTTy = D->getType();
5524480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5525349cc55cSDimitry Andric       llvm::Constant *GV =
5526349cc55cSDimitry Andric           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5527480093f4SDimitry Andric       DI->EmitExternalVariable(
5528480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5529480093f4SDimitry Andric     }
5530480093f4SDimitry Andric }
5531480093f4SDimitry Andric 
isVarDeclStrongDefinition(const ASTContext & Context,CodeGenModule & CGM,const VarDecl * D,bool NoCommon)55320b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
55330b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
55340b57cec5SDimitry Andric                                       bool NoCommon) {
55350b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
55360b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
55370b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
55380b57cec5SDimitry Andric     return true;
55390b57cec5SDimitry Andric 
55400b57cec5SDimitry Andric   // C11 6.9.2/2:
55410b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
55420b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
55430b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
55440b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
55450b57cec5SDimitry Andric     return true;
55460b57cec5SDimitry Andric 
55470b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
55480b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
55490b57cec5SDimitry Andric     return true;
55500b57cec5SDimitry Andric 
55510b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
55520b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
55530b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
55540b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
55550b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
5556a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
55570b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
55580b57cec5SDimitry Andric     return true;
55590b57cec5SDimitry Andric 
55600b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
55610b57cec5SDimitry Andric   if (D->getTLSKind())
55620b57cec5SDimitry Andric     return true;
55630b57cec5SDimitry Andric 
55640b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
55650b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
55660b57cec5SDimitry Andric     return true;
55670b57cec5SDimitry Andric 
55680b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
55690b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
55700b57cec5SDimitry Andric     return true;
55710b57cec5SDimitry Andric 
55720b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
55730b57cec5SDimitry Andric   // mode.
55740b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
55750b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
55760b57cec5SDimitry Andric       return true;
55770b57cec5SDimitry Andric     QualType VarType = D->getType();
55780b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
55790b57cec5SDimitry Andric       return true;
55800b57cec5SDimitry Andric 
55810b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
55820b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
55830b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
55840b57cec5SDimitry Andric         if (FD->isBitField())
55850b57cec5SDimitry Andric           continue;
55860b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
55870b57cec5SDimitry Andric           return true;
55880b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
55890b57cec5SDimitry Andric           return true;
55900b57cec5SDimitry Andric       }
55910b57cec5SDimitry Andric     }
55920b57cec5SDimitry Andric   }
55930b57cec5SDimitry Andric 
55940b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
55950b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
55960b57cec5SDimitry Andric   // common.
55970b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
55980b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
55990b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
56000b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
56010b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
56020b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
56030b57cec5SDimitry Andric     return true;
56040b57cec5SDimitry Andric 
56050b57cec5SDimitry Andric   return false;
56060b57cec5SDimitry Andric }
56070b57cec5SDimitry Andric 
5608271697daSDimitry Andric llvm::GlobalValue::LinkageTypes
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage)5609271697daSDimitry Andric CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
5610271697daSDimitry Andric                                            GVALinkage Linkage) {
56110b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
56120b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
56130b57cec5SDimitry Andric 
561481ad6265SDimitry Andric   if (D->hasAttr<WeakAttr>())
56150b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakAnyLinkage;
56160b57cec5SDimitry Andric 
56170b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
56180b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
56190b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
56200b57cec5SDimitry Andric 
56210b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
56220b57cec5SDimitry Andric   // so we can use available_externally linkage.
56230b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
56240b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
56250b57cec5SDimitry Andric 
56260b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
56270b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
56280b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
56290b57cec5SDimitry Andric   // instantiations we'll map to external.
56300b57cec5SDimitry Andric 
56310b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
56320b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
56330b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
56340b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
56350b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
56360b57cec5SDimitry Andric   // definition is dependable.
56370b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
56380b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
56390b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
56400b57cec5SDimitry Andric 
56410b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
56420b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
56430b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
56440b57cec5SDimitry Andric   // throw away these explicit instantiations.
56450b57cec5SDimitry Andric   //
5646e8d8bef9SDimitry Andric   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
56470b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
5648e8d8bef9SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations. For
5649e8d8bef9SDimitry Andric   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5650e8d8bef9SDimitry Andric   // therefore we need to follow the normal linkage paradigm.
56510b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
5652e8d8bef9SDimitry Andric     if (getLangOpts().AppleKext)
56530b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
5654e8d8bef9SDimitry Andric     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5655e8d8bef9SDimitry Andric         !getLangOpts().GPURelocatableDeviceCode)
56560b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
56570b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
56580b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
56590b57cec5SDimitry Andric   }
56600b57cec5SDimitry Andric 
56610b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
56620b57cec5SDimitry Andric   // linkage.
56630b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
56640b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
56650b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
56660b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
56670b57cec5SDimitry Andric 
56680b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
56690b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
56700b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
56710b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
56720b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
56730b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
56740b57cec5SDimitry Andric 
56750b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
56760b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
56770b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
56780b57cec5SDimitry Andric }
56790b57cec5SDimitry Andric 
5680271697daSDimitry Andric llvm::GlobalValue::LinkageTypes
getLLVMLinkageVarDefinition(const VarDecl * VD)5681271697daSDimitry Andric CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
56820b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5683271697daSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage);
56840b57cec5SDimitry Andric }
56850b57cec5SDimitry Andric 
56860b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
56870b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)56880b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
56890b57cec5SDimitry Andric                                           llvm::Function *newFn) {
56900b57cec5SDimitry Andric   // Fast path.
56910b57cec5SDimitry Andric   if (old->use_empty()) return;
56920b57cec5SDimitry Andric 
56930b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
56940b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
56950b57cec5SDimitry Andric 
56960b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
56970b57cec5SDimitry Andric          ui != ue; ) {
56980b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
56990b57cec5SDimitry Andric     llvm::User *user = use->getUser();
57000b57cec5SDimitry Andric 
57010b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
57020b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
57030b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
57040b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
57050b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
57060b57cec5SDimitry Andric       continue;
57070b57cec5SDimitry Andric     }
57080b57cec5SDimitry Andric 
57090b57cec5SDimitry Andric     // Recognize calls to the function.
57100b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
57110b57cec5SDimitry Andric     if (!callSite) continue;
57120b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
57130b57cec5SDimitry Andric       continue;
57140b57cec5SDimitry Andric 
57150b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
57160b57cec5SDimitry Andric     // transform this call unless it's dead.
57170b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
57180b57cec5SDimitry Andric       continue;
57190b57cec5SDimitry Andric 
57200b57cec5SDimitry Andric     // Get the call site's attribute list.
57210b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
57220b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
57230b57cec5SDimitry Andric 
57240b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
57250b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
57260b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
57270b57cec5SDimitry Andric       continue;
57280b57cec5SDimitry Andric 
57290b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
57300b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
57310b57cec5SDimitry Andric     unsigned argNo = 0;
57320b57cec5SDimitry Andric     bool dontTransform = false;
57330b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
57340b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
57350b57cec5SDimitry Andric         dontTransform = true;
57360b57cec5SDimitry Andric         break;
57370b57cec5SDimitry Andric       }
57380b57cec5SDimitry Andric 
57390b57cec5SDimitry Andric       // Add any parameter attributes.
5740349cc55cSDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
57410b57cec5SDimitry Andric       argNo++;
57420b57cec5SDimitry Andric     }
57430b57cec5SDimitry Andric     if (dontTransform)
57440b57cec5SDimitry Andric       continue;
57450b57cec5SDimitry Andric 
57460b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
57470b57cec5SDimitry Andric     // over the required information.
57480b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
57490b57cec5SDimitry Andric 
57500b57cec5SDimitry Andric     // Copy over any operand bundles.
5751fe6060f1SDimitry Andric     SmallVector<llvm::OperandBundleDef, 1> newBundles;
57520b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
57530b57cec5SDimitry Andric 
57540b57cec5SDimitry Andric     llvm::CallBase *newCall;
5755349cc55cSDimitry Andric     if (isa<llvm::CallInst>(callSite)) {
57560b57cec5SDimitry Andric       newCall =
57570b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
57580b57cec5SDimitry Andric     } else {
57590b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
57600b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
57610b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
57620b57cec5SDimitry Andric                                          newBundles, "", callSite);
57630b57cec5SDimitry Andric     }
57640b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
57650b57cec5SDimitry Andric 
57660b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
57670b57cec5SDimitry Andric       newCall->takeName(callSite);
5768349cc55cSDimitry Andric     newCall->setAttributes(
5769349cc55cSDimitry Andric         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5770349cc55cSDimitry Andric                                  oldAttrs.getRetAttrs(), newArgAttrs));
57710b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
57720b57cec5SDimitry Andric 
57730b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
57740b57cec5SDimitry Andric     if (!callSite->use_empty())
57750b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
57760b57cec5SDimitry Andric 
57770b57cec5SDimitry Andric     // Copy debug location attached to CI.
57780b57cec5SDimitry Andric     if (callSite->getDebugLoc())
57790b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
57800b57cec5SDimitry Andric 
57810b57cec5SDimitry Andric     callSite->eraseFromParent();
57820b57cec5SDimitry Andric   }
57830b57cec5SDimitry Andric }
57840b57cec5SDimitry Andric 
57850b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
57860b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
57870b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
57880b57cec5SDimitry Andric /// call the new function directly.
57890b57cec5SDimitry Andric ///
57900b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
57910b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
57920b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
57930b57cec5SDimitry Andric /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)57940b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
57950b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
57960b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
57970b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
57980b57cec5SDimitry Andric 
57990b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
58000b57cec5SDimitry Andric }
58010b57cec5SDimitry Andric 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)58020b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
58030b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
58040b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
58050b57cec5SDimitry Andric     return;
58060b57cec5SDimitry Andric 
58070b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
58080b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
58090b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
58100b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
58110b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
58120b57cec5SDimitry Andric 
58130b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
58140b57cec5SDimitry Andric }
58150b57cec5SDimitry Andric 
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)58160b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
58170b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
58180b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
58190b57cec5SDimitry Andric 
58200b57cec5SDimitry Andric   // Compute the function info and LLVM type.
58210b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
58220b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
58230b57cec5SDimitry Andric 
58240b57cec5SDimitry Andric   // Get or create the prototype for the function.
58255ffd83dbSDimitry Andric   if (!GV || (GV->getValueType() != Ty))
58260b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
58270b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
58280b57cec5SDimitry Andric                                                    ForDefinition));
58290b57cec5SDimitry Andric 
58300b57cec5SDimitry Andric   // Already emitted.
58310b57cec5SDimitry Andric   if (!GV->isDeclaration())
58320b57cec5SDimitry Andric     return;
58330b57cec5SDimitry Andric 
58340b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
58350b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
58360b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
58370b57cec5SDimitry Andric   // declarations).
58380b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
58390b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
58400b57cec5SDimitry Andric 
58410b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
58420b57cec5SDimitry Andric   setGVProperties(Fn, GD);
58430b57cec5SDimitry Andric 
58440b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
58450b57cec5SDimitry Andric 
58460b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
58470b57cec5SDimitry Andric 
58485ffd83dbSDimitry Andric   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
58490b57cec5SDimitry Andric 
58500b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
58510b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
58520b57cec5SDimitry Andric 
58530b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
58540b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
58550b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5856e8d8bef9SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority(), true);
5857c9157d92SDimitry Andric   if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
5858c9157d92SDimitry Andric     getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
58590b57cec5SDimitry Andric }
58600b57cec5SDimitry Andric 
EmitAliasDefinition(GlobalDecl GD)58610b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
58620b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
58630b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
58640b57cec5SDimitry Andric   assert(AA && "Not an alias?");
58650b57cec5SDimitry Andric 
58660b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
58670b57cec5SDimitry Andric 
58680b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
58690b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
58700b57cec5SDimitry Andric     return;
58710b57cec5SDimitry Andric   }
58720b57cec5SDimitry Andric 
58730b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
58740b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
58750b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
58760b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
58770b57cec5SDimitry Andric     return;
58780b57cec5SDimitry Andric 
58790b57cec5SDimitry Andric   Aliases.push_back(GD);
58800b57cec5SDimitry Andric 
58810b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
58820b57cec5SDimitry Andric 
58830b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
58840b57cec5SDimitry Andric   // if a deferred decl.
58850b57cec5SDimitry Andric   llvm::Constant *Aliasee;
58860b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
58870b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
58880b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
58890b57cec5SDimitry Andric                                       /*ForVTable=*/false);
58900b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
58910b57cec5SDimitry Andric   } else {
5892349cc55cSDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
58930b57cec5SDimitry Andric                                     /*D=*/nullptr);
5894e8d8bef9SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5895271697daSDimitry Andric       LT = getLLVMLinkageVarDefinition(VD);
5896e8d8bef9SDimitry Andric     else
5897e8d8bef9SDimitry Andric       LT = getFunctionLinkage(GD);
58980b57cec5SDimitry Andric   }
58990b57cec5SDimitry Andric 
59000b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
59015ffd83dbSDimitry Andric   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
59020b57cec5SDimitry Andric   auto *GA =
59035ffd83dbSDimitry Andric       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
59040b57cec5SDimitry Andric 
59050b57cec5SDimitry Andric   if (Entry) {
59060b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
59070b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
59080b57cec5SDimitry Andric       return;
59090b57cec5SDimitry Andric     }
59100b57cec5SDimitry Andric 
59110b57cec5SDimitry Andric     assert(Entry->isDeclaration());
59120b57cec5SDimitry Andric 
59130b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
59140b57cec5SDimitry Andric     // by the alias, as in:
59150b57cec5SDimitry Andric     //   extern int test6();
59160b57cec5SDimitry Andric     //   ...
59170b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
59180b57cec5SDimitry Andric     //
59190b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
59200b57cec5SDimitry Andric     GA->takeName(Entry);
59210b57cec5SDimitry Andric 
5922c9157d92SDimitry Andric     Entry->replaceAllUsesWith(GA);
59230b57cec5SDimitry Andric     Entry->eraseFromParent();
59240b57cec5SDimitry Andric   } else {
59250b57cec5SDimitry Andric     GA->setName(MangledName);
59260b57cec5SDimitry Andric   }
59270b57cec5SDimitry Andric 
59280b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
59290b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
59300b57cec5SDimitry Andric   // variable/function.
59310b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
59320b57cec5SDimitry Andric       D->isWeakImported()) {
59330b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
59340b57cec5SDimitry Andric   }
59350b57cec5SDimitry Andric 
59360b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
59370b57cec5SDimitry Andric     if (VD->getTLSKind())
59380b57cec5SDimitry Andric       setTLSMode(GA, *VD);
59390b57cec5SDimitry Andric 
59400b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
594181ad6265SDimitry Andric 
594281ad6265SDimitry Andric   // Emit global alias debug information.
594381ad6265SDimitry Andric   if (isa<VarDecl>(D))
594481ad6265SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5945bdd1243dSDimitry Andric       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
59460b57cec5SDimitry Andric }
59470b57cec5SDimitry Andric 
emitIFuncDefinition(GlobalDecl GD)59480b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
59490b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
59500b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
59510b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
59520b57cec5SDimitry Andric 
59530b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
59540b57cec5SDimitry Andric 
59550b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
59560b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
59570b57cec5SDimitry Andric     return;
59580b57cec5SDimitry Andric   }
59590b57cec5SDimitry Andric 
59600b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
59610b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
59620b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
59630b57cec5SDimitry Andric     GlobalDecl OtherGD;
59640b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
59650b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
59660b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
59670b57cec5SDimitry Andric           << MangledName;
59680b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
59690b57cec5SDimitry Andric                    diag::note_previous_definition);
59700b57cec5SDimitry Andric     }
59710b57cec5SDimitry Andric     return;
59720b57cec5SDimitry Andric   }
59730b57cec5SDimitry Andric 
59740b57cec5SDimitry Andric   Aliases.push_back(GD);
59750b57cec5SDimitry Andric 
59760b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5977349cc55cSDimitry Andric   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
59780b57cec5SDimitry Andric   llvm::Constant *Resolver =
5979349cc55cSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
59800b57cec5SDimitry Andric                               /*ForVTable=*/false);
59810b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
59820b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
59830b57cec5SDimitry Andric                                 "", Resolver, &getModule());
59840b57cec5SDimitry Andric   if (Entry) {
59850b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
59860b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
59870b57cec5SDimitry Andric       return;
59880b57cec5SDimitry Andric     }
59890b57cec5SDimitry Andric     assert(Entry->isDeclaration());
59900b57cec5SDimitry Andric 
59910b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
59920b57cec5SDimitry Andric     // by the ifunc, as in:
59930b57cec5SDimitry Andric     //   extern int test();
59940b57cec5SDimitry Andric     //   ...
59950b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
59960b57cec5SDimitry Andric     //
59970b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
59980b57cec5SDimitry Andric     GIF->takeName(Entry);
59990b57cec5SDimitry Andric 
6000c9157d92SDimitry Andric     Entry->replaceAllUsesWith(GIF);
60010b57cec5SDimitry Andric     Entry->eraseFromParent();
60020b57cec5SDimitry Andric   } else
60030b57cec5SDimitry Andric     GIF->setName(MangledName);
6004c9157d92SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(Resolver)) {
6005c9157d92SDimitry Andric     F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
6006c9157d92SDimitry Andric   }
60070b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
60080b57cec5SDimitry Andric }
60090b57cec5SDimitry Andric 
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)60100b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
60110b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
60120b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
60130b57cec5SDimitry Andric                                          Tys);
60140b57cec5SDimitry Andric }
60150b57cec5SDimitry Andric 
60160b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)60170b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
60180b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
60190b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
60200b57cec5SDimitry Andric   StringRef String = Literal->getString();
60210b57cec5SDimitry Andric   unsigned NumBytes = String.size();
60220b57cec5SDimitry Andric 
60230b57cec5SDimitry Andric   // Check for simple case.
60240b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
60250b57cec5SDimitry Andric     StringLength = NumBytes;
60260b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
60270b57cec5SDimitry Andric   }
60280b57cec5SDimitry Andric 
60290b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
60300b57cec5SDimitry Andric   IsUTF16 = true;
60310b57cec5SDimitry Andric 
60320b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
60330b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
60340b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
60350b57cec5SDimitry Andric 
60360b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
60370b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
60380b57cec5SDimitry Andric 
60390b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
60400b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
60410b57cec5SDimitry Andric 
60420b57cec5SDimitry Andric   // Add an explicit null.
60430b57cec5SDimitry Andric   *ToPtr = 0;
60440b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
60450b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
60460b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
60470b57cec5SDimitry Andric                          nullptr)).first;
60480b57cec5SDimitry Andric }
60490b57cec5SDimitry Andric 
60500b57cec5SDimitry Andric ConstantAddress
GetAddrOfConstantCFString(const StringLiteral * Literal)60510b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
60520b57cec5SDimitry Andric   unsigned StringLength = 0;
60530b57cec5SDimitry Andric   bool isUTF16 = false;
60540b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
60550b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
60560b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
60570b57cec5SDimitry Andric                                StringLength);
60580b57cec5SDimitry Andric 
60590b57cec5SDimitry Andric   if (auto *C = Entry.second)
60600eae32dcSDimitry Andric     return ConstantAddress(
60610eae32dcSDimitry Andric         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
60620b57cec5SDimitry Andric 
60630b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
60640b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
60650b57cec5SDimitry Andric 
60660b57cec5SDimitry Andric   const ASTContext &Context = getContext();
60670b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
60680b57cec5SDimitry Andric 
60690b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
60700b57cec5SDimitry Andric   const bool IsSwiftABI =
60710b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
60720b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
60730b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
60740b57cec5SDimitry Andric 
60750b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
60760b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
60770b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
60780b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
60790b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
60800b57cec5SDimitry Andric 
60810b57cec5SDimitry Andric     switch (CFRuntime) {
60820b57cec5SDimitry Andric     default: break;
6083bdd1243dSDimitry Andric     case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
60840b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
60850b57cec5SDimitry Andric       CFConstantStringClassName =
60860b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
60870b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
60880b57cec5SDimitry Andric       Ty = IntPtrTy;
60890b57cec5SDimitry Andric       break;
60900b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
60910b57cec5SDimitry Andric       CFConstantStringClassName =
60920b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
60930b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
60940b57cec5SDimitry Andric       Ty = IntPtrTy;
60950b57cec5SDimitry Andric       break;
60960b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
60970b57cec5SDimitry Andric       CFConstantStringClassName =
60980b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
60990b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
61000b57cec5SDimitry Andric       Ty = IntPtrTy;
61010b57cec5SDimitry Andric       break;
61020b57cec5SDimitry Andric     }
61030b57cec5SDimitry Andric 
61040b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
61050b57cec5SDimitry Andric 
61060b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
61070b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
61080b57cec5SDimitry Andric 
61090b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
61100b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
61110b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
61120b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
61130b57cec5SDimitry Andric 
61140b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
6115fe6060f1SDimitry Andric         for (const auto *Result : DC->lookup(&II))
61160b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
61170b57cec5SDimitry Andric             break;
61180b57cec5SDimitry Andric 
61190b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
61200b57cec5SDimitry Andric           if (!VD)
61210b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
61220b57cec5SDimitry Andric         } else {
61230b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
61240b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
61250b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
61260b57cec5SDimitry Andric           else
61270b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
61280b57cec5SDimitry Andric         }
61290b57cec5SDimitry Andric 
61300b57cec5SDimitry Andric         setDSOLocal(GV);
61310b57cec5SDimitry Andric       }
61320b57cec5SDimitry Andric     }
61330b57cec5SDimitry Andric 
61340b57cec5SDimitry Andric     // Decay array -> ptr
61350b57cec5SDimitry Andric     CFConstantStringClassRef =
61360b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
61370b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
61380b57cec5SDimitry Andric   }
61390b57cec5SDimitry Andric 
61400b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
61410b57cec5SDimitry Andric 
61420b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
61430b57cec5SDimitry Andric 
61440b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
61450b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
61460b57cec5SDimitry Andric 
61470b57cec5SDimitry Andric   // Class pointer.
614881ad6265SDimitry Andric   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
61490b57cec5SDimitry Andric 
61500b57cec5SDimitry Andric   // Flags.
61510b57cec5SDimitry Andric   if (IsSwiftABI) {
61520b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
61530b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
61540b57cec5SDimitry Andric   } else {
61550b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
61560b57cec5SDimitry Andric   }
61570b57cec5SDimitry Andric 
61580b57cec5SDimitry Andric   // String pointer.
61590b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
61600b57cec5SDimitry Andric   if (isUTF16) {
6161bdd1243dSDimitry Andric     auto Arr = llvm::ArrayRef(
61620b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
61630b57cec5SDimitry Andric         Entry.first().size() / 2);
61640b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
61650b57cec5SDimitry Andric   } else {
61660b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
61670b57cec5SDimitry Andric   }
61680b57cec5SDimitry Andric 
61690b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
6170c9157d92SDimitry Andric   // CFStrings writable.
61710b57cec5SDimitry Andric   auto *GV =
61720b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
61730b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
61740b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
61750b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
61760b57cec5SDimitry Andric   // of the string is via this class initializer.
61770b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
61780b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
6179a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
61800b57cec5SDimitry Andric 
61810b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
61820b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
61830b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
61840b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
61850b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
61860b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
61870b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
61880b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
61890b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
61900b57cec5SDimitry Andric     GV->setSection(".rodata");
61910b57cec5SDimitry Andric 
61920b57cec5SDimitry Andric   // String.
61930b57cec5SDimitry Andric   llvm::Constant *Str =
61940b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
61950b57cec5SDimitry Andric 
61960b57cec5SDimitry Andric   Fields.add(Str);
61970b57cec5SDimitry Andric 
61980b57cec5SDimitry Andric   // String length.
61990b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
62000b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
62010b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
62020b57cec5SDimitry Andric   if (IsSwiftABI) {
62030b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
62040b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
62050b57cec5SDimitry Andric       LengthTy = Int32Ty;
62060b57cec5SDimitry Andric     else
62070b57cec5SDimitry Andric       LengthTy = IntPtrTy;
62080b57cec5SDimitry Andric   }
62090b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
62100b57cec5SDimitry Andric 
6211a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6212a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
6213a7dea167SDimitry Andric   CharUnits Alignment =
6214a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
62150b57cec5SDimitry Andric 
62160b57cec5SDimitry Andric   // The struct.
62170b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
62180b57cec5SDimitry Andric                                     /*isConstant=*/false,
62190b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
62200b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
62210b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
62220b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
62230b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
622481ad6265SDimitry Andric   case llvm::Triple::DXContainer:
6225e8d8bef9SDimitry Andric   case llvm::Triple::GOFF:
622681ad6265SDimitry Andric   case llvm::Triple::SPIRV:
62270b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
622881ad6265SDimitry Andric     llvm_unreachable("unimplemented");
62290b57cec5SDimitry Andric   case llvm::Triple::COFF:
62300b57cec5SDimitry Andric   case llvm::Triple::ELF:
62310b57cec5SDimitry Andric   case llvm::Triple::Wasm:
62320b57cec5SDimitry Andric     GV->setSection("cfstring");
62330b57cec5SDimitry Andric     break;
62340b57cec5SDimitry Andric   case llvm::Triple::MachO:
62350b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
62360b57cec5SDimitry Andric     break;
62370b57cec5SDimitry Andric   }
62380b57cec5SDimitry Andric   Entry.second = GV;
62390b57cec5SDimitry Andric 
62400eae32dcSDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
62410b57cec5SDimitry Andric }
62420b57cec5SDimitry Andric 
getExpressionLocationsEnabled() const62430b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
62440b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
62450b57cec5SDimitry Andric }
62460b57cec5SDimitry Andric 
getObjCFastEnumerationStateType()62470b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
62480b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
62490b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
62500b57cec5SDimitry Andric     D->startDefinition();
62510b57cec5SDimitry Andric 
62520b57cec5SDimitry Andric     QualType FieldTypes[] = {
6253c9157d92SDimitry Andric         Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
62540b57cec5SDimitry Andric         Context.getPointerType(Context.UnsignedLongTy),
6255c9157d92SDimitry Andric         Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6256c9157d92SDimitry Andric                                      nullptr, ArraySizeModifier::Normal, 0)};
62570b57cec5SDimitry Andric 
62580b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
62590b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
62600b57cec5SDimitry Andric                                            D,
62610b57cec5SDimitry Andric                                            SourceLocation(),
62620b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
62630b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
62640b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
62650b57cec5SDimitry Andric                                            /*Mutable=*/false,
62660b57cec5SDimitry Andric                                            ICIS_NoInit);
62670b57cec5SDimitry Andric       Field->setAccess(AS_public);
62680b57cec5SDimitry Andric       D->addDecl(Field);
62690b57cec5SDimitry Andric     }
62700b57cec5SDimitry Andric 
62710b57cec5SDimitry Andric     D->completeDefinition();
62720b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
62730b57cec5SDimitry Andric   }
62740b57cec5SDimitry Andric 
62750b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
62760b57cec5SDimitry Andric }
62770b57cec5SDimitry Andric 
62780b57cec5SDimitry Andric llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)62790b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
62800b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
62810b57cec5SDimitry Andric 
62820b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
62830b57cec5SDimitry Andric   // as an inline array.
62840b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
62850b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
62860b57cec5SDimitry Andric 
62870b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
62880b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
6289fe013be4SDimitry Andric     assert(CAT && "String literal not of constant array type!");
62900b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
62910b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
62920b57cec5SDimitry Andric   }
62930b57cec5SDimitry Andric 
62940b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
62950b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
62960b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
62970b57cec5SDimitry Andric 
62980b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
62990b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
63000b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
63010b57cec5SDimitry Andric     Elements.reserve(NumElements);
63020b57cec5SDimitry Andric 
63030b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
63040b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
63050b57cec5SDimitry Andric     Elements.resize(NumElements);
63060b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
63070b57cec5SDimitry Andric   }
63080b57cec5SDimitry Andric 
63090b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
63100b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
63110b57cec5SDimitry Andric   Elements.reserve(NumElements);
63120b57cec5SDimitry Andric 
63130b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
63140b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
63150b57cec5SDimitry Andric   Elements.resize(NumElements);
63160b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
63170b57cec5SDimitry Andric }
63180b57cec5SDimitry Andric 
63190b57cec5SDimitry Andric static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,CharUnits Alignment)63200b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
63210b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
63220b57cec5SDimitry Andric                       CharUnits Alignment) {
63230b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6324fe6060f1SDimitry Andric       CGM.GetGlobalConstantAddressSpace());
63250b57cec5SDimitry Andric 
63260b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
63270b57cec5SDimitry Andric   // Create a global variable for this string
63280b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
63290b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
63300b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6331a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
63320b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
63330b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
63340b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
63350b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
63360b57cec5SDimitry Andric   }
63370b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
63380b57cec5SDimitry Andric 
63390b57cec5SDimitry Andric   return GV;
63400b57cec5SDimitry Andric }
63410b57cec5SDimitry Andric 
63420b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
63430b57cec5SDimitry Andric /// constant array for the given string literal.
63440b57cec5SDimitry Andric ConstantAddress
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)63450b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
63460b57cec5SDimitry Andric                                                   StringRef Name) {
63470b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
63480b57cec5SDimitry Andric 
63490b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
63500b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
63510b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
63520b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
63530b57cec5SDimitry Andric     if (auto GV = *Entry) {
6354349cc55cSDimitry Andric       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6355a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
63560b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
63570eae32dcSDimitry Andric                              GV->getValueType(), Alignment);
63580b57cec5SDimitry Andric     }
63590b57cec5SDimitry Andric   }
63600b57cec5SDimitry Andric 
63610b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
63620b57cec5SDimitry Andric   StringRef GlobalVariableName;
63630b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
63640b57cec5SDimitry Andric 
63650b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
63660b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
63670b57cec5SDimitry Andric   // affect strings in another.
63680b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
63690b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
63700b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
63710b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
63720b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
63730b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
63740b57cec5SDimitry Andric   } else {
63750b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
63760b57cec5SDimitry Andric     GlobalVariableName = Name;
63770b57cec5SDimitry Andric   }
63780b57cec5SDimitry Andric 
63790b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
638081ad6265SDimitry Andric 
638181ad6265SDimitry Andric   CGDebugInfo *DI = getModuleDebugInfo();
638281ad6265SDimitry Andric   if (DI && getCodeGenOpts().hasReducedDebugInfo())
638381ad6265SDimitry Andric     DI->AddStringLiteralDebugInfo(GV, S);
638481ad6265SDimitry Andric 
63850b57cec5SDimitry Andric   if (Entry)
63860b57cec5SDimitry Andric     *Entry = GV;
63870b57cec5SDimitry Andric 
638881ad6265SDimitry Andric   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
63890b57cec5SDimitry Andric 
63900b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
63910eae32dcSDimitry Andric                          GV->getValueType(), Alignment);
63920b57cec5SDimitry Andric }
63930b57cec5SDimitry Andric 
63940b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
63950b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
63960b57cec5SDimitry Andric ConstantAddress
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)63970b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
63980b57cec5SDimitry Andric   std::string Str;
63990b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
64000b57cec5SDimitry Andric 
64010b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
64020b57cec5SDimitry Andric }
64030b57cec5SDimitry Andric 
64040b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
64050b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
64060b57cec5SDimitry Andric /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName)64070b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
64080b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
64090b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
64100b57cec5SDimitry Andric   CharUnits Alignment =
64110b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
64120b57cec5SDimitry Andric 
64130b57cec5SDimitry Andric   llvm::Constant *C =
64140b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
64150b57cec5SDimitry Andric 
64160b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
64170b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
64180b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
64190b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
64200b57cec5SDimitry Andric     if (auto GV = *Entry) {
6421349cc55cSDimitry Andric       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6422a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
64230b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
64240eae32dcSDimitry Andric                              GV->getValueType(), Alignment);
64250b57cec5SDimitry Andric     }
64260b57cec5SDimitry Andric   }
64270b57cec5SDimitry Andric 
64280b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
64290b57cec5SDimitry Andric   if (!GlobalName)
64300b57cec5SDimitry Andric     GlobalName = ".str";
64310b57cec5SDimitry Andric   // Create a global variable for this.
64320b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
64330b57cec5SDimitry Andric                                   GlobalName, Alignment);
64340b57cec5SDimitry Andric   if (Entry)
64350b57cec5SDimitry Andric     *Entry = GV;
64360b57cec5SDimitry Andric 
64370b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
64380eae32dcSDimitry Andric                          GV->getValueType(), Alignment);
64390b57cec5SDimitry Andric }
64400b57cec5SDimitry Andric 
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)64410b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
64420b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
64430b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
64440b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
64450b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
64460b57cec5SDimitry Andric 
64470b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
64480b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
64490b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
6450480093f4SDimitry Andric   if (Init == E->getSubExpr())
64510b57cec5SDimitry Andric     MaterializedType = E->getType();
64520b57cec5SDimitry Andric 
64530b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
64540b57cec5SDimitry Andric 
6455fe6060f1SDimitry Andric   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6456fe6060f1SDimitry Andric   if (!InsertResult.second) {
6457fe6060f1SDimitry Andric     // We've seen this before: either we already created it or we're in the
6458fe6060f1SDimitry Andric     // process of doing so.
6459fe6060f1SDimitry Andric     if (!InsertResult.first->second) {
6460fe6060f1SDimitry Andric       // We recursively re-entered this function, probably during emission of
6461fe6060f1SDimitry Andric       // the initializer. Create a placeholder. We'll clean this up in the
6462fe6060f1SDimitry Andric       // outer call, at the end of this function.
6463fe6060f1SDimitry Andric       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6464fe6060f1SDimitry Andric       InsertResult.first->second = new llvm::GlobalVariable(
6465fe6060f1SDimitry Andric           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6466fe6060f1SDimitry Andric           nullptr);
6467fe6060f1SDimitry Andric     }
646881ad6265SDimitry Andric     return ConstantAddress(InsertResult.first->second,
646981ad6265SDimitry Andric                            llvm::cast<llvm::GlobalVariable>(
647081ad6265SDimitry Andric                                InsertResult.first->second->stripPointerCasts())
647181ad6265SDimitry Andric                                ->getValueType(),
647281ad6265SDimitry Andric                            Align);
6473fe6060f1SDimitry Andric   }
64740b57cec5SDimitry Andric 
64750b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
64760b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
64770b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
64780b57cec5SDimitry Andric   SmallString<256> Name;
64790b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
64800b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
64810b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
64820b57cec5SDimitry Andric 
64830b57cec5SDimitry Andric   APValue *Value = nullptr;
6484c9157d92SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
6485a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
6486a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
6487a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
6488a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
6489a7dea167SDimitry Andric     // expression modifies the temporary.
6490480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
64910b57cec5SDimitry Andric   }
64920b57cec5SDimitry Andric 
64930b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
64940b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
64950b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
64960b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
64970b57cec5SDimitry Andric     Value = &EvalResult.Val;
64980b57cec5SDimitry Andric 
6499c9157d92SDimitry Andric   LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
65000b57cec5SDimitry Andric 
6501bdd1243dSDimitry Andric   std::optional<ConstantEmitter> emitter;
65020b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
65030b57cec5SDimitry Andric   bool Constant = false;
65040b57cec5SDimitry Andric   llvm::Type *Type;
65050b57cec5SDimitry Andric   if (Value) {
65060b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
65070b57cec5SDimitry Andric     emitter.emplace(*this);
65080b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
65090b57cec5SDimitry Andric                                                MaterializedType);
6510c9157d92SDimitry Andric     Constant =
6511c9157d92SDimitry Andric         MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
6512fe013be4SDimitry Andric                                            /*ExcludeDtor*/ false);
65130b57cec5SDimitry Andric     Type = InitialValue->getType();
65140b57cec5SDimitry Andric   } else {
65150b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
65160b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
65170b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
65180b57cec5SDimitry Andric   }
65190b57cec5SDimitry Andric 
65200b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
6521271697daSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
65220b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
65230b57cec5SDimitry Andric     const VarDecl *InitVD;
65240b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
65250b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
65260b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
65270b57cec5SDimitry Andric       // class can be defined in multiple translation units.
65280b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
65290b57cec5SDimitry Andric     } else {
65300b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
65310b57cec5SDimitry Andric       // VarDecl has external linkage.
65320b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
65330b57cec5SDimitry Andric     }
65340b57cec5SDimitry Andric   }
65350b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
65360b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
65370b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
65380b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
65390b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
6540bdd1243dSDimitry Andric   // Don't assign dllimport or dllexport to local linkage globals.
6541bdd1243dSDimitry Andric   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
65420b57cec5SDimitry Andric     setGVProperties(GV, VD);
654381ad6265SDimitry Andric     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
654481ad6265SDimitry Andric       // The reference temporary should never be dllexport.
654581ad6265SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6546bdd1243dSDimitry Andric   }
6547a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
65480b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
65490b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
65500b57cec5SDimitry Andric   if (VD->getTLSKind())
65510b57cec5SDimitry Andric     setTLSMode(GV, *VD);
65520b57cec5SDimitry Andric   llvm::Constant *CV = GV;
65530b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
65540b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
65550b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
6556c9157d92SDimitry Andric         llvm::PointerType::get(
6557c9157d92SDimitry Andric             getLLVMContext(),
65580b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
6559fe6060f1SDimitry Andric 
6560fe6060f1SDimitry Andric   // Update the map with the new temporary. If we created a placeholder above,
6561fe6060f1SDimitry Andric   // replace it with the new global now.
6562fe6060f1SDimitry Andric   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6563fe6060f1SDimitry Andric   if (Entry) {
6564c9157d92SDimitry Andric     Entry->replaceAllUsesWith(CV);
6565fe6060f1SDimitry Andric     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6566fe6060f1SDimitry Andric   }
6567fe6060f1SDimitry Andric   Entry = CV;
6568fe6060f1SDimitry Andric 
65690eae32dcSDimitry Andric   return ConstantAddress(CV, Type, Align);
65700b57cec5SDimitry Andric }
65710b57cec5SDimitry Andric 
65720b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
65730b57cec5SDimitry Andric /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)65740b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
65750b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
65760b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
65770b57cec5SDimitry Andric     // Dynamic is just for type-checking.
65780b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
65790b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
65800b57cec5SDimitry Andric 
65810b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
65820b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
65830b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
65840b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
65850b57cec5SDimitry Andric       // this implementation.
6586480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
6587480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
65880b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
65890b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
6590480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
6591480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
65920b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
65930b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
65940b57cec5SDimitry Andric     }
65950b57cec5SDimitry Andric   }
65960b57cec5SDimitry Andric }
65970b57cec5SDimitry Andric 
needsDestructMethod(ObjCImplementationDecl * impl)65980b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
65990b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
66000b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
66010b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
66020b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
66030b57cec5SDimitry Andric       return true;
66040b57cec5SDimitry Andric 
66050b57cec5SDimitry Andric   return false;
66060b57cec5SDimitry Andric }
66070b57cec5SDimitry Andric 
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)66080b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
66090b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
66100b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
66110b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
66120b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
66130b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
66140b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
66150b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
66160b57cec5SDimitry Andric       return false;
66170b57cec5SDimitry Andric   }
66180b57cec5SDimitry Andric   return true;
66190b57cec5SDimitry Andric }
66200b57cec5SDimitry Andric 
66210b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
66220b57cec5SDimitry Andric /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)66230b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
66240b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
66250b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
66260b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
66270b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6628480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6629480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6630480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
66310b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
6632480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6633480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
6634c9157d92SDimitry Andric         /*isDefined=*/false, ObjCImplementationControl::Required);
66350b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
66360b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
66370b57cec5SDimitry Andric     D->setHasDestructors(true);
66380b57cec5SDimitry Andric   }
66390b57cec5SDimitry Andric 
66400b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
66410b57cec5SDimitry Andric   // a .cxx_construct.
66420b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
66430b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
66440b57cec5SDimitry Andric     return;
66450b57cec5SDimitry Andric 
66460b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
66470b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
66480b57cec5SDimitry Andric   // The constructor returns 'self'.
6649480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6650480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6651480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
66520b57cec5SDimitry Andric       /*isVariadic=*/false,
6653480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
66540b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
6655c9157d92SDimitry Andric       /*isDefined=*/false, ObjCImplementationControl::Required);
66560b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
66570b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
66580b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
66590b57cec5SDimitry Andric }
66600b57cec5SDimitry Andric 
66610b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)66620b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6663c9157d92SDimitry Andric   if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
6664c9157d92SDimitry Andric       LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) {
66650b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
66660b57cec5SDimitry Andric     return;
66670b57cec5SDimitry Andric   }
66680b57cec5SDimitry Andric 
66690b57cec5SDimitry Andric   EmitDeclContext(LSD);
66700b57cec5SDimitry Andric }
66710b57cec5SDimitry Andric 
EmitTopLevelStmt(const TopLevelStmtDecl * D)6672bdd1243dSDimitry Andric void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6673fe013be4SDimitry Andric   // Device code should not be at top level.
6674fe013be4SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6675fe013be4SDimitry Andric     return;
6676fe013be4SDimitry Andric 
6677bdd1243dSDimitry Andric   std::unique_ptr<CodeGenFunction> &CurCGF =
6678bdd1243dSDimitry Andric       GlobalTopLevelStmtBlockInFlight.first;
6679bdd1243dSDimitry Andric 
6680bdd1243dSDimitry Andric   // We emitted a top-level stmt but after it there is initialization.
6681bdd1243dSDimitry Andric   // Stop squashing the top-level stmts into a single function.
6682bdd1243dSDimitry Andric   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6683bdd1243dSDimitry Andric     CurCGF->FinishFunction(D->getEndLoc());
6684bdd1243dSDimitry Andric     CurCGF = nullptr;
6685bdd1243dSDimitry Andric   }
6686bdd1243dSDimitry Andric 
6687bdd1243dSDimitry Andric   if (!CurCGF) {
6688bdd1243dSDimitry Andric     // void __stmts__N(void)
6689bdd1243dSDimitry Andric     // FIXME: Ask the ABI name mangler to pick a name.
6690bdd1243dSDimitry Andric     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6691bdd1243dSDimitry Andric     FunctionArgList Args;
6692bdd1243dSDimitry Andric     QualType RetTy = getContext().VoidTy;
6693bdd1243dSDimitry Andric     const CGFunctionInfo &FnInfo =
6694bdd1243dSDimitry Andric         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6695bdd1243dSDimitry Andric     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6696bdd1243dSDimitry Andric     llvm::Function *Fn = llvm::Function::Create(
6697bdd1243dSDimitry Andric         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6698bdd1243dSDimitry Andric 
6699bdd1243dSDimitry Andric     CurCGF.reset(new CodeGenFunction(*this));
6700bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight.second = D;
6701bdd1243dSDimitry Andric     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6702bdd1243dSDimitry Andric                           D->getBeginLoc(), D->getBeginLoc());
6703bdd1243dSDimitry Andric     CXXGlobalInits.push_back(Fn);
6704bdd1243dSDimitry Andric   }
6705bdd1243dSDimitry Andric 
6706bdd1243dSDimitry Andric   CurCGF->EmitStmt(D->getStmt());
6707bdd1243dSDimitry Andric }
6708bdd1243dSDimitry Andric 
EmitDeclContext(const DeclContext * DC)67090b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
67100b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
67110b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
67120b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
67130b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
67140b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
67150b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
67160b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
67170b57cec5SDimitry Andric       for (auto *M : OID->methods())
67180b57cec5SDimitry Andric         EmitTopLevelDecl(M);
67190b57cec5SDimitry Andric     }
67200b57cec5SDimitry Andric 
67210b57cec5SDimitry Andric     EmitTopLevelDecl(I);
67220b57cec5SDimitry Andric   }
67230b57cec5SDimitry Andric }
67240b57cec5SDimitry Andric 
67250b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)67260b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
67270b57cec5SDimitry Andric   // Ignore dependent declarations.
67280b57cec5SDimitry Andric   if (D->isTemplated())
67290b57cec5SDimitry Andric     return;
67300b57cec5SDimitry Andric 
67315ffd83dbSDimitry Andric   // Consteval function shouldn't be emitted.
6732fe013be4SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
67335ffd83dbSDimitry Andric     return;
67345ffd83dbSDimitry Andric 
67350b57cec5SDimitry Andric   switch (D->getKind()) {
67360b57cec5SDimitry Andric   case Decl::CXXConversion:
67370b57cec5SDimitry Andric   case Decl::CXXMethod:
67380b57cec5SDimitry Andric   case Decl::Function:
67390b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
67400b57cec5SDimitry Andric     // Always provide some coverage mapping
67410b57cec5SDimitry Andric     // even for the functions that aren't emitted.
67420b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
67430b57cec5SDimitry Andric     break;
67440b57cec5SDimitry Andric 
67450b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
67460b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
67470b57cec5SDimitry Andric     break;
67480b57cec5SDimitry Andric 
67490b57cec5SDimitry Andric   case Decl::Var:
67500b57cec5SDimitry Andric   case Decl::Decomposition:
67510b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
67520b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
67530b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
67540b57cec5SDimitry Andric       for (auto *B : DD->bindings())
67550b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
67560b57cec5SDimitry Andric           EmitGlobal(HD);
67570b57cec5SDimitry Andric     break;
67580b57cec5SDimitry Andric 
67590b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
67600b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
67610b57cec5SDimitry Andric   case Decl::IndirectField:
67620b57cec5SDimitry Andric     break;
67630b57cec5SDimitry Andric 
67640b57cec5SDimitry Andric   // C++ Decls
67650b57cec5SDimitry Andric   case Decl::Namespace:
67660b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
67670b57cec5SDimitry Andric     break;
67680b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
67690b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
67705ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
67715ffd83dbSDimitry Andric       if (Spec->getSpecializationKind() ==
67725ffd83dbSDimitry Andric               TSK_ExplicitInstantiationDefinition &&
67730b57cec5SDimitry Andric           Spec->hasDefinition())
67745ffd83dbSDimitry Andric         DI->completeTemplateDefinition(*Spec);
6775bdd1243dSDimitry Andric   } [[fallthrough]];
6776e8d8bef9SDimitry Andric   case Decl::CXXRecord: {
6777e8d8bef9SDimitry Andric     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6778e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6779e8d8bef9SDimitry Andric       if (CRD->hasDefinition())
6780e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
67810b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
67820b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6783e8d8bef9SDimitry Andric           DI->completeUnusedClass(*CRD);
6784e8d8bef9SDimitry Andric     }
67850b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
6786e8d8bef9SDimitry Andric     for (auto *I : CRD->decls())
67870b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
67880b57cec5SDimitry Andric         EmitTopLevelDecl(I);
67890b57cec5SDimitry Andric     break;
6790e8d8bef9SDimitry Andric   }
67910b57cec5SDimitry Andric     // No code generation needed.
67920b57cec5SDimitry Andric   case Decl::UsingShadow:
67930b57cec5SDimitry Andric   case Decl::ClassTemplate:
67940b57cec5SDimitry Andric   case Decl::VarTemplate:
67950b57cec5SDimitry Andric   case Decl::Concept:
67960b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
67970b57cec5SDimitry Andric   case Decl::FunctionTemplate:
67980b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
67990b57cec5SDimitry Andric   case Decl::Block:
68000b57cec5SDimitry Andric   case Decl::Empty:
68010b57cec5SDimitry Andric   case Decl::Binding:
68020b57cec5SDimitry Andric     break;
68030b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
68040b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
68050b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
68065ffd83dbSDimitry Andric     break;
6807fe6060f1SDimitry Andric   case Decl::UsingEnum: // using enum X; [C++]
6808fe6060f1SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6809fe6060f1SDimitry Andric       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6810fe6060f1SDimitry Andric     break;
68110b57cec5SDimitry Andric   case Decl::NamespaceAlias:
68120b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
68130b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
68145ffd83dbSDimitry Andric     break;
68150b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
68160b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
68170b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
68185ffd83dbSDimitry Andric     break;
68190b57cec5SDimitry Andric   case Decl::CXXConstructor:
68200b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
68210b57cec5SDimitry Andric     break;
68220b57cec5SDimitry Andric   case Decl::CXXDestructor:
68230b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
68240b57cec5SDimitry Andric     break;
68250b57cec5SDimitry Andric 
68260b57cec5SDimitry Andric   case Decl::StaticAssert:
68270b57cec5SDimitry Andric     // Nothing to do.
68280b57cec5SDimitry Andric     break;
68290b57cec5SDimitry Andric 
68300b57cec5SDimitry Andric   // Objective-C Decls
68310b57cec5SDimitry Andric 
68320b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
68330b57cec5SDimitry Andric   case Decl::ObjCInterface:
68340b57cec5SDimitry Andric   case Decl::ObjCCategory:
68350b57cec5SDimitry Andric     break;
68360b57cec5SDimitry Andric 
68370b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
68380b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
68390b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
68400b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
68410b57cec5SDimitry Andric     break;
68420b57cec5SDimitry Andric   }
68430b57cec5SDimitry Andric 
68440b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
68450b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
68460b57cec5SDimitry Andric     // can ignore them here.
68470b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
68480b57cec5SDimitry Andric     break;
68490b57cec5SDimitry Andric 
68500b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
68510b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
68520b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
68530b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
68540b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
68550b57cec5SDimitry Andric     // Emit global variable debug information.
68560b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6857480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
68580b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
68590b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
68600b57cec5SDimitry Andric     break;
68610b57cec5SDimitry Andric   }
68620b57cec5SDimitry Andric   case Decl::ObjCMethod: {
68630b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
68640b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
68650b57cec5SDimitry Andric     if (OMD->getBody())
68660b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
68670b57cec5SDimitry Andric     break;
68680b57cec5SDimitry Andric   }
68690b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
68700b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
68710b57cec5SDimitry Andric     break;
68720b57cec5SDimitry Andric 
68730b57cec5SDimitry Andric   case Decl::PragmaComment: {
68740b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
68750b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
68760b57cec5SDimitry Andric     case PCK_Unknown:
68770b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
68780b57cec5SDimitry Andric     case PCK_Linker:
68790b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
68800b57cec5SDimitry Andric       break;
68810b57cec5SDimitry Andric     case PCK_Lib:
68820b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
68830b57cec5SDimitry Andric       break;
68840b57cec5SDimitry Andric     case PCK_Compiler:
68850b57cec5SDimitry Andric     case PCK_ExeStr:
68860b57cec5SDimitry Andric     case PCK_User:
68870b57cec5SDimitry Andric       break; // We ignore all of these.
68880b57cec5SDimitry Andric     }
68890b57cec5SDimitry Andric     break;
68900b57cec5SDimitry Andric   }
68910b57cec5SDimitry Andric 
68920b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
68930b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
68940b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
68950b57cec5SDimitry Andric     break;
68960b57cec5SDimitry Andric   }
68970b57cec5SDimitry Andric 
68980b57cec5SDimitry Andric   case Decl::LinkageSpec:
68990b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
69000b57cec5SDimitry Andric     break;
69010b57cec5SDimitry Andric 
69020b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
69030b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
69040b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
69050b57cec5SDimitry Andric       break;
69060b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
6907fe013be4SDimitry Andric     if (LangOpts.OpenMPIsTargetDevice)
69080b57cec5SDimitry Andric       break;
6909fe6060f1SDimitry Andric     // File-scope asm is ignored during device-side SYCL compilation.
6910fe6060f1SDimitry Andric     if (LangOpts.SYCLIsDevice)
6911fe6060f1SDimitry Andric       break;
69120b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
69130b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
69140b57cec5SDimitry Andric     break;
69150b57cec5SDimitry Andric   }
69160b57cec5SDimitry Andric 
6917bdd1243dSDimitry Andric   case Decl::TopLevelStmt:
6918bdd1243dSDimitry Andric     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6919bdd1243dSDimitry Andric     break;
6920bdd1243dSDimitry Andric 
69210b57cec5SDimitry Andric   case Decl::Import: {
69220b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
69230b57cec5SDimitry Andric 
69240b57cec5SDimitry Andric     // If we've already imported this module, we're done.
69250b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
69260b57cec5SDimitry Andric       break;
69270b57cec5SDimitry Andric 
69280b57cec5SDimitry Andric     // Emit debug information for direct imports.
69290b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
69300b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
69310b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
69320b57cec5SDimitry Andric     }
69330b57cec5SDimitry Andric 
6934fcaf7f86SDimitry Andric     // For C++ standard modules we are done - we will call the module
6935fcaf7f86SDimitry Andric     // initializer for imported modules, and that will likewise call those for
6936fcaf7f86SDimitry Andric     // any imports it has.
6937fcaf7f86SDimitry Andric     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6938fcaf7f86SDimitry Andric         !Import->getImportedOwningModule()->isModuleMapModule())
6939fcaf7f86SDimitry Andric       break;
6940fcaf7f86SDimitry Andric 
6941fcaf7f86SDimitry Andric     // For clang C++ module map modules the initializers for sub-modules are
6942fcaf7f86SDimitry Andric     // emitted here.
6943fcaf7f86SDimitry Andric 
69440b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
69450b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
69460b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
69470b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
69480b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
69490b57cec5SDimitry Andric 
69500b57cec5SDimitry Andric     while (!Stack.empty()) {
69510b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
69520b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
69530b57cec5SDimitry Andric         continue;
69540b57cec5SDimitry Andric 
69550b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
69560b57cec5SDimitry Andric         EmitTopLevelDecl(D);
69570b57cec5SDimitry Andric 
69580b57cec5SDimitry Andric       // Visit the submodules of this module.
6959fe013be4SDimitry Andric       for (auto *Submodule : Mod->submodules()) {
69600b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
69610b57cec5SDimitry Andric         // the initializers.
6962fe013be4SDimitry Andric         if (Submodule->IsExplicit)
69630b57cec5SDimitry Andric           continue;
69640b57cec5SDimitry Andric 
6965fe013be4SDimitry Andric         if (Visited.insert(Submodule).second)
6966fe013be4SDimitry Andric           Stack.push_back(Submodule);
69670b57cec5SDimitry Andric       }
69680b57cec5SDimitry Andric     }
69690b57cec5SDimitry Andric     break;
69700b57cec5SDimitry Andric   }
69710b57cec5SDimitry Andric 
69720b57cec5SDimitry Andric   case Decl::Export:
69730b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
69740b57cec5SDimitry Andric     break;
69750b57cec5SDimitry Andric 
69760b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
69770b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
69780b57cec5SDimitry Andric     break;
69790b57cec5SDimitry Andric 
69800b57cec5SDimitry Andric   case Decl::OMPAllocate:
6981fe6060f1SDimitry Andric     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
69820b57cec5SDimitry Andric     break;
69830b57cec5SDimitry Andric 
69840b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
69850b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
69860b57cec5SDimitry Andric     break;
69870b57cec5SDimitry Andric 
69880b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
69890b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
69900b57cec5SDimitry Andric     break;
69910b57cec5SDimitry Andric 
69920b57cec5SDimitry Andric   case Decl::OMPRequires:
69930b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
69940b57cec5SDimitry Andric     break;
69950b57cec5SDimitry Andric 
6996e8d8bef9SDimitry Andric   case Decl::Typedef:
6997e8d8bef9SDimitry Andric   case Decl::TypeAlias: // using foo = bar; [C++11]
6998e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6999e8d8bef9SDimitry Andric       DI->EmitAndRetainType(
7000e8d8bef9SDimitry Andric           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
7001e8d8bef9SDimitry Andric     break;
7002e8d8bef9SDimitry Andric 
7003e8d8bef9SDimitry Andric   case Decl::Record:
7004e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
7005e8d8bef9SDimitry Andric       if (cast<RecordDecl>(D)->getDefinition())
7006e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
7007e8d8bef9SDimitry Andric     break;
7008e8d8bef9SDimitry Andric 
7009e8d8bef9SDimitry Andric   case Decl::Enum:
7010e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
7011e8d8bef9SDimitry Andric       if (cast<EnumDecl>(D)->getDefinition())
7012e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
7013e8d8bef9SDimitry Andric     break;
7014e8d8bef9SDimitry Andric 
7015bdd1243dSDimitry Andric   case Decl::HLSLBuffer:
7016bdd1243dSDimitry Andric     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
7017bdd1243dSDimitry Andric     break;
7018bdd1243dSDimitry Andric 
70190b57cec5SDimitry Andric   default:
70200b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
70210b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
70220b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
70230b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
70240b57cec5SDimitry Andric     break;
70250b57cec5SDimitry Andric   }
70260b57cec5SDimitry Andric }
70270b57cec5SDimitry Andric 
AddDeferredUnusedCoverageMapping(Decl * D)70280b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
70290b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
70300b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
70310b57cec5SDimitry Andric     return;
70320b57cec5SDimitry Andric   switch (D->getKind()) {
70330b57cec5SDimitry Andric   case Decl::CXXConversion:
70340b57cec5SDimitry Andric   case Decl::CXXMethod:
70350b57cec5SDimitry Andric   case Decl::Function:
70360b57cec5SDimitry Andric   case Decl::ObjCMethod:
70370b57cec5SDimitry Andric   case Decl::CXXConstructor:
70380b57cec5SDimitry Andric   case Decl::CXXDestructor: {
70390b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
70405ffd83dbSDimitry Andric       break;
70410b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
70420b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
70435ffd83dbSDimitry Andric       break;
7044c9157d92SDimitry Andric     DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
70450b57cec5SDimitry Andric     break;
70460b57cec5SDimitry Andric   }
70470b57cec5SDimitry Andric   default:
70480b57cec5SDimitry Andric     break;
70490b57cec5SDimitry Andric   };
70500b57cec5SDimitry Andric }
70510b57cec5SDimitry Andric 
ClearUnusedCoverageMapping(const Decl * D)70520b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
70530b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
70540b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
70550b57cec5SDimitry Andric     return;
70560b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
70570b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
70580b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
70590b57cec5SDimitry Andric   }
7060c9157d92SDimitry Andric   DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
70610b57cec5SDimitry Andric }
70620b57cec5SDimitry Andric 
EmitDeferredUnusedCoverageMappings()70630b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
70640b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
70650b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
70660b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
70670b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
70680b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
70690b57cec5SDimitry Andric     if (!Entry.second)
70700b57cec5SDimitry Andric       continue;
70710b57cec5SDimitry Andric     const Decl *D = Entry.first;
70720b57cec5SDimitry Andric     switch (D->getKind()) {
70730b57cec5SDimitry Andric     case Decl::CXXConversion:
70740b57cec5SDimitry Andric     case Decl::CXXMethod:
70750b57cec5SDimitry Andric     case Decl::Function:
70760b57cec5SDimitry Andric     case Decl::ObjCMethod: {
70770b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
70780b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
70790b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
70800b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
70810b57cec5SDimitry Andric       break;
70820b57cec5SDimitry Andric     }
70830b57cec5SDimitry Andric     case Decl::CXXConstructor: {
70840b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
70850b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
70860b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
70870b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
70880b57cec5SDimitry Andric       break;
70890b57cec5SDimitry Andric     }
70900b57cec5SDimitry Andric     case Decl::CXXDestructor: {
70910b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
70920b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
70930b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
70940b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
70950b57cec5SDimitry Andric       break;
70960b57cec5SDimitry Andric     }
70970b57cec5SDimitry Andric     default:
70980b57cec5SDimitry Andric       break;
70990b57cec5SDimitry Andric     };
71000b57cec5SDimitry Andric   }
71010b57cec5SDimitry Andric }
71020b57cec5SDimitry Andric 
EmitMainVoidAlias()71035ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() {
71045ffd83dbSDimitry Andric   // In order to transition away from "__original_main" gracefully, emit an
71055ffd83dbSDimitry Andric   // alias for "main" in the no-argument case so that libc can detect when
71065ffd83dbSDimitry Andric   // new-style no-argument main is in used.
71075ffd83dbSDimitry Andric   if (llvm::Function *F = getModule().getFunction("main")) {
71085ffd83dbSDimitry Andric     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
710981ad6265SDimitry Andric         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
711081ad6265SDimitry Andric       auto *GA = llvm::GlobalAlias::create("__main_void", F);
711181ad6265SDimitry Andric       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
711281ad6265SDimitry Andric     }
71135ffd83dbSDimitry Andric   }
71145ffd83dbSDimitry Andric }
71155ffd83dbSDimitry Andric 
71160b57cec5SDimitry Andric /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)71170b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
71180b57cec5SDimitry Andric                                           const void *Ptr) {
71190b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
71200b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
71210b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
71220b57cec5SDimitry Andric }
71230b57cec5SDimitry Andric 
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)71240b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
71250b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
71260b57cec5SDimitry Andric                                    GlobalDecl D,
71270b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
71280b57cec5SDimitry Andric   if (!GlobalMetadata)
71290b57cec5SDimitry Andric     GlobalMetadata =
71300b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
71310b57cec5SDimitry Andric 
71320b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
71330b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
71340b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
71350b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
71360b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
71370b57cec5SDimitry Andric }
71380b57cec5SDimitry Andric 
CheckAndReplaceExternCIFuncs(llvm::GlobalValue * Elem,llvm::GlobalValue * CppFunc)713981ad6265SDimitry Andric bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
714081ad6265SDimitry Andric                                                  llvm::GlobalValue *CppFunc) {
714181ad6265SDimitry Andric   // Store the list of ifuncs we need to replace uses in.
714281ad6265SDimitry Andric   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
714381ad6265SDimitry Andric   // List of ConstantExprs that we should be able to delete when we're done
714481ad6265SDimitry Andric   // here.
714581ad6265SDimitry Andric   llvm::SmallVector<llvm::ConstantExpr *> CEs;
714681ad6265SDimitry Andric 
714781ad6265SDimitry Andric   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
714881ad6265SDimitry Andric   if (Elem == CppFunc)
714981ad6265SDimitry Andric     return false;
715081ad6265SDimitry Andric 
715181ad6265SDimitry Andric   // First make sure that all users of this are ifuncs (or ifuncs via a
715281ad6265SDimitry Andric   // bitcast), and collect the list of ifuncs and CEs so we can work on them
715381ad6265SDimitry Andric   // later.
715481ad6265SDimitry Andric   for (llvm::User *User : Elem->users()) {
715581ad6265SDimitry Andric     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
715681ad6265SDimitry Andric     // ifunc directly. In any other case, just give up, as we don't know what we
715781ad6265SDimitry Andric     // could break by changing those.
715881ad6265SDimitry Andric     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
715981ad6265SDimitry Andric       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
716081ad6265SDimitry Andric         return false;
716181ad6265SDimitry Andric 
716281ad6265SDimitry Andric       for (llvm::User *CEUser : ConstExpr->users()) {
716381ad6265SDimitry Andric         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
716481ad6265SDimitry Andric           IFuncs.push_back(IFunc);
716581ad6265SDimitry Andric         } else {
716681ad6265SDimitry Andric           return false;
716781ad6265SDimitry Andric         }
716881ad6265SDimitry Andric       }
716981ad6265SDimitry Andric       CEs.push_back(ConstExpr);
717081ad6265SDimitry Andric     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
717181ad6265SDimitry Andric       IFuncs.push_back(IFunc);
717281ad6265SDimitry Andric     } else {
717381ad6265SDimitry Andric       // This user is one we don't know how to handle, so fail redirection. This
717481ad6265SDimitry Andric       // will result in an ifunc retaining a resolver name that will ultimately
717581ad6265SDimitry Andric       // fail to be resolved to a defined function.
717681ad6265SDimitry Andric       return false;
717781ad6265SDimitry Andric     }
717881ad6265SDimitry Andric   }
717981ad6265SDimitry Andric 
718081ad6265SDimitry Andric   // Now we know this is a valid case where we can do this alias replacement, we
718181ad6265SDimitry Andric   // need to remove all of the references to Elem (and the bitcasts!) so we can
718281ad6265SDimitry Andric   // delete it.
718381ad6265SDimitry Andric   for (llvm::GlobalIFunc *IFunc : IFuncs)
718481ad6265SDimitry Andric     IFunc->setResolver(nullptr);
718581ad6265SDimitry Andric   for (llvm::ConstantExpr *ConstExpr : CEs)
718681ad6265SDimitry Andric     ConstExpr->destroyConstant();
718781ad6265SDimitry Andric 
718881ad6265SDimitry Andric   // We should now be out of uses for the 'old' version of this function, so we
718981ad6265SDimitry Andric   // can erase it as well.
719081ad6265SDimitry Andric   Elem->eraseFromParent();
719181ad6265SDimitry Andric 
719281ad6265SDimitry Andric   for (llvm::GlobalIFunc *IFunc : IFuncs) {
719381ad6265SDimitry Andric     // The type of the resolver is always just a function-type that returns the
719481ad6265SDimitry Andric     // type of the IFunc, so create that here. If the type of the actual
719581ad6265SDimitry Andric     // resolver doesn't match, it just gets bitcast to the right thing.
719681ad6265SDimitry Andric     auto *ResolverTy =
719781ad6265SDimitry Andric         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
719881ad6265SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
719981ad6265SDimitry Andric         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
720081ad6265SDimitry Andric     IFunc->setResolver(Resolver);
720181ad6265SDimitry Andric   }
720281ad6265SDimitry Andric   return true;
720381ad6265SDimitry Andric }
720481ad6265SDimitry Andric 
72050b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
72060b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
72070b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
72080b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
72090b57cec5SDimitry Andric /// same translation unit.
EmitStaticExternCAliases()72100b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
72110b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
72120b57cec5SDimitry Andric     return;
72130b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
72140b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
72150b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
721681ad6265SDimitry Andric 
721781ad6265SDimitry Andric     // If Val is null, that implies there were multiple declarations that each
721881ad6265SDimitry Andric     // had a claim to the unmangled name. In this case, generation of the alias
721981ad6265SDimitry Andric     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
722081ad6265SDimitry Andric     if (!Val)
722181ad6265SDimitry Andric       break;
722281ad6265SDimitry Andric 
722381ad6265SDimitry Andric     llvm::GlobalValue *ExistingElem =
722481ad6265SDimitry Andric         getModule().getNamedValue(Name->getName());
722581ad6265SDimitry Andric 
722681ad6265SDimitry Andric     // If there is either not something already by this name, or we were able to
722781ad6265SDimitry Andric     // replace all uses from IFuncs, create the alias.
722881ad6265SDimitry Andric     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7229fe6060f1SDimitry Andric       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
72300b57cec5SDimitry Andric   }
72310b57cec5SDimitry Andric }
72320b57cec5SDimitry Andric 
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const72330b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
72340b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
72350b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
72360b57cec5SDimitry Andric   if (Res == Manglings.end())
72370b57cec5SDimitry Andric     return false;
72380b57cec5SDimitry Andric   Result = Res->getValue();
72390b57cec5SDimitry Andric   return true;
72400b57cec5SDimitry Andric }
72410b57cec5SDimitry Andric 
72420b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
72430b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
72440b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
72450b57cec5SDimitry Andric ///
72460b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
72470b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
72480b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()72490b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
72500b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
72510b57cec5SDimitry Andric 
72520b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
72530b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
72540b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
72550b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
72560b57cec5SDimitry Andric     if (Addr)
72570b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
72580b57cec5SDimitry Andric   }
72590b57cec5SDimitry Andric }
72600b57cec5SDimitry Andric 
72610b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
72620b57cec5SDimitry Andric /// function.
EmitDeclMetadata()72630b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
72640b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
72650b57cec5SDimitry Andric 
72660b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
72670b57cec5SDimitry Andric 
72680b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
72690b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
72700b57cec5SDimitry Andric 
72710b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
72720b57cec5SDimitry Andric 
72730b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
72740b57cec5SDimitry Andric     const Decl *D = I.first;
72750b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
72760b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
72770b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
72780b57cec5SDimitry Andric       Alloca->setMetadata(
72790b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
72800b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
72810b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
72820b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
72830b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
72840b57cec5SDimitry Andric     }
72850b57cec5SDimitry Andric   }
72860b57cec5SDimitry Andric }
72870b57cec5SDimitry Andric 
EmitVersionIdentMetadata()72880b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
72890b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
72900b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
72910b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
72920b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
72930b57cec5SDimitry Andric 
72940b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
72950b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
72960b57cec5SDimitry Andric }
72970b57cec5SDimitry Andric 
EmitCommandLineMetadata()72980b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
72990b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
73000b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
73010b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
73020b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
73030b57cec5SDimitry Andric 
73040b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
73050b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
73060b57cec5SDimitry Andric }
73070b57cec5SDimitry Andric 
EmitCoverageFile()73080b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
73090b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
73100b57cec5SDimitry Andric   if (!CUNode)
73110b57cec5SDimitry Andric     return;
73120b57cec5SDimitry Andric 
73130b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
73140b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
73150b57cec5SDimitry Andric   auto *CoverageDataFile =
73160b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
73170b57cec5SDimitry Andric   auto *CoverageNotesFile =
73180b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
73190b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
73200b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
73210b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
73220b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
73230b57cec5SDimitry Andric   }
73240b57cec5SDimitry Andric }
73250b57cec5SDimitry Andric 
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)73260b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
73270b57cec5SDimitry Andric                                                        bool ForEH) {
73280b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
73290b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
73300b57cec5SDimitry Andric   // and it's not for EH?
7331fe013be4SDimitry Andric   if (!shouldEmitRTTI(ForEH))
7332fe013be4SDimitry Andric     return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
73330b57cec5SDimitry Andric 
73340b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
73350b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
73360b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
73370b57cec5SDimitry Andric 
73380b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
73390b57cec5SDimitry Andric }
73400b57cec5SDimitry Andric 
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)73410b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
73420b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
73430b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
73440b57cec5SDimitry Andric     return;
73450b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
73460b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
73470b57cec5SDimitry Andric     bool PerformInit =
73480b57cec5SDimitry Andric         VD->getAnyInitializer() &&
73490b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
73500b57cec5SDimitry Andric                                                         /*ForRef=*/false);
73510b57cec5SDimitry Andric 
735281ad6265SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD),
735381ad6265SDimitry Andric                  getTypes().ConvertTypeForMem(VD->getType()),
735481ad6265SDimitry Andric                  getContext().getDeclAlign(VD));
73550b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
73560b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
73570b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
73580b57cec5SDimitry Andric   }
73590b57cec5SDimitry Andric }
73600b57cec5SDimitry Andric 
73610b57cec5SDimitry Andric llvm::Metadata *
CreateMetadataIdentifierImpl(QualType T,MetadataTypeMap & Map,StringRef Suffix)73620b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
73630b57cec5SDimitry Andric                                             StringRef Suffix) {
73640eae32dcSDimitry Andric   if (auto *FnType = T->getAs<FunctionProtoType>())
73650eae32dcSDimitry Andric     T = getContext().getFunctionType(
73660eae32dcSDimitry Andric         FnType->getReturnType(), FnType->getParamTypes(),
73670eae32dcSDimitry Andric         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
73680eae32dcSDimitry Andric 
73690b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
73700b57cec5SDimitry Andric   if (InternalId)
73710b57cec5SDimitry Andric     return InternalId;
73720b57cec5SDimitry Andric 
73730b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
73740b57cec5SDimitry Andric     std::string OutName;
73750b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
7376c9157d92SDimitry Andric     getCXXABI().getMangleContext().mangleCanonicalTypeName(
7377fe013be4SDimitry Andric         T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
7378fe013be4SDimitry Andric 
7379fe013be4SDimitry Andric     if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
7380fe013be4SDimitry Andric       Out << ".normalized";
7381fe013be4SDimitry Andric 
73820b57cec5SDimitry Andric     Out << Suffix;
73830b57cec5SDimitry Andric 
73840b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
73850b57cec5SDimitry Andric   } else {
73860b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
73870b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
73880b57cec5SDimitry Andric   }
73890b57cec5SDimitry Andric 
73900b57cec5SDimitry Andric   return InternalId;
73910b57cec5SDimitry Andric }
73920b57cec5SDimitry Andric 
CreateMetadataIdentifierForType(QualType T)73930b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
73940b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
73950b57cec5SDimitry Andric }
73960b57cec5SDimitry Andric 
73970b57cec5SDimitry Andric llvm::Metadata *
CreateMetadataIdentifierForVirtualMemPtrType(QualType T)73980b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
73990b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
74000b57cec5SDimitry Andric }
74010b57cec5SDimitry Andric 
74020b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
74030b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
74040b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
74050b57cec5SDimitry Andric // 'void *'.
GeneralizeType(ASTContext & Ctx,QualType Ty)74060b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
74070b57cec5SDimitry Andric   if (!Ty->isPointerType())
74080b57cec5SDimitry Andric     return Ty;
74090b57cec5SDimitry Andric 
74100b57cec5SDimitry Andric   return Ctx.getPointerType(
74110b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
74120b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
74130b57cec5SDimitry Andric }
74140b57cec5SDimitry Andric 
74150b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
GeneralizeFunctionType(ASTContext & Ctx,QualType Ty)74160b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
74170b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
74180b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
74190b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
74200b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
74210b57cec5SDimitry Andric 
74220b57cec5SDimitry Andric     return Ctx.getFunctionType(
74230b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
74240b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
74250b57cec5SDimitry Andric   }
74260b57cec5SDimitry Andric 
74270b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
74280b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
74290b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
74300b57cec5SDimitry Andric 
74310b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
74320b57cec5SDimitry Andric }
74330b57cec5SDimitry Andric 
CreateMetadataIdentifierGeneralized(QualType T)74340b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
74350b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
74360b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
74370b57cec5SDimitry Andric }
74380b57cec5SDimitry Andric 
74390b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
NeedAllVtablesTypeId() const74400b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
74410b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
74420b57cec5SDimitry Andric   // is not in the trapping mode.
74430b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
74440b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
74450b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
74460b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
74470b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
74480b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
74490b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
74500b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
74510b57cec5SDimitry Andric }
74520b57cec5SDimitry Andric 
AddVTableTypeMetadata(llvm::GlobalVariable * VTable,CharUnits Offset,const CXXRecordDecl * RD)74530b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
74540b57cec5SDimitry Andric                                           CharUnits Offset,
74550b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
74560b57cec5SDimitry Andric   llvm::Metadata *MD =
74570b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
74580b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
74590b57cec5SDimitry Andric 
74600b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
74610b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
74620b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
74630b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
74640b57cec5SDimitry Andric 
74650b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
74660b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
74670b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
74680b57cec5SDimitry Andric   }
74690b57cec5SDimitry Andric }
74700b57cec5SDimitry Andric 
getSanStats()74710b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
74720b57cec5SDimitry Andric   if (!SanStats)
7473a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
74740b57cec5SDimitry Andric 
74750b57cec5SDimitry Andric   return *SanStats;
74760b57cec5SDimitry Andric }
747723408297SDimitry Andric 
74780b57cec5SDimitry Andric llvm::Value *
createOpenCLIntToSamplerConversion(const Expr * E,CodeGenFunction & CGF)74790b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
74800b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
74810b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
748223408297SDimitry Andric   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
748323408297SDimitry Andric   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7484fe6060f1SDimitry Andric   auto *Call = CGF.EmitRuntimeCall(
748523408297SDimitry Andric       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
748623408297SDimitry Andric   return Call;
74870b57cec5SDimitry Andric }
74885ffd83dbSDimitry Andric 
getNaturalPointeeTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)74895ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
74905ffd83dbSDimitry Andric     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
74915ffd83dbSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
74925ffd83dbSDimitry Andric                                  /* forPointeeType= */ true);
74935ffd83dbSDimitry Andric }
74945ffd83dbSDimitry Andric 
getNaturalTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,bool forPointeeType)74955ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
74965ffd83dbSDimitry Andric                                                  LValueBaseInfo *BaseInfo,
74975ffd83dbSDimitry Andric                                                  TBAAAccessInfo *TBAAInfo,
74985ffd83dbSDimitry Andric                                                  bool forPointeeType) {
74995ffd83dbSDimitry Andric   if (TBAAInfo)
75005ffd83dbSDimitry Andric     *TBAAInfo = getTBAAAccessInfo(T);
75015ffd83dbSDimitry Andric 
75025ffd83dbSDimitry Andric   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
75035ffd83dbSDimitry Andric   // that doesn't return the information we need to compute BaseInfo.
75045ffd83dbSDimitry Andric 
75055ffd83dbSDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
75065ffd83dbSDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
75075ffd83dbSDimitry Andric   // there's an expressivity gap here.
75085ffd83dbSDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
75095ffd83dbSDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
75105ffd83dbSDimitry Andric       if (BaseInfo)
75115ffd83dbSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
75125ffd83dbSDimitry Andric       return getContext().toCharUnitsFromBits(Align);
75135ffd83dbSDimitry Andric     }
75145ffd83dbSDimitry Andric   }
75155ffd83dbSDimitry Andric 
75165ffd83dbSDimitry Andric   bool AlignForArray = T->isArrayType();
75175ffd83dbSDimitry Andric 
75185ffd83dbSDimitry Andric   // Analyze the base element type, so we don't get confused by incomplete
75195ffd83dbSDimitry Andric   // array types.
75205ffd83dbSDimitry Andric   T = getContext().getBaseElementType(T);
75215ffd83dbSDimitry Andric 
75225ffd83dbSDimitry Andric   if (T->isIncompleteType()) {
75235ffd83dbSDimitry Andric     // We could try to replicate the logic from
75245ffd83dbSDimitry Andric     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
75255ffd83dbSDimitry Andric     // type is incomplete, so it's impossible to test. We could try to reuse
75265ffd83dbSDimitry Andric     // getTypeAlignIfKnown, but that doesn't return the information we need
75275ffd83dbSDimitry Andric     // to set BaseInfo.  So just ignore the possibility that the alignment is
75285ffd83dbSDimitry Andric     // greater than one.
75295ffd83dbSDimitry Andric     if (BaseInfo)
75305ffd83dbSDimitry Andric       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
75315ffd83dbSDimitry Andric     return CharUnits::One();
75325ffd83dbSDimitry Andric   }
75335ffd83dbSDimitry Andric 
75345ffd83dbSDimitry Andric   if (BaseInfo)
75355ffd83dbSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
75365ffd83dbSDimitry Andric 
75375ffd83dbSDimitry Andric   CharUnits Alignment;
7538e8d8bef9SDimitry Andric   const CXXRecordDecl *RD;
7539e8d8bef9SDimitry Andric   if (T.getQualifiers().hasUnaligned()) {
7540e8d8bef9SDimitry Andric     Alignment = CharUnits::One();
7541e8d8bef9SDimitry Andric   } else if (forPointeeType && !AlignForArray &&
7542e8d8bef9SDimitry Andric              (RD = T->getAsCXXRecordDecl())) {
75435ffd83dbSDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
75445ffd83dbSDimitry Andric     // base or a complete object, so we generally need to use the
75455ffd83dbSDimitry Andric     // non-virtual alignment.
75465ffd83dbSDimitry Andric     Alignment = getClassPointerAlignment(RD);
75475ffd83dbSDimitry Andric   } else {
75485ffd83dbSDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
75495ffd83dbSDimitry Andric   }
75505ffd83dbSDimitry Andric 
75515ffd83dbSDimitry Andric   // Cap to the global maximum type alignment unless the alignment
75525ffd83dbSDimitry Andric   // was somehow explicit on the type.
75535ffd83dbSDimitry Andric   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
75545ffd83dbSDimitry Andric     if (Alignment.getQuantity() > MaxAlign &&
75555ffd83dbSDimitry Andric         !getContext().isAlignmentRequired(T))
75565ffd83dbSDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
75575ffd83dbSDimitry Andric   }
75585ffd83dbSDimitry Andric   return Alignment;
75595ffd83dbSDimitry Andric }
75605ffd83dbSDimitry Andric 
stopAutoInit()75615ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() {
75625ffd83dbSDimitry Andric   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
75635ffd83dbSDimitry Andric   if (StopAfter) {
75645ffd83dbSDimitry Andric     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
75655ffd83dbSDimitry Andric     // used
75665ffd83dbSDimitry Andric     if (NumAutoVarInit >= StopAfter) {
75675ffd83dbSDimitry Andric       return true;
75685ffd83dbSDimitry Andric     }
75695ffd83dbSDimitry Andric     if (!NumAutoVarInit) {
75705ffd83dbSDimitry Andric       unsigned DiagID = getDiags().getCustomDiagID(
75715ffd83dbSDimitry Andric           DiagnosticsEngine::Warning,
75725ffd83dbSDimitry Andric           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
75735ffd83dbSDimitry Andric           "number of times ftrivial-auto-var-init=%1 gets applied.");
75745ffd83dbSDimitry Andric       getDiags().Report(DiagID)
75755ffd83dbSDimitry Andric           << StopAfter
75765ffd83dbSDimitry Andric           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
75775ffd83dbSDimitry Andric                       LangOptions::TrivialAutoVarInitKind::Zero
75785ffd83dbSDimitry Andric                   ? "zero"
75795ffd83dbSDimitry Andric                   : "pattern");
75805ffd83dbSDimitry Andric     }
75815ffd83dbSDimitry Andric     ++NumAutoVarInit;
75825ffd83dbSDimitry Andric   }
75835ffd83dbSDimitry Andric   return false;
75845ffd83dbSDimitry Andric }
7585fe6060f1SDimitry Andric 
printPostfixForExternalizedDecl(llvm::raw_ostream & OS,const Decl * D) const75862a66634dSDimitry Andric void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
75872a66634dSDimitry Andric                                                     const Decl *D) const {
75882a66634dSDimitry Andric   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
75892a66634dSDimitry Andric   // postfix beginning with '.' since the symbol name can be demangled.
75902a66634dSDimitry Andric   if (LangOpts.HIP)
759181ad6265SDimitry Andric     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
75922a66634dSDimitry Andric   else
759381ad6265SDimitry Andric     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
759481ad6265SDimitry Andric 
759581ad6265SDimitry Andric   // If the CUID is not specified we try to generate a unique postfix.
759681ad6265SDimitry Andric   if (getLangOpts().CUID.empty()) {
759781ad6265SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
759881ad6265SDimitry Andric     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
759981ad6265SDimitry Andric     assert(PLoc.isValid() && "Source location is expected to be valid.");
760081ad6265SDimitry Andric 
760181ad6265SDimitry Andric     // Get the hash of the user defined macros.
760281ad6265SDimitry Andric     llvm::MD5 Hash;
760381ad6265SDimitry Andric     llvm::MD5::MD5Result Result;
760481ad6265SDimitry Andric     for (const auto &Arg : PreprocessorOpts.Macros)
760581ad6265SDimitry Andric       Hash.update(Arg.first);
760681ad6265SDimitry Andric     Hash.final(Result);
760781ad6265SDimitry Andric 
760881ad6265SDimitry Andric     // Get the UniqueID for the file containing the decl.
760981ad6265SDimitry Andric     llvm::sys::fs::UniqueID ID;
7610c9157d92SDimitry Andric     if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
761181ad6265SDimitry Andric       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
761281ad6265SDimitry Andric       assert(PLoc.isValid() && "Source location is expected to be valid.");
761381ad6265SDimitry Andric       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
761481ad6265SDimitry Andric         SM.getDiagnostics().Report(diag::err_cannot_open_file)
761581ad6265SDimitry Andric             << PLoc.getFilename() << EC.message();
761681ad6265SDimitry Andric     }
761781ad6265SDimitry Andric     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
761881ad6265SDimitry Andric        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
761981ad6265SDimitry Andric   } else {
762081ad6265SDimitry Andric     OS << getContext().getCUIDHash();
762181ad6265SDimitry Andric   }
7622fe6060f1SDimitry Andric }
7623fcaf7f86SDimitry Andric 
moveLazyEmissionStates(CodeGenModule * NewBuilder)7624fcaf7f86SDimitry Andric void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7625fcaf7f86SDimitry Andric   assert(DeferredDeclsToEmit.empty() &&
7626fcaf7f86SDimitry Andric          "Should have emitted all decls deferred to emit.");
7627fcaf7f86SDimitry Andric   assert(NewBuilder->DeferredDecls.empty() &&
7628fcaf7f86SDimitry Andric          "Newly created module should not have deferred decls");
7629fcaf7f86SDimitry Andric   NewBuilder->DeferredDecls = std::move(DeferredDecls);
7630c9157d92SDimitry Andric   assert(EmittedDeferredDecls.empty() &&
7631c9157d92SDimitry Andric          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7632fcaf7f86SDimitry Andric 
7633fcaf7f86SDimitry Andric   assert(NewBuilder->DeferredVTables.empty() &&
7634fcaf7f86SDimitry Andric          "Newly created module should not have deferred vtables");
7635fcaf7f86SDimitry Andric   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7636fcaf7f86SDimitry Andric 
7637fcaf7f86SDimitry Andric   assert(NewBuilder->MangledDeclNames.empty() &&
7638fcaf7f86SDimitry Andric          "Newly created module should not have mangled decl names");
7639fcaf7f86SDimitry Andric   assert(NewBuilder->Manglings.empty() &&
7640fcaf7f86SDimitry Andric          "Newly created module should not have manglings");
7641fcaf7f86SDimitry Andric   NewBuilder->Manglings = std::move(Manglings);
7642fcaf7f86SDimitry Andric 
7643fcaf7f86SDimitry Andric   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7644fcaf7f86SDimitry Andric 
7645fcaf7f86SDimitry Andric   NewBuilder->TBAA = std::move(TBAA);
7646fcaf7f86SDimitry Andric 
7647972a253aSDimitry Andric   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7648fcaf7f86SDimitry Andric }
7649