/src/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This coordinates the per-module state used while generating code. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | #include "CodeGenModule.h" |
14 | | #include "ABIInfo.h" |
15 | | #include "CGBlocks.h" |
16 | | #include "CGCUDARuntime.h" |
17 | | #include "CGCXXABI.h" |
18 | | #include "CGCall.h" |
19 | | #include "CGDebugInfo.h" |
20 | | #include "CGHLSLRuntime.h" |
21 | | #include "CGObjCRuntime.h" |
22 | | #include "CGOpenCLRuntime.h" |
23 | | #include "CGOpenMPRuntime.h" |
24 | | #include "CGOpenMPRuntimeGPU.h" |
25 | | #include "CodeGenFunction.h" |
26 | | #include "CodeGenPGO.h" |
27 | | #include "ConstantEmitter.h" |
28 | | #include "CoverageMappingGen.h" |
29 | | #include "TargetInfo.h" |
30 | | #include "clang/AST/ASTContext.h" |
31 | | #include "clang/AST/ASTLambda.h" |
32 | | #include "clang/AST/CharUnits.h" |
33 | | #include "clang/AST/DeclCXX.h" |
34 | | #include "clang/AST/DeclObjC.h" |
35 | | #include "clang/AST/DeclTemplate.h" |
36 | | #include "clang/AST/Mangle.h" |
37 | | #include "clang/AST/RecursiveASTVisitor.h" |
38 | | #include "clang/AST/StmtVisitor.h" |
39 | | #include "clang/Basic/Builtins.h" |
40 | | #include "clang/Basic/CharInfo.h" |
41 | | #include "clang/Basic/CodeGenOptions.h" |
42 | | #include "clang/Basic/Diagnostic.h" |
43 | | #include "clang/Basic/FileManager.h" |
44 | | #include "clang/Basic/Module.h" |
45 | | #include "clang/Basic/SourceManager.h" |
46 | | #include "clang/Basic/TargetInfo.h" |
47 | | #include "clang/Basic/Version.h" |
48 | | #include "clang/CodeGen/BackendUtil.h" |
49 | | #include "clang/CodeGen/ConstantInitBuilder.h" |
50 | | #include "clang/Frontend/FrontendDiagnostic.h" |
51 | | #include "llvm/ADT/STLExtras.h" |
52 | | #include "llvm/ADT/StringExtras.h" |
53 | | #include "llvm/ADT/StringSwitch.h" |
54 | | #include "llvm/Analysis/TargetLibraryInfo.h" |
55 | | #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" |
56 | | #include "llvm/IR/AttributeMask.h" |
57 | | #include "llvm/IR/CallingConv.h" |
58 | | #include "llvm/IR/DataLayout.h" |
59 | | #include "llvm/IR/Intrinsics.h" |
60 | | #include "llvm/IR/LLVMContext.h" |
61 | | #include "llvm/IR/Module.h" |
62 | | #include "llvm/IR/ProfileSummary.h" |
63 | | #include "llvm/ProfileData/InstrProfReader.h" |
64 | | #include "llvm/ProfileData/SampleProf.h" |
65 | | #include "llvm/Support/CRC.h" |
66 | | #include "llvm/Support/CodeGen.h" |
67 | | #include "llvm/Support/CommandLine.h" |
68 | | #include "llvm/Support/ConvertUTF.h" |
69 | | #include "llvm/Support/ErrorHandling.h" |
70 | | #include "llvm/Support/TimeProfiler.h" |
71 | | #include "llvm/Support/xxhash.h" |
72 | | #include "llvm/TargetParser/Triple.h" |
73 | | #include "llvm/TargetParser/X86TargetParser.h" |
74 | | #include <optional> |
75 | | |
76 | | using namespace clang; |
77 | | using namespace CodeGen; |
78 | | |
79 | | static llvm::cl::opt<bool> LimitedCoverage( |
80 | | "limited-coverage-experimental", llvm::cl::Hidden, |
81 | | llvm::cl::desc("Emit limited coverage mapping information (experimental)")); |
82 | | |
83 | | static const char AnnotationSection[] = "llvm.metadata"; |
84 | | |
85 | 46 | static CGCXXABI *createCXXABI(CodeGenModule &CGM) { |
86 | 46 | switch (CGM.getContext().getCXXABIKind()) { |
87 | 0 | case TargetCXXABI::AppleARM64: |
88 | 0 | case TargetCXXABI::Fuchsia: |
89 | 0 | case TargetCXXABI::GenericAArch64: |
90 | 0 | case TargetCXXABI::GenericARM: |
91 | 0 | case TargetCXXABI::iOS: |
92 | 0 | case TargetCXXABI::WatchOS: |
93 | 0 | case TargetCXXABI::GenericMIPS: |
94 | 46 | case TargetCXXABI::GenericItanium: |
95 | 46 | case TargetCXXABI::WebAssembly: |
96 | 46 | case TargetCXXABI::XL: |
97 | 46 | return CreateItaniumCXXABI(CGM); |
98 | 0 | case TargetCXXABI::Microsoft: |
99 | 0 | return CreateMicrosoftCXXABI(CGM); |
100 | 46 | } |
101 | | |
102 | 0 | llvm_unreachable("invalid C++ ABI kind"); |
103 | 0 | } |
104 | | |
105 | | static std::unique_ptr<TargetCodeGenInfo> |
106 | 46 | createTargetCodeGenInfo(CodeGenModule &CGM) { |
107 | 46 | const TargetInfo &Target = CGM.getTarget(); |
108 | 46 | const llvm::Triple &Triple = Target.getTriple(); |
109 | 46 | const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); |
110 | | |
111 | 46 | switch (Triple.getArch()) { |
112 | 0 | default: |
113 | 0 | return createDefaultTargetCodeGenInfo(CGM); |
114 | | |
115 | 0 | case llvm::Triple::le32: |
116 | 0 | return createPNaClTargetCodeGenInfo(CGM); |
117 | 0 | case llvm::Triple::m68k: |
118 | 0 | return createM68kTargetCodeGenInfo(CGM); |
119 | 0 | case llvm::Triple::mips: |
120 | 0 | case llvm::Triple::mipsel: |
121 | 0 | if (Triple.getOS() == llvm::Triple::NaCl) |
122 | 0 | return createPNaClTargetCodeGenInfo(CGM); |
123 | 0 | return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); |
124 | | |
125 | 0 | case llvm::Triple::mips64: |
126 | 0 | case llvm::Triple::mips64el: |
127 | 0 | return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false); |
128 | | |
129 | 0 | case llvm::Triple::avr: { |
130 | | // For passing parameters, R8~R25 are used on avr, and R18~R25 are used |
131 | | // on avrtiny. For passing return value, R18~R25 are used on avr, and |
132 | | // R22~R25 are used on avrtiny. |
133 | 0 | unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18; |
134 | 0 | unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8; |
135 | 0 | return createAVRTargetCodeGenInfo(CGM, NPR, NRR); |
136 | 0 | } |
137 | | |
138 | 0 | case llvm::Triple::aarch64: |
139 | 0 | case llvm::Triple::aarch64_32: |
140 | 0 | case llvm::Triple::aarch64_be: { |
141 | 0 | AArch64ABIKind Kind = AArch64ABIKind::AAPCS; |
142 | 0 | if (Target.getABI() == "darwinpcs") |
143 | 0 | Kind = AArch64ABIKind::DarwinPCS; |
144 | 0 | else if (Triple.isOSWindows()) |
145 | 0 | return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64); |
146 | | |
147 | 0 | return createAArch64TargetCodeGenInfo(CGM, Kind); |
148 | 0 | } |
149 | | |
150 | 0 | case llvm::Triple::wasm32: |
151 | 0 | case llvm::Triple::wasm64: { |
152 | 0 | WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP; |
153 | 0 | if (Target.getABI() == "experimental-mv") |
154 | 0 | Kind = WebAssemblyABIKind::ExperimentalMV; |
155 | 0 | return createWebAssemblyTargetCodeGenInfo(CGM, Kind); |
156 | 0 | } |
157 | | |
158 | 0 | case llvm::Triple::arm: |
159 | 0 | case llvm::Triple::armeb: |
160 | 0 | case llvm::Triple::thumb: |
161 | 0 | case llvm::Triple::thumbeb: { |
162 | 0 | if (Triple.getOS() == llvm::Triple::Win32) |
163 | 0 | return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP); |
164 | | |
165 | 0 | ARMABIKind Kind = ARMABIKind::AAPCS; |
166 | 0 | StringRef ABIStr = Target.getABI(); |
167 | 0 | if (ABIStr == "apcs-gnu") |
168 | 0 | Kind = ARMABIKind::APCS; |
169 | 0 | else if (ABIStr == "aapcs16") |
170 | 0 | Kind = ARMABIKind::AAPCS16_VFP; |
171 | 0 | else if (CodeGenOpts.FloatABI == "hard" || |
172 | 0 | (CodeGenOpts.FloatABI != "soft" && |
173 | 0 | (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || |
174 | 0 | Triple.getEnvironment() == llvm::Triple::MuslEABIHF || |
175 | 0 | Triple.getEnvironment() == llvm::Triple::EABIHF))) |
176 | 0 | Kind = ARMABIKind::AAPCS_VFP; |
177 | |
|
178 | 0 | return createARMTargetCodeGenInfo(CGM, Kind); |
179 | 0 | } |
180 | | |
181 | 0 | case llvm::Triple::ppc: { |
182 | 0 | if (Triple.isOSAIX()) |
183 | 0 | return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false); |
184 | | |
185 | 0 | bool IsSoftFloat = |
186 | 0 | CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe"); |
187 | 0 | return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); |
188 | 0 | } |
189 | 0 | case llvm::Triple::ppcle: { |
190 | 0 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; |
191 | 0 | return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); |
192 | 0 | } |
193 | 0 | case llvm::Triple::ppc64: |
194 | 0 | if (Triple.isOSAIX()) |
195 | 0 | return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true); |
196 | | |
197 | 0 | if (Triple.isOSBinFormatELF()) { |
198 | 0 | PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1; |
199 | 0 | if (Target.getABI() == "elfv2") |
200 | 0 | Kind = PPC64_SVR4_ABIKind::ELFv2; |
201 | 0 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; |
202 | |
|
203 | 0 | return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); |
204 | 0 | } |
205 | 0 | return createPPC64TargetCodeGenInfo(CGM); |
206 | 0 | case llvm::Triple::ppc64le: { |
207 | 0 | assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); |
208 | 0 | PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2; |
209 | 0 | if (Target.getABI() == "elfv1") |
210 | 0 | Kind = PPC64_SVR4_ABIKind::ELFv1; |
211 | 0 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; |
212 | |
|
213 | 0 | return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); |
214 | 0 | } |
215 | | |
216 | 0 | case llvm::Triple::nvptx: |
217 | 0 | case llvm::Triple::nvptx64: |
218 | 0 | return createNVPTXTargetCodeGenInfo(CGM); |
219 | | |
220 | 0 | case llvm::Triple::msp430: |
221 | 0 | return createMSP430TargetCodeGenInfo(CGM); |
222 | | |
223 | 0 | case llvm::Triple::riscv32: |
224 | 0 | case llvm::Triple::riscv64: { |
225 | 0 | StringRef ABIStr = Target.getABI(); |
226 | 0 | unsigned XLen = Target.getPointerWidth(LangAS::Default); |
227 | 0 | unsigned ABIFLen = 0; |
228 | 0 | if (ABIStr.ends_with("f")) |
229 | 0 | ABIFLen = 32; |
230 | 0 | else if (ABIStr.ends_with("d")) |
231 | 0 | ABIFLen = 64; |
232 | 0 | bool EABI = ABIStr.ends_with("e"); |
233 | 0 | return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI); |
234 | 0 | } |
235 | | |
236 | 0 | case llvm::Triple::systemz: { |
237 | 0 | bool SoftFloat = CodeGenOpts.FloatABI == "soft"; |
238 | 0 | bool HasVector = !SoftFloat && Target.getABI() == "vector"; |
239 | 0 | return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat); |
240 | 0 | } |
241 | | |
242 | 0 | case llvm::Triple::tce: |
243 | 0 | case llvm::Triple::tcele: |
244 | 0 | return createTCETargetCodeGenInfo(CGM); |
245 | | |
246 | 0 | case llvm::Triple::x86: { |
247 | 0 | bool IsDarwinVectorABI = Triple.isOSDarwin(); |
248 | 0 | bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); |
249 | |
|
250 | 0 | if (Triple.getOS() == llvm::Triple::Win32) { |
251 | 0 | return createWinX86_32TargetCodeGenInfo( |
252 | 0 | CGM, IsDarwinVectorABI, IsWin32FloatStructABI, |
253 | 0 | CodeGenOpts.NumRegisterParameters); |
254 | 0 | } |
255 | 0 | return createX86_32TargetCodeGenInfo( |
256 | 0 | CGM, IsDarwinVectorABI, IsWin32FloatStructABI, |
257 | 0 | CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft"); |
258 | 0 | } |
259 | | |
260 | 46 | case llvm::Triple::x86_64: { |
261 | 46 | StringRef ABI = Target.getABI(); |
262 | 46 | X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 |
263 | 46 | : ABI == "avx" ? X86AVXABILevel::AVX |
264 | 46 | : X86AVXABILevel::None); |
265 | | |
266 | 46 | switch (Triple.getOS()) { |
267 | 0 | case llvm::Triple::Win32: |
268 | 0 | return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel); |
269 | 46 | default: |
270 | 46 | return createX86_64TargetCodeGenInfo(CGM, AVXLevel); |
271 | 46 | } |
272 | 46 | } |
273 | 0 | case llvm::Triple::hexagon: |
274 | 0 | return createHexagonTargetCodeGenInfo(CGM); |
275 | 0 | case llvm::Triple::lanai: |
276 | 0 | return createLanaiTargetCodeGenInfo(CGM); |
277 | 0 | case llvm::Triple::r600: |
278 | 0 | return createAMDGPUTargetCodeGenInfo(CGM); |
279 | 0 | case llvm::Triple::amdgcn: |
280 | 0 | return createAMDGPUTargetCodeGenInfo(CGM); |
281 | 0 | case llvm::Triple::sparc: |
282 | 0 | return createSparcV8TargetCodeGenInfo(CGM); |
283 | 0 | case llvm::Triple::sparcv9: |
284 | 0 | return createSparcV9TargetCodeGenInfo(CGM); |
285 | 0 | case llvm::Triple::xcore: |
286 | 0 | return createXCoreTargetCodeGenInfo(CGM); |
287 | 0 | case llvm::Triple::arc: |
288 | 0 | return createARCTargetCodeGenInfo(CGM); |
289 | 0 | case llvm::Triple::spir: |
290 | 0 | case llvm::Triple::spir64: |
291 | 0 | return createCommonSPIRTargetCodeGenInfo(CGM); |
292 | 0 | case llvm::Triple::spirv32: |
293 | 0 | case llvm::Triple::spirv64: |
294 | 0 | return createSPIRVTargetCodeGenInfo(CGM); |
295 | 0 | case llvm::Triple::ve: |
296 | 0 | return createVETargetCodeGenInfo(CGM); |
297 | 0 | case llvm::Triple::csky: { |
298 | 0 | bool IsSoftFloat = !Target.hasFeature("hard-float-abi"); |
299 | 0 | bool hasFP64 = |
300 | 0 | Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df"); |
301 | 0 | return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0 |
302 | 0 | : hasFP64 ? 64 |
303 | 0 | : 32); |
304 | 0 | } |
305 | 0 | case llvm::Triple::bpfeb: |
306 | 0 | case llvm::Triple::bpfel: |
307 | 0 | return createBPFTargetCodeGenInfo(CGM); |
308 | 0 | case llvm::Triple::loongarch32: |
309 | 0 | case llvm::Triple::loongarch64: { |
310 | 0 | StringRef ABIStr = Target.getABI(); |
311 | 0 | unsigned ABIFRLen = 0; |
312 | 0 | if (ABIStr.ends_with("f")) |
313 | 0 | ABIFRLen = 32; |
314 | 0 | else if (ABIStr.ends_with("d")) |
315 | 0 | ABIFRLen = 64; |
316 | 0 | return createLoongArchTargetCodeGenInfo( |
317 | 0 | CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen); |
318 | 0 | } |
319 | 46 | } |
320 | 46 | } |
321 | | |
322 | 138 | const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { |
323 | 138 | if (!TheTargetCodeGenInfo) |
324 | 46 | TheTargetCodeGenInfo = createTargetCodeGenInfo(*this); |
325 | 138 | return *TheTargetCodeGenInfo; |
326 | 138 | } |
327 | | |
328 | | CodeGenModule::CodeGenModule(ASTContext &C, |
329 | | IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, |
330 | | const HeaderSearchOptions &HSO, |
331 | | const PreprocessorOptions &PPO, |
332 | | const CodeGenOptions &CGO, llvm::Module &M, |
333 | | DiagnosticsEngine &diags, |
334 | | CoverageSourceInfo *CoverageInfo) |
335 | | : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO), |
336 | | PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), |
337 | | Target(C.getTargetInfo()), ABI(createCXXABI(*this)), |
338 | | VMContext(M.getContext()), Types(*this), VTables(*this), |
339 | 46 | SanitizerMD(new SanitizerMetadata(*this)) { |
340 | | |
341 | | // Initialize the type cache. |
342 | 46 | llvm::LLVMContext &LLVMContext = M.getContext(); |
343 | 46 | VoidTy = llvm::Type::getVoidTy(LLVMContext); |
344 | 46 | Int8Ty = llvm::Type::getInt8Ty(LLVMContext); |
345 | 46 | Int16Ty = llvm::Type::getInt16Ty(LLVMContext); |
346 | 46 | Int32Ty = llvm::Type::getInt32Ty(LLVMContext); |
347 | 46 | Int64Ty = llvm::Type::getInt64Ty(LLVMContext); |
348 | 46 | HalfTy = llvm::Type::getHalfTy(LLVMContext); |
349 | 46 | BFloatTy = llvm::Type::getBFloatTy(LLVMContext); |
350 | 46 | FloatTy = llvm::Type::getFloatTy(LLVMContext); |
351 | 46 | DoubleTy = llvm::Type::getDoubleTy(LLVMContext); |
352 | 46 | PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default); |
353 | 46 | PointerAlignInBytes = |
354 | 46 | C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default)) |
355 | 46 | .getQuantity(); |
356 | 46 | SizeSizeInBytes = |
357 | 46 | C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); |
358 | 46 | IntAlignInBytes = |
359 | 46 | C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); |
360 | 46 | CharTy = |
361 | 46 | llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); |
362 | 46 | IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); |
363 | 46 | IntPtrTy = llvm::IntegerType::get(LLVMContext, |
364 | 46 | C.getTargetInfo().getMaxPointerWidth()); |
365 | 46 | Int8PtrTy = llvm::PointerType::get(LLVMContext, 0); |
366 | 46 | const llvm::DataLayout &DL = M.getDataLayout(); |
367 | 46 | AllocaInt8PtrTy = |
368 | 46 | llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace()); |
369 | 46 | GlobalsInt8PtrTy = |
370 | 46 | llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace()); |
371 | 46 | ConstGlobalsPtrTy = llvm::PointerType::get( |
372 | 46 | LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace())); |
373 | 46 | ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); |
374 | | |
375 | | // Build C++20 Module initializers. |
376 | | // TODO: Add Microsoft here once we know the mangling required for the |
377 | | // initializers. |
378 | 46 | CXX20ModuleInits = |
379 | 46 | LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == |
380 | 0 | ItaniumMangleContext::MK_Itanium; |
381 | | |
382 | 46 | RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); |
383 | | |
384 | 46 | if (LangOpts.ObjC) |
385 | 23 | createObjCRuntime(); |
386 | 46 | if (LangOpts.OpenCL) |
387 | 0 | createOpenCLRuntime(); |
388 | 46 | if (LangOpts.OpenMP) |
389 | 0 | createOpenMPRuntime(); |
390 | 46 | if (LangOpts.CUDA) |
391 | 0 | createCUDARuntime(); |
392 | 46 | if (LangOpts.HLSL) |
393 | 0 | createHLSLRuntime(); |
394 | | |
395 | | // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. |
396 | 46 | if (LangOpts.Sanitize.has(SanitizerKind::Thread) || |
397 | 46 | (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) |
398 | 46 | TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), |
399 | 46 | getCXXABI().getMangleContext())); |
400 | | |
401 | | // If debug info or coverage generation is enabled, create the CGDebugInfo |
402 | | // object. |
403 | 46 | if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo || |
404 | 46 | CodeGenOpts.CoverageNotesFile.size() || |
405 | 46 | CodeGenOpts.CoverageDataFile.size()) |
406 | 0 | DebugInfo.reset(new CGDebugInfo(*this)); |
407 | | |
408 | 46 | Block.GlobalUniqueCount = 0; |
409 | | |
410 | 46 | if (C.getLangOpts().ObjC) |
411 | 23 | ObjCData.reset(new ObjCEntrypoints()); |
412 | | |
413 | 46 | if (CodeGenOpts.hasProfileClangUse()) { |
414 | 0 | auto ReaderOrErr = llvm::IndexedInstrProfReader::create( |
415 | 0 | CodeGenOpts.ProfileInstrumentUsePath, *FS, |
416 | 0 | CodeGenOpts.ProfileRemappingFile); |
417 | | // We're checking for profile read errors in CompilerInvocation, so if |
418 | | // there was an error it should've already been caught. If it hasn't been |
419 | | // somehow, trip an assertion. |
420 | 0 | assert(ReaderOrErr); |
421 | 0 | PGOReader = std::move(ReaderOrErr.get()); |
422 | 0 | } |
423 | | |
424 | | // If coverage mapping generation is enabled, create the |
425 | | // CoverageMappingModuleGen object. |
426 | 46 | if (CodeGenOpts.CoverageMapping) |
427 | 0 | CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); |
428 | | |
429 | | // Generate the module name hash here if needed. |
430 | 46 | if (CodeGenOpts.UniqueInternalLinkageNames && |
431 | 46 | !getModule().getSourceFileName().empty()) { |
432 | 0 | std::string Path = getModule().getSourceFileName(); |
433 | | // Check if a path substitution is needed from the MacroPrefixMap. |
434 | 0 | for (const auto &Entry : LangOpts.MacroPrefixMap) |
435 | 0 | if (Path.rfind(Entry.first, 0) != std::string::npos) { |
436 | 0 | Path = Entry.second + Path.substr(Entry.first.size()); |
437 | 0 | break; |
438 | 0 | } |
439 | 0 | ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); |
440 | 0 | } |
441 | 46 | } |
442 | | |
443 | 46 | CodeGenModule::~CodeGenModule() {} |
444 | | |
445 | 23 | void CodeGenModule::createObjCRuntime() { |
446 | | // This is just isGNUFamily(), but we want to force implementors of |
447 | | // new ABIs to decide how best to do this. |
448 | 23 | switch (LangOpts.ObjCRuntime.getKind()) { |
449 | 0 | case ObjCRuntime::GNUstep: |
450 | 0 | case ObjCRuntime::GCC: |
451 | 0 | case ObjCRuntime::ObjFW: |
452 | 0 | ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); |
453 | 0 | return; |
454 | | |
455 | 0 | case ObjCRuntime::FragileMacOSX: |
456 | 23 | case ObjCRuntime::MacOSX: |
457 | 23 | case ObjCRuntime::iOS: |
458 | 23 | case ObjCRuntime::WatchOS: |
459 | 23 | ObjCRuntime.reset(CreateMacObjCRuntime(*this)); |
460 | 23 | return; |
461 | 23 | } |
462 | 0 | llvm_unreachable("bad runtime kind"); |
463 | 0 | } |
464 | | |
465 | 0 | void CodeGenModule::createOpenCLRuntime() { |
466 | 0 | OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); |
467 | 0 | } |
468 | | |
469 | 0 | void CodeGenModule::createOpenMPRuntime() { |
470 | | // Select a specialized code generation class based on the target, if any. |
471 | | // If it does not exist use the default implementation. |
472 | 0 | switch (getTriple().getArch()) { |
473 | 0 | case llvm::Triple::nvptx: |
474 | 0 | case llvm::Triple::nvptx64: |
475 | 0 | case llvm::Triple::amdgcn: |
476 | 0 | assert(getLangOpts().OpenMPIsTargetDevice && |
477 | 0 | "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); |
478 | 0 | OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); |
479 | 0 | break; |
480 | 0 | default: |
481 | 0 | if (LangOpts.OpenMPSimd) |
482 | 0 | OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); |
483 | 0 | else |
484 | 0 | OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); |
485 | 0 | break; |
486 | 0 | } |
487 | 0 | } |
488 | | |
489 | 0 | void CodeGenModule::createCUDARuntime() { |
490 | 0 | CUDARuntime.reset(CreateNVCUDARuntime(*this)); |
491 | 0 | } |
492 | | |
493 | 0 | void CodeGenModule::createHLSLRuntime() { |
494 | 0 | HLSLRuntime.reset(new CGHLSLRuntime(*this)); |
495 | 0 | } |
496 | | |
497 | 0 | void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { |
498 | 0 | Replacements[Name] = C; |
499 | 0 | } |
500 | | |
501 | 0 | void CodeGenModule::applyReplacements() { |
502 | 0 | for (auto &I : Replacements) { |
503 | 0 | StringRef MangledName = I.first; |
504 | 0 | llvm::Constant *Replacement = I.second; |
505 | 0 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); |
506 | 0 | if (!Entry) |
507 | 0 | continue; |
508 | 0 | auto *OldF = cast<llvm::Function>(Entry); |
509 | 0 | auto *NewF = dyn_cast<llvm::Function>(Replacement); |
510 | 0 | if (!NewF) { |
511 | 0 | if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { |
512 | 0 | NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); |
513 | 0 | } else { |
514 | 0 | auto *CE = cast<llvm::ConstantExpr>(Replacement); |
515 | 0 | assert(CE->getOpcode() == llvm::Instruction::BitCast || |
516 | 0 | CE->getOpcode() == llvm::Instruction::GetElementPtr); |
517 | 0 | NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); |
518 | 0 | } |
519 | 0 | } |
520 | | |
521 | | // Replace old with new, but keep the old order. |
522 | 0 | OldF->replaceAllUsesWith(Replacement); |
523 | 0 | if (NewF) { |
524 | 0 | NewF->removeFromParent(); |
525 | 0 | OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), |
526 | 0 | NewF); |
527 | 0 | } |
528 | 0 | OldF->eraseFromParent(); |
529 | 0 | } |
530 | 0 | } |
531 | | |
532 | 0 | void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { |
533 | 0 | GlobalValReplacements.push_back(std::make_pair(GV, C)); |
534 | 0 | } |
535 | | |
536 | 0 | void CodeGenModule::applyGlobalValReplacements() { |
537 | 0 | for (auto &I : GlobalValReplacements) { |
538 | 0 | llvm::GlobalValue *GV = I.first; |
539 | 0 | llvm::Constant *C = I.second; |
540 | |
|
541 | 0 | GV->replaceAllUsesWith(C); |
542 | 0 | GV->eraseFromParent(); |
543 | 0 | } |
544 | 0 | } |
545 | | |
546 | | // This is only used in aliases that we created and we know they have a |
547 | | // linear structure. |
548 | 0 | static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { |
549 | 0 | const llvm::Constant *C; |
550 | 0 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) |
551 | 0 | C = GA->getAliasee(); |
552 | 0 | else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) |
553 | 0 | C = GI->getResolver(); |
554 | 0 | else |
555 | 0 | return GV; |
556 | | |
557 | 0 | const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); |
558 | 0 | if (!AliaseeGV) |
559 | 0 | return nullptr; |
560 | | |
561 | 0 | const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); |
562 | 0 | if (FinalGV == GV) |
563 | 0 | return nullptr; |
564 | | |
565 | 0 | return FinalGV; |
566 | 0 | } |
567 | | |
568 | | static bool checkAliasedGlobal( |
569 | | const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, |
570 | | bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, |
571 | | const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames, |
572 | 0 | SourceRange AliasRange) { |
573 | 0 | GV = getAliasedGlobal(Alias); |
574 | 0 | if (!GV) { |
575 | 0 | Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; |
576 | 0 | return false; |
577 | 0 | } |
578 | | |
579 | 0 | if (GV->hasCommonLinkage()) { |
580 | 0 | const llvm::Triple &Triple = Context.getTargetInfo().getTriple(); |
581 | 0 | if (Triple.getObjectFormat() == llvm::Triple::XCOFF) { |
582 | 0 | Diags.Report(Location, diag::err_alias_to_common); |
583 | 0 | return false; |
584 | 0 | } |
585 | 0 | } |
586 | | |
587 | 0 | if (GV->isDeclaration()) { |
588 | 0 | Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; |
589 | 0 | Diags.Report(Location, diag::note_alias_requires_mangled_name) |
590 | 0 | << IsIFunc << IsIFunc; |
591 | | // Provide a note if the given function is not found and exists as a |
592 | | // mangled name. |
593 | 0 | for (const auto &[Decl, Name] : MangledDeclNames) { |
594 | 0 | if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) { |
595 | 0 | if (ND->getName() == GV->getName()) { |
596 | 0 | Diags.Report(Location, diag::note_alias_mangled_name_alternative) |
597 | 0 | << Name |
598 | 0 | << FixItHint::CreateReplacement( |
599 | 0 | AliasRange, |
600 | 0 | (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")") |
601 | 0 | .str()); |
602 | 0 | } |
603 | 0 | } |
604 | 0 | } |
605 | 0 | return false; |
606 | 0 | } |
607 | | |
608 | 0 | if (IsIFunc) { |
609 | | // Check resolver function type. |
610 | 0 | const auto *F = dyn_cast<llvm::Function>(GV); |
611 | 0 | if (!F) { |
612 | 0 | Diags.Report(Location, diag::err_alias_to_undefined) |
613 | 0 | << IsIFunc << IsIFunc; |
614 | 0 | return false; |
615 | 0 | } |
616 | | |
617 | 0 | llvm::FunctionType *FTy = F->getFunctionType(); |
618 | 0 | if (!FTy->getReturnType()->isPointerTy()) { |
619 | 0 | Diags.Report(Location, diag::err_ifunc_resolver_return); |
620 | 0 | return false; |
621 | 0 | } |
622 | 0 | } |
623 | | |
624 | 0 | return true; |
625 | 0 | } |
626 | | |
627 | 0 | void CodeGenModule::checkAliases() { |
628 | | // Check if the constructed aliases are well formed. It is really unfortunate |
629 | | // that we have to do this in CodeGen, but we only construct mangled names |
630 | | // and aliases during codegen. |
631 | 0 | bool Error = false; |
632 | 0 | DiagnosticsEngine &Diags = getDiags(); |
633 | 0 | for (const GlobalDecl &GD : Aliases) { |
634 | 0 | const auto *D = cast<ValueDecl>(GD.getDecl()); |
635 | 0 | SourceLocation Location; |
636 | 0 | SourceRange Range; |
637 | 0 | bool IsIFunc = D->hasAttr<IFuncAttr>(); |
638 | 0 | if (const Attr *A = D->getDefiningAttr()) { |
639 | 0 | Location = A->getLocation(); |
640 | 0 | Range = A->getRange(); |
641 | 0 | } else |
642 | 0 | llvm_unreachable("Not an alias or ifunc?"); |
643 | |
|
644 | 0 | StringRef MangledName = getMangledName(GD); |
645 | 0 | llvm::GlobalValue *Alias = GetGlobalValue(MangledName); |
646 | 0 | const llvm::GlobalValue *GV = nullptr; |
647 | 0 | if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV, |
648 | 0 | MangledDeclNames, Range)) { |
649 | 0 | Error = true; |
650 | 0 | continue; |
651 | 0 | } |
652 | | |
653 | 0 | llvm::Constant *Aliasee = |
654 | 0 | IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() |
655 | 0 | : cast<llvm::GlobalAlias>(Alias)->getAliasee(); |
656 | |
|
657 | 0 | llvm::GlobalValue *AliaseeGV; |
658 | 0 | if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) |
659 | 0 | AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); |
660 | 0 | else |
661 | 0 | AliaseeGV = cast<llvm::GlobalValue>(Aliasee); |
662 | |
|
663 | 0 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { |
664 | 0 | StringRef AliasSection = SA->getName(); |
665 | 0 | if (AliasSection != AliaseeGV->getSection()) |
666 | 0 | Diags.Report(SA->getLocation(), diag::warn_alias_with_section) |
667 | 0 | << AliasSection << IsIFunc << IsIFunc; |
668 | 0 | } |
669 | | |
670 | | // We have to handle alias to weak aliases in here. LLVM itself disallows |
671 | | // this since the object semantics would not match the IL one. For |
672 | | // compatibility with gcc we implement it by just pointing the alias |
673 | | // to its aliasee's aliasee. We also warn, since the user is probably |
674 | | // expecting the link to be weak. |
675 | 0 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { |
676 | 0 | if (GA->isInterposable()) { |
677 | 0 | Diags.Report(Location, diag::warn_alias_to_weak_alias) |
678 | 0 | << GV->getName() << GA->getName() << IsIFunc; |
679 | 0 | Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
680 | 0 | GA->getAliasee(), Alias->getType()); |
681 | |
|
682 | 0 | if (IsIFunc) |
683 | 0 | cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); |
684 | 0 | else |
685 | 0 | cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); |
686 | 0 | } |
687 | 0 | } |
688 | 0 | } |
689 | 0 | if (!Error) |
690 | 0 | return; |
691 | | |
692 | 0 | for (const GlobalDecl &GD : Aliases) { |
693 | 0 | StringRef MangledName = getMangledName(GD); |
694 | 0 | llvm::GlobalValue *Alias = GetGlobalValue(MangledName); |
695 | 0 | Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); |
696 | 0 | Alias->eraseFromParent(); |
697 | 0 | } |
698 | 0 | } |
699 | | |
700 | 46 | void CodeGenModule::clear() { |
701 | 46 | DeferredDeclsToEmit.clear(); |
702 | 46 | EmittedDeferredDecls.clear(); |
703 | 46 | DeferredAnnotations.clear(); |
704 | 46 | if (OpenMPRuntime) |
705 | 0 | OpenMPRuntime->clear(); |
706 | 46 | } |
707 | | |
708 | | void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, |
709 | 0 | StringRef MainFile) { |
710 | 0 | if (!hasDiagnostics()) |
711 | 0 | return; |
712 | 0 | if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { |
713 | 0 | if (MainFile.empty()) |
714 | 0 | MainFile = "<stdin>"; |
715 | 0 | Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; |
716 | 0 | } else { |
717 | 0 | if (Mismatched > 0) |
718 | 0 | Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; |
719 | |
|
720 | 0 | if (Missing > 0) |
721 | 0 | Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; |
722 | 0 | } |
723 | 0 | } |
724 | | |
725 | | static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, |
726 | 0 | llvm::Module &M) { |
727 | 0 | if (!LO.VisibilityFromDLLStorageClass) |
728 | 0 | return; |
729 | | |
730 | 0 | llvm::GlobalValue::VisibilityTypes DLLExportVisibility = |
731 | 0 | CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); |
732 | 0 | llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = |
733 | 0 | CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); |
734 | 0 | llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = |
735 | 0 | CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); |
736 | 0 | llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = |
737 | 0 | CodeGenModule::GetLLVMVisibility( |
738 | 0 | LO.getExternDeclNoDLLStorageClassVisibility()); |
739 | |
|
740 | 0 | for (llvm::GlobalValue &GV : M.global_values()) { |
741 | 0 | if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) |
742 | 0 | continue; |
743 | | |
744 | | // Reset DSO locality before setting the visibility. This removes |
745 | | // any effects that visibility options and annotations may have |
746 | | // had on the DSO locality. Setting the visibility will implicitly set |
747 | | // appropriate globals to DSO Local; however, this will be pessimistic |
748 | | // w.r.t. to the normal compiler IRGen. |
749 | 0 | GV.setDSOLocal(false); |
750 | |
|
751 | 0 | if (GV.isDeclarationForLinker()) { |
752 | 0 | GV.setVisibility(GV.getDLLStorageClass() == |
753 | 0 | llvm::GlobalValue::DLLImportStorageClass |
754 | 0 | ? ExternDeclDLLImportVisibility |
755 | 0 | : ExternDeclNoDLLStorageClassVisibility); |
756 | 0 | } else { |
757 | 0 | GV.setVisibility(GV.getDLLStorageClass() == |
758 | 0 | llvm::GlobalValue::DLLExportStorageClass |
759 | 0 | ? DLLExportVisibility |
760 | 0 | : NoDLLStorageClassVisibility); |
761 | 0 | } |
762 | |
|
763 | 0 | GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
764 | 0 | } |
765 | 0 | } |
766 | | |
767 | | static bool isStackProtectorOn(const LangOptions &LangOpts, |
768 | | const llvm::Triple &Triple, |
769 | 0 | clang::LangOptions::StackProtectorMode Mode) { |
770 | 0 | if (Triple.isAMDGPU() || Triple.isNVPTX()) |
771 | 0 | return false; |
772 | 0 | return LangOpts.getStackProtector() == Mode; |
773 | 0 | } |
774 | | |
775 | 0 | void CodeGenModule::Release() { |
776 | 0 | Module *Primary = getContext().getCurrentNamedModule(); |
777 | 0 | if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) |
778 | 0 | EmitModuleInitializers(Primary); |
779 | 0 | EmitDeferred(); |
780 | 0 | DeferredDecls.insert(EmittedDeferredDecls.begin(), |
781 | 0 | EmittedDeferredDecls.end()); |
782 | 0 | EmittedDeferredDecls.clear(); |
783 | 0 | EmitVTablesOpportunistically(); |
784 | 0 | applyGlobalValReplacements(); |
785 | 0 | applyReplacements(); |
786 | 0 | emitMultiVersionFunctions(); |
787 | |
|
788 | 0 | if (Context.getLangOpts().IncrementalExtensions && |
789 | 0 | GlobalTopLevelStmtBlockInFlight.first) { |
790 | 0 | const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; |
791 | 0 | GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc()); |
792 | 0 | GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; |
793 | 0 | } |
794 | | |
795 | | // Module implementations are initialized the same way as a regular TU that |
796 | | // imports one or more modules. |
797 | 0 | if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) |
798 | 0 | EmitCXXModuleInitFunc(Primary); |
799 | 0 | else |
800 | 0 | EmitCXXGlobalInitFunc(); |
801 | 0 | EmitCXXGlobalCleanUpFunc(); |
802 | 0 | registerGlobalDtorsWithAtExit(); |
803 | 0 | EmitCXXThreadLocalInitFunc(); |
804 | 0 | if (ObjCRuntime) |
805 | 0 | if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) |
806 | 0 | AddGlobalCtor(ObjCInitFunction); |
807 | 0 | if (Context.getLangOpts().CUDA && CUDARuntime) { |
808 | 0 | if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) |
809 | 0 | AddGlobalCtor(CudaCtorFunction); |
810 | 0 | } |
811 | 0 | if (OpenMPRuntime) { |
812 | 0 | if (llvm::Function *OpenMPRequiresDirectiveRegFun = |
813 | 0 | OpenMPRuntime->emitRequiresDirectiveRegFun()) { |
814 | 0 | AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); |
815 | 0 | } |
816 | 0 | OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); |
817 | 0 | OpenMPRuntime->clear(); |
818 | 0 | } |
819 | 0 | if (PGOReader) { |
820 | 0 | getModule().setProfileSummary( |
821 | 0 | PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), |
822 | 0 | llvm::ProfileSummary::PSK_Instr); |
823 | 0 | if (PGOStats.hasDiagnostics()) |
824 | 0 | PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); |
825 | 0 | } |
826 | 0 | llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) { |
827 | 0 | return L.LexOrder < R.LexOrder; |
828 | 0 | }); |
829 | 0 | EmitCtorList(GlobalCtors, "llvm.global_ctors"); |
830 | 0 | EmitCtorList(GlobalDtors, "llvm.global_dtors"); |
831 | 0 | EmitGlobalAnnotations(); |
832 | 0 | EmitStaticExternCAliases(); |
833 | 0 | checkAliases(); |
834 | 0 | EmitDeferredUnusedCoverageMappings(); |
835 | 0 | CodeGenPGO(*this).setValueProfilingFlag(getModule()); |
836 | 0 | if (CoverageMapping) |
837 | 0 | CoverageMapping->emit(); |
838 | 0 | if (CodeGenOpts.SanitizeCfiCrossDso) { |
839 | 0 | CodeGenFunction(*this).EmitCfiCheckFail(); |
840 | 0 | CodeGenFunction(*this).EmitCfiCheckStub(); |
841 | 0 | } |
842 | 0 | if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) |
843 | 0 | finalizeKCFITypes(); |
844 | 0 | emitAtAvailableLinkGuard(); |
845 | 0 | if (Context.getTargetInfo().getTriple().isWasm()) |
846 | 0 | EmitMainVoidAlias(); |
847 | |
|
848 | 0 | if (getTriple().isAMDGPU()) { |
849 | | // Emit amdgpu_code_object_version module flag, which is code object version |
850 | | // times 100. |
851 | 0 | if (getTarget().getTargetOpts().CodeObjectVersion != |
852 | 0 | llvm::CodeObjectVersionKind::COV_None) { |
853 | 0 | getModule().addModuleFlag(llvm::Module::Error, |
854 | 0 | "amdgpu_code_object_version", |
855 | 0 | getTarget().getTargetOpts().CodeObjectVersion); |
856 | 0 | } |
857 | | |
858 | | // Currently, "-mprintf-kind" option is only supported for HIP |
859 | 0 | if (LangOpts.HIP) { |
860 | 0 | auto *MDStr = llvm::MDString::get( |
861 | 0 | getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal == |
862 | 0 | TargetOptions::AMDGPUPrintfKind::Hostcall) |
863 | 0 | ? "hostcall" |
864 | 0 | : "buffered"); |
865 | 0 | getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind", |
866 | 0 | MDStr); |
867 | 0 | } |
868 | 0 | } |
869 | | |
870 | | // Emit a global array containing all external kernels or device variables |
871 | | // used by host functions and mark it as used for CUDA/HIP. This is necessary |
872 | | // to get kernels or device variables in archives linked in even if these |
873 | | // kernels or device variables are only used in host functions. |
874 | 0 | if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { |
875 | 0 | SmallVector<llvm::Constant *, 8> UsedArray; |
876 | 0 | for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { |
877 | 0 | GlobalDecl GD; |
878 | 0 | if (auto *FD = dyn_cast<FunctionDecl>(D)) |
879 | 0 | GD = GlobalDecl(FD, KernelReferenceKind::Kernel); |
880 | 0 | else |
881 | 0 | GD = GlobalDecl(D); |
882 | 0 | UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
883 | 0 | GetAddrOfGlobal(GD), Int8PtrTy)); |
884 | 0 | } |
885 | |
|
886 | 0 | llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); |
887 | |
|
888 | 0 | auto *GV = new llvm::GlobalVariable( |
889 | 0 | getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, |
890 | 0 | llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); |
891 | 0 | addCompilerUsedGlobal(GV); |
892 | 0 | } |
893 | |
|
894 | 0 | emitLLVMUsed(); |
895 | 0 | if (SanStats) |
896 | 0 | SanStats->finish(); |
897 | |
|
898 | 0 | if (CodeGenOpts.Autolink && |
899 | 0 | (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { |
900 | 0 | EmitModuleLinkOptions(); |
901 | 0 | } |
902 | | |
903 | | // On ELF we pass the dependent library specifiers directly to the linker |
904 | | // without manipulating them. This is in contrast to other platforms where |
905 | | // they are mapped to a specific linker option by the compiler. This |
906 | | // difference is a result of the greater variety of ELF linkers and the fact |
907 | | // that ELF linkers tend to handle libraries in a more complicated fashion |
908 | | // than on other platforms. This forces us to defer handling the dependent |
909 | | // libs to the linker. |
910 | | // |
911 | | // CUDA/HIP device and host libraries are different. Currently there is no |
912 | | // way to differentiate dependent libraries for host or device. Existing |
913 | | // usage of #pragma comment(lib, *) is intended for host libraries on |
914 | | // Windows. Therefore emit llvm.dependent-libraries only for host. |
915 | 0 | if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { |
916 | 0 | auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); |
917 | 0 | for (auto *MD : ELFDependentLibraries) |
918 | 0 | NMD->addOperand(MD); |
919 | 0 | } |
920 | | |
921 | | // Record mregparm value now so it is visible through rest of codegen. |
922 | 0 | if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) |
923 | 0 | getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", |
924 | 0 | CodeGenOpts.NumRegisterParameters); |
925 | |
|
926 | 0 | if (CodeGenOpts.DwarfVersion) { |
927 | 0 | getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", |
928 | 0 | CodeGenOpts.DwarfVersion); |
929 | 0 | } |
930 | |
|
931 | 0 | if (CodeGenOpts.Dwarf64) |
932 | 0 | getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); |
933 | |
|
934 | 0 | if (Context.getLangOpts().SemanticInterposition) |
935 | | // Require various optimization to respect semantic interposition. |
936 | 0 | getModule().setSemanticInterposition(true); |
937 | |
|
938 | 0 | if (CodeGenOpts.EmitCodeView) { |
939 | | // Indicate that we want CodeView in the metadata. |
940 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); |
941 | 0 | } |
942 | 0 | if (CodeGenOpts.CodeViewGHash) { |
943 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); |
944 | 0 | } |
945 | 0 | if (CodeGenOpts.ControlFlowGuard) { |
946 | | // Function ID tables and checks for Control Flow Guard (cfguard=2). |
947 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); |
948 | 0 | } else if (CodeGenOpts.ControlFlowGuardNoChecks) { |
949 | | // Function ID tables for Control Flow Guard (cfguard=1). |
950 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); |
951 | 0 | } |
952 | 0 | if (CodeGenOpts.EHContGuard) { |
953 | | // Function ID tables for EH Continuation Guard. |
954 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); |
955 | 0 | } |
956 | 0 | if (Context.getLangOpts().Kernel) { |
957 | | // Note if we are compiling with /kernel. |
958 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1); |
959 | 0 | } |
960 | 0 | if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { |
961 | | // We don't support LTO with 2 with different StrictVTablePointers |
962 | | // FIXME: we could support it by stripping all the information introduced |
963 | | // by StrictVTablePointers. |
964 | |
|
965 | 0 | getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); |
966 | |
|
967 | 0 | llvm::Metadata *Ops[2] = { |
968 | 0 | llvm::MDString::get(VMContext, "StrictVTablePointers"), |
969 | 0 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( |
970 | 0 | llvm::Type::getInt32Ty(VMContext), 1))}; |
971 | |
|
972 | 0 | getModule().addModuleFlag(llvm::Module::Require, |
973 | 0 | "StrictVTablePointersRequirement", |
974 | 0 | llvm::MDNode::get(VMContext, Ops)); |
975 | 0 | } |
976 | 0 | if (getModuleDebugInfo()) |
977 | | // We support a single version in the linked module. The LLVM |
978 | | // parser will drop debug info with a different version number |
979 | | // (and warn about it, too). |
980 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", |
981 | 0 | llvm::DEBUG_METADATA_VERSION); |
982 | | |
983 | | // We need to record the widths of enums and wchar_t, so that we can generate |
984 | | // the correct build attributes in the ARM backend. wchar_size is also used by |
985 | | // TargetLibraryInfo. |
986 | 0 | uint64_t WCharWidth = |
987 | 0 | Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); |
988 | 0 | getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); |
989 | |
|
990 | 0 | if (getTriple().isOSzOS()) { |
991 | 0 | getModule().addModuleFlag(llvm::Module::Warning, |
992 | 0 | "zos_product_major_version", |
993 | 0 | uint32_t(CLANG_VERSION_MAJOR)); |
994 | 0 | getModule().addModuleFlag(llvm::Module::Warning, |
995 | 0 | "zos_product_minor_version", |
996 | 0 | uint32_t(CLANG_VERSION_MINOR)); |
997 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel", |
998 | 0 | uint32_t(CLANG_VERSION_PATCHLEVEL)); |
999 | 0 | std::string ProductId = getClangVendor() + "clang"; |
1000 | 0 | getModule().addModuleFlag(llvm::Module::Error, "zos_product_id", |
1001 | 0 | llvm::MDString::get(VMContext, ProductId)); |
1002 | | |
1003 | | // Record the language because we need it for the PPA2. |
1004 | 0 | StringRef lang_str = languageToString( |
1005 | 0 | LangStandard::getLangStandardForKind(LangOpts.LangStd).Language); |
1006 | 0 | getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language", |
1007 | 0 | llvm::MDString::get(VMContext, lang_str)); |
1008 | |
|
1009 | 0 | time_t TT = PreprocessorOpts.SourceDateEpoch |
1010 | 0 | ? *PreprocessorOpts.SourceDateEpoch |
1011 | 0 | : std::time(nullptr); |
1012 | 0 | getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time", |
1013 | 0 | static_cast<uint64_t>(TT)); |
1014 | | |
1015 | | // Multiple modes will be supported here. |
1016 | 0 | getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode", |
1017 | 0 | llvm::MDString::get(VMContext, "ascii")); |
1018 | 0 | } |
1019 | |
|
1020 | 0 | llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); |
1021 | 0 | if ( Arch == llvm::Triple::arm |
1022 | 0 | || Arch == llvm::Triple::armeb |
1023 | 0 | || Arch == llvm::Triple::thumb |
1024 | 0 | || Arch == llvm::Triple::thumbeb) { |
1025 | | // The minimum width of an enum in bytes |
1026 | 0 | uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; |
1027 | 0 | getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); |
1028 | 0 | } |
1029 | |
|
1030 | 0 | if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { |
1031 | 0 | StringRef ABIStr = Target.getABI(); |
1032 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1033 | 0 | getModule().addModuleFlag(llvm::Module::Error, "target-abi", |
1034 | 0 | llvm::MDString::get(Ctx, ABIStr)); |
1035 | 0 | } |
1036 | |
|
1037 | 0 | if (CodeGenOpts.SanitizeCfiCrossDso) { |
1038 | | // Indicate that we want cross-DSO control flow integrity checks. |
1039 | 0 | getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); |
1040 | 0 | } |
1041 | |
|
1042 | 0 | if (CodeGenOpts.WholeProgramVTables) { |
1043 | | // Indicate whether VFE was enabled for this module, so that the |
1044 | | // vcall_visibility metadata added under whole program vtables is handled |
1045 | | // appropriately in the optimizer. |
1046 | 0 | getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", |
1047 | 0 | CodeGenOpts.VirtualFunctionElimination); |
1048 | 0 | } |
1049 | |
|
1050 | 0 | if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { |
1051 | 0 | getModule().addModuleFlag(llvm::Module::Override, |
1052 | 0 | "CFI Canonical Jump Tables", |
1053 | 0 | CodeGenOpts.SanitizeCfiCanonicalJumpTables); |
1054 | 0 | } |
1055 | |
|
1056 | 0 | if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) { |
1057 | 0 | getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1); |
1058 | | // KCFI assumes patchable-function-prefix is the same for all indirectly |
1059 | | // called functions. Store the expected offset for code generation. |
1060 | 0 | if (CodeGenOpts.PatchableFunctionEntryOffset) |
1061 | 0 | getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset", |
1062 | 0 | CodeGenOpts.PatchableFunctionEntryOffset); |
1063 | 0 | } |
1064 | |
|
1065 | 0 | if (CodeGenOpts.CFProtectionReturn && |
1066 | 0 | Target.checkCFProtectionReturnSupported(getDiags())) { |
1067 | | // Indicate that we want to instrument return control flow protection. |
1068 | 0 | getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return", |
1069 | 0 | 1); |
1070 | 0 | } |
1071 | |
|
1072 | 0 | if (CodeGenOpts.CFProtectionBranch && |
1073 | 0 | Target.checkCFProtectionBranchSupported(getDiags())) { |
1074 | | // Indicate that we want to instrument branch control flow protection. |
1075 | 0 | getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch", |
1076 | 0 | 1); |
1077 | 0 | } |
1078 | |
|
1079 | 0 | if (CodeGenOpts.FunctionReturnThunks) |
1080 | 0 | getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1); |
1081 | |
|
1082 | 0 | if (CodeGenOpts.IndirectBranchCSPrefix) |
1083 | 0 | getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1); |
1084 | | |
1085 | | // Add module metadata for return address signing (ignoring |
1086 | | // non-leaf/all) and stack tagging. These are actually turned on by function |
1087 | | // attributes, but we use module metadata to emit build attributes. This is |
1088 | | // needed for LTO, where the function attributes are inside bitcode |
1089 | | // serialised into a global variable by the time build attributes are |
1090 | | // emitted, so we can't access them. LTO objects could be compiled with |
1091 | | // different flags therefore module flags are set to "Min" behavior to achieve |
1092 | | // the same end result of the normal build where e.g BTI is off if any object |
1093 | | // doesn't support it. |
1094 | 0 | if (Context.getTargetInfo().hasFeature("ptrauth") && |
1095 | 0 | LangOpts.getSignReturnAddressScope() != |
1096 | 0 | LangOptions::SignReturnAddressScopeKind::None) |
1097 | 0 | getModule().addModuleFlag(llvm::Module::Override, |
1098 | 0 | "sign-return-address-buildattr", 1); |
1099 | 0 | if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack)) |
1100 | 0 | getModule().addModuleFlag(llvm::Module::Override, |
1101 | 0 | "tag-stack-memory-buildattr", 1); |
1102 | |
|
1103 | 0 | if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || |
1104 | 0 | Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || |
1105 | 0 | Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || |
1106 | 0 | Arch == llvm::Triple::aarch64_be) { |
1107 | 0 | if (LangOpts.BranchTargetEnforcement) |
1108 | 0 | getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement", |
1109 | 0 | 1); |
1110 | 0 | if (LangOpts.BranchProtectionPAuthLR) |
1111 | 0 | getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr", |
1112 | 0 | 1); |
1113 | 0 | if (LangOpts.GuardedControlStack) |
1114 | 0 | getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1); |
1115 | 0 | if (LangOpts.hasSignReturnAddress()) |
1116 | 0 | getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1); |
1117 | 0 | if (LangOpts.isSignReturnAddressScopeAll()) |
1118 | 0 | getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all", |
1119 | 0 | 1); |
1120 | 0 | if (!LangOpts.isSignReturnAddressWithAKey()) |
1121 | 0 | getModule().addModuleFlag(llvm::Module::Min, |
1122 | 0 | "sign-return-address-with-bkey", 1); |
1123 | 0 | } |
1124 | |
|
1125 | 0 | if (CodeGenOpts.StackClashProtector) |
1126 | 0 | getModule().addModuleFlag( |
1127 | 0 | llvm::Module::Override, "probe-stack", |
1128 | 0 | llvm::MDString::get(TheModule.getContext(), "inline-asm")); |
1129 | |
|
1130 | 0 | if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) |
1131 | 0 | getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size", |
1132 | 0 | CodeGenOpts.StackProbeSize); |
1133 | |
|
1134 | 0 | if (!CodeGenOpts.MemoryProfileOutput.empty()) { |
1135 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1136 | 0 | getModule().addModuleFlag( |
1137 | 0 | llvm::Module::Error, "MemProfProfileFilename", |
1138 | 0 | llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); |
1139 | 0 | } |
1140 | |
|
1141 | 0 | if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { |
1142 | | // Indicate whether __nvvm_reflect should be configured to flush denormal |
1143 | | // floating point values to 0. (This corresponds to its "__CUDA_FTZ" |
1144 | | // property.) |
1145 | 0 | getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", |
1146 | 0 | CodeGenOpts.FP32DenormalMode.Output != |
1147 | 0 | llvm::DenormalMode::IEEE); |
1148 | 0 | } |
1149 | |
|
1150 | 0 | if (LangOpts.EHAsynch) |
1151 | 0 | getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); |
1152 | | |
1153 | | // Indicate whether this Module was compiled with -fopenmp |
1154 | 0 | if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) |
1155 | 0 | getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); |
1156 | 0 | if (getLangOpts().OpenMPIsTargetDevice) |
1157 | 0 | getModule().addModuleFlag(llvm::Module::Max, "openmp-device", |
1158 | 0 | LangOpts.OpenMP); |
1159 | | |
1160 | | // Emit OpenCL specific module metadata: OpenCL/SPIR version. |
1161 | 0 | if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { |
1162 | 0 | EmitOpenCLMetadata(); |
1163 | | // Emit SPIR version. |
1164 | 0 | if (getTriple().isSPIR()) { |
1165 | | // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the |
1166 | | // opencl.spir.version named metadata. |
1167 | | // C++ for OpenCL has a distinct mapping for version compatibility with |
1168 | | // OpenCL. |
1169 | 0 | auto Version = LangOpts.getOpenCLCompatibleVersion(); |
1170 | 0 | llvm::Metadata *SPIRVerElts[] = { |
1171 | 0 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( |
1172 | 0 | Int32Ty, Version / 100)), |
1173 | 0 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( |
1174 | 0 | Int32Ty, (Version / 100 > 1) ? 0 : 2))}; |
1175 | 0 | llvm::NamedMDNode *SPIRVerMD = |
1176 | 0 | TheModule.getOrInsertNamedMetadata("opencl.spir.version"); |
1177 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1178 | 0 | SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); |
1179 | 0 | } |
1180 | 0 | } |
1181 | | |
1182 | | // HLSL related end of code gen work items. |
1183 | 0 | if (LangOpts.HLSL) |
1184 | 0 | getHLSLRuntime().finishCodeGen(); |
1185 | |
|
1186 | 0 | if (uint32_t PLevel = Context.getLangOpts().PICLevel) { |
1187 | 0 | assert(PLevel < 3 && "Invalid PIC Level"); |
1188 | 0 | getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); |
1189 | 0 | if (Context.getLangOpts().PIE) |
1190 | 0 | getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); |
1191 | 0 | } |
1192 | | |
1193 | 0 | if (getCodeGenOpts().CodeModel.size() > 0) { |
1194 | 0 | unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) |
1195 | 0 | .Case("tiny", llvm::CodeModel::Tiny) |
1196 | 0 | .Case("small", llvm::CodeModel::Small) |
1197 | 0 | .Case("kernel", llvm::CodeModel::Kernel) |
1198 | 0 | .Case("medium", llvm::CodeModel::Medium) |
1199 | 0 | .Case("large", llvm::CodeModel::Large) |
1200 | 0 | .Default(~0u); |
1201 | 0 | if (CM != ~0u) { |
1202 | 0 | llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); |
1203 | 0 | getModule().setCodeModel(codeModel); |
1204 | |
|
1205 | 0 | if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) && |
1206 | 0 | Context.getTargetInfo().getTriple().getArch() == |
1207 | 0 | llvm::Triple::x86_64) { |
1208 | 0 | getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold); |
1209 | 0 | } |
1210 | 0 | } |
1211 | 0 | } |
1212 | |
|
1213 | 0 | if (CodeGenOpts.NoPLT) |
1214 | 0 | getModule().setRtLibUseGOT(); |
1215 | 0 | if (getTriple().isOSBinFormatELF() && |
1216 | 0 | CodeGenOpts.DirectAccessExternalData != |
1217 | 0 | getModule().getDirectAccessExternalData()) { |
1218 | 0 | getModule().setDirectAccessExternalData( |
1219 | 0 | CodeGenOpts.DirectAccessExternalData); |
1220 | 0 | } |
1221 | 0 | if (CodeGenOpts.UnwindTables) |
1222 | 0 | getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); |
1223 | |
|
1224 | 0 | switch (CodeGenOpts.getFramePointer()) { |
1225 | 0 | case CodeGenOptions::FramePointerKind::None: |
1226 | | // 0 ("none") is the default. |
1227 | 0 | break; |
1228 | 0 | case CodeGenOptions::FramePointerKind::NonLeaf: |
1229 | 0 | getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); |
1230 | 0 | break; |
1231 | 0 | case CodeGenOptions::FramePointerKind::All: |
1232 | 0 | getModule().setFramePointer(llvm::FramePointerKind::All); |
1233 | 0 | break; |
1234 | 0 | } |
1235 | | |
1236 | 0 | SimplifyPersonality(); |
1237 | |
|
1238 | 0 | if (getCodeGenOpts().EmitDeclMetadata) |
1239 | 0 | EmitDeclMetadata(); |
1240 | |
|
1241 | 0 | if (getCodeGenOpts().CoverageNotesFile.size() || |
1242 | 0 | getCodeGenOpts().CoverageDataFile.size()) |
1243 | 0 | EmitCoverageFile(); |
1244 | |
|
1245 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
1246 | 0 | DI->finalize(); |
1247 | |
|
1248 | 0 | if (getCodeGenOpts().EmitVersionIdentMetadata) |
1249 | 0 | EmitVersionIdentMetadata(); |
1250 | |
|
1251 | 0 | if (!getCodeGenOpts().RecordCommandLine.empty()) |
1252 | 0 | EmitCommandLineMetadata(); |
1253 | |
|
1254 | 0 | if (!getCodeGenOpts().StackProtectorGuard.empty()) |
1255 | 0 | getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); |
1256 | 0 | if (!getCodeGenOpts().StackProtectorGuardReg.empty()) |
1257 | 0 | getModule().setStackProtectorGuardReg( |
1258 | 0 | getCodeGenOpts().StackProtectorGuardReg); |
1259 | 0 | if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) |
1260 | 0 | getModule().setStackProtectorGuardSymbol( |
1261 | 0 | getCodeGenOpts().StackProtectorGuardSymbol); |
1262 | 0 | if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) |
1263 | 0 | getModule().setStackProtectorGuardOffset( |
1264 | 0 | getCodeGenOpts().StackProtectorGuardOffset); |
1265 | 0 | if (getCodeGenOpts().StackAlignment) |
1266 | 0 | getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); |
1267 | 0 | if (getCodeGenOpts().SkipRaxSetup) |
1268 | 0 | getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); |
1269 | 0 | if (getLangOpts().RegCall4) |
1270 | 0 | getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1); |
1271 | |
|
1272 | 0 | if (getContext().getTargetInfo().getMaxTLSAlign()) |
1273 | 0 | getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign", |
1274 | 0 | getContext().getTargetInfo().getMaxTLSAlign()); |
1275 | |
|
1276 | 0 | getTargetCodeGenInfo().emitTargetGlobals(*this); |
1277 | |
|
1278 | 0 | getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); |
1279 | |
|
1280 | 0 | EmitBackendOptionsMetadata(getCodeGenOpts()); |
1281 | | |
1282 | | // If there is device offloading code embed it in the host now. |
1283 | 0 | EmbedObject(&getModule(), CodeGenOpts, getDiags()); |
1284 | | |
1285 | | // Set visibility from DLL storage class |
1286 | | // We do this at the end of LLVM IR generation; after any operation |
1287 | | // that might affect the DLL storage class or the visibility, and |
1288 | | // before anything that might act on these. |
1289 | 0 | setVisibilityFromDLLStorageClass(LangOpts, getModule()); |
1290 | 0 | } |
1291 | | |
1292 | 0 | void CodeGenModule::EmitOpenCLMetadata() { |
1293 | | // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the |
1294 | | // opencl.ocl.version named metadata node. |
1295 | | // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. |
1296 | 0 | auto Version = LangOpts.getOpenCLCompatibleVersion(); |
1297 | 0 | llvm::Metadata *OCLVerElts[] = { |
1298 | 0 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( |
1299 | 0 | Int32Ty, Version / 100)), |
1300 | 0 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( |
1301 | 0 | Int32Ty, (Version % 100) / 10))}; |
1302 | 0 | llvm::NamedMDNode *OCLVerMD = |
1303 | 0 | TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); |
1304 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1305 | 0 | OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); |
1306 | 0 | } |
1307 | | |
1308 | | void CodeGenModule::EmitBackendOptionsMetadata( |
1309 | 0 | const CodeGenOptions &CodeGenOpts) { |
1310 | 0 | if (getTriple().isRISCV()) { |
1311 | 0 | getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit", |
1312 | 0 | CodeGenOpts.SmallDataLimit); |
1313 | 0 | } |
1314 | 0 | } |
1315 | | |
1316 | 0 | void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { |
1317 | | // Make sure that this type is translated. |
1318 | 0 | Types.UpdateCompletedType(TD); |
1319 | 0 | } |
1320 | | |
1321 | 0 | void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { |
1322 | | // Make sure that this type is translated. |
1323 | 0 | Types.RefreshTypeCacheForClass(RD); |
1324 | 0 | } |
1325 | | |
1326 | 0 | llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { |
1327 | 0 | if (!TBAA) |
1328 | 0 | return nullptr; |
1329 | 0 | return TBAA->getTypeInfo(QTy); |
1330 | 0 | } |
1331 | | |
1332 | 0 | TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { |
1333 | 0 | if (!TBAA) |
1334 | 0 | return TBAAAccessInfo(); |
1335 | 0 | if (getLangOpts().CUDAIsDevice) { |
1336 | | // As CUDA builtin surface/texture types are replaced, skip generating TBAA |
1337 | | // access info. |
1338 | 0 | if (AccessType->isCUDADeviceBuiltinSurfaceType()) { |
1339 | 0 | if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != |
1340 | 0 | nullptr) |
1341 | 0 | return TBAAAccessInfo(); |
1342 | 0 | } else if (AccessType->isCUDADeviceBuiltinTextureType()) { |
1343 | 0 | if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != |
1344 | 0 | nullptr) |
1345 | 0 | return TBAAAccessInfo(); |
1346 | 0 | } |
1347 | 0 | } |
1348 | 0 | return TBAA->getAccessInfo(AccessType); |
1349 | 0 | } |
1350 | | |
1351 | | TBAAAccessInfo |
1352 | 0 | CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { |
1353 | 0 | if (!TBAA) |
1354 | 0 | return TBAAAccessInfo(); |
1355 | 0 | return TBAA->getVTablePtrAccessInfo(VTablePtrType); |
1356 | 0 | } |
1357 | | |
1358 | 0 | llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { |
1359 | 0 | if (!TBAA) |
1360 | 0 | return nullptr; |
1361 | 0 | return TBAA->getTBAAStructInfo(QTy); |
1362 | 0 | } |
1363 | | |
1364 | 0 | llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { |
1365 | 0 | if (!TBAA) |
1366 | 0 | return nullptr; |
1367 | 0 | return TBAA->getBaseTypeInfo(QTy); |
1368 | 0 | } |
1369 | | |
1370 | 0 | llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { |
1371 | 0 | if (!TBAA) |
1372 | 0 | return nullptr; |
1373 | 0 | return TBAA->getAccessTagInfo(Info); |
1374 | 0 | } |
1375 | | |
1376 | | TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, |
1377 | 0 | TBAAAccessInfo TargetInfo) { |
1378 | 0 | if (!TBAA) |
1379 | 0 | return TBAAAccessInfo(); |
1380 | 0 | return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); |
1381 | 0 | } |
1382 | | |
1383 | | TBAAAccessInfo |
1384 | | CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, |
1385 | 0 | TBAAAccessInfo InfoB) { |
1386 | 0 | if (!TBAA) |
1387 | 0 | return TBAAAccessInfo(); |
1388 | 0 | return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); |
1389 | 0 | } |
1390 | | |
1391 | | TBAAAccessInfo |
1392 | | CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, |
1393 | 0 | TBAAAccessInfo SrcInfo) { |
1394 | 0 | if (!TBAA) |
1395 | 0 | return TBAAAccessInfo(); |
1396 | 0 | return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); |
1397 | 0 | } |
1398 | | |
1399 | | void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, |
1400 | 0 | TBAAAccessInfo TBAAInfo) { |
1401 | 0 | if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) |
1402 | 0 | Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); |
1403 | 0 | } |
1404 | | |
1405 | | void CodeGenModule::DecorateInstructionWithInvariantGroup( |
1406 | 0 | llvm::Instruction *I, const CXXRecordDecl *RD) { |
1407 | 0 | I->setMetadata(llvm::LLVMContext::MD_invariant_group, |
1408 | 0 | llvm::MDNode::get(getLLVMContext(), {})); |
1409 | 0 | } |
1410 | | |
1411 | 0 | void CodeGenModule::Error(SourceLocation loc, StringRef message) { |
1412 | 0 | unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); |
1413 | 0 | getDiags().Report(Context.getFullLoc(loc), diagID) << message; |
1414 | 0 | } |
1415 | | |
1416 | | /// ErrorUnsupported - Print out an error that codegen doesn't support the |
1417 | | /// specified stmt yet. |
1418 | 0 | void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { |
1419 | 0 | unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, |
1420 | 0 | "cannot compile this %0 yet"); |
1421 | 0 | std::string Msg = Type; |
1422 | 0 | getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) |
1423 | 0 | << Msg << S->getSourceRange(); |
1424 | 0 | } |
1425 | | |
1426 | | /// ErrorUnsupported - Print out an error that codegen doesn't support the |
1427 | | /// specified decl yet. |
1428 | 0 | void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { |
1429 | 0 | unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, |
1430 | 0 | "cannot compile this %0 yet"); |
1431 | 0 | std::string Msg = Type; |
1432 | 0 | getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; |
1433 | 0 | } |
1434 | | |
1435 | 0 | llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { |
1436 | 0 | return llvm::ConstantInt::get(SizeTy, size.getQuantity()); |
1437 | 0 | } |
1438 | | |
1439 | | void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, |
1440 | 0 | const NamedDecl *D) const { |
1441 | | // Internal definitions always have default visibility. |
1442 | 0 | if (GV->hasLocalLinkage()) { |
1443 | 0 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); |
1444 | 0 | return; |
1445 | 0 | } |
1446 | 0 | if (!D) |
1447 | 0 | return; |
1448 | | |
1449 | | // Set visibility for definitions, and for declarations if requested globally |
1450 | | // or set explicitly. |
1451 | 0 | LinkageInfo LV = D->getLinkageAndVisibility(); |
1452 | | |
1453 | | // OpenMP declare target variables must be visible to the host so they can |
1454 | | // be registered. We require protected visibility unless the variable has |
1455 | | // the DT_nohost modifier and does not need to be registered. |
1456 | 0 | if (Context.getLangOpts().OpenMP && |
1457 | 0 | Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) && |
1458 | 0 | D->hasAttr<OMPDeclareTargetDeclAttr>() && |
1459 | 0 | D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() != |
1460 | 0 | OMPDeclareTargetDeclAttr::DT_NoHost && |
1461 | 0 | LV.getVisibility() == HiddenVisibility) { |
1462 | 0 | GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); |
1463 | 0 | return; |
1464 | 0 | } |
1465 | | |
1466 | 0 | if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { |
1467 | | // Reject incompatible dlllstorage and visibility annotations. |
1468 | 0 | if (!LV.isVisibilityExplicit()) |
1469 | 0 | return; |
1470 | 0 | if (GV->hasDLLExportStorageClass()) { |
1471 | 0 | if (LV.getVisibility() == HiddenVisibility) |
1472 | 0 | getDiags().Report(D->getLocation(), |
1473 | 0 | diag::err_hidden_visibility_dllexport); |
1474 | 0 | } else if (LV.getVisibility() != DefaultVisibility) { |
1475 | 0 | getDiags().Report(D->getLocation(), |
1476 | 0 | diag::err_non_default_visibility_dllimport); |
1477 | 0 | } |
1478 | 0 | return; |
1479 | 0 | } |
1480 | | |
1481 | 0 | if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || |
1482 | 0 | !GV->isDeclarationForLinker()) |
1483 | 0 | GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); |
1484 | 0 | } |
1485 | | |
1486 | | static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, |
1487 | 0 | llvm::GlobalValue *GV) { |
1488 | 0 | if (GV->hasLocalLinkage()) |
1489 | 0 | return true; |
1490 | | |
1491 | 0 | if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) |
1492 | 0 | return true; |
1493 | | |
1494 | | // DLLImport explicitly marks the GV as external. |
1495 | 0 | if (GV->hasDLLImportStorageClass()) |
1496 | 0 | return false; |
1497 | | |
1498 | 0 | const llvm::Triple &TT = CGM.getTriple(); |
1499 | 0 | const auto &CGOpts = CGM.getCodeGenOpts(); |
1500 | 0 | if (TT.isWindowsGNUEnvironment()) { |
1501 | | // In MinGW, variables without DLLImport can still be automatically |
1502 | | // imported from a DLL by the linker; don't mark variables that |
1503 | | // potentially could come from another DLL as DSO local. |
1504 | | |
1505 | | // With EmulatedTLS, TLS variables can be autoimported from other DLLs |
1506 | | // (and this actually happens in the public interface of libstdc++), so |
1507 | | // such variables can't be marked as DSO local. (Native TLS variables |
1508 | | // can't be dllimported at all, though.) |
1509 | 0 | if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && |
1510 | 0 | (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) && |
1511 | 0 | CGOpts.AutoImport) |
1512 | 0 | return false; |
1513 | 0 | } |
1514 | | |
1515 | | // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols |
1516 | | // remain unresolved in the link, they can be resolved to zero, which is |
1517 | | // outside the current DSO. |
1518 | 0 | if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) |
1519 | 0 | return false; |
1520 | | |
1521 | | // Every other GV is local on COFF. |
1522 | | // Make an exception for windows OS in the triple: Some firmware builds use |
1523 | | // *-win32-macho triples. This (accidentally?) produced windows relocations |
1524 | | // without GOT tables in older clang versions; Keep this behaviour. |
1525 | | // FIXME: even thread local variables? |
1526 | 0 | if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) |
1527 | 0 | return true; |
1528 | | |
1529 | | // Only handle COFF and ELF for now. |
1530 | 0 | if (!TT.isOSBinFormatELF()) |
1531 | 0 | return false; |
1532 | | |
1533 | | // If this is not an executable, don't assume anything is local. |
1534 | 0 | llvm::Reloc::Model RM = CGOpts.RelocationModel; |
1535 | 0 | const auto &LOpts = CGM.getLangOpts(); |
1536 | 0 | if (RM != llvm::Reloc::Static && !LOpts.PIE) { |
1537 | | // On ELF, if -fno-semantic-interposition is specified and the target |
1538 | | // supports local aliases, there will be neither CC1 |
1539 | | // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set |
1540 | | // dso_local on the function if using a local alias is preferable (can avoid |
1541 | | // PLT indirection). |
1542 | 0 | if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) |
1543 | 0 | return false; |
1544 | 0 | return !(CGM.getLangOpts().SemanticInterposition || |
1545 | 0 | CGM.getLangOpts().HalfNoSemanticInterposition); |
1546 | 0 | } |
1547 | | |
1548 | | // A definition cannot be preempted from an executable. |
1549 | 0 | if (!GV->isDeclarationForLinker()) |
1550 | 0 | return true; |
1551 | | |
1552 | | // Most PIC code sequences that assume that a symbol is local cannot produce a |
1553 | | // 0 if it turns out the symbol is undefined. While this is ABI and relocation |
1554 | | // depended, it seems worth it to handle it here. |
1555 | 0 | if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) |
1556 | 0 | return false; |
1557 | | |
1558 | | // PowerPC64 prefers TOC indirection to avoid copy relocations. |
1559 | 0 | if (TT.isPPC64()) |
1560 | 0 | return false; |
1561 | | |
1562 | 0 | if (CGOpts.DirectAccessExternalData) { |
1563 | | // If -fdirect-access-external-data (default for -fno-pic), set dso_local |
1564 | | // for non-thread-local variables. If the symbol is not defined in the |
1565 | | // executable, a copy relocation will be needed at link time. dso_local is |
1566 | | // excluded for thread-local variables because they generally don't support |
1567 | | // copy relocations. |
1568 | 0 | if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) |
1569 | 0 | if (!Var->isThreadLocal()) |
1570 | 0 | return true; |
1571 | | |
1572 | | // -fno-pic sets dso_local on a function declaration to allow direct |
1573 | | // accesses when taking its address (similar to a data symbol). If the |
1574 | | // function is not defined in the executable, a canonical PLT entry will be |
1575 | | // needed at link time. -fno-direct-access-external-data can avoid the |
1576 | | // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as |
1577 | | // it could just cause trouble without providing perceptible benefits. |
1578 | 0 | if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) |
1579 | 0 | return true; |
1580 | 0 | } |
1581 | | |
1582 | | // If we can use copy relocations we can assume it is local. |
1583 | | |
1584 | | // Otherwise don't assume it is local. |
1585 | 0 | return false; |
1586 | 0 | } |
1587 | | |
1588 | 0 | void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { |
1589 | 0 | GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); |
1590 | 0 | } |
1591 | | |
1592 | | void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, |
1593 | 0 | GlobalDecl GD) const { |
1594 | 0 | const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); |
1595 | | // C++ destructors have a few C++ ABI specific special cases. |
1596 | 0 | if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { |
1597 | 0 | getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); |
1598 | 0 | return; |
1599 | 0 | } |
1600 | 0 | setDLLImportDLLExport(GV, D); |
1601 | 0 | } |
1602 | | |
1603 | | void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, |
1604 | 0 | const NamedDecl *D) const { |
1605 | 0 | if (D && D->isExternallyVisible()) { |
1606 | 0 | if (D->hasAttr<DLLImportAttr>()) |
1607 | 0 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); |
1608 | 0 | else if ((D->hasAttr<DLLExportAttr>() || |
1609 | 0 | shouldMapVisibilityToDLLExport(D)) && |
1610 | 0 | !GV->isDeclarationForLinker()) |
1611 | 0 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); |
1612 | 0 | } |
1613 | 0 | } |
1614 | | |
1615 | | void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, |
1616 | 0 | GlobalDecl GD) const { |
1617 | 0 | setDLLImportDLLExport(GV, GD); |
1618 | 0 | setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); |
1619 | 0 | } |
1620 | | |
1621 | | void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, |
1622 | 0 | const NamedDecl *D) const { |
1623 | 0 | setDLLImportDLLExport(GV, D); |
1624 | 0 | setGVPropertiesAux(GV, D); |
1625 | 0 | } |
1626 | | |
1627 | | void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, |
1628 | 0 | const NamedDecl *D) const { |
1629 | 0 | setGlobalVisibility(GV, D); |
1630 | 0 | setDSOLocal(GV); |
1631 | 0 | GV->setPartition(CodeGenOpts.SymbolPartition); |
1632 | 0 | } |
1633 | | |
1634 | 0 | static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { |
1635 | 0 | return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) |
1636 | 0 | .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) |
1637 | 0 | .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) |
1638 | 0 | .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) |
1639 | 0 | .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); |
1640 | 0 | } |
1641 | | |
1642 | | llvm::GlobalVariable::ThreadLocalMode |
1643 | 0 | CodeGenModule::GetDefaultLLVMTLSModel() const { |
1644 | 0 | switch (CodeGenOpts.getDefaultTLSModel()) { |
1645 | 0 | case CodeGenOptions::GeneralDynamicTLSModel: |
1646 | 0 | return llvm::GlobalVariable::GeneralDynamicTLSModel; |
1647 | 0 | case CodeGenOptions::LocalDynamicTLSModel: |
1648 | 0 | return llvm::GlobalVariable::LocalDynamicTLSModel; |
1649 | 0 | case CodeGenOptions::InitialExecTLSModel: |
1650 | 0 | return llvm::GlobalVariable::InitialExecTLSModel; |
1651 | 0 | case CodeGenOptions::LocalExecTLSModel: |
1652 | 0 | return llvm::GlobalVariable::LocalExecTLSModel; |
1653 | 0 | } |
1654 | 0 | llvm_unreachable("Invalid TLS model!"); |
1655 | 0 | } |
1656 | | |
1657 | 0 | void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { |
1658 | 0 | assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); |
1659 | | |
1660 | 0 | llvm::GlobalValue::ThreadLocalMode TLM; |
1661 | 0 | TLM = GetDefaultLLVMTLSModel(); |
1662 | | |
1663 | | // Override the TLS model if it is explicitly specified. |
1664 | 0 | if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { |
1665 | 0 | TLM = GetLLVMTLSModel(Attr->getModel()); |
1666 | 0 | } |
1667 | |
|
1668 | 0 | GV->setThreadLocalMode(TLM); |
1669 | 0 | } |
1670 | | |
1671 | | static std::string getCPUSpecificMangling(const CodeGenModule &CGM, |
1672 | 0 | StringRef Name) { |
1673 | 0 | const TargetInfo &Target = CGM.getTarget(); |
1674 | 0 | return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); |
1675 | 0 | } |
1676 | | |
1677 | | static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, |
1678 | | const CPUSpecificAttr *Attr, |
1679 | | unsigned CPUIndex, |
1680 | 0 | raw_ostream &Out) { |
1681 | | // cpu_specific gets the current name, dispatch gets the resolver if IFunc is |
1682 | | // supported. |
1683 | 0 | if (Attr) |
1684 | 0 | Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); |
1685 | 0 | else if (CGM.getTarget().supportsIFunc()) |
1686 | 0 | Out << ".resolver"; |
1687 | 0 | } |
1688 | | |
1689 | | static void AppendTargetVersionMangling(const CodeGenModule &CGM, |
1690 | | const TargetVersionAttr *Attr, |
1691 | 0 | raw_ostream &Out) { |
1692 | 0 | if (Attr->isDefaultVersion()) |
1693 | 0 | return; |
1694 | 0 | Out << "._"; |
1695 | 0 | const TargetInfo &TI = CGM.getTarget(); |
1696 | 0 | llvm::SmallVector<StringRef, 8> Feats; |
1697 | 0 | Attr->getFeatures(Feats); |
1698 | 0 | llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) { |
1699 | 0 | return TI.multiVersionSortPriority(FeatL) < |
1700 | 0 | TI.multiVersionSortPriority(FeatR); |
1701 | 0 | }); |
1702 | 0 | for (const auto &Feat : Feats) { |
1703 | 0 | Out << 'M'; |
1704 | 0 | Out << Feat; |
1705 | 0 | } |
1706 | 0 | } |
1707 | | |
1708 | | static void AppendTargetMangling(const CodeGenModule &CGM, |
1709 | 0 | const TargetAttr *Attr, raw_ostream &Out) { |
1710 | 0 | if (Attr->isDefaultVersion()) |
1711 | 0 | return; |
1712 | | |
1713 | 0 | Out << '.'; |
1714 | 0 | const TargetInfo &Target = CGM.getTarget(); |
1715 | 0 | ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr()); |
1716 | 0 | llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) { |
1717 | | // Multiversioning doesn't allow "no-${feature}", so we can |
1718 | | // only have "+" prefixes here. |
1719 | 0 | assert(LHS.starts_with("+") && RHS.starts_with("+") && |
1720 | 0 | "Features should always have a prefix."); |
1721 | 0 | return Target.multiVersionSortPriority(LHS.substr(1)) > |
1722 | 0 | Target.multiVersionSortPriority(RHS.substr(1)); |
1723 | 0 | }); |
1724 | |
|
1725 | 0 | bool IsFirst = true; |
1726 | |
|
1727 | 0 | if (!Info.CPU.empty()) { |
1728 | 0 | IsFirst = false; |
1729 | 0 | Out << "arch_" << Info.CPU; |
1730 | 0 | } |
1731 | |
|
1732 | 0 | for (StringRef Feat : Info.Features) { |
1733 | 0 | if (!IsFirst) |
1734 | 0 | Out << '_'; |
1735 | 0 | IsFirst = false; |
1736 | 0 | Out << Feat.substr(1); |
1737 | 0 | } |
1738 | 0 | } |
1739 | | |
1740 | | // Returns true if GD is a function decl with internal linkage and |
1741 | | // needs a unique suffix after the mangled name. |
1742 | | static bool isUniqueInternalLinkageDecl(GlobalDecl GD, |
1743 | 0 | CodeGenModule &CGM) { |
1744 | 0 | const Decl *D = GD.getDecl(); |
1745 | 0 | return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && |
1746 | 0 | (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); |
1747 | 0 | } |
1748 | | |
1749 | | static void AppendTargetClonesMangling(const CodeGenModule &CGM, |
1750 | | const TargetClonesAttr *Attr, |
1751 | | unsigned VersionIndex, |
1752 | 0 | raw_ostream &Out) { |
1753 | 0 | const TargetInfo &TI = CGM.getTarget(); |
1754 | 0 | if (TI.getTriple().isAArch64()) { |
1755 | 0 | StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); |
1756 | 0 | if (FeatureStr == "default") |
1757 | 0 | return; |
1758 | 0 | Out << "._"; |
1759 | 0 | SmallVector<StringRef, 8> Features; |
1760 | 0 | FeatureStr.split(Features, "+"); |
1761 | 0 | llvm::stable_sort(Features, |
1762 | 0 | [&TI](const StringRef FeatL, const StringRef FeatR) { |
1763 | 0 | return TI.multiVersionSortPriority(FeatL) < |
1764 | 0 | TI.multiVersionSortPriority(FeatR); |
1765 | 0 | }); |
1766 | 0 | for (auto &Feat : Features) { |
1767 | 0 | Out << 'M'; |
1768 | 0 | Out << Feat; |
1769 | 0 | } |
1770 | 0 | } else { |
1771 | 0 | Out << '.'; |
1772 | 0 | StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); |
1773 | 0 | if (FeatureStr.starts_with("arch=")) |
1774 | 0 | Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); |
1775 | 0 | else |
1776 | 0 | Out << FeatureStr; |
1777 | |
|
1778 | 0 | Out << '.' << Attr->getMangledIndex(VersionIndex); |
1779 | 0 | } |
1780 | 0 | } |
1781 | | |
1782 | | static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, |
1783 | | const NamedDecl *ND, |
1784 | 0 | bool OmitMultiVersionMangling = false) { |
1785 | 0 | SmallString<256> Buffer; |
1786 | 0 | llvm::raw_svector_ostream Out(Buffer); |
1787 | 0 | MangleContext &MC = CGM.getCXXABI().getMangleContext(); |
1788 | 0 | if (!CGM.getModuleNameHash().empty()) |
1789 | 0 | MC.needsUniqueInternalLinkageNames(); |
1790 | 0 | bool ShouldMangle = MC.shouldMangleDeclName(ND); |
1791 | 0 | if (ShouldMangle) |
1792 | 0 | MC.mangleName(GD.getWithDecl(ND), Out); |
1793 | 0 | else { |
1794 | 0 | IdentifierInfo *II = ND->getIdentifier(); |
1795 | 0 | assert(II && "Attempt to mangle unnamed decl."); |
1796 | 0 | const auto *FD = dyn_cast<FunctionDecl>(ND); |
1797 | |
|
1798 | 0 | if (FD && |
1799 | 0 | FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { |
1800 | 0 | if (CGM.getLangOpts().RegCall4) |
1801 | 0 | Out << "__regcall4__" << II->getName(); |
1802 | 0 | else |
1803 | 0 | Out << "__regcall3__" << II->getName(); |
1804 | 0 | } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && |
1805 | 0 | GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { |
1806 | 0 | Out << "__device_stub__" << II->getName(); |
1807 | 0 | } else { |
1808 | 0 | Out << II->getName(); |
1809 | 0 | } |
1810 | 0 | } |
1811 | | |
1812 | | // Check if the module name hash should be appended for internal linkage |
1813 | | // symbols. This should come before multi-version target suffixes are |
1814 | | // appended. This is to keep the name and module hash suffix of the |
1815 | | // internal linkage function together. The unique suffix should only be |
1816 | | // added when name mangling is done to make sure that the final name can |
1817 | | // be properly demangled. For example, for C functions without prototypes, |
1818 | | // name mangling is not done and the unique suffix should not be appeneded |
1819 | | // then. |
1820 | 0 | if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { |
1821 | 0 | assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && |
1822 | 0 | "Hash computed when not explicitly requested"); |
1823 | 0 | Out << CGM.getModuleNameHash(); |
1824 | 0 | } |
1825 | | |
1826 | 0 | if (const auto *FD = dyn_cast<FunctionDecl>(ND)) |
1827 | 0 | if (FD->isMultiVersion() && !OmitMultiVersionMangling) { |
1828 | 0 | switch (FD->getMultiVersionKind()) { |
1829 | 0 | case MultiVersionKind::CPUDispatch: |
1830 | 0 | case MultiVersionKind::CPUSpecific: |
1831 | 0 | AppendCPUSpecificCPUDispatchMangling(CGM, |
1832 | 0 | FD->getAttr<CPUSpecificAttr>(), |
1833 | 0 | GD.getMultiVersionIndex(), Out); |
1834 | 0 | break; |
1835 | 0 | case MultiVersionKind::Target: |
1836 | 0 | AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); |
1837 | 0 | break; |
1838 | 0 | case MultiVersionKind::TargetVersion: |
1839 | 0 | AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); |
1840 | 0 | break; |
1841 | 0 | case MultiVersionKind::TargetClones: |
1842 | 0 | AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), |
1843 | 0 | GD.getMultiVersionIndex(), Out); |
1844 | 0 | break; |
1845 | 0 | case MultiVersionKind::None: |
1846 | 0 | llvm_unreachable("None multiversion type isn't valid here"); |
1847 | 0 | } |
1848 | 0 | } |
1849 | | |
1850 | | // Make unique name for device side static file-scope variable for HIP. |
1851 | 0 | if (CGM.getContext().shouldExternalize(ND) && |
1852 | 0 | CGM.getLangOpts().GPURelocatableDeviceCode && |
1853 | 0 | CGM.getLangOpts().CUDAIsDevice) |
1854 | 0 | CGM.printPostfixForExternalizedDecl(Out, ND); |
1855 | |
|
1856 | 0 | return std::string(Out.str()); |
1857 | 0 | } |
1858 | | |
1859 | | void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, |
1860 | | const FunctionDecl *FD, |
1861 | 0 | StringRef &CurName) { |
1862 | 0 | if (!FD->isMultiVersion()) |
1863 | 0 | return; |
1864 | | |
1865 | | // Get the name of what this would be without the 'target' attribute. This |
1866 | | // allows us to lookup the version that was emitted when this wasn't a |
1867 | | // multiversion function. |
1868 | 0 | std::string NonTargetName = |
1869 | 0 | getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); |
1870 | 0 | GlobalDecl OtherGD; |
1871 | 0 | if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { |
1872 | 0 | assert(OtherGD.getCanonicalDecl() |
1873 | 0 | .getDecl() |
1874 | 0 | ->getAsFunction() |
1875 | 0 | ->isMultiVersion() && |
1876 | 0 | "Other GD should now be a multiversioned function"); |
1877 | | // OtherFD is the version of this function that was mangled BEFORE |
1878 | | // becoming a MultiVersion function. It potentially needs to be updated. |
1879 | 0 | const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() |
1880 | 0 | .getDecl() |
1881 | 0 | ->getAsFunction() |
1882 | 0 | ->getMostRecentDecl(); |
1883 | 0 | std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); |
1884 | | // This is so that if the initial version was already the 'default' |
1885 | | // version, we don't try to update it. |
1886 | 0 | if (OtherName != NonTargetName) { |
1887 | | // Remove instead of erase, since others may have stored the StringRef |
1888 | | // to this. |
1889 | 0 | const auto ExistingRecord = Manglings.find(NonTargetName); |
1890 | 0 | if (ExistingRecord != std::end(Manglings)) |
1891 | 0 | Manglings.remove(&(*ExistingRecord)); |
1892 | 0 | auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); |
1893 | 0 | StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = |
1894 | 0 | Result.first->first(); |
1895 | | // If this is the current decl is being created, make sure we update the name. |
1896 | 0 | if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) |
1897 | 0 | CurName = OtherNameRef; |
1898 | 0 | if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) |
1899 | 0 | Entry->setName(OtherName); |
1900 | 0 | } |
1901 | 0 | } |
1902 | 0 | } |
1903 | | |
1904 | 0 | StringRef CodeGenModule::getMangledName(GlobalDecl GD) { |
1905 | 0 | GlobalDecl CanonicalGD = GD.getCanonicalDecl(); |
1906 | | |
1907 | | // Some ABIs don't have constructor variants. Make sure that base and |
1908 | | // complete constructors get mangled the same. |
1909 | 0 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { |
1910 | 0 | if (!getTarget().getCXXABI().hasConstructorVariants()) { |
1911 | 0 | CXXCtorType OrigCtorType = GD.getCtorType(); |
1912 | 0 | assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); |
1913 | 0 | if (OrigCtorType == Ctor_Base) |
1914 | 0 | CanonicalGD = GlobalDecl(CD, Ctor_Complete); |
1915 | 0 | } |
1916 | 0 | } |
1917 | | |
1918 | | // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a |
1919 | | // static device variable depends on whether the variable is referenced by |
1920 | | // a host or device host function. Therefore the mangled name cannot be |
1921 | | // cached. |
1922 | 0 | if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { |
1923 | 0 | auto FoundName = MangledDeclNames.find(CanonicalGD); |
1924 | 0 | if (FoundName != MangledDeclNames.end()) |
1925 | 0 | return FoundName->second; |
1926 | 0 | } |
1927 | | |
1928 | | // Keep the first result in the case of a mangling collision. |
1929 | 0 | const auto *ND = cast<NamedDecl>(GD.getDecl()); |
1930 | 0 | std::string MangledName = getMangledNameImpl(*this, GD, ND); |
1931 | | |
1932 | | // Ensure either we have different ABIs between host and device compilations, |
1933 | | // says host compilation following MSVC ABI but device compilation follows |
1934 | | // Itanium C++ ABI or, if they follow the same ABI, kernel names after |
1935 | | // mangling should be the same after name stubbing. The later checking is |
1936 | | // very important as the device kernel name being mangled in host-compilation |
1937 | | // is used to resolve the device binaries to be executed. Inconsistent naming |
1938 | | // result in undefined behavior. Even though we cannot check that naming |
1939 | | // directly between host- and device-compilations, the host- and |
1940 | | // device-mangling in host compilation could help catching certain ones. |
1941 | 0 | assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || |
1942 | 0 | getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || |
1943 | 0 | (getContext().getAuxTargetInfo() && |
1944 | 0 | (getContext().getAuxTargetInfo()->getCXXABI() != |
1945 | 0 | getContext().getTargetInfo().getCXXABI())) || |
1946 | 0 | getCUDARuntime().getDeviceSideName(ND) == |
1947 | 0 | getMangledNameImpl( |
1948 | 0 | *this, |
1949 | 0 | GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), |
1950 | 0 | ND)); |
1951 | | |
1952 | 0 | auto Result = Manglings.insert(std::make_pair(MangledName, GD)); |
1953 | 0 | return MangledDeclNames[CanonicalGD] = Result.first->first(); |
1954 | 0 | } |
1955 | | |
1956 | | StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, |
1957 | 0 | const BlockDecl *BD) { |
1958 | 0 | MangleContext &MangleCtx = getCXXABI().getMangleContext(); |
1959 | 0 | const Decl *D = GD.getDecl(); |
1960 | |
|
1961 | 0 | SmallString<256> Buffer; |
1962 | 0 | llvm::raw_svector_ostream Out(Buffer); |
1963 | 0 | if (!D) |
1964 | 0 | MangleCtx.mangleGlobalBlock(BD, |
1965 | 0 | dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); |
1966 | 0 | else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) |
1967 | 0 | MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); |
1968 | 0 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) |
1969 | 0 | MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); |
1970 | 0 | else |
1971 | 0 | MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); |
1972 | |
|
1973 | 0 | auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); |
1974 | 0 | return Result.first->first(); |
1975 | 0 | } |
1976 | | |
1977 | 0 | const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { |
1978 | 0 | auto it = MangledDeclNames.begin(); |
1979 | 0 | while (it != MangledDeclNames.end()) { |
1980 | 0 | if (it->second == Name) |
1981 | 0 | return it->first; |
1982 | 0 | it++; |
1983 | 0 | } |
1984 | 0 | return GlobalDecl(); |
1985 | 0 | } |
1986 | | |
1987 | 0 | llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { |
1988 | 0 | return getModule().getNamedValue(Name); |
1989 | 0 | } |
1990 | | |
1991 | | /// AddGlobalCtor - Add a function to the list that will be called before |
1992 | | /// main() runs. |
1993 | | void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, |
1994 | | unsigned LexOrder, |
1995 | 0 | llvm::Constant *AssociatedData) { |
1996 | | // FIXME: Type coercion of void()* types. |
1997 | 0 | GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData)); |
1998 | 0 | } |
1999 | | |
2000 | | /// AddGlobalDtor - Add a function to the list that will be called |
2001 | | /// when the module is unloaded. |
2002 | | void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, |
2003 | 0 | bool IsDtorAttrFunc) { |
2004 | 0 | if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && |
2005 | 0 | (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { |
2006 | 0 | DtorsUsingAtExit[Priority].push_back(Dtor); |
2007 | 0 | return; |
2008 | 0 | } |
2009 | | |
2010 | | // FIXME: Type coercion of void()* types. |
2011 | 0 | GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr)); |
2012 | 0 | } |
2013 | | |
2014 | 0 | void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { |
2015 | 0 | if (Fns.empty()) return; |
2016 | | |
2017 | | // Ctor function type is void()*. |
2018 | 0 | llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); |
2019 | 0 | llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, |
2020 | 0 | TheModule.getDataLayout().getProgramAddressSpace()); |
2021 | | |
2022 | | // Get the type of a ctor entry, { i32, void ()*, i8* }. |
2023 | 0 | llvm::StructType *CtorStructTy = llvm::StructType::get( |
2024 | 0 | Int32Ty, CtorPFTy, VoidPtrTy); |
2025 | | |
2026 | | // Construct the constructor and destructor arrays. |
2027 | 0 | ConstantInitBuilder builder(*this); |
2028 | 0 | auto ctors = builder.beginArray(CtorStructTy); |
2029 | 0 | for (const auto &I : Fns) { |
2030 | 0 | auto ctor = ctors.beginStruct(CtorStructTy); |
2031 | 0 | ctor.addInt(Int32Ty, I.Priority); |
2032 | 0 | ctor.add(I.Initializer); |
2033 | 0 | if (I.AssociatedData) |
2034 | 0 | ctor.add(I.AssociatedData); |
2035 | 0 | else |
2036 | 0 | ctor.addNullPointer(VoidPtrTy); |
2037 | 0 | ctor.finishAndAddTo(ctors); |
2038 | 0 | } |
2039 | |
|
2040 | 0 | auto list = |
2041 | 0 | ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), |
2042 | 0 | /*constant*/ false, |
2043 | 0 | llvm::GlobalValue::AppendingLinkage); |
2044 | | |
2045 | | // The LTO linker doesn't seem to like it when we set an alignment |
2046 | | // on appending variables. Take it off as a workaround. |
2047 | 0 | list->setAlignment(std::nullopt); |
2048 | |
|
2049 | 0 | Fns.clear(); |
2050 | 0 | } |
2051 | | |
2052 | | llvm::GlobalValue::LinkageTypes |
2053 | 0 | CodeGenModule::getFunctionLinkage(GlobalDecl GD) { |
2054 | 0 | const auto *D = cast<FunctionDecl>(GD.getDecl()); |
2055 | |
|
2056 | 0 | GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); |
2057 | |
|
2058 | 0 | if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) |
2059 | 0 | return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); |
2060 | | |
2061 | 0 | return getLLVMLinkageForDeclarator(D, Linkage); |
2062 | 0 | } |
2063 | | |
2064 | 0 | llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { |
2065 | 0 | llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); |
2066 | 0 | if (!MDS) return nullptr; |
2067 | | |
2068 | 0 | return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); |
2069 | 0 | } |
2070 | | |
2071 | 0 | llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { |
2072 | 0 | if (auto *FnType = T->getAs<FunctionProtoType>()) |
2073 | 0 | T = getContext().getFunctionType( |
2074 | 0 | FnType->getReturnType(), FnType->getParamTypes(), |
2075 | 0 | FnType->getExtProtoInfo().withExceptionSpec(EST_None)); |
2076 | |
|
2077 | 0 | std::string OutName; |
2078 | 0 | llvm::raw_string_ostream Out(OutName); |
2079 | 0 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
2080 | 0 | T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); |
2081 | |
|
2082 | 0 | if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) |
2083 | 0 | Out << ".normalized"; |
2084 | |
|
2085 | 0 | return llvm::ConstantInt::get(Int32Ty, |
2086 | 0 | static_cast<uint32_t>(llvm::xxHash64(OutName))); |
2087 | 0 | } |
2088 | | |
2089 | | void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, |
2090 | | const CGFunctionInfo &Info, |
2091 | 0 | llvm::Function *F, bool IsThunk) { |
2092 | 0 | unsigned CallingConv; |
2093 | 0 | llvm::AttributeList PAL; |
2094 | 0 | ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, |
2095 | 0 | /*AttrOnCallSite=*/false, IsThunk); |
2096 | 0 | F->setAttributes(PAL); |
2097 | 0 | F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); |
2098 | 0 | } |
2099 | | |
2100 | 0 | static void removeImageAccessQualifier(std::string& TyName) { |
2101 | 0 | std::string ReadOnlyQual("__read_only"); |
2102 | 0 | std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); |
2103 | 0 | if (ReadOnlyPos != std::string::npos) |
2104 | | // "+ 1" for the space after access qualifier. |
2105 | 0 | TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); |
2106 | 0 | else { |
2107 | 0 | std::string WriteOnlyQual("__write_only"); |
2108 | 0 | std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); |
2109 | 0 | if (WriteOnlyPos != std::string::npos) |
2110 | 0 | TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); |
2111 | 0 | else { |
2112 | 0 | std::string ReadWriteQual("__read_write"); |
2113 | 0 | std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); |
2114 | 0 | if (ReadWritePos != std::string::npos) |
2115 | 0 | TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); |
2116 | 0 | } |
2117 | 0 | } |
2118 | 0 | } |
2119 | | |
2120 | | // Returns the address space id that should be produced to the |
2121 | | // kernel_arg_addr_space metadata. This is always fixed to the ids |
2122 | | // as specified in the SPIR 2.0 specification in order to differentiate |
2123 | | // for example in clGetKernelArgInfo() implementation between the address |
2124 | | // spaces with targets without unique mapping to the OpenCL address spaces |
2125 | | // (basically all single AS CPUs). |
2126 | 0 | static unsigned ArgInfoAddressSpace(LangAS AS) { |
2127 | 0 | switch (AS) { |
2128 | 0 | case LangAS::opencl_global: |
2129 | 0 | return 1; |
2130 | 0 | case LangAS::opencl_constant: |
2131 | 0 | return 2; |
2132 | 0 | case LangAS::opencl_local: |
2133 | 0 | return 3; |
2134 | 0 | case LangAS::opencl_generic: |
2135 | 0 | return 4; // Not in SPIR 2.0 specs. |
2136 | 0 | case LangAS::opencl_global_device: |
2137 | 0 | return 5; |
2138 | 0 | case LangAS::opencl_global_host: |
2139 | 0 | return 6; |
2140 | 0 | default: |
2141 | 0 | return 0; // Assume private. |
2142 | 0 | } |
2143 | 0 | } |
2144 | | |
2145 | | void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, |
2146 | | const FunctionDecl *FD, |
2147 | 0 | CodeGenFunction *CGF) { |
2148 | 0 | assert(((FD && CGF) || (!FD && !CGF)) && |
2149 | 0 | "Incorrect use - FD and CGF should either be both null or not!"); |
2150 | | // Create MDNodes that represent the kernel arg metadata. |
2151 | | // Each MDNode is a list in the form of "key", N number of values which is |
2152 | | // the same number of values as their are kernel arguments. |
2153 | | |
2154 | 0 | const PrintingPolicy &Policy = Context.getPrintingPolicy(); |
2155 | | |
2156 | | // MDNode for the kernel argument address space qualifiers. |
2157 | 0 | SmallVector<llvm::Metadata *, 8> addressQuals; |
2158 | | |
2159 | | // MDNode for the kernel argument access qualifiers (images only). |
2160 | 0 | SmallVector<llvm::Metadata *, 8> accessQuals; |
2161 | | |
2162 | | // MDNode for the kernel argument type names. |
2163 | 0 | SmallVector<llvm::Metadata *, 8> argTypeNames; |
2164 | | |
2165 | | // MDNode for the kernel argument base type names. |
2166 | 0 | SmallVector<llvm::Metadata *, 8> argBaseTypeNames; |
2167 | | |
2168 | | // MDNode for the kernel argument type qualifiers. |
2169 | 0 | SmallVector<llvm::Metadata *, 8> argTypeQuals; |
2170 | | |
2171 | | // MDNode for the kernel argument names. |
2172 | 0 | SmallVector<llvm::Metadata *, 8> argNames; |
2173 | |
|
2174 | 0 | if (FD && CGF) |
2175 | 0 | for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { |
2176 | 0 | const ParmVarDecl *parm = FD->getParamDecl(i); |
2177 | | // Get argument name. |
2178 | 0 | argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); |
2179 | |
|
2180 | 0 | if (!getLangOpts().OpenCL) |
2181 | 0 | continue; |
2182 | 0 | QualType ty = parm->getType(); |
2183 | 0 | std::string typeQuals; |
2184 | | |
2185 | | // Get image and pipe access qualifier: |
2186 | 0 | if (ty->isImageType() || ty->isPipeType()) { |
2187 | 0 | const Decl *PDecl = parm; |
2188 | 0 | if (const auto *TD = ty->getAs<TypedefType>()) |
2189 | 0 | PDecl = TD->getDecl(); |
2190 | 0 | const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); |
2191 | 0 | if (A && A->isWriteOnly()) |
2192 | 0 | accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); |
2193 | 0 | else if (A && A->isReadWrite()) |
2194 | 0 | accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); |
2195 | 0 | else |
2196 | 0 | accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); |
2197 | 0 | } else |
2198 | 0 | accessQuals.push_back(llvm::MDString::get(VMContext, "none")); |
2199 | |
|
2200 | 0 | auto getTypeSpelling = [&](QualType Ty) { |
2201 | 0 | auto typeName = Ty.getUnqualifiedType().getAsString(Policy); |
2202 | |
|
2203 | 0 | if (Ty.isCanonical()) { |
2204 | 0 | StringRef typeNameRef = typeName; |
2205 | | // Turn "unsigned type" to "utype" |
2206 | 0 | if (typeNameRef.consume_front("unsigned ")) |
2207 | 0 | return std::string("u") + typeNameRef.str(); |
2208 | 0 | if (typeNameRef.consume_front("signed ")) |
2209 | 0 | return typeNameRef.str(); |
2210 | 0 | } |
2211 | | |
2212 | 0 | return typeName; |
2213 | 0 | }; |
2214 | |
|
2215 | 0 | if (ty->isPointerType()) { |
2216 | 0 | QualType pointeeTy = ty->getPointeeType(); |
2217 | | |
2218 | | // Get address qualifier. |
2219 | 0 | addressQuals.push_back( |
2220 | 0 | llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( |
2221 | 0 | ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); |
2222 | | |
2223 | | // Get argument type name. |
2224 | 0 | std::string typeName = getTypeSpelling(pointeeTy) + "*"; |
2225 | 0 | std::string baseTypeName = |
2226 | 0 | getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; |
2227 | 0 | argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); |
2228 | 0 | argBaseTypeNames.push_back( |
2229 | 0 | llvm::MDString::get(VMContext, baseTypeName)); |
2230 | | |
2231 | | // Get argument type qualifiers: |
2232 | 0 | if (ty.isRestrictQualified()) |
2233 | 0 | typeQuals = "restrict"; |
2234 | 0 | if (pointeeTy.isConstQualified() || |
2235 | 0 | (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) |
2236 | 0 | typeQuals += typeQuals.empty() ? "const" : " const"; |
2237 | 0 | if (pointeeTy.isVolatileQualified()) |
2238 | 0 | typeQuals += typeQuals.empty() ? "volatile" : " volatile"; |
2239 | 0 | } else { |
2240 | 0 | uint32_t AddrSpc = 0; |
2241 | 0 | bool isPipe = ty->isPipeType(); |
2242 | 0 | if (ty->isImageType() || isPipe) |
2243 | 0 | AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); |
2244 | |
|
2245 | 0 | addressQuals.push_back( |
2246 | 0 | llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); |
2247 | | |
2248 | | // Get argument type name. |
2249 | 0 | ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; |
2250 | 0 | std::string typeName = getTypeSpelling(ty); |
2251 | 0 | std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); |
2252 | | |
2253 | | // Remove access qualifiers on images |
2254 | | // (as they are inseparable from type in clang implementation, |
2255 | | // but OpenCL spec provides a special query to get access qualifier |
2256 | | // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): |
2257 | 0 | if (ty->isImageType()) { |
2258 | 0 | removeImageAccessQualifier(typeName); |
2259 | 0 | removeImageAccessQualifier(baseTypeName); |
2260 | 0 | } |
2261 | |
|
2262 | 0 | argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); |
2263 | 0 | argBaseTypeNames.push_back( |
2264 | 0 | llvm::MDString::get(VMContext, baseTypeName)); |
2265 | |
|
2266 | 0 | if (isPipe) |
2267 | 0 | typeQuals = "pipe"; |
2268 | 0 | } |
2269 | 0 | argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); |
2270 | 0 | } |
2271 | |
|
2272 | 0 | if (getLangOpts().OpenCL) { |
2273 | 0 | Fn->setMetadata("kernel_arg_addr_space", |
2274 | 0 | llvm::MDNode::get(VMContext, addressQuals)); |
2275 | 0 | Fn->setMetadata("kernel_arg_access_qual", |
2276 | 0 | llvm::MDNode::get(VMContext, accessQuals)); |
2277 | 0 | Fn->setMetadata("kernel_arg_type", |
2278 | 0 | llvm::MDNode::get(VMContext, argTypeNames)); |
2279 | 0 | Fn->setMetadata("kernel_arg_base_type", |
2280 | 0 | llvm::MDNode::get(VMContext, argBaseTypeNames)); |
2281 | 0 | Fn->setMetadata("kernel_arg_type_qual", |
2282 | 0 | llvm::MDNode::get(VMContext, argTypeQuals)); |
2283 | 0 | } |
2284 | 0 | if (getCodeGenOpts().EmitOpenCLArgMetadata || |
2285 | 0 | getCodeGenOpts().HIPSaveKernelArgName) |
2286 | 0 | Fn->setMetadata("kernel_arg_name", |
2287 | 0 | llvm::MDNode::get(VMContext, argNames)); |
2288 | 0 | } |
2289 | | |
2290 | | /// Determines whether the language options require us to model |
2291 | | /// unwind exceptions. We treat -fexceptions as mandating this |
2292 | | /// except under the fragile ObjC ABI with only ObjC exceptions |
2293 | | /// enabled. This means, for example, that C with -fexceptions |
2294 | | /// enables this. |
2295 | 0 | static bool hasUnwindExceptions(const LangOptions &LangOpts) { |
2296 | | // If exceptions are completely disabled, obviously this is false. |
2297 | 0 | if (!LangOpts.Exceptions) return false; |
2298 | | |
2299 | | // If C++ exceptions are enabled, this is true. |
2300 | 0 | if (LangOpts.CXXExceptions) return true; |
2301 | | |
2302 | | // If ObjC exceptions are enabled, this depends on the ABI. |
2303 | 0 | if (LangOpts.ObjCExceptions) { |
2304 | 0 | return LangOpts.ObjCRuntime.hasUnwindExceptions(); |
2305 | 0 | } |
2306 | | |
2307 | 0 | return true; |
2308 | 0 | } |
2309 | | |
2310 | | static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, |
2311 | 0 | const CXXMethodDecl *MD) { |
2312 | | // Check that the type metadata can ever actually be used by a call. |
2313 | 0 | if (!CGM.getCodeGenOpts().LTOUnit || |
2314 | 0 | !CGM.HasHiddenLTOVisibility(MD->getParent())) |
2315 | 0 | return false; |
2316 | | |
2317 | | // Only functions whose address can be taken with a member function pointer |
2318 | | // need this sort of type metadata. |
2319 | 0 | return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() && |
2320 | 0 | !isa<CXXConstructorDecl, CXXDestructorDecl>(MD); |
2321 | 0 | } |
2322 | | |
2323 | | SmallVector<const CXXRecordDecl *, 0> |
2324 | 0 | CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { |
2325 | 0 | llvm::SetVector<const CXXRecordDecl *> MostBases; |
2326 | |
|
2327 | 0 | std::function<void (const CXXRecordDecl *)> CollectMostBases; |
2328 | 0 | CollectMostBases = [&](const CXXRecordDecl *RD) { |
2329 | 0 | if (RD->getNumBases() == 0) |
2330 | 0 | MostBases.insert(RD); |
2331 | 0 | for (const CXXBaseSpecifier &B : RD->bases()) |
2332 | 0 | CollectMostBases(B.getType()->getAsCXXRecordDecl()); |
2333 | 0 | }; |
2334 | 0 | CollectMostBases(RD); |
2335 | 0 | return MostBases.takeVector(); |
2336 | 0 | } |
2337 | | |
2338 | | void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, |
2339 | 0 | llvm::Function *F) { |
2340 | 0 | llvm::AttrBuilder B(F->getContext()); |
2341 | |
|
2342 | 0 | if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) |
2343 | 0 | B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); |
2344 | |
|
2345 | 0 | if (CodeGenOpts.StackClashProtector) |
2346 | 0 | B.addAttribute("probe-stack", "inline-asm"); |
2347 | |
|
2348 | 0 | if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) |
2349 | 0 | B.addAttribute("stack-probe-size", |
2350 | 0 | std::to_string(CodeGenOpts.StackProbeSize)); |
2351 | |
|
2352 | 0 | if (!hasUnwindExceptions(LangOpts)) |
2353 | 0 | B.addAttribute(llvm::Attribute::NoUnwind); |
2354 | |
|
2355 | 0 | if (D && D->hasAttr<NoStackProtectorAttr>()) |
2356 | 0 | ; // Do nothing. |
2357 | 0 | else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && |
2358 | 0 | isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) |
2359 | 0 | B.addAttribute(llvm::Attribute::StackProtectStrong); |
2360 | 0 | else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) |
2361 | 0 | B.addAttribute(llvm::Attribute::StackProtect); |
2362 | 0 | else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong)) |
2363 | 0 | B.addAttribute(llvm::Attribute::StackProtectStrong); |
2364 | 0 | else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq)) |
2365 | 0 | B.addAttribute(llvm::Attribute::StackProtectReq); |
2366 | |
|
2367 | 0 | if (!D) { |
2368 | | // If we don't have a declaration to control inlining, the function isn't |
2369 | | // explicitly marked as alwaysinline for semantic reasons, and inlining is |
2370 | | // disabled, mark the function as noinline. |
2371 | 0 | if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && |
2372 | 0 | CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) |
2373 | 0 | B.addAttribute(llvm::Attribute::NoInline); |
2374 | |
|
2375 | 0 | F->addFnAttrs(B); |
2376 | 0 | return; |
2377 | 0 | } |
2378 | | |
2379 | | // Handle SME attributes that apply to function definitions, |
2380 | | // rather than to function prototypes. |
2381 | 0 | if (D->hasAttr<ArmLocallyStreamingAttr>()) |
2382 | 0 | B.addAttribute("aarch64_pstate_sm_body"); |
2383 | |
|
2384 | 0 | if (auto *Attr = D->getAttr<ArmNewAttr>()) { |
2385 | 0 | if (Attr->isNewZA()) |
2386 | 0 | B.addAttribute("aarch64_pstate_za_new"); |
2387 | 0 | } |
2388 | | |
2389 | | // Track whether we need to add the optnone LLVM attribute, |
2390 | | // starting with the default for this optimization level. |
2391 | 0 | bool ShouldAddOptNone = |
2392 | 0 | !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; |
2393 | | // We can't add optnone in the following cases, it won't pass the verifier. |
2394 | 0 | ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); |
2395 | 0 | ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); |
2396 | | |
2397 | | // Add optnone, but do so only if the function isn't always_inline. |
2398 | 0 | if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && |
2399 | 0 | !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { |
2400 | 0 | B.addAttribute(llvm::Attribute::OptimizeNone); |
2401 | | |
2402 | | // OptimizeNone implies noinline; we should not be inlining such functions. |
2403 | 0 | B.addAttribute(llvm::Attribute::NoInline); |
2404 | | |
2405 | | // We still need to handle naked functions even though optnone subsumes |
2406 | | // much of their semantics. |
2407 | 0 | if (D->hasAttr<NakedAttr>()) |
2408 | 0 | B.addAttribute(llvm::Attribute::Naked); |
2409 | | |
2410 | | // OptimizeNone wins over OptimizeForSize and MinSize. |
2411 | 0 | F->removeFnAttr(llvm::Attribute::OptimizeForSize); |
2412 | 0 | F->removeFnAttr(llvm::Attribute::MinSize); |
2413 | 0 | } else if (D->hasAttr<NakedAttr>()) { |
2414 | | // Naked implies noinline: we should not be inlining such functions. |
2415 | 0 | B.addAttribute(llvm::Attribute::Naked); |
2416 | 0 | B.addAttribute(llvm::Attribute::NoInline); |
2417 | 0 | } else if (D->hasAttr<NoDuplicateAttr>()) { |
2418 | 0 | B.addAttribute(llvm::Attribute::NoDuplicate); |
2419 | 0 | } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { |
2420 | | // Add noinline if the function isn't always_inline. |
2421 | 0 | B.addAttribute(llvm::Attribute::NoInline); |
2422 | 0 | } else if (D->hasAttr<AlwaysInlineAttr>() && |
2423 | 0 | !F->hasFnAttribute(llvm::Attribute::NoInline)) { |
2424 | | // (noinline wins over always_inline, and we can't specify both in IR) |
2425 | 0 | B.addAttribute(llvm::Attribute::AlwaysInline); |
2426 | 0 | } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { |
2427 | | // If we're not inlining, then force everything that isn't always_inline to |
2428 | | // carry an explicit noinline attribute. |
2429 | 0 | if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) |
2430 | 0 | B.addAttribute(llvm::Attribute::NoInline); |
2431 | 0 | } else { |
2432 | | // Otherwise, propagate the inline hint attribute and potentially use its |
2433 | | // absence to mark things as noinline. |
2434 | 0 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { |
2435 | | // Search function and template pattern redeclarations for inline. |
2436 | 0 | auto CheckForInline = [](const FunctionDecl *FD) { |
2437 | 0 | auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { |
2438 | 0 | return Redecl->isInlineSpecified(); |
2439 | 0 | }; |
2440 | 0 | if (any_of(FD->redecls(), CheckRedeclForInline)) |
2441 | 0 | return true; |
2442 | 0 | const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); |
2443 | 0 | if (!Pattern) |
2444 | 0 | return false; |
2445 | 0 | return any_of(Pattern->redecls(), CheckRedeclForInline); |
2446 | 0 | }; |
2447 | 0 | if (CheckForInline(FD)) { |
2448 | 0 | B.addAttribute(llvm::Attribute::InlineHint); |
2449 | 0 | } else if (CodeGenOpts.getInlining() == |
2450 | 0 | CodeGenOptions::OnlyHintInlining && |
2451 | 0 | !FD->isInlined() && |
2452 | 0 | !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { |
2453 | 0 | B.addAttribute(llvm::Attribute::NoInline); |
2454 | 0 | } |
2455 | 0 | } |
2456 | 0 | } |
2457 | | |
2458 | | // Add other optimization related attributes if we are optimizing this |
2459 | | // function. |
2460 | 0 | if (!D->hasAttr<OptimizeNoneAttr>()) { |
2461 | 0 | if (D->hasAttr<ColdAttr>()) { |
2462 | 0 | if (!ShouldAddOptNone) |
2463 | 0 | B.addAttribute(llvm::Attribute::OptimizeForSize); |
2464 | 0 | B.addAttribute(llvm::Attribute::Cold); |
2465 | 0 | } |
2466 | 0 | if (D->hasAttr<HotAttr>()) |
2467 | 0 | B.addAttribute(llvm::Attribute::Hot); |
2468 | 0 | if (D->hasAttr<MinSizeAttr>()) |
2469 | 0 | B.addAttribute(llvm::Attribute::MinSize); |
2470 | 0 | } |
2471 | |
|
2472 | 0 | F->addFnAttrs(B); |
2473 | |
|
2474 | 0 | unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); |
2475 | 0 | if (alignment) |
2476 | 0 | F->setAlignment(llvm::Align(alignment)); |
2477 | |
|
2478 | 0 | if (!D->hasAttr<AlignedAttr>()) |
2479 | 0 | if (LangOpts.FunctionAlignment) |
2480 | 0 | F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); |
2481 | | |
2482 | | // Some C++ ABIs require 2-byte alignment for member functions, in order to |
2483 | | // reserve a bit for differentiating between virtual and non-virtual member |
2484 | | // functions. If the current target's C++ ABI requires this and this is a |
2485 | | // member function, set its alignment accordingly. |
2486 | 0 | if (getTarget().getCXXABI().areMemberFunctionsAligned()) { |
2487 | 0 | if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2) |
2488 | 0 | F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne())); |
2489 | 0 | } |
2490 | | |
2491 | | // In the cross-dso CFI mode with canonical jump tables, we want !type |
2492 | | // attributes on definitions only. |
2493 | 0 | if (CodeGenOpts.SanitizeCfiCrossDso && |
2494 | 0 | CodeGenOpts.SanitizeCfiCanonicalJumpTables) { |
2495 | 0 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { |
2496 | | // Skip available_externally functions. They won't be codegen'ed in the |
2497 | | // current module anyway. |
2498 | 0 | if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) |
2499 | 0 | CreateFunctionTypeMetadataForIcall(FD, F); |
2500 | 0 | } |
2501 | 0 | } |
2502 | | |
2503 | | // Emit type metadata on member functions for member function pointer checks. |
2504 | | // These are only ever necessary on definitions; we're guaranteed that the |
2505 | | // definition will be present in the LTO unit as a result of LTO visibility. |
2506 | 0 | auto *MD = dyn_cast<CXXMethodDecl>(D); |
2507 | 0 | if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { |
2508 | 0 | for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { |
2509 | 0 | llvm::Metadata *Id = |
2510 | 0 | CreateMetadataIdentifierForType(Context.getMemberPointerType( |
2511 | 0 | MD->getType(), Context.getRecordType(Base).getTypePtr())); |
2512 | 0 | F->addTypeMetadata(0, Id); |
2513 | 0 | } |
2514 | 0 | } |
2515 | 0 | } |
2516 | | |
2517 | 0 | void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { |
2518 | 0 | const Decl *D = GD.getDecl(); |
2519 | 0 | if (isa_and_nonnull<NamedDecl>(D)) |
2520 | 0 | setGVProperties(GV, GD); |
2521 | 0 | else |
2522 | 0 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); |
2523 | |
|
2524 | 0 | if (D && D->hasAttr<UsedAttr>()) |
2525 | 0 | addUsedOrCompilerUsedGlobal(GV); |
2526 | |
|
2527 | 0 | if (const auto *VD = dyn_cast_if_present<VarDecl>(D); |
2528 | 0 | VD && |
2529 | 0 | ((CodeGenOpts.KeepPersistentStorageVariables && |
2530 | 0 | (VD->getStorageDuration() == SD_Static || |
2531 | 0 | VD->getStorageDuration() == SD_Thread)) || |
2532 | 0 | (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && |
2533 | 0 | VD->getType().isConstQualified()))) |
2534 | 0 | addUsedOrCompilerUsedGlobal(GV); |
2535 | 0 | } |
2536 | | |
2537 | | bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, |
2538 | | llvm::AttrBuilder &Attrs, |
2539 | 0 | bool SetTargetFeatures) { |
2540 | | // Add target-cpu and target-features attributes to functions. If |
2541 | | // we have a decl for the function and it has a target attribute then |
2542 | | // parse that and add it to the feature set. |
2543 | 0 | StringRef TargetCPU = getTarget().getTargetOpts().CPU; |
2544 | 0 | StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; |
2545 | 0 | std::vector<std::string> Features; |
2546 | 0 | const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); |
2547 | 0 | FD = FD ? FD->getMostRecentDecl() : FD; |
2548 | 0 | const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; |
2549 | 0 | const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; |
2550 | 0 | assert((!TD || !TV) && "both target_version and target specified"); |
2551 | 0 | const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; |
2552 | 0 | const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; |
2553 | 0 | bool AddedAttr = false; |
2554 | 0 | if (TD || TV || SD || TC) { |
2555 | 0 | llvm::StringMap<bool> FeatureMap; |
2556 | 0 | getContext().getFunctionFeatureMap(FeatureMap, GD); |
2557 | | |
2558 | | // Produce the canonical string for this set of features. |
2559 | 0 | for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) |
2560 | 0 | Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); |
2561 | | |
2562 | | // Now add the target-cpu and target-features to the function. |
2563 | | // While we populated the feature map above, we still need to |
2564 | | // get and parse the target attribute so we can get the cpu for |
2565 | | // the function. |
2566 | 0 | if (TD) { |
2567 | 0 | ParsedTargetAttr ParsedAttr = |
2568 | 0 | Target.parseTargetAttr(TD->getFeaturesStr()); |
2569 | 0 | if (!ParsedAttr.CPU.empty() && |
2570 | 0 | getTarget().isValidCPUName(ParsedAttr.CPU)) { |
2571 | 0 | TargetCPU = ParsedAttr.CPU; |
2572 | 0 | TuneCPU = ""; // Clear the tune CPU. |
2573 | 0 | } |
2574 | 0 | if (!ParsedAttr.Tune.empty() && |
2575 | 0 | getTarget().isValidCPUName(ParsedAttr.Tune)) |
2576 | 0 | TuneCPU = ParsedAttr.Tune; |
2577 | 0 | } |
2578 | |
|
2579 | 0 | if (SD) { |
2580 | | // Apply the given CPU name as the 'tune-cpu' so that the optimizer can |
2581 | | // favor this processor. |
2582 | 0 | TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName(); |
2583 | 0 | } |
2584 | 0 | } else { |
2585 | | // Otherwise just add the existing target cpu and target features to the |
2586 | | // function. |
2587 | 0 | Features = getTarget().getTargetOpts().Features; |
2588 | 0 | } |
2589 | |
|
2590 | 0 | if (!TargetCPU.empty()) { |
2591 | 0 | Attrs.addAttribute("target-cpu", TargetCPU); |
2592 | 0 | AddedAttr = true; |
2593 | 0 | } |
2594 | 0 | if (!TuneCPU.empty()) { |
2595 | 0 | Attrs.addAttribute("tune-cpu", TuneCPU); |
2596 | 0 | AddedAttr = true; |
2597 | 0 | } |
2598 | 0 | if (!Features.empty() && SetTargetFeatures) { |
2599 | 0 | llvm::erase_if(Features, [&](const std::string& F) { |
2600 | 0 | return getTarget().isReadOnlyFeature(F.substr(1)); |
2601 | 0 | }); |
2602 | 0 | llvm::sort(Features); |
2603 | 0 | Attrs.addAttribute("target-features", llvm::join(Features, ",")); |
2604 | 0 | AddedAttr = true; |
2605 | 0 | } |
2606 | |
|
2607 | 0 | return AddedAttr; |
2608 | 0 | } |
2609 | | |
2610 | | void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, |
2611 | 0 | llvm::GlobalObject *GO) { |
2612 | 0 | const Decl *D = GD.getDecl(); |
2613 | 0 | SetCommonAttributes(GD, GO); |
2614 | |
|
2615 | 0 | if (D) { |
2616 | 0 | if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { |
2617 | 0 | if (D->hasAttr<RetainAttr>()) |
2618 | 0 | addUsedGlobal(GV); |
2619 | 0 | if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) |
2620 | 0 | GV->addAttribute("bss-section", SA->getName()); |
2621 | 0 | if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) |
2622 | 0 | GV->addAttribute("data-section", SA->getName()); |
2623 | 0 | if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) |
2624 | 0 | GV->addAttribute("rodata-section", SA->getName()); |
2625 | 0 | if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) |
2626 | 0 | GV->addAttribute("relro-section", SA->getName()); |
2627 | 0 | } |
2628 | |
|
2629 | 0 | if (auto *F = dyn_cast<llvm::Function>(GO)) { |
2630 | 0 | if (D->hasAttr<RetainAttr>()) |
2631 | 0 | addUsedGlobal(F); |
2632 | 0 | if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) |
2633 | 0 | if (!D->getAttr<SectionAttr>()) |
2634 | 0 | F->addFnAttr("implicit-section-name", SA->getName()); |
2635 | |
|
2636 | 0 | llvm::AttrBuilder Attrs(F->getContext()); |
2637 | 0 | if (GetCPUAndFeaturesAttributes(GD, Attrs)) { |
2638 | | // We know that GetCPUAndFeaturesAttributes will always have the |
2639 | | // newest set, since it has the newest possible FunctionDecl, so the |
2640 | | // new ones should replace the old. |
2641 | 0 | llvm::AttributeMask RemoveAttrs; |
2642 | 0 | RemoveAttrs.addAttribute("target-cpu"); |
2643 | 0 | RemoveAttrs.addAttribute("target-features"); |
2644 | 0 | RemoveAttrs.addAttribute("tune-cpu"); |
2645 | 0 | F->removeFnAttrs(RemoveAttrs); |
2646 | 0 | F->addFnAttrs(Attrs); |
2647 | 0 | } |
2648 | 0 | } |
2649 | |
|
2650 | 0 | if (const auto *CSA = D->getAttr<CodeSegAttr>()) |
2651 | 0 | GO->setSection(CSA->getName()); |
2652 | 0 | else if (const auto *SA = D->getAttr<SectionAttr>()) |
2653 | 0 | GO->setSection(SA->getName()); |
2654 | 0 | } |
2655 | |
|
2656 | 0 | getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); |
2657 | 0 | } |
2658 | | |
2659 | | void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, |
2660 | | llvm::Function *F, |
2661 | 0 | const CGFunctionInfo &FI) { |
2662 | 0 | const Decl *D = GD.getDecl(); |
2663 | 0 | SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); |
2664 | 0 | SetLLVMFunctionAttributesForDefinition(D, F); |
2665 | |
|
2666 | 0 | F->setLinkage(llvm::Function::InternalLinkage); |
2667 | |
|
2668 | 0 | setNonAliasAttributes(GD, F); |
2669 | 0 | } |
2670 | | |
2671 | 0 | static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { |
2672 | | // Set linkage and visibility in case we never see a definition. |
2673 | 0 | LinkageInfo LV = ND->getLinkageAndVisibility(); |
2674 | | // Don't set internal linkage on declarations. |
2675 | | // "extern_weak" is overloaded in LLVM; we probably should have |
2676 | | // separate linkage types for this. |
2677 | 0 | if (isExternallyVisible(LV.getLinkage()) && |
2678 | 0 | (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) |
2679 | 0 | GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); |
2680 | 0 | } |
2681 | | |
2682 | | void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, |
2683 | 0 | llvm::Function *F) { |
2684 | | // Only if we are checking indirect calls. |
2685 | 0 | if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) |
2686 | 0 | return; |
2687 | | |
2688 | | // Non-static class methods are handled via vtable or member function pointer |
2689 | | // checks elsewhere. |
2690 | 0 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) |
2691 | 0 | return; |
2692 | | |
2693 | 0 | llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); |
2694 | 0 | F->addTypeMetadata(0, MD); |
2695 | 0 | F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); |
2696 | | |
2697 | | // Emit a hash-based bit set entry for cross-DSO calls. |
2698 | 0 | if (CodeGenOpts.SanitizeCfiCrossDso) |
2699 | 0 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) |
2700 | 0 | F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); |
2701 | 0 | } |
2702 | | |
2703 | 0 | void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { |
2704 | 0 | llvm::LLVMContext &Ctx = F->getContext(); |
2705 | 0 | llvm::MDBuilder MDB(Ctx); |
2706 | 0 | F->setMetadata(llvm::LLVMContext::MD_kcfi_type, |
2707 | 0 | llvm::MDNode::get( |
2708 | 0 | Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); |
2709 | 0 | } |
2710 | | |
2711 | 0 | static bool allowKCFIIdentifier(StringRef Name) { |
2712 | | // KCFI type identifier constants are only necessary for external assembly |
2713 | | // functions, which means it's safe to skip unusual names. Subset of |
2714 | | // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). |
2715 | 0 | return llvm::all_of(Name, [](const char &C) { |
2716 | 0 | return llvm::isAlnum(C) || C == '_' || C == '.'; |
2717 | 0 | }); |
2718 | 0 | } |
2719 | | |
2720 | 0 | void CodeGenModule::finalizeKCFITypes() { |
2721 | 0 | llvm::Module &M = getModule(); |
2722 | 0 | for (auto &F : M.functions()) { |
2723 | | // Remove KCFI type metadata from non-address-taken local functions. |
2724 | 0 | bool AddressTaken = F.hasAddressTaken(); |
2725 | 0 | if (!AddressTaken && F.hasLocalLinkage()) |
2726 | 0 | F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); |
2727 | | |
2728 | | // Generate a constant with the expected KCFI type identifier for all |
2729 | | // address-taken function declarations to support annotating indirectly |
2730 | | // called assembly functions. |
2731 | 0 | if (!AddressTaken || !F.isDeclaration()) |
2732 | 0 | continue; |
2733 | | |
2734 | 0 | const llvm::ConstantInt *Type; |
2735 | 0 | if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) |
2736 | 0 | Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); |
2737 | 0 | else |
2738 | 0 | continue; |
2739 | | |
2740 | 0 | StringRef Name = F.getName(); |
2741 | 0 | if (!allowKCFIIdentifier(Name)) |
2742 | 0 | continue; |
2743 | | |
2744 | 0 | std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + |
2745 | 0 | Name + ", " + Twine(Type->getZExtValue()) + "\n") |
2746 | 0 | .str(); |
2747 | 0 | M.appendModuleInlineAsm(Asm); |
2748 | 0 | } |
2749 | 0 | } |
2750 | | |
2751 | | void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, |
2752 | | bool IsIncompleteFunction, |
2753 | 0 | bool IsThunk) { |
2754 | |
|
2755 | 0 | if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { |
2756 | | // If this is an intrinsic function, set the function's attributes |
2757 | | // to the intrinsic's attributes. |
2758 | 0 | F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); |
2759 | 0 | return; |
2760 | 0 | } |
2761 | | |
2762 | 0 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); |
2763 | |
|
2764 | 0 | if (!IsIncompleteFunction) |
2765 | 0 | SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, |
2766 | 0 | IsThunk); |
2767 | | |
2768 | | // Add the Returned attribute for "this", except for iOS 5 and earlier |
2769 | | // where substantial code, including the libstdc++ dylib, was compiled with |
2770 | | // GCC and does not actually return "this". |
2771 | 0 | if (!IsThunk && getCXXABI().HasThisReturn(GD) && |
2772 | 0 | !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { |
2773 | 0 | assert(!F->arg_empty() && |
2774 | 0 | F->arg_begin()->getType() |
2775 | 0 | ->canLosslesslyBitCastTo(F->getReturnType()) && |
2776 | 0 | "unexpected this return"); |
2777 | 0 | F->addParamAttr(0, llvm::Attribute::Returned); |
2778 | 0 | } |
2779 | | |
2780 | | // Only a few attributes are set on declarations; these may later be |
2781 | | // overridden by a definition. |
2782 | | |
2783 | 0 | setLinkageForGV(F, FD); |
2784 | 0 | setGVProperties(F, FD); |
2785 | | |
2786 | | // Setup target-specific attributes. |
2787 | 0 | if (!IsIncompleteFunction && F->isDeclaration()) |
2788 | 0 | getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); |
2789 | |
|
2790 | 0 | if (const auto *CSA = FD->getAttr<CodeSegAttr>()) |
2791 | 0 | F->setSection(CSA->getName()); |
2792 | 0 | else if (const auto *SA = FD->getAttr<SectionAttr>()) |
2793 | 0 | F->setSection(SA->getName()); |
2794 | |
|
2795 | 0 | if (const auto *EA = FD->getAttr<ErrorAttr>()) { |
2796 | 0 | if (EA->isError()) |
2797 | 0 | F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); |
2798 | 0 | else if (EA->isWarning()) |
2799 | 0 | F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); |
2800 | 0 | } |
2801 | | |
2802 | | // If we plan on emitting this inline builtin, we can't treat it as a builtin. |
2803 | 0 | if (FD->isInlineBuiltinDeclaration()) { |
2804 | 0 | const FunctionDecl *FDBody; |
2805 | 0 | bool HasBody = FD->hasBody(FDBody); |
2806 | 0 | (void)HasBody; |
2807 | 0 | assert(HasBody && "Inline builtin declarations should always have an " |
2808 | 0 | "available body!"); |
2809 | 0 | if (shouldEmitFunction(FDBody)) |
2810 | 0 | F->addFnAttr(llvm::Attribute::NoBuiltin); |
2811 | 0 | } |
2812 | | |
2813 | 0 | if (FD->isReplaceableGlobalAllocationFunction()) { |
2814 | | // A replaceable global allocation function does not act like a builtin by |
2815 | | // default, only if it is invoked by a new-expression or delete-expression. |
2816 | 0 | F->addFnAttr(llvm::Attribute::NoBuiltin); |
2817 | 0 | } |
2818 | |
|
2819 | 0 | if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) |
2820 | 0 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
2821 | 0 | else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) |
2822 | 0 | if (MD->isVirtual()) |
2823 | 0 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
2824 | | |
2825 | | // Don't emit entries for function declarations in the cross-DSO mode. This |
2826 | | // is handled with better precision by the receiving DSO. But if jump tables |
2827 | | // are non-canonical then we need type metadata in order to produce the local |
2828 | | // jump table. |
2829 | 0 | if (!CodeGenOpts.SanitizeCfiCrossDso || |
2830 | 0 | !CodeGenOpts.SanitizeCfiCanonicalJumpTables) |
2831 | 0 | CreateFunctionTypeMetadataForIcall(FD, F); |
2832 | |
|
2833 | 0 | if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) |
2834 | 0 | setKCFIType(FD, F); |
2835 | |
|
2836 | 0 | if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) |
2837 | 0 | getOpenMPRuntime().emitDeclareSimdFunction(FD, F); |
2838 | |
|
2839 | 0 | if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) |
2840 | 0 | F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); |
2841 | |
|
2842 | 0 | if (const auto *CB = FD->getAttr<CallbackAttr>()) { |
2843 | | // Annotate the callback behavior as metadata: |
2844 | | // - The callback callee (as argument number). |
2845 | | // - The callback payloads (as argument numbers). |
2846 | 0 | llvm::LLVMContext &Ctx = F->getContext(); |
2847 | 0 | llvm::MDBuilder MDB(Ctx); |
2848 | | |
2849 | | // The payload indices are all but the first one in the encoding. The first |
2850 | | // identifies the callback callee. |
2851 | 0 | int CalleeIdx = *CB->encoding_begin(); |
2852 | 0 | ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); |
2853 | 0 | F->addMetadata(llvm::LLVMContext::MD_callback, |
2854 | 0 | *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( |
2855 | 0 | CalleeIdx, PayloadIndices, |
2856 | 0 | /* VarArgsArePassed */ false)})); |
2857 | 0 | } |
2858 | 0 | } |
2859 | | |
2860 | 0 | void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { |
2861 | 0 | assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && |
2862 | 0 | "Only globals with definition can force usage."); |
2863 | 0 | LLVMUsed.emplace_back(GV); |
2864 | 0 | } |
2865 | | |
2866 | 0 | void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { |
2867 | 0 | assert(!GV->isDeclaration() && |
2868 | 0 | "Only globals with definition can force usage."); |
2869 | 0 | LLVMCompilerUsed.emplace_back(GV); |
2870 | 0 | } |
2871 | | |
2872 | 0 | void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { |
2873 | 0 | assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && |
2874 | 0 | "Only globals with definition can force usage."); |
2875 | 0 | if (getTriple().isOSBinFormatELF()) |
2876 | 0 | LLVMCompilerUsed.emplace_back(GV); |
2877 | 0 | else |
2878 | 0 | LLVMUsed.emplace_back(GV); |
2879 | 0 | } |
2880 | | |
2881 | | static void emitUsed(CodeGenModule &CGM, StringRef Name, |
2882 | 0 | std::vector<llvm::WeakTrackingVH> &List) { |
2883 | | // Don't create llvm.used if there is no need. |
2884 | 0 | if (List.empty()) |
2885 | 0 | return; |
2886 | | |
2887 | | // Convert List to what ConstantArray needs. |
2888 | 0 | SmallVector<llvm::Constant*, 8> UsedArray; |
2889 | 0 | UsedArray.resize(List.size()); |
2890 | 0 | for (unsigned i = 0, e = List.size(); i != e; ++i) { |
2891 | 0 | UsedArray[i] = |
2892 | 0 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
2893 | 0 | cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); |
2894 | 0 | } |
2895 | |
|
2896 | 0 | if (UsedArray.empty()) |
2897 | 0 | return; |
2898 | 0 | llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); |
2899 | |
|
2900 | 0 | auto *GV = new llvm::GlobalVariable( |
2901 | 0 | CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, |
2902 | 0 | llvm::ConstantArray::get(ATy, UsedArray), Name); |
2903 | |
|
2904 | 0 | GV->setSection("llvm.metadata"); |
2905 | 0 | } |
2906 | | |
2907 | 0 | void CodeGenModule::emitLLVMUsed() { |
2908 | 0 | emitUsed(*this, "llvm.used", LLVMUsed); |
2909 | 0 | emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); |
2910 | 0 | } |
2911 | | |
2912 | 0 | void CodeGenModule::AppendLinkerOptions(StringRef Opts) { |
2913 | 0 | auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); |
2914 | 0 | LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); |
2915 | 0 | } |
2916 | | |
2917 | 0 | void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { |
2918 | 0 | llvm::SmallString<32> Opt; |
2919 | 0 | getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); |
2920 | 0 | if (Opt.empty()) |
2921 | 0 | return; |
2922 | 0 | auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); |
2923 | 0 | LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); |
2924 | 0 | } |
2925 | | |
2926 | 0 | void CodeGenModule::AddDependentLib(StringRef Lib) { |
2927 | 0 | auto &C = getLLVMContext(); |
2928 | 0 | if (getTarget().getTriple().isOSBinFormatELF()) { |
2929 | 0 | ELFDependentLibraries.push_back( |
2930 | 0 | llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); |
2931 | 0 | return; |
2932 | 0 | } |
2933 | | |
2934 | 0 | llvm::SmallString<24> Opt; |
2935 | 0 | getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); |
2936 | 0 | auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); |
2937 | 0 | LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); |
2938 | 0 | } |
2939 | | |
2940 | | /// Add link options implied by the given module, including modules |
2941 | | /// it depends on, using a postorder walk. |
2942 | | static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, |
2943 | | SmallVectorImpl<llvm::MDNode *> &Metadata, |
2944 | 0 | llvm::SmallPtrSet<Module *, 16> &Visited) { |
2945 | | // Import this module's parent. |
2946 | 0 | if (Mod->Parent && Visited.insert(Mod->Parent).second) { |
2947 | 0 | addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); |
2948 | 0 | } |
2949 | | |
2950 | | // Import this module's dependencies. |
2951 | 0 | for (Module *Import : llvm::reverse(Mod->Imports)) { |
2952 | 0 | if (Visited.insert(Import).second) |
2953 | 0 | addLinkOptionsPostorder(CGM, Import, Metadata, Visited); |
2954 | 0 | } |
2955 | | |
2956 | | // Add linker options to link against the libraries/frameworks |
2957 | | // described by this module. |
2958 | 0 | llvm::LLVMContext &Context = CGM.getLLVMContext(); |
2959 | 0 | bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); |
2960 | | |
2961 | | // For modules that use export_as for linking, use that module |
2962 | | // name instead. |
2963 | 0 | if (Mod->UseExportAsModuleLinkName) |
2964 | 0 | return; |
2965 | | |
2966 | 0 | for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { |
2967 | | // Link against a framework. Frameworks are currently Darwin only, so we |
2968 | | // don't to ask TargetCodeGenInfo for the spelling of the linker option. |
2969 | 0 | if (LL.IsFramework) { |
2970 | 0 | llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), |
2971 | 0 | llvm::MDString::get(Context, LL.Library)}; |
2972 | |
|
2973 | 0 | Metadata.push_back(llvm::MDNode::get(Context, Args)); |
2974 | 0 | continue; |
2975 | 0 | } |
2976 | | |
2977 | | // Link against a library. |
2978 | 0 | if (IsELF) { |
2979 | 0 | llvm::Metadata *Args[2] = { |
2980 | 0 | llvm::MDString::get(Context, "lib"), |
2981 | 0 | llvm::MDString::get(Context, LL.Library), |
2982 | 0 | }; |
2983 | 0 | Metadata.push_back(llvm::MDNode::get(Context, Args)); |
2984 | 0 | } else { |
2985 | 0 | llvm::SmallString<24> Opt; |
2986 | 0 | CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); |
2987 | 0 | auto *OptString = llvm::MDString::get(Context, Opt); |
2988 | 0 | Metadata.push_back(llvm::MDNode::get(Context, OptString)); |
2989 | 0 | } |
2990 | 0 | } |
2991 | 0 | } |
2992 | | |
2993 | 0 | void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { |
2994 | 0 | assert(Primary->isNamedModuleUnit() && |
2995 | 0 | "We should only emit module initializers for named modules."); |
2996 | | |
2997 | | // Emit the initializers in the order that sub-modules appear in the |
2998 | | // source, first Global Module Fragments, if present. |
2999 | 0 | if (auto GMF = Primary->getGlobalModuleFragment()) { |
3000 | 0 | for (Decl *D : getContext().getModuleInitializers(GMF)) { |
3001 | 0 | if (isa<ImportDecl>(D)) |
3002 | 0 | continue; |
3003 | 0 | assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?"); |
3004 | 0 | EmitTopLevelDecl(D); |
3005 | 0 | } |
3006 | 0 | } |
3007 | | // Second any associated with the module, itself. |
3008 | 0 | for (Decl *D : getContext().getModuleInitializers(Primary)) { |
3009 | | // Skip import decls, the inits for those are called explicitly. |
3010 | 0 | if (isa<ImportDecl>(D)) |
3011 | 0 | continue; |
3012 | 0 | EmitTopLevelDecl(D); |
3013 | 0 | } |
3014 | | // Third any associated with the Privat eMOdule Fragment, if present. |
3015 | 0 | if (auto PMF = Primary->getPrivateModuleFragment()) { |
3016 | 0 | for (Decl *D : getContext().getModuleInitializers(PMF)) { |
3017 | | // Skip import decls, the inits for those are called explicitly. |
3018 | 0 | if (isa<ImportDecl>(D)) |
3019 | 0 | continue; |
3020 | 0 | assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?"); |
3021 | 0 | EmitTopLevelDecl(D); |
3022 | 0 | } |
3023 | 0 | } |
3024 | 0 | } |
3025 | | |
3026 | 0 | void CodeGenModule::EmitModuleLinkOptions() { |
3027 | | // Collect the set of all of the modules we want to visit to emit link |
3028 | | // options, which is essentially the imported modules and all of their |
3029 | | // non-explicit child modules. |
3030 | 0 | llvm::SetVector<clang::Module *> LinkModules; |
3031 | 0 | llvm::SmallPtrSet<clang::Module *, 16> Visited; |
3032 | 0 | SmallVector<clang::Module *, 16> Stack; |
3033 | | |
3034 | | // Seed the stack with imported modules. |
3035 | 0 | for (Module *M : ImportedModules) { |
3036 | | // Do not add any link flags when an implementation TU of a module imports |
3037 | | // a header of that same module. |
3038 | 0 | if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && |
3039 | 0 | !getLangOpts().isCompilingModule()) |
3040 | 0 | continue; |
3041 | 0 | if (Visited.insert(M).second) |
3042 | 0 | Stack.push_back(M); |
3043 | 0 | } |
3044 | | |
3045 | | // Find all of the modules to import, making a little effort to prune |
3046 | | // non-leaf modules. |
3047 | 0 | while (!Stack.empty()) { |
3048 | 0 | clang::Module *Mod = Stack.pop_back_val(); |
3049 | |
|
3050 | 0 | bool AnyChildren = false; |
3051 | | |
3052 | | // Visit the submodules of this module. |
3053 | 0 | for (const auto &SM : Mod->submodules()) { |
3054 | | // Skip explicit children; they need to be explicitly imported to be |
3055 | | // linked against. |
3056 | 0 | if (SM->IsExplicit) |
3057 | 0 | continue; |
3058 | | |
3059 | 0 | if (Visited.insert(SM).second) { |
3060 | 0 | Stack.push_back(SM); |
3061 | 0 | AnyChildren = true; |
3062 | 0 | } |
3063 | 0 | } |
3064 | | |
3065 | | // We didn't find any children, so add this module to the list of |
3066 | | // modules to link against. |
3067 | 0 | if (!AnyChildren) { |
3068 | 0 | LinkModules.insert(Mod); |
3069 | 0 | } |
3070 | 0 | } |
3071 | | |
3072 | | // Add link options for all of the imported modules in reverse topological |
3073 | | // order. We don't do anything to try to order import link flags with respect |
3074 | | // to linker options inserted by things like #pragma comment(). |
3075 | 0 | SmallVector<llvm::MDNode *, 16> MetadataArgs; |
3076 | 0 | Visited.clear(); |
3077 | 0 | for (Module *M : LinkModules) |
3078 | 0 | if (Visited.insert(M).second) |
3079 | 0 | addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); |
3080 | 0 | std::reverse(MetadataArgs.begin(), MetadataArgs.end()); |
3081 | 0 | LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); |
3082 | | |
3083 | | // Add the linker options metadata flag. |
3084 | 0 | auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); |
3085 | 0 | for (auto *MD : LinkerOptionsMetadata) |
3086 | 0 | NMD->addOperand(MD); |
3087 | 0 | } |
3088 | | |
3089 | 0 | void CodeGenModule::EmitDeferred() { |
3090 | | // Emit deferred declare target declarations. |
3091 | 0 | if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) |
3092 | 0 | getOpenMPRuntime().emitDeferredTargetDecls(); |
3093 | | |
3094 | | // Emit code for any potentially referenced deferred decls. Since a |
3095 | | // previously unused static decl may become used during the generation of code |
3096 | | // for a static function, iterate until no changes are made. |
3097 | |
|
3098 | 0 | if (!DeferredVTables.empty()) { |
3099 | 0 | EmitDeferredVTables(); |
3100 | | |
3101 | | // Emitting a vtable doesn't directly cause more vtables to |
3102 | | // become deferred, although it can cause functions to be |
3103 | | // emitted that then need those vtables. |
3104 | 0 | assert(DeferredVTables.empty()); |
3105 | 0 | } |
3106 | | |
3107 | | // Emit CUDA/HIP static device variables referenced by host code only. |
3108 | | // Note we should not clear CUDADeviceVarODRUsedByHost since it is still |
3109 | | // needed for further handling. |
3110 | 0 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) |
3111 | 0 | llvm::append_range(DeferredDeclsToEmit, |
3112 | 0 | getContext().CUDADeviceVarODRUsedByHost); |
3113 | | |
3114 | | // Stop if we're out of both deferred vtables and deferred declarations. |
3115 | 0 | if (DeferredDeclsToEmit.empty()) |
3116 | 0 | return; |
3117 | | |
3118 | | // Grab the list of decls to emit. If EmitGlobalDefinition schedules more |
3119 | | // work, it will not interfere with this. |
3120 | 0 | std::vector<GlobalDecl> CurDeclsToEmit; |
3121 | 0 | CurDeclsToEmit.swap(DeferredDeclsToEmit); |
3122 | |
|
3123 | 0 | for (GlobalDecl &D : CurDeclsToEmit) { |
3124 | | // We should call GetAddrOfGlobal with IsForDefinition set to true in order |
3125 | | // to get GlobalValue with exactly the type we need, not something that |
3126 | | // might had been created for another decl with the same mangled name but |
3127 | | // different type. |
3128 | 0 | llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( |
3129 | 0 | GetAddrOfGlobal(D, ForDefinition)); |
3130 | | |
3131 | | // In case of different address spaces, we may still get a cast, even with |
3132 | | // IsForDefinition equal to true. Query mangled names table to get |
3133 | | // GlobalValue. |
3134 | 0 | if (!GV) |
3135 | 0 | GV = GetGlobalValue(getMangledName(D)); |
3136 | | |
3137 | | // Make sure GetGlobalValue returned non-null. |
3138 | 0 | assert(GV); |
3139 | | |
3140 | | // Check to see if we've already emitted this. This is necessary |
3141 | | // for a couple of reasons: first, decls can end up in the |
3142 | | // deferred-decls queue multiple times, and second, decls can end |
3143 | | // up with definitions in unusual ways (e.g. by an extern inline |
3144 | | // function acquiring a strong function redefinition). Just |
3145 | | // ignore these cases. |
3146 | 0 | if (!GV->isDeclaration()) |
3147 | 0 | continue; |
3148 | | |
3149 | | // If this is OpenMP, check if it is legal to emit this global normally. |
3150 | 0 | if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) |
3151 | 0 | continue; |
3152 | | |
3153 | | // Otherwise, emit the definition and move on to the next one. |
3154 | 0 | EmitGlobalDefinition(D, GV); |
3155 | | |
3156 | | // If we found out that we need to emit more decls, do that recursively. |
3157 | | // This has the advantage that the decls are emitted in a DFS and related |
3158 | | // ones are close together, which is convenient for testing. |
3159 | 0 | if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { |
3160 | 0 | EmitDeferred(); |
3161 | 0 | assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); |
3162 | 0 | } |
3163 | 0 | } |
3164 | 0 | } |
3165 | | |
3166 | 0 | void CodeGenModule::EmitVTablesOpportunistically() { |
3167 | | // Try to emit external vtables as available_externally if they have emitted |
3168 | | // all inlined virtual functions. It runs after EmitDeferred() and therefore |
3169 | | // is not allowed to create new references to things that need to be emitted |
3170 | | // lazily. Note that it also uses fact that we eagerly emitting RTTI. |
3171 | |
|
3172 | 0 | assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) |
3173 | 0 | && "Only emit opportunistic vtables with optimizations"); |
3174 | | |
3175 | 0 | for (const CXXRecordDecl *RD : OpportunisticVTables) { |
3176 | 0 | assert(getVTables().isVTableExternal(RD) && |
3177 | 0 | "This queue should only contain external vtables"); |
3178 | 0 | if (getCXXABI().canSpeculativelyEmitVTable(RD)) |
3179 | 0 | VTables.GenerateClassData(RD); |
3180 | 0 | } |
3181 | 0 | OpportunisticVTables.clear(); |
3182 | 0 | } |
3183 | | |
3184 | 0 | void CodeGenModule::EmitGlobalAnnotations() { |
3185 | 0 | for (const auto& [MangledName, VD] : DeferredAnnotations) { |
3186 | 0 | llvm::GlobalValue *GV = GetGlobalValue(MangledName); |
3187 | 0 | if (GV) |
3188 | 0 | AddGlobalAnnotations(VD, GV); |
3189 | 0 | } |
3190 | 0 | DeferredAnnotations.clear(); |
3191 | |
|
3192 | 0 | if (Annotations.empty()) |
3193 | 0 | return; |
3194 | | |
3195 | | // Create a new global variable for the ConstantStruct in the Module. |
3196 | 0 | llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( |
3197 | 0 | Annotations[0]->getType(), Annotations.size()), Annotations); |
3198 | 0 | auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, |
3199 | 0 | llvm::GlobalValue::AppendingLinkage, |
3200 | 0 | Array, "llvm.global.annotations"); |
3201 | 0 | gv->setSection(AnnotationSection); |
3202 | 0 | } |
3203 | | |
3204 | 0 | llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { |
3205 | 0 | llvm::Constant *&AStr = AnnotationStrings[Str]; |
3206 | 0 | if (AStr) |
3207 | 0 | return AStr; |
3208 | | |
3209 | | // Not found yet, create a new global. |
3210 | 0 | llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); |
3211 | 0 | auto *gv = new llvm::GlobalVariable( |
3212 | 0 | getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, |
3213 | 0 | ".str", nullptr, llvm::GlobalValue::NotThreadLocal, |
3214 | 0 | ConstGlobalsPtrTy->getAddressSpace()); |
3215 | 0 | gv->setSection(AnnotationSection); |
3216 | 0 | gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
3217 | 0 | AStr = gv; |
3218 | 0 | return gv; |
3219 | 0 | } |
3220 | | |
3221 | 0 | llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { |
3222 | 0 | SourceManager &SM = getContext().getSourceManager(); |
3223 | 0 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); |
3224 | 0 | if (PLoc.isValid()) |
3225 | 0 | return EmitAnnotationString(PLoc.getFilename()); |
3226 | 0 | return EmitAnnotationString(SM.getBufferName(Loc)); |
3227 | 0 | } |
3228 | | |
3229 | 0 | llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { |
3230 | 0 | SourceManager &SM = getContext().getSourceManager(); |
3231 | 0 | PresumedLoc PLoc = SM.getPresumedLoc(L); |
3232 | 0 | unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : |
3233 | 0 | SM.getExpansionLineNumber(L); |
3234 | 0 | return llvm::ConstantInt::get(Int32Ty, LineNo); |
3235 | 0 | } |
3236 | | |
3237 | 0 | llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { |
3238 | 0 | ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; |
3239 | 0 | if (Exprs.empty()) |
3240 | 0 | return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy); |
3241 | | |
3242 | 0 | llvm::FoldingSetNodeID ID; |
3243 | 0 | for (Expr *E : Exprs) { |
3244 | 0 | ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); |
3245 | 0 | } |
3246 | 0 | llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; |
3247 | 0 | if (Lookup) |
3248 | 0 | return Lookup; |
3249 | | |
3250 | 0 | llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; |
3251 | 0 | LLVMArgs.reserve(Exprs.size()); |
3252 | 0 | ConstantEmitter ConstEmiter(*this); |
3253 | 0 | llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { |
3254 | 0 | const auto *CE = cast<clang::ConstantExpr>(E); |
3255 | 0 | return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), |
3256 | 0 | CE->getType()); |
3257 | 0 | }); |
3258 | 0 | auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); |
3259 | 0 | auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, |
3260 | 0 | llvm::GlobalValue::PrivateLinkage, Struct, |
3261 | 0 | ".args"); |
3262 | 0 | GV->setSection(AnnotationSection); |
3263 | 0 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
3264 | |
|
3265 | 0 | Lookup = GV; |
3266 | 0 | return GV; |
3267 | 0 | } |
3268 | | |
3269 | | llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, |
3270 | | const AnnotateAttr *AA, |
3271 | 0 | SourceLocation L) { |
3272 | | // Get the globals for file name, annotation, and the line number. |
3273 | 0 | llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), |
3274 | 0 | *UnitGV = EmitAnnotationUnit(L), |
3275 | 0 | *LineNoCst = EmitAnnotationLineNo(L), |
3276 | 0 | *Args = EmitAnnotationArgs(AA); |
3277 | |
|
3278 | 0 | llvm::Constant *GVInGlobalsAS = GV; |
3279 | 0 | if (GV->getAddressSpace() != |
3280 | 0 | getDataLayout().getDefaultGlobalsAddressSpace()) { |
3281 | 0 | GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( |
3282 | 0 | GV, |
3283 | 0 | llvm::PointerType::get( |
3284 | 0 | GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace())); |
3285 | 0 | } |
3286 | | |
3287 | | // Create the ConstantStruct for the global annotation. |
3288 | 0 | llvm::Constant *Fields[] = { |
3289 | 0 | GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args, |
3290 | 0 | }; |
3291 | 0 | return llvm::ConstantStruct::getAnon(Fields); |
3292 | 0 | } |
3293 | | |
3294 | | void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, |
3295 | 0 | llvm::GlobalValue *GV) { |
3296 | 0 | assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); |
3297 | | // Get the struct elements for these annotations. |
3298 | 0 | for (const auto *I : D->specific_attrs<AnnotateAttr>()) |
3299 | 0 | Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); |
3300 | 0 | } |
3301 | | |
3302 | | bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, |
3303 | 0 | SourceLocation Loc) const { |
3304 | 0 | const auto &NoSanitizeL = getContext().getNoSanitizeList(); |
3305 | | // NoSanitize by function name. |
3306 | 0 | if (NoSanitizeL.containsFunction(Kind, Fn->getName())) |
3307 | 0 | return true; |
3308 | | // NoSanitize by location. Check "mainfile" prefix. |
3309 | 0 | auto &SM = Context.getSourceManager(); |
3310 | 0 | FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID()); |
3311 | 0 | if (NoSanitizeL.containsMainFile(Kind, MainFile.getName())) |
3312 | 0 | return true; |
3313 | | |
3314 | | // Check "src" prefix. |
3315 | 0 | if (Loc.isValid()) |
3316 | 0 | return NoSanitizeL.containsLocation(Kind, Loc); |
3317 | | // If location is unknown, this may be a compiler-generated function. Assume |
3318 | | // it's located in the main file. |
3319 | 0 | return NoSanitizeL.containsFile(Kind, MainFile.getName()); |
3320 | 0 | } |
3321 | | |
3322 | | bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, |
3323 | | llvm::GlobalVariable *GV, |
3324 | | SourceLocation Loc, QualType Ty, |
3325 | 0 | StringRef Category) const { |
3326 | 0 | const auto &NoSanitizeL = getContext().getNoSanitizeList(); |
3327 | 0 | if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) |
3328 | 0 | return true; |
3329 | 0 | auto &SM = Context.getSourceManager(); |
3330 | 0 | if (NoSanitizeL.containsMainFile( |
3331 | 0 | Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(), |
3332 | 0 | Category)) |
3333 | 0 | return true; |
3334 | 0 | if (NoSanitizeL.containsLocation(Kind, Loc, Category)) |
3335 | 0 | return true; |
3336 | | |
3337 | | // Check global type. |
3338 | 0 | if (!Ty.isNull()) { |
3339 | | // Drill down the array types: if global variable of a fixed type is |
3340 | | // not sanitized, we also don't instrument arrays of them. |
3341 | 0 | while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) |
3342 | 0 | Ty = AT->getElementType(); |
3343 | 0 | Ty = Ty.getCanonicalType().getUnqualifiedType(); |
3344 | | // Only record types (classes, structs etc.) are ignored. |
3345 | 0 | if (Ty->isRecordType()) { |
3346 | 0 | std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); |
3347 | 0 | if (NoSanitizeL.containsType(Kind, TypeStr, Category)) |
3348 | 0 | return true; |
3349 | 0 | } |
3350 | 0 | } |
3351 | 0 | return false; |
3352 | 0 | } |
3353 | | |
3354 | | bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, |
3355 | 0 | StringRef Category) const { |
3356 | 0 | const auto &XRayFilter = getContext().getXRayFilter(); |
3357 | 0 | using ImbueAttr = XRayFunctionFilter::ImbueAttribute; |
3358 | 0 | auto Attr = ImbueAttr::NONE; |
3359 | 0 | if (Loc.isValid()) |
3360 | 0 | Attr = XRayFilter.shouldImbueLocation(Loc, Category); |
3361 | 0 | if (Attr == ImbueAttr::NONE) |
3362 | 0 | Attr = XRayFilter.shouldImbueFunction(Fn->getName()); |
3363 | 0 | switch (Attr) { |
3364 | 0 | case ImbueAttr::NONE: |
3365 | 0 | return false; |
3366 | 0 | case ImbueAttr::ALWAYS: |
3367 | 0 | Fn->addFnAttr("function-instrument", "xray-always"); |
3368 | 0 | break; |
3369 | 0 | case ImbueAttr::ALWAYS_ARG1: |
3370 | 0 | Fn->addFnAttr("function-instrument", "xray-always"); |
3371 | 0 | Fn->addFnAttr("xray-log-args", "1"); |
3372 | 0 | break; |
3373 | 0 | case ImbueAttr::NEVER: |
3374 | 0 | Fn->addFnAttr("function-instrument", "xray-never"); |
3375 | 0 | break; |
3376 | 0 | } |
3377 | 0 | return true; |
3378 | 0 | } |
3379 | | |
3380 | | ProfileList::ExclusionType |
3381 | | CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, |
3382 | 0 | SourceLocation Loc) const { |
3383 | 0 | const auto &ProfileList = getContext().getProfileList(); |
3384 | | // If the profile list is empty, then instrument everything. |
3385 | 0 | if (ProfileList.isEmpty()) |
3386 | 0 | return ProfileList::Allow; |
3387 | 0 | CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); |
3388 | | // First, check the function name. |
3389 | 0 | if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) |
3390 | 0 | return *V; |
3391 | | // Next, check the source location. |
3392 | 0 | if (Loc.isValid()) |
3393 | 0 | if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) |
3394 | 0 | return *V; |
3395 | | // If location is unknown, this may be a compiler-generated function. Assume |
3396 | | // it's located in the main file. |
3397 | 0 | auto &SM = Context.getSourceManager(); |
3398 | 0 | if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID())) |
3399 | 0 | if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) |
3400 | 0 | return *V; |
3401 | 0 | return ProfileList.getDefault(Kind); |
3402 | 0 | } |
3403 | | |
3404 | | ProfileList::ExclusionType |
3405 | | CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, |
3406 | 0 | SourceLocation Loc) const { |
3407 | 0 | auto V = isFunctionBlockedByProfileList(Fn, Loc); |
3408 | 0 | if (V != ProfileList::Allow) |
3409 | 0 | return V; |
3410 | | |
3411 | 0 | auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; |
3412 | 0 | if (NumGroups > 1) { |
3413 | 0 | auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups; |
3414 | 0 | if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) |
3415 | 0 | return ProfileList::Skip; |
3416 | 0 | } |
3417 | 0 | return ProfileList::Allow; |
3418 | 0 | } |
3419 | | |
3420 | 0 | bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { |
3421 | | // Never defer when EmitAllDecls is specified. |
3422 | 0 | if (LangOpts.EmitAllDecls) |
3423 | 0 | return true; |
3424 | | |
3425 | 0 | const auto *VD = dyn_cast<VarDecl>(Global); |
3426 | 0 | if (VD && |
3427 | 0 | ((CodeGenOpts.KeepPersistentStorageVariables && |
3428 | 0 | (VD->getStorageDuration() == SD_Static || |
3429 | 0 | VD->getStorageDuration() == SD_Thread)) || |
3430 | 0 | (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && |
3431 | 0 | VD->getType().isConstQualified()))) |
3432 | 0 | return true; |
3433 | | |
3434 | 0 | return getContext().DeclMustBeEmitted(Global); |
3435 | 0 | } |
3436 | | |
3437 | 0 | bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { |
3438 | | // In OpenMP 5.0 variables and function may be marked as |
3439 | | // device_type(host/nohost) and we should not emit them eagerly unless we sure |
3440 | | // that they must be emitted on the host/device. To be sure we need to have |
3441 | | // seen a declare target with an explicit mentioning of the function, we know |
3442 | | // we have if the level of the declare target attribute is -1. Note that we |
3443 | | // check somewhere else if we should emit this at all. |
3444 | 0 | if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { |
3445 | 0 | std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = |
3446 | 0 | OMPDeclareTargetDeclAttr::getActiveAttr(Global); |
3447 | 0 | if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) |
3448 | 0 | return false; |
3449 | 0 | } |
3450 | | |
3451 | 0 | if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { |
3452 | 0 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
3453 | | // Implicit template instantiations may change linkage if they are later |
3454 | | // explicitly instantiated, so they should not be emitted eagerly. |
3455 | 0 | return false; |
3456 | 0 | } |
3457 | 0 | if (const auto *VD = dyn_cast<VarDecl>(Global)) { |
3458 | 0 | if (Context.getInlineVariableDefinitionKind(VD) == |
3459 | 0 | ASTContext::InlineVariableDefinitionKind::WeakUnknown) |
3460 | | // A definition of an inline constexpr static data member may change |
3461 | | // linkage later if it's redeclared outside the class. |
3462 | 0 | return false; |
3463 | 0 | if (CXX20ModuleInits && VD->getOwningModule() && |
3464 | 0 | !VD->getOwningModule()->isModuleMapModule()) { |
3465 | | // For CXX20, module-owned initializers need to be deferred, since it is |
3466 | | // not known at this point if they will be run for the current module or |
3467 | | // as part of the initializer for an imported one. |
3468 | 0 | return false; |
3469 | 0 | } |
3470 | 0 | } |
3471 | | // If OpenMP is enabled and threadprivates must be generated like TLS, delay |
3472 | | // codegen for global variables, because they may be marked as threadprivate. |
3473 | 0 | if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && |
3474 | 0 | getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && |
3475 | 0 | !Global->getType().isConstantStorage(getContext(), false, false) && |
3476 | 0 | !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) |
3477 | 0 | return false; |
3478 | | |
3479 | 0 | return true; |
3480 | 0 | } |
3481 | | |
3482 | 0 | ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { |
3483 | 0 | StringRef Name = getMangledName(GD); |
3484 | | |
3485 | | // The UUID descriptor should be pointer aligned. |
3486 | 0 | CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); |
3487 | | |
3488 | | // Look for an existing global. |
3489 | 0 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) |
3490 | 0 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3491 | | |
3492 | 0 | ConstantEmitter Emitter(*this); |
3493 | 0 | llvm::Constant *Init; |
3494 | |
|
3495 | 0 | APValue &V = GD->getAsAPValue(); |
3496 | 0 | if (!V.isAbsent()) { |
3497 | | // If possible, emit the APValue version of the initializer. In particular, |
3498 | | // this gets the type of the constant right. |
3499 | 0 | Init = Emitter.emitForInitializer( |
3500 | 0 | GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); |
3501 | 0 | } else { |
3502 | | // As a fallback, directly construct the constant. |
3503 | | // FIXME: This may get padding wrong under esoteric struct layout rules. |
3504 | | // MSVC appears to create a complete type 'struct __s_GUID' that it |
3505 | | // presumably uses to represent these constants. |
3506 | 0 | MSGuidDecl::Parts Parts = GD->getParts(); |
3507 | 0 | llvm::Constant *Fields[4] = { |
3508 | 0 | llvm::ConstantInt::get(Int32Ty, Parts.Part1), |
3509 | 0 | llvm::ConstantInt::get(Int16Ty, Parts.Part2), |
3510 | 0 | llvm::ConstantInt::get(Int16Ty, Parts.Part3), |
3511 | 0 | llvm::ConstantDataArray::getRaw( |
3512 | 0 | StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, |
3513 | 0 | Int8Ty)}; |
3514 | 0 | Init = llvm::ConstantStruct::getAnon(Fields); |
3515 | 0 | } |
3516 | |
|
3517 | 0 | auto *GV = new llvm::GlobalVariable( |
3518 | 0 | getModule(), Init->getType(), |
3519 | 0 | /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); |
3520 | 0 | if (supportsCOMDAT()) |
3521 | 0 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); |
3522 | 0 | setDSOLocal(GV); |
3523 | |
|
3524 | 0 | if (!V.isAbsent()) { |
3525 | 0 | Emitter.finalize(GV); |
3526 | 0 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3527 | 0 | } |
3528 | | |
3529 | 0 | llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); |
3530 | 0 | return ConstantAddress(GV, Ty, Alignment); |
3531 | 0 | } |
3532 | | |
3533 | | ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( |
3534 | 0 | const UnnamedGlobalConstantDecl *GCD) { |
3535 | 0 | CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); |
3536 | |
|
3537 | 0 | llvm::GlobalVariable **Entry = nullptr; |
3538 | 0 | Entry = &UnnamedGlobalConstantDeclMap[GCD]; |
3539 | 0 | if (*Entry) |
3540 | 0 | return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); |
3541 | | |
3542 | 0 | ConstantEmitter Emitter(*this); |
3543 | 0 | llvm::Constant *Init; |
3544 | |
|
3545 | 0 | const APValue &V = GCD->getValue(); |
3546 | |
|
3547 | 0 | assert(!V.isAbsent()); |
3548 | 0 | Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), |
3549 | 0 | GCD->getType()); |
3550 | |
|
3551 | 0 | auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), |
3552 | 0 | /*isConstant=*/true, |
3553 | 0 | llvm::GlobalValue::PrivateLinkage, Init, |
3554 | 0 | ".constant"); |
3555 | 0 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
3556 | 0 | GV->setAlignment(Alignment.getAsAlign()); |
3557 | |
|
3558 | 0 | Emitter.finalize(GV); |
3559 | |
|
3560 | 0 | *Entry = GV; |
3561 | 0 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3562 | 0 | } |
3563 | | |
3564 | | ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( |
3565 | 0 | const TemplateParamObjectDecl *TPO) { |
3566 | 0 | StringRef Name = getMangledName(TPO); |
3567 | 0 | CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); |
3568 | |
|
3569 | 0 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) |
3570 | 0 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3571 | | |
3572 | 0 | ConstantEmitter Emitter(*this); |
3573 | 0 | llvm::Constant *Init = Emitter.emitForInitializer( |
3574 | 0 | TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); |
3575 | |
|
3576 | 0 | if (!Init) { |
3577 | 0 | ErrorUnsupported(TPO, "template parameter object"); |
3578 | 0 | return ConstantAddress::invalid(); |
3579 | 0 | } |
3580 | | |
3581 | 0 | llvm::GlobalValue::LinkageTypes Linkage = |
3582 | 0 | isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage()) |
3583 | 0 | ? llvm::GlobalValue::LinkOnceODRLinkage |
3584 | 0 | : llvm::GlobalValue::InternalLinkage; |
3585 | 0 | auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), |
3586 | 0 | /*isConstant=*/true, Linkage, Init, Name); |
3587 | 0 | setGVProperties(GV, TPO); |
3588 | 0 | if (supportsCOMDAT()) |
3589 | 0 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); |
3590 | 0 | Emitter.finalize(GV); |
3591 | |
|
3592 | 0 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3593 | 0 | } |
3594 | | |
3595 | 0 | ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { |
3596 | 0 | const AliasAttr *AA = VD->getAttr<AliasAttr>(); |
3597 | 0 | assert(AA && "No alias?"); |
3598 | | |
3599 | 0 | CharUnits Alignment = getContext().getDeclAlign(VD); |
3600 | 0 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); |
3601 | | |
3602 | | // See if there is already something with the target's name in the module. |
3603 | 0 | llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); |
3604 | 0 | if (Entry) |
3605 | 0 | return ConstantAddress(Entry, DeclTy, Alignment); |
3606 | | |
3607 | 0 | llvm::Constant *Aliasee; |
3608 | 0 | if (isa<llvm::FunctionType>(DeclTy)) |
3609 | 0 | Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, |
3610 | 0 | GlobalDecl(cast<FunctionDecl>(VD)), |
3611 | 0 | /*ForVTable=*/false); |
3612 | 0 | else |
3613 | 0 | Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, |
3614 | 0 | nullptr); |
3615 | |
|
3616 | 0 | auto *F = cast<llvm::GlobalValue>(Aliasee); |
3617 | 0 | F->setLinkage(llvm::Function::ExternalWeakLinkage); |
3618 | 0 | WeakRefReferences.insert(F); |
3619 | |
|
3620 | 0 | return ConstantAddress(Aliasee, DeclTy, Alignment); |
3621 | 0 | } |
3622 | | |
3623 | 0 | template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) { |
3624 | 0 | if (!D) |
3625 | 0 | return false; |
3626 | 0 | if (auto *A = D->getAttr<AttrT>()) |
3627 | 0 | return A->isImplicit(); |
3628 | 0 | return D->isImplicit(); |
3629 | 0 | } Unexecuted instantiation: CodeGenModule.cpp:bool hasImplicitAttr<clang::CUDAHostAttr>(clang::ValueDecl const*) Unexecuted instantiation: CodeGenModule.cpp:bool hasImplicitAttr<clang::CUDADeviceAttr>(clang::ValueDecl const*) |
3630 | | |
3631 | 0 | void CodeGenModule::EmitGlobal(GlobalDecl GD) { |
3632 | 0 | const auto *Global = cast<ValueDecl>(GD.getDecl()); |
3633 | | |
3634 | | // Weak references don't produce any output by themselves. |
3635 | 0 | if (Global->hasAttr<WeakRefAttr>()) |
3636 | 0 | return; |
3637 | | |
3638 | | // If this is an alias definition (which otherwise looks like a declaration) |
3639 | | // emit it now. |
3640 | 0 | if (Global->hasAttr<AliasAttr>()) |
3641 | 0 | return EmitAliasDefinition(GD); |
3642 | | |
3643 | | // IFunc like an alias whose value is resolved at runtime by calling resolver. |
3644 | 0 | if (Global->hasAttr<IFuncAttr>()) |
3645 | 0 | return emitIFuncDefinition(GD); |
3646 | | |
3647 | | // If this is a cpu_dispatch multiversion function, emit the resolver. |
3648 | 0 | if (Global->hasAttr<CPUDispatchAttr>()) |
3649 | 0 | return emitCPUDispatchDefinition(GD); |
3650 | | |
3651 | | // If this is CUDA, be selective about which declarations we emit. |
3652 | | // Non-constexpr non-lambda implicit host device functions are not emitted |
3653 | | // unless they are used on device side. |
3654 | 0 | if (LangOpts.CUDA) { |
3655 | 0 | if (LangOpts.CUDAIsDevice) { |
3656 | 0 | const auto *FD = dyn_cast<FunctionDecl>(Global); |
3657 | 0 | if ((!Global->hasAttr<CUDADeviceAttr>() || |
3658 | 0 | (LangOpts.OffloadImplicitHostDeviceTemplates && FD && |
3659 | 0 | hasImplicitAttr<CUDAHostAttr>(FD) && |
3660 | 0 | hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() && |
3661 | 0 | !isLambdaCallOperator(FD) && |
3662 | 0 | !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) && |
3663 | 0 | !Global->hasAttr<CUDAGlobalAttr>() && |
3664 | 0 | !Global->hasAttr<CUDAConstantAttr>() && |
3665 | 0 | !Global->hasAttr<CUDASharedAttr>() && |
3666 | 0 | !Global->getType()->isCUDADeviceBuiltinSurfaceType() && |
3667 | 0 | !Global->getType()->isCUDADeviceBuiltinTextureType() && |
3668 | 0 | !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) && |
3669 | 0 | !Global->hasAttr<CUDAHostAttr>())) |
3670 | 0 | return; |
3671 | 0 | } else { |
3672 | | // We need to emit host-side 'shadows' for all global |
3673 | | // device-side variables because the CUDA runtime needs their |
3674 | | // size and host-side address in order to provide access to |
3675 | | // their device-side incarnations. |
3676 | | |
3677 | | // So device-only functions are the only things we skip. |
3678 | 0 | if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && |
3679 | 0 | Global->hasAttr<CUDADeviceAttr>()) |
3680 | 0 | return; |
3681 | | |
3682 | 0 | assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && |
3683 | 0 | "Expected Variable or Function"); |
3684 | 0 | } |
3685 | 0 | } |
3686 | | |
3687 | 0 | if (LangOpts.OpenMP) { |
3688 | | // If this is OpenMP, check if it is legal to emit this global normally. |
3689 | 0 | if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) |
3690 | 0 | return; |
3691 | 0 | if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { |
3692 | 0 | if (MustBeEmitted(Global)) |
3693 | 0 | EmitOMPDeclareReduction(DRD); |
3694 | 0 | return; |
3695 | 0 | } |
3696 | 0 | if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { |
3697 | 0 | if (MustBeEmitted(Global)) |
3698 | 0 | EmitOMPDeclareMapper(DMD); |
3699 | 0 | return; |
3700 | 0 | } |
3701 | 0 | } |
3702 | | |
3703 | | // Ignore declarations, they will be emitted on their first use. |
3704 | 0 | if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { |
3705 | | // Update deferred annotations with the latest declaration if the function |
3706 | | // function was already used or defined. |
3707 | 0 | if (FD->hasAttr<AnnotateAttr>()) { |
3708 | 0 | StringRef MangledName = getMangledName(GD); |
3709 | 0 | if (GetGlobalValue(MangledName)) |
3710 | 0 | DeferredAnnotations[MangledName] = FD; |
3711 | 0 | } |
3712 | | |
3713 | | // Forward declarations are emitted lazily on first use. |
3714 | 0 | if (!FD->doesThisDeclarationHaveABody()) { |
3715 | 0 | if (!FD->doesDeclarationForceExternallyVisibleDefinition()) |
3716 | 0 | return; |
3717 | | |
3718 | 0 | StringRef MangledName = getMangledName(GD); |
3719 | | |
3720 | | // Compute the function info and LLVM type. |
3721 | 0 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
3722 | 0 | llvm::Type *Ty = getTypes().GetFunctionType(FI); |
3723 | |
|
3724 | 0 | GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, |
3725 | 0 | /*DontDefer=*/false); |
3726 | 0 | return; |
3727 | 0 | } |
3728 | 0 | } else { |
3729 | 0 | const auto *VD = cast<VarDecl>(Global); |
3730 | 0 | assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); |
3731 | 0 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition && |
3732 | 0 | !Context.isMSStaticDataMemberInlineDefinition(VD)) { |
3733 | 0 | if (LangOpts.OpenMP) { |
3734 | | // Emit declaration of the must-be-emitted declare target variable. |
3735 | 0 | if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = |
3736 | 0 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { |
3737 | | |
3738 | | // If this variable has external storage and doesn't require special |
3739 | | // link handling we defer to its canonical definition. |
3740 | 0 | if (VD->hasExternalStorage() && |
3741 | 0 | Res != OMPDeclareTargetDeclAttr::MT_Link) |
3742 | 0 | return; |
3743 | | |
3744 | 0 | bool UnifiedMemoryEnabled = |
3745 | 0 | getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); |
3746 | 0 | if ((*Res == OMPDeclareTargetDeclAttr::MT_To || |
3747 | 0 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && |
3748 | 0 | !UnifiedMemoryEnabled) { |
3749 | 0 | (void)GetAddrOfGlobalVar(VD); |
3750 | 0 | } else { |
3751 | 0 | assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || |
3752 | 0 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || |
3753 | 0 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && |
3754 | 0 | UnifiedMemoryEnabled)) && |
3755 | 0 | "Link clause or to clause with unified memory expected."); |
3756 | 0 | (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); |
3757 | 0 | } |
3758 | | |
3759 | 0 | return; |
3760 | 0 | } |
3761 | 0 | } |
3762 | | // If this declaration may have caused an inline variable definition to |
3763 | | // change linkage, make sure that it's emitted. |
3764 | 0 | if (Context.getInlineVariableDefinitionKind(VD) == |
3765 | 0 | ASTContext::InlineVariableDefinitionKind::Strong) |
3766 | 0 | GetAddrOfGlobalVar(VD); |
3767 | 0 | return; |
3768 | 0 | } |
3769 | 0 | } |
3770 | | |
3771 | | // Defer code generation to first use when possible, e.g. if this is an inline |
3772 | | // function. If the global must always be emitted, do it eagerly if possible |
3773 | | // to benefit from cache locality. |
3774 | 0 | if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { |
3775 | | // Emit the definition if it can't be deferred. |
3776 | 0 | EmitGlobalDefinition(GD); |
3777 | 0 | addEmittedDeferredDecl(GD); |
3778 | 0 | return; |
3779 | 0 | } |
3780 | | |
3781 | | // If we're deferring emission of a C++ variable with an |
3782 | | // initializer, remember the order in which it appeared in the file. |
3783 | 0 | if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && |
3784 | 0 | cast<VarDecl>(Global)->hasInit()) { |
3785 | 0 | DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); |
3786 | 0 | CXXGlobalInits.push_back(nullptr); |
3787 | 0 | } |
3788 | |
|
3789 | 0 | StringRef MangledName = getMangledName(GD); |
3790 | 0 | if (GetGlobalValue(MangledName) != nullptr) { |
3791 | | // The value has already been used and should therefore be emitted. |
3792 | 0 | addDeferredDeclToEmit(GD); |
3793 | 0 | } else if (MustBeEmitted(Global)) { |
3794 | | // The value must be emitted, but cannot be emitted eagerly. |
3795 | 0 | assert(!MayBeEmittedEagerly(Global)); |
3796 | 0 | addDeferredDeclToEmit(GD); |
3797 | 0 | } else { |
3798 | | // Otherwise, remember that we saw a deferred decl with this name. The |
3799 | | // first use of the mangled name will cause it to move into |
3800 | | // DeferredDeclsToEmit. |
3801 | 0 | DeferredDecls[MangledName] = GD; |
3802 | 0 | } |
3803 | 0 | } |
3804 | | |
3805 | | // Check if T is a class type with a destructor that's not dllimport. |
3806 | 0 | static bool HasNonDllImportDtor(QualType T) { |
3807 | 0 | if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) |
3808 | 0 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) |
3809 | 0 | if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) |
3810 | 0 | return true; |
3811 | | |
3812 | 0 | return false; |
3813 | 0 | } |
3814 | | |
3815 | | namespace { |
3816 | | struct FunctionIsDirectlyRecursive |
3817 | | : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { |
3818 | | const StringRef Name; |
3819 | | const Builtin::Context &BI; |
3820 | | FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) |
3821 | 0 | : Name(N), BI(C) {} |
3822 | | |
3823 | 0 | bool VisitCallExpr(const CallExpr *E) { |
3824 | 0 | const FunctionDecl *FD = E->getDirectCallee(); |
3825 | 0 | if (!FD) |
3826 | 0 | return false; |
3827 | 0 | AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); |
3828 | 0 | if (Attr && Name == Attr->getLabel()) |
3829 | 0 | return true; |
3830 | 0 | unsigned BuiltinID = FD->getBuiltinID(); |
3831 | 0 | if (!BuiltinID || !BI.isLibFunction(BuiltinID)) |
3832 | 0 | return false; |
3833 | 0 | StringRef BuiltinName = BI.getName(BuiltinID); |
3834 | 0 | if (BuiltinName.starts_with("__builtin_") && |
3835 | 0 | Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { |
3836 | 0 | return true; |
3837 | 0 | } |
3838 | 0 | return false; |
3839 | 0 | } |
3840 | | |
3841 | 0 | bool VisitStmt(const Stmt *S) { |
3842 | 0 | for (const Stmt *Child : S->children()) |
3843 | 0 | if (Child && this->Visit(Child)) |
3844 | 0 | return true; |
3845 | 0 | return false; |
3846 | 0 | } |
3847 | | }; |
3848 | | |
3849 | | // Make sure we're not referencing non-imported vars or functions. |
3850 | | struct DLLImportFunctionVisitor |
3851 | | : public RecursiveASTVisitor<DLLImportFunctionVisitor> { |
3852 | | bool SafeToInline = true; |
3853 | | |
3854 | 0 | bool shouldVisitImplicitCode() const { return true; } |
3855 | | |
3856 | 0 | bool VisitVarDecl(VarDecl *VD) { |
3857 | 0 | if (VD->getTLSKind()) { |
3858 | | // A thread-local variable cannot be imported. |
3859 | 0 | SafeToInline = false; |
3860 | 0 | return SafeToInline; |
3861 | 0 | } |
3862 | | |
3863 | | // A variable definition might imply a destructor call. |
3864 | 0 | if (VD->isThisDeclarationADefinition()) |
3865 | 0 | SafeToInline = !HasNonDllImportDtor(VD->getType()); |
3866 | |
|
3867 | 0 | return SafeToInline; |
3868 | 0 | } |
3869 | | |
3870 | 0 | bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { |
3871 | 0 | if (const auto *D = E->getTemporary()->getDestructor()) |
3872 | 0 | SafeToInline = D->hasAttr<DLLImportAttr>(); |
3873 | 0 | return SafeToInline; |
3874 | 0 | } |
3875 | | |
3876 | 0 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
3877 | 0 | ValueDecl *VD = E->getDecl(); |
3878 | 0 | if (isa<FunctionDecl>(VD)) |
3879 | 0 | SafeToInline = VD->hasAttr<DLLImportAttr>(); |
3880 | 0 | else if (VarDecl *V = dyn_cast<VarDecl>(VD)) |
3881 | 0 | SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); |
3882 | 0 | return SafeToInline; |
3883 | 0 | } |
3884 | | |
3885 | 0 | bool VisitCXXConstructExpr(CXXConstructExpr *E) { |
3886 | 0 | SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); |
3887 | 0 | return SafeToInline; |
3888 | 0 | } |
3889 | | |
3890 | 0 | bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { |
3891 | 0 | CXXMethodDecl *M = E->getMethodDecl(); |
3892 | 0 | if (!M) { |
3893 | | // Call through a pointer to member function. This is safe to inline. |
3894 | 0 | SafeToInline = true; |
3895 | 0 | } else { |
3896 | 0 | SafeToInline = M->hasAttr<DLLImportAttr>(); |
3897 | 0 | } |
3898 | 0 | return SafeToInline; |
3899 | 0 | } |
3900 | | |
3901 | 0 | bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { |
3902 | 0 | SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); |
3903 | 0 | return SafeToInline; |
3904 | 0 | } |
3905 | | |
3906 | 0 | bool VisitCXXNewExpr(CXXNewExpr *E) { |
3907 | 0 | SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); |
3908 | 0 | return SafeToInline; |
3909 | 0 | } |
3910 | | }; |
3911 | | } |
3912 | | |
3913 | | // isTriviallyRecursive - Check if this function calls another |
3914 | | // decl that, because of the asm attribute or the other decl being a builtin, |
3915 | | // ends up pointing to itself. |
3916 | | bool |
3917 | 0 | CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { |
3918 | 0 | StringRef Name; |
3919 | 0 | if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { |
3920 | | // asm labels are a special kind of mangling we have to support. |
3921 | 0 | AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); |
3922 | 0 | if (!Attr) |
3923 | 0 | return false; |
3924 | 0 | Name = Attr->getLabel(); |
3925 | 0 | } else { |
3926 | 0 | Name = FD->getName(); |
3927 | 0 | } |
3928 | | |
3929 | 0 | FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); |
3930 | 0 | const Stmt *Body = FD->getBody(); |
3931 | 0 | return Body ? Walker.Visit(Body) : false; |
3932 | 0 | } |
3933 | | |
3934 | 0 | bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { |
3935 | 0 | if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) |
3936 | 0 | return true; |
3937 | | |
3938 | 0 | const auto *F = cast<FunctionDecl>(GD.getDecl()); |
3939 | 0 | if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) |
3940 | 0 | return false; |
3941 | | |
3942 | | // We don't import function bodies from other named module units since that |
3943 | | // behavior may break ABI compatibility of the current unit. |
3944 | 0 | if (const Module *M = F->getOwningModule(); |
3945 | 0 | M && M->getTopLevelModule()->isNamedModule() && |
3946 | 0 | getContext().getCurrentNamedModule() != M->getTopLevelModule() && |
3947 | 0 | !F->hasAttr<AlwaysInlineAttr>()) |
3948 | 0 | return false; |
3949 | | |
3950 | 0 | if (F->hasAttr<NoInlineAttr>()) |
3951 | 0 | return false; |
3952 | | |
3953 | 0 | if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { |
3954 | | // Check whether it would be safe to inline this dllimport function. |
3955 | 0 | DLLImportFunctionVisitor Visitor; |
3956 | 0 | Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); |
3957 | 0 | if (!Visitor.SafeToInline) |
3958 | 0 | return false; |
3959 | | |
3960 | 0 | if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { |
3961 | | // Implicit destructor invocations aren't captured in the AST, so the |
3962 | | // check above can't see them. Check for them manually here. |
3963 | 0 | for (const Decl *Member : Dtor->getParent()->decls()) |
3964 | 0 | if (isa<FieldDecl>(Member)) |
3965 | 0 | if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) |
3966 | 0 | return false; |
3967 | 0 | for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) |
3968 | 0 | if (HasNonDllImportDtor(B.getType())) |
3969 | 0 | return false; |
3970 | 0 | } |
3971 | 0 | } |
3972 | | |
3973 | | // Inline builtins declaration must be emitted. They often are fortified |
3974 | | // functions. |
3975 | 0 | if (F->isInlineBuiltinDeclaration()) |
3976 | 0 | return true; |
3977 | | |
3978 | | // PR9614. Avoid cases where the source code is lying to us. An available |
3979 | | // externally function should have an equivalent function somewhere else, |
3980 | | // but a function that calls itself through asm label/`__builtin_` trickery is |
3981 | | // clearly not equivalent to the real implementation. |
3982 | | // This happens in glibc's btowc and in some configure checks. |
3983 | 0 | return !isTriviallyRecursive(F); |
3984 | 0 | } |
3985 | | |
3986 | 0 | bool CodeGenModule::shouldOpportunisticallyEmitVTables() { |
3987 | 0 | return CodeGenOpts.OptimizationLevel > 0; |
3988 | 0 | } |
3989 | | |
3990 | | void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, |
3991 | 0 | llvm::GlobalValue *GV) { |
3992 | 0 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); |
3993 | |
|
3994 | 0 | if (FD->isCPUSpecificMultiVersion()) { |
3995 | 0 | auto *Spec = FD->getAttr<CPUSpecificAttr>(); |
3996 | 0 | for (unsigned I = 0; I < Spec->cpus_size(); ++I) |
3997 | 0 | EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); |
3998 | 0 | } else if (FD->isTargetClonesMultiVersion()) { |
3999 | 0 | auto *Clone = FD->getAttr<TargetClonesAttr>(); |
4000 | 0 | for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) |
4001 | 0 | if (Clone->isFirstOfVersion(I)) |
4002 | 0 | EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); |
4003 | | // Ensure that the resolver function is also emitted. |
4004 | 0 | GetOrCreateMultiVersionResolver(GD); |
4005 | 0 | } else |
4006 | 0 | EmitGlobalFunctionDefinition(GD, GV); |
4007 | 0 | } |
4008 | | |
4009 | 0 | void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { |
4010 | 0 | const auto *D = cast<ValueDecl>(GD.getDecl()); |
4011 | |
|
4012 | 0 | PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), |
4013 | 0 | Context.getSourceManager(), |
4014 | 0 | "Generating code for declaration"); |
4015 | |
|
4016 | 0 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { |
4017 | | // At -O0, don't generate IR for functions with available_externally |
4018 | | // linkage. |
4019 | 0 | if (!shouldEmitFunction(GD)) |
4020 | 0 | return; |
4021 | | |
4022 | 0 | llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { |
4023 | 0 | std::string Name; |
4024 | 0 | llvm::raw_string_ostream OS(Name); |
4025 | 0 | FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), |
4026 | 0 | /*Qualified=*/true); |
4027 | 0 | return Name; |
4028 | 0 | }); |
4029 | |
|
4030 | 0 | if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { |
4031 | | // Make sure to emit the definition(s) before we emit the thunks. |
4032 | | // This is necessary for the generation of certain thunks. |
4033 | 0 | if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) |
4034 | 0 | ABI->emitCXXStructor(GD); |
4035 | 0 | else if (FD->isMultiVersion()) |
4036 | 0 | EmitMultiVersionFunctionDefinition(GD, GV); |
4037 | 0 | else |
4038 | 0 | EmitGlobalFunctionDefinition(GD, GV); |
4039 | |
|
4040 | 0 | if (Method->isVirtual()) |
4041 | 0 | getVTables().EmitThunks(GD); |
4042 | |
|
4043 | 0 | return; |
4044 | 0 | } |
4045 | | |
4046 | 0 | if (FD->isMultiVersion()) |
4047 | 0 | return EmitMultiVersionFunctionDefinition(GD, GV); |
4048 | 0 | return EmitGlobalFunctionDefinition(GD, GV); |
4049 | 0 | } |
4050 | | |
4051 | 0 | if (const auto *VD = dyn_cast<VarDecl>(D)) |
4052 | 0 | return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); |
4053 | | |
4054 | 0 | llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); |
4055 | 0 | } |
4056 | | |
4057 | | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, |
4058 | | llvm::Function *NewFn); |
4059 | | |
4060 | | static unsigned |
4061 | | TargetMVPriority(const TargetInfo &TI, |
4062 | 0 | const CodeGenFunction::MultiVersionResolverOption &RO) { |
4063 | 0 | unsigned Priority = 0; |
4064 | 0 | unsigned NumFeatures = 0; |
4065 | 0 | for (StringRef Feat : RO.Conditions.Features) { |
4066 | 0 | Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); |
4067 | 0 | NumFeatures++; |
4068 | 0 | } |
4069 | |
|
4070 | 0 | if (!RO.Conditions.Architecture.empty()) |
4071 | 0 | Priority = std::max( |
4072 | 0 | Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); |
4073 | |
|
4074 | 0 | Priority += TI.multiVersionFeatureCost() * NumFeatures; |
4075 | |
|
4076 | 0 | return Priority; |
4077 | 0 | } |
4078 | | |
4079 | | // Multiversion functions should be at most 'WeakODRLinkage' so that a different |
4080 | | // TU can forward declare the function without causing problems. Particularly |
4081 | | // in the cases of CPUDispatch, this causes issues. This also makes sure we |
4082 | | // work with internal linkage functions, so that the same function name can be |
4083 | | // used with internal linkage in multiple TUs. |
4084 | | llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, |
4085 | 0 | GlobalDecl GD) { |
4086 | 0 | const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); |
4087 | 0 | if (FD->getFormalLinkage() == Linkage::Internal) |
4088 | 0 | return llvm::GlobalValue::InternalLinkage; |
4089 | 0 | return llvm::GlobalValue::WeakODRLinkage; |
4090 | 0 | } |
4091 | | |
4092 | 0 | void CodeGenModule::emitMultiVersionFunctions() { |
4093 | 0 | std::vector<GlobalDecl> MVFuncsToEmit; |
4094 | 0 | MultiVersionFuncs.swap(MVFuncsToEmit); |
4095 | 0 | for (GlobalDecl GD : MVFuncsToEmit) { |
4096 | 0 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); |
4097 | 0 | assert(FD && "Expected a FunctionDecl"); |
4098 | | |
4099 | 0 | SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; |
4100 | 0 | if (FD->isTargetMultiVersion()) { |
4101 | 0 | getContext().forEachMultiversionedFunctionVersion( |
4102 | 0 | FD, [this, &GD, &Options](const FunctionDecl *CurFD) { |
4103 | 0 | GlobalDecl CurGD{ |
4104 | 0 | (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; |
4105 | 0 | StringRef MangledName = getMangledName(CurGD); |
4106 | 0 | llvm::Constant *Func = GetGlobalValue(MangledName); |
4107 | 0 | if (!Func) { |
4108 | 0 | if (CurFD->isDefined()) { |
4109 | 0 | EmitGlobalFunctionDefinition(CurGD, nullptr); |
4110 | 0 | Func = GetGlobalValue(MangledName); |
4111 | 0 | } else { |
4112 | 0 | const CGFunctionInfo &FI = |
4113 | 0 | getTypes().arrangeGlobalDeclaration(GD); |
4114 | 0 | llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); |
4115 | 0 | Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, |
4116 | 0 | /*DontDefer=*/false, ForDefinition); |
4117 | 0 | } |
4118 | 0 | assert(Func && "This should have just been created"); |
4119 | 0 | } |
4120 | 0 | if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { |
4121 | 0 | const auto *TA = CurFD->getAttr<TargetAttr>(); |
4122 | 0 | llvm::SmallVector<StringRef, 8> Feats; |
4123 | 0 | TA->getAddedFeatures(Feats); |
4124 | 0 | Options.emplace_back(cast<llvm::Function>(Func), |
4125 | 0 | TA->getArchitecture(), Feats); |
4126 | 0 | } else { |
4127 | 0 | const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); |
4128 | 0 | llvm::SmallVector<StringRef, 8> Feats; |
4129 | 0 | TVA->getFeatures(Feats); |
4130 | 0 | Options.emplace_back(cast<llvm::Function>(Func), |
4131 | 0 | /*Architecture*/ "", Feats); |
4132 | 0 | } |
4133 | 0 | }); |
4134 | 0 | } else if (FD->isTargetClonesMultiVersion()) { |
4135 | 0 | const auto *TC = FD->getAttr<TargetClonesAttr>(); |
4136 | 0 | for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); |
4137 | 0 | ++VersionIndex) { |
4138 | 0 | if (!TC->isFirstOfVersion(VersionIndex)) |
4139 | 0 | continue; |
4140 | 0 | GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), |
4141 | 0 | VersionIndex}; |
4142 | 0 | StringRef Version = TC->getFeatureStr(VersionIndex); |
4143 | 0 | StringRef MangledName = getMangledName(CurGD); |
4144 | 0 | llvm::Constant *Func = GetGlobalValue(MangledName); |
4145 | 0 | if (!Func) { |
4146 | 0 | if (FD->isDefined()) { |
4147 | 0 | EmitGlobalFunctionDefinition(CurGD, nullptr); |
4148 | 0 | Func = GetGlobalValue(MangledName); |
4149 | 0 | } else { |
4150 | 0 | const CGFunctionInfo &FI = |
4151 | 0 | getTypes().arrangeGlobalDeclaration(CurGD); |
4152 | 0 | llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); |
4153 | 0 | Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, |
4154 | 0 | /*DontDefer=*/false, ForDefinition); |
4155 | 0 | } |
4156 | 0 | assert(Func && "This should have just been created"); |
4157 | 0 | } |
4158 | | |
4159 | 0 | StringRef Architecture; |
4160 | 0 | llvm::SmallVector<StringRef, 1> Feature; |
4161 | |
|
4162 | 0 | if (getTarget().getTriple().isAArch64()) { |
4163 | 0 | if (Version != "default") { |
4164 | 0 | llvm::SmallVector<StringRef, 8> VerFeats; |
4165 | 0 | Version.split(VerFeats, "+"); |
4166 | 0 | for (auto &CurFeat : VerFeats) |
4167 | 0 | Feature.push_back(CurFeat.trim()); |
4168 | 0 | } |
4169 | 0 | } else { |
4170 | 0 | if (Version.starts_with("arch=")) |
4171 | 0 | Architecture = Version.drop_front(sizeof("arch=") - 1); |
4172 | 0 | else if (Version != "default") |
4173 | 0 | Feature.push_back(Version); |
4174 | 0 | } |
4175 | |
|
4176 | 0 | Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); |
4177 | 0 | } |
4178 | 0 | } else { |
4179 | 0 | assert(0 && "Expected a target or target_clones multiversion function"); |
4180 | 0 | continue; |
4181 | 0 | } |
4182 | | |
4183 | 0 | llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); |
4184 | 0 | if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) { |
4185 | 0 | ResolverConstant = IFunc->getResolver(); |
4186 | | // In Aarch64, default versions of multiversioned functions are mangled to |
4187 | | // their 'normal' assembly name. This deviates from other targets which |
4188 | | // append a '.default' string. As a result we need to continue appending |
4189 | | // .ifunc in Aarch64. |
4190 | | // FIXME: Should Aarch64 mangling for 'default' multiversion function and |
4191 | | // in turn ifunc function match that of other targets? |
4192 | 0 | if (FD->isTargetClonesMultiVersion() && |
4193 | 0 | !getTarget().getTriple().isAArch64()) { |
4194 | 0 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4195 | 0 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); |
4196 | 0 | std::string MangledName = getMangledNameImpl( |
4197 | 0 | *this, GD, FD, /*OmitMultiVersionMangling=*/true); |
4198 | | // In prior versions of Clang, the mangling for ifuncs incorrectly |
4199 | | // included an .ifunc suffix. This alias is generated for backward |
4200 | | // compatibility. It is deprecated, and may be removed in the future. |
4201 | 0 | auto *Alias = llvm::GlobalAlias::create( |
4202 | 0 | DeclTy, 0, getMultiversionLinkage(*this, GD), |
4203 | 0 | MangledName + ".ifunc", IFunc, &getModule()); |
4204 | 0 | SetCommonAttributes(FD, Alias); |
4205 | 0 | } |
4206 | 0 | } |
4207 | 0 | llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); |
4208 | |
|
4209 | 0 | ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); |
4210 | |
|
4211 | 0 | if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT()) |
4212 | 0 | ResolverFunc->setComdat( |
4213 | 0 | getModule().getOrInsertComdat(ResolverFunc->getName())); |
4214 | |
|
4215 | 0 | const TargetInfo &TI = getTarget(); |
4216 | 0 | llvm::stable_sort( |
4217 | 0 | Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, |
4218 | 0 | const CodeGenFunction::MultiVersionResolverOption &RHS) { |
4219 | 0 | return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); |
4220 | 0 | }); |
4221 | 0 | CodeGenFunction CGF(*this); |
4222 | 0 | CGF.EmitMultiVersionResolver(ResolverFunc, Options); |
4223 | 0 | } |
4224 | | |
4225 | | // Ensure that any additions to the deferred decls list caused by emitting a |
4226 | | // variant are emitted. This can happen when the variant itself is inline and |
4227 | | // calls a function without linkage. |
4228 | 0 | if (!MVFuncsToEmit.empty()) |
4229 | 0 | EmitDeferred(); |
4230 | | |
4231 | | // Ensure that any additions to the multiversion funcs list from either the |
4232 | | // deferred decls or the multiversion functions themselves are emitted. |
4233 | 0 | if (!MultiVersionFuncs.empty()) |
4234 | 0 | emitMultiVersionFunctions(); |
4235 | 0 | } |
4236 | | |
4237 | 0 | void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { |
4238 | 0 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); |
4239 | 0 | assert(FD && "Not a FunctionDecl?"); |
4240 | 0 | assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); |
4241 | 0 | const auto *DD = FD->getAttr<CPUDispatchAttr>(); |
4242 | 0 | assert(DD && "Not a cpu_dispatch Function?"); |
4243 | | |
4244 | 0 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4245 | 0 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); |
4246 | |
|
4247 | 0 | StringRef ResolverName = getMangledName(GD); |
4248 | 0 | UpdateMultiVersionNames(GD, FD, ResolverName); |
4249 | |
|
4250 | 0 | llvm::Type *ResolverType; |
4251 | 0 | GlobalDecl ResolverGD; |
4252 | 0 | if (getTarget().supportsIFunc()) { |
4253 | 0 | ResolverType = llvm::FunctionType::get( |
4254 | 0 | llvm::PointerType::get(DeclTy, |
4255 | 0 | getTypes().getTargetAddressSpace(FD->getType())), |
4256 | 0 | false); |
4257 | 0 | } |
4258 | 0 | else { |
4259 | 0 | ResolverType = DeclTy; |
4260 | 0 | ResolverGD = GD; |
4261 | 0 | } |
4262 | |
|
4263 | 0 | auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( |
4264 | 0 | ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); |
4265 | 0 | ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); |
4266 | 0 | if (supportsCOMDAT()) |
4267 | 0 | ResolverFunc->setComdat( |
4268 | 0 | getModule().getOrInsertComdat(ResolverFunc->getName())); |
4269 | |
|
4270 | 0 | SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; |
4271 | 0 | const TargetInfo &Target = getTarget(); |
4272 | 0 | unsigned Index = 0; |
4273 | 0 | for (const IdentifierInfo *II : DD->cpus()) { |
4274 | | // Get the name of the target function so we can look it up/create it. |
4275 | 0 | std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + |
4276 | 0 | getCPUSpecificMangling(*this, II->getName()); |
4277 | |
|
4278 | 0 | llvm::Constant *Func = GetGlobalValue(MangledName); |
4279 | |
|
4280 | 0 | if (!Func) { |
4281 | 0 | GlobalDecl ExistingDecl = Manglings.lookup(MangledName); |
4282 | 0 | if (ExistingDecl.getDecl() && |
4283 | 0 | ExistingDecl.getDecl()->getAsFunction()->isDefined()) { |
4284 | 0 | EmitGlobalFunctionDefinition(ExistingDecl, nullptr); |
4285 | 0 | Func = GetGlobalValue(MangledName); |
4286 | 0 | } else { |
4287 | 0 | if (!ExistingDecl.getDecl()) |
4288 | 0 | ExistingDecl = GD.getWithMultiVersionIndex(Index); |
4289 | |
|
4290 | 0 | Func = GetOrCreateLLVMFunction( |
4291 | 0 | MangledName, DeclTy, ExistingDecl, |
4292 | 0 | /*ForVTable=*/false, /*DontDefer=*/true, |
4293 | 0 | /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); |
4294 | 0 | } |
4295 | 0 | } |
4296 | |
|
4297 | 0 | llvm::SmallVector<StringRef, 32> Features; |
4298 | 0 | Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); |
4299 | 0 | llvm::transform(Features, Features.begin(), |
4300 | 0 | [](StringRef Str) { return Str.substr(1); }); |
4301 | 0 | llvm::erase_if(Features, [&Target](StringRef Feat) { |
4302 | 0 | return !Target.validateCpuSupports(Feat); |
4303 | 0 | }); |
4304 | 0 | Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); |
4305 | 0 | ++Index; |
4306 | 0 | } |
4307 | |
|
4308 | 0 | llvm::stable_sort( |
4309 | 0 | Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, |
4310 | 0 | const CodeGenFunction::MultiVersionResolverOption &RHS) { |
4311 | 0 | return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > |
4312 | 0 | llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); |
4313 | 0 | }); |
4314 | | |
4315 | | // If the list contains multiple 'default' versions, such as when it contains |
4316 | | // 'pentium' and 'generic', don't emit the call to the generic one (since we |
4317 | | // always run on at least a 'pentium'). We do this by deleting the 'least |
4318 | | // advanced' (read, lowest mangling letter). |
4319 | 0 | while (Options.size() > 1 && |
4320 | 0 | llvm::all_of(llvm::X86::getCpuSupportsMask( |
4321 | 0 | (Options.end() - 2)->Conditions.Features), |
4322 | 0 | [](auto X) { return X == 0; })) { |
4323 | 0 | StringRef LHSName = (Options.end() - 2)->Function->getName(); |
4324 | 0 | StringRef RHSName = (Options.end() - 1)->Function->getName(); |
4325 | 0 | if (LHSName.compare(RHSName) < 0) |
4326 | 0 | Options.erase(Options.end() - 2); |
4327 | 0 | else |
4328 | 0 | Options.erase(Options.end() - 1); |
4329 | 0 | } |
4330 | |
|
4331 | 0 | CodeGenFunction CGF(*this); |
4332 | 0 | CGF.EmitMultiVersionResolver(ResolverFunc, Options); |
4333 | |
|
4334 | 0 | if (getTarget().supportsIFunc()) { |
4335 | 0 | llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); |
4336 | 0 | auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); |
4337 | | |
4338 | | // Fix up function declarations that were created for cpu_specific before |
4339 | | // cpu_dispatch was known |
4340 | 0 | if (!isa<llvm::GlobalIFunc>(IFunc)) { |
4341 | 0 | assert(cast<llvm::Function>(IFunc)->isDeclaration()); |
4342 | 0 | auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, |
4343 | 0 | &getModule()); |
4344 | 0 | GI->takeName(IFunc); |
4345 | 0 | IFunc->replaceAllUsesWith(GI); |
4346 | 0 | IFunc->eraseFromParent(); |
4347 | 0 | IFunc = GI; |
4348 | 0 | } |
4349 | | |
4350 | 0 | std::string AliasName = getMangledNameImpl( |
4351 | 0 | *this, GD, FD, /*OmitMultiVersionMangling=*/true); |
4352 | 0 | llvm::Constant *AliasFunc = GetGlobalValue(AliasName); |
4353 | 0 | if (!AliasFunc) { |
4354 | 0 | auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, |
4355 | 0 | &getModule()); |
4356 | 0 | SetCommonAttributes(GD, GA); |
4357 | 0 | } |
4358 | 0 | } |
4359 | 0 | } |
4360 | | |
4361 | | /// If a dispatcher for the specified mangled name is not in the module, create |
4362 | | /// and return an llvm Function with the specified type. |
4363 | 0 | llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { |
4364 | 0 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); |
4365 | 0 | assert(FD && "Not a FunctionDecl?"); |
4366 | | |
4367 | 0 | std::string MangledName = |
4368 | 0 | getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); |
4369 | | |
4370 | | // Holds the name of the resolver, in ifunc mode this is the ifunc (which has |
4371 | | // a separate resolver). |
4372 | 0 | std::string ResolverName = MangledName; |
4373 | 0 | if (getTarget().supportsIFunc()) { |
4374 | | // In Aarch64, default versions of multiversioned functions are mangled to |
4375 | | // their 'normal' assembly name. This deviates from other targets which |
4376 | | // append a '.default' string. As a result we need to continue appending |
4377 | | // .ifunc in Aarch64. |
4378 | | // FIXME: Should Aarch64 mangling for 'default' multiversion function and |
4379 | | // in turn ifunc function match that of other targets? |
4380 | 0 | if (!FD->isTargetClonesMultiVersion() || |
4381 | 0 | getTarget().getTriple().isAArch64()) |
4382 | 0 | ResolverName += ".ifunc"; |
4383 | 0 | } else if (FD->isTargetMultiVersion()) { |
4384 | 0 | ResolverName += ".resolver"; |
4385 | 0 | } |
4386 | | |
4387 | | // If the resolver has already been created, just return it. |
4388 | 0 | if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) |
4389 | 0 | return ResolverGV; |
4390 | | |
4391 | 0 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4392 | 0 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); |
4393 | | |
4394 | | // The resolver needs to be created. For target and target_clones, defer |
4395 | | // creation until the end of the TU. |
4396 | 0 | if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) |
4397 | 0 | MultiVersionFuncs.push_back(GD); |
4398 | | |
4399 | | // For cpu_specific, don't create an ifunc yet because we don't know if the |
4400 | | // cpu_dispatch will be emitted in this translation unit. |
4401 | 0 | if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { |
4402 | 0 | llvm::Type *ResolverType = llvm::FunctionType::get( |
4403 | 0 | llvm::PointerType::get(DeclTy, |
4404 | 0 | getTypes().getTargetAddressSpace(FD->getType())), |
4405 | 0 | false); |
4406 | 0 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
4407 | 0 | MangledName + ".resolver", ResolverType, GlobalDecl{}, |
4408 | 0 | /*ForVTable=*/false); |
4409 | 0 | llvm::GlobalIFunc *GIF = |
4410 | 0 | llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), |
4411 | 0 | "", Resolver, &getModule()); |
4412 | 0 | GIF->setName(ResolverName); |
4413 | 0 | SetCommonAttributes(FD, GIF); |
4414 | |
|
4415 | 0 | return GIF; |
4416 | 0 | } |
4417 | | |
4418 | 0 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
4419 | 0 | ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); |
4420 | 0 | assert(isa<llvm::GlobalValue>(Resolver) && |
4421 | 0 | "Resolver should be created for the first time"); |
4422 | 0 | SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); |
4423 | 0 | return Resolver; |
4424 | 0 | } |
4425 | | |
4426 | | /// GetOrCreateLLVMFunction - If the specified mangled name is not in the |
4427 | | /// module, create and return an llvm Function with the specified type. If there |
4428 | | /// is something in the module with the specified name, return it potentially |
4429 | | /// bitcasted to the right type. |
4430 | | /// |
4431 | | /// If D is non-null, it specifies a decl that correspond to this. This is used |
4432 | | /// to set the attributes on the function when it is first created. |
4433 | | llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( |
4434 | | StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, |
4435 | | bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, |
4436 | 0 | ForDefinition_t IsForDefinition) { |
4437 | 0 | const Decl *D = GD.getDecl(); |
4438 | | |
4439 | | // Any attempts to use a MultiVersion function should result in retrieving |
4440 | | // the iFunc instead. Name Mangling will handle the rest of the changes. |
4441 | 0 | if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { |
4442 | | // For the device mark the function as one that should be emitted. |
4443 | 0 | if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime && |
4444 | 0 | !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && |
4445 | 0 | !DontDefer && !IsForDefinition) { |
4446 | 0 | if (const FunctionDecl *FDDef = FD->getDefinition()) { |
4447 | 0 | GlobalDecl GDDef; |
4448 | 0 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) |
4449 | 0 | GDDef = GlobalDecl(CD, GD.getCtorType()); |
4450 | 0 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) |
4451 | 0 | GDDef = GlobalDecl(DD, GD.getDtorType()); |
4452 | 0 | else |
4453 | 0 | GDDef = GlobalDecl(FDDef); |
4454 | 0 | EmitGlobal(GDDef); |
4455 | 0 | } |
4456 | 0 | } |
4457 | |
|
4458 | 0 | if (FD->isMultiVersion()) { |
4459 | 0 | UpdateMultiVersionNames(GD, FD, MangledName); |
4460 | 0 | if (!IsForDefinition) |
4461 | 0 | return GetOrCreateMultiVersionResolver(GD); |
4462 | 0 | } |
4463 | 0 | } |
4464 | | |
4465 | | // Lookup the entry, lazily creating it if necessary. |
4466 | 0 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); |
4467 | 0 | if (Entry) { |
4468 | 0 | if (WeakRefReferences.erase(Entry)) { |
4469 | 0 | const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); |
4470 | 0 | if (FD && !FD->hasAttr<WeakAttr>()) |
4471 | 0 | Entry->setLinkage(llvm::Function::ExternalLinkage); |
4472 | 0 | } |
4473 | | |
4474 | | // Handle dropped DLL attributes. |
4475 | 0 | if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && |
4476 | 0 | !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { |
4477 | 0 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
4478 | 0 | setDSOLocal(Entry); |
4479 | 0 | } |
4480 | | |
4481 | | // If there are two attempts to define the same mangled name, issue an |
4482 | | // error. |
4483 | 0 | if (IsForDefinition && !Entry->isDeclaration()) { |
4484 | 0 | GlobalDecl OtherGD; |
4485 | | // Check that GD is not yet in DiagnosedConflictingDefinitions is required |
4486 | | // to make sure that we issue an error only once. |
4487 | 0 | if (lookupRepresentativeDecl(MangledName, OtherGD) && |
4488 | 0 | (GD.getCanonicalDecl().getDecl() != |
4489 | 0 | OtherGD.getCanonicalDecl().getDecl()) && |
4490 | 0 | DiagnosedConflictingDefinitions.insert(GD).second) { |
4491 | 0 | getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) |
4492 | 0 | << MangledName; |
4493 | 0 | getDiags().Report(OtherGD.getDecl()->getLocation(), |
4494 | 0 | diag::note_previous_definition); |
4495 | 0 | } |
4496 | 0 | } |
4497 | |
|
4498 | 0 | if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && |
4499 | 0 | (Entry->getValueType() == Ty)) { |
4500 | 0 | return Entry; |
4501 | 0 | } |
4502 | | |
4503 | | // Make sure the result is of the correct type. |
4504 | | // (If function is requested for a definition, we always need to create a new |
4505 | | // function, not just return a bitcast.) |
4506 | 0 | if (!IsForDefinition) |
4507 | 0 | return Entry; |
4508 | 0 | } |
4509 | | |
4510 | | // This function doesn't have a complete type (for example, the return |
4511 | | // type is an incomplete struct). Use a fake type instead, and make |
4512 | | // sure not to try to set attributes. |
4513 | 0 | bool IsIncompleteFunction = false; |
4514 | |
|
4515 | 0 | llvm::FunctionType *FTy; |
4516 | 0 | if (isa<llvm::FunctionType>(Ty)) { |
4517 | 0 | FTy = cast<llvm::FunctionType>(Ty); |
4518 | 0 | } else { |
4519 | 0 | FTy = llvm::FunctionType::get(VoidTy, false); |
4520 | 0 | IsIncompleteFunction = true; |
4521 | 0 | } |
4522 | |
|
4523 | 0 | llvm::Function *F = |
4524 | 0 | llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, |
4525 | 0 | Entry ? StringRef() : MangledName, &getModule()); |
4526 | | |
4527 | | // Store the declaration associated with this function so it is potentially |
4528 | | // updated by further declarations or definitions and emitted at the end. |
4529 | 0 | if (D && D->hasAttr<AnnotateAttr>()) |
4530 | 0 | DeferredAnnotations[MangledName] = cast<ValueDecl>(D); |
4531 | | |
4532 | | // If we already created a function with the same mangled name (but different |
4533 | | // type) before, take its name and add it to the list of functions to be |
4534 | | // replaced with F at the end of CodeGen. |
4535 | | // |
4536 | | // This happens if there is a prototype for a function (e.g. "int f()") and |
4537 | | // then a definition of a different type (e.g. "int f(int x)"). |
4538 | 0 | if (Entry) { |
4539 | 0 | F->takeName(Entry); |
4540 | | |
4541 | | // This might be an implementation of a function without a prototype, in |
4542 | | // which case, try to do special replacement of calls which match the new |
4543 | | // prototype. The really key thing here is that we also potentially drop |
4544 | | // arguments from the call site so as to make a direct call, which makes the |
4545 | | // inliner happier and suppresses a number of optimizer warnings (!) about |
4546 | | // dropping arguments. |
4547 | 0 | if (!Entry->use_empty()) { |
4548 | 0 | ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); |
4549 | 0 | Entry->removeDeadConstantUsers(); |
4550 | 0 | } |
4551 | |
|
4552 | 0 | addGlobalValReplacement(Entry, F); |
4553 | 0 | } |
4554 | |
|
4555 | 0 | assert(F->getName() == MangledName && "name was uniqued!"); |
4556 | 0 | if (D) |
4557 | 0 | SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); |
4558 | 0 | if (ExtraAttrs.hasFnAttrs()) { |
4559 | 0 | llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); |
4560 | 0 | F->addFnAttrs(B); |
4561 | 0 | } |
4562 | |
|
4563 | 0 | if (!DontDefer) { |
4564 | | // All MSVC dtors other than the base dtor are linkonce_odr and delegate to |
4565 | | // each other bottoming out with the base dtor. Therefore we emit non-base |
4566 | | // dtors on usage, even if there is no dtor definition in the TU. |
4567 | 0 | if (isa_and_nonnull<CXXDestructorDecl>(D) && |
4568 | 0 | getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), |
4569 | 0 | GD.getDtorType())) |
4570 | 0 | addDeferredDeclToEmit(GD); |
4571 | | |
4572 | | // This is the first use or definition of a mangled name. If there is a |
4573 | | // deferred decl with this name, remember that we need to emit it at the end |
4574 | | // of the file. |
4575 | 0 | auto DDI = DeferredDecls.find(MangledName); |
4576 | 0 | if (DDI != DeferredDecls.end()) { |
4577 | | // Move the potentially referenced deferred decl to the |
4578 | | // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we |
4579 | | // don't need it anymore). |
4580 | 0 | addDeferredDeclToEmit(DDI->second); |
4581 | 0 | DeferredDecls.erase(DDI); |
4582 | | |
4583 | | // Otherwise, there are cases we have to worry about where we're |
4584 | | // using a declaration for which we must emit a definition but where |
4585 | | // we might not find a top-level definition: |
4586 | | // - member functions defined inline in their classes |
4587 | | // - friend functions defined inline in some class |
4588 | | // - special member functions with implicit definitions |
4589 | | // If we ever change our AST traversal to walk into class methods, |
4590 | | // this will be unnecessary. |
4591 | | // |
4592 | | // We also don't emit a definition for a function if it's going to be an |
4593 | | // entry in a vtable, unless it's already marked as used. |
4594 | 0 | } else if (getLangOpts().CPlusPlus && D) { |
4595 | | // Look for a declaration that's lexically in a record. |
4596 | 0 | for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; |
4597 | 0 | FD = FD->getPreviousDecl()) { |
4598 | 0 | if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { |
4599 | 0 | if (FD->doesThisDeclarationHaveABody()) { |
4600 | 0 | addDeferredDeclToEmit(GD.getWithDecl(FD)); |
4601 | 0 | break; |
4602 | 0 | } |
4603 | 0 | } |
4604 | 0 | } |
4605 | 0 | } |
4606 | 0 | } |
4607 | | |
4608 | | // Make sure the result is of the requested type. |
4609 | 0 | if (!IsIncompleteFunction) { |
4610 | 0 | assert(F->getFunctionType() == Ty); |
4611 | 0 | return F; |
4612 | 0 | } |
4613 | | |
4614 | 0 | return F; |
4615 | 0 | } |
4616 | | |
4617 | | /// GetAddrOfFunction - Return the address of the given function. If Ty is |
4618 | | /// non-null, then this function will use the specified type if it has to |
4619 | | /// create it (this occurs when we see a definition of the function). |
4620 | | llvm::Constant * |
4621 | | CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable, |
4622 | | bool DontDefer, |
4623 | 0 | ForDefinition_t IsForDefinition) { |
4624 | | // If there was no specific requested type, just convert it now. |
4625 | 0 | if (!Ty) { |
4626 | 0 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); |
4627 | 0 | Ty = getTypes().ConvertType(FD->getType()); |
4628 | 0 | } |
4629 | | |
4630 | | // Devirtualized destructor calls may come through here instead of via |
4631 | | // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead |
4632 | | // of the complete destructor when necessary. |
4633 | 0 | if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { |
4634 | 0 | if (getTarget().getCXXABI().isMicrosoft() && |
4635 | 0 | GD.getDtorType() == Dtor_Complete && |
4636 | 0 | DD->getParent()->getNumVBases() == 0) |
4637 | 0 | GD = GlobalDecl(DD, Dtor_Base); |
4638 | 0 | } |
4639 | |
|
4640 | 0 | StringRef MangledName = getMangledName(GD); |
4641 | 0 | auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, |
4642 | 0 | /*IsThunk=*/false, llvm::AttributeList(), |
4643 | 0 | IsForDefinition); |
4644 | | // Returns kernel handle for HIP kernel stub function. |
4645 | 0 | if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && |
4646 | 0 | cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { |
4647 | 0 | auto *Handle = getCUDARuntime().getKernelHandle( |
4648 | 0 | cast<llvm::Function>(F->stripPointerCasts()), GD); |
4649 | 0 | if (IsForDefinition) |
4650 | 0 | return F; |
4651 | 0 | return Handle; |
4652 | 0 | } |
4653 | 0 | return F; |
4654 | 0 | } |
4655 | | |
4656 | 0 | llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { |
4657 | 0 | llvm::GlobalValue *F = |
4658 | 0 | cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); |
4659 | |
|
4660 | 0 | return llvm::NoCFIValue::get(F); |
4661 | 0 | } |
4662 | | |
4663 | | static const FunctionDecl * |
4664 | 0 | GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { |
4665 | 0 | TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); |
4666 | 0 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); |
4667 | |
|
4668 | 0 | IdentifierInfo &CII = C.Idents.get(Name); |
4669 | 0 | for (const auto *Result : DC->lookup(&CII)) |
4670 | 0 | if (const auto *FD = dyn_cast<FunctionDecl>(Result)) |
4671 | 0 | return FD; |
4672 | | |
4673 | 0 | if (!C.getLangOpts().CPlusPlus) |
4674 | 0 | return nullptr; |
4675 | | |
4676 | | // Demangle the premangled name from getTerminateFn() |
4677 | 0 | IdentifierInfo &CXXII = |
4678 | 0 | (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") |
4679 | 0 | ? C.Idents.get("terminate") |
4680 | 0 | : C.Idents.get(Name); |
4681 | |
|
4682 | 0 | for (const auto &N : {"__cxxabiv1", "std"}) { |
4683 | 0 | IdentifierInfo &NS = C.Idents.get(N); |
4684 | 0 | for (const auto *Result : DC->lookup(&NS)) { |
4685 | 0 | const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); |
4686 | 0 | if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) |
4687 | 0 | for (const auto *Result : LSD->lookup(&NS)) |
4688 | 0 | if ((ND = dyn_cast<NamespaceDecl>(Result))) |
4689 | 0 | break; |
4690 | |
|
4691 | 0 | if (ND) |
4692 | 0 | for (const auto *Result : ND->lookup(&CXXII)) |
4693 | 0 | if (const auto *FD = dyn_cast<FunctionDecl>(Result)) |
4694 | 0 | return FD; |
4695 | 0 | } |
4696 | 0 | } |
4697 | | |
4698 | 0 | return nullptr; |
4699 | 0 | } |
4700 | | |
4701 | | /// CreateRuntimeFunction - Create a new runtime function with the specified |
4702 | | /// type and name. |
4703 | | llvm::FunctionCallee |
4704 | | CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, |
4705 | | llvm::AttributeList ExtraAttrs, bool Local, |
4706 | 0 | bool AssumeConvergent) { |
4707 | 0 | if (AssumeConvergent) { |
4708 | 0 | ExtraAttrs = |
4709 | 0 | ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); |
4710 | 0 | } |
4711 | |
|
4712 | 0 | llvm::Constant *C = |
4713 | 0 | GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, |
4714 | 0 | /*DontDefer=*/false, /*IsThunk=*/false, |
4715 | 0 | ExtraAttrs); |
4716 | |
|
4717 | 0 | if (auto *F = dyn_cast<llvm::Function>(C)) { |
4718 | 0 | if (F->empty()) { |
4719 | 0 | F->setCallingConv(getRuntimeCC()); |
4720 | | |
4721 | | // In Windows Itanium environments, try to mark runtime functions |
4722 | | // dllimport. For Mingw and MSVC, don't. We don't really know if the user |
4723 | | // will link their standard library statically or dynamically. Marking |
4724 | | // functions imported when they are not imported can cause linker errors |
4725 | | // and warnings. |
4726 | 0 | if (!Local && getTriple().isWindowsItaniumEnvironment() && |
4727 | 0 | !getCodeGenOpts().LTOVisibilityPublicStd) { |
4728 | 0 | const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); |
4729 | 0 | if (!FD || FD->hasAttr<DLLImportAttr>()) { |
4730 | 0 | F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
4731 | 0 | F->setLinkage(llvm::GlobalValue::ExternalLinkage); |
4732 | 0 | } |
4733 | 0 | } |
4734 | 0 | setDSOLocal(F); |
4735 | 0 | } |
4736 | 0 | } |
4737 | |
|
4738 | 0 | return {FTy, C}; |
4739 | 0 | } |
4740 | | |
4741 | | /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, |
4742 | | /// create and return an llvm GlobalVariable with the specified type and address |
4743 | | /// space. If there is something in the module with the specified name, return |
4744 | | /// it potentially bitcasted to the right type. |
4745 | | /// |
4746 | | /// If D is non-null, it specifies a decl that correspond to this. This is used |
4747 | | /// to set the attributes on the global when it is first created. |
4748 | | /// |
4749 | | /// If IsForDefinition is true, it is guaranteed that an actual global with |
4750 | | /// type Ty will be returned, not conversion of a variable with the same |
4751 | | /// mangled name but some other type. |
4752 | | llvm::Constant * |
4753 | | CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, |
4754 | | LangAS AddrSpace, const VarDecl *D, |
4755 | 0 | ForDefinition_t IsForDefinition) { |
4756 | | // Lookup the entry, lazily creating it if necessary. |
4757 | 0 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); |
4758 | 0 | unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); |
4759 | 0 | if (Entry) { |
4760 | 0 | if (WeakRefReferences.erase(Entry)) { |
4761 | 0 | if (D && !D->hasAttr<WeakAttr>()) |
4762 | 0 | Entry->setLinkage(llvm::Function::ExternalLinkage); |
4763 | 0 | } |
4764 | | |
4765 | | // Handle dropped DLL attributes. |
4766 | 0 | if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && |
4767 | 0 | !shouldMapVisibilityToDLLExport(D)) |
4768 | 0 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
4769 | |
|
4770 | 0 | if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) |
4771 | 0 | getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); |
4772 | |
|
4773 | 0 | if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) |
4774 | 0 | return Entry; |
4775 | | |
4776 | | // If there are two attempts to define the same mangled name, issue an |
4777 | | // error. |
4778 | 0 | if (IsForDefinition && !Entry->isDeclaration()) { |
4779 | 0 | GlobalDecl OtherGD; |
4780 | 0 | const VarDecl *OtherD; |
4781 | | |
4782 | | // Check that D is not yet in DiagnosedConflictingDefinitions is required |
4783 | | // to make sure that we issue an error only once. |
4784 | 0 | if (D && lookupRepresentativeDecl(MangledName, OtherGD) && |
4785 | 0 | (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && |
4786 | 0 | (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && |
4787 | 0 | OtherD->hasInit() && |
4788 | 0 | DiagnosedConflictingDefinitions.insert(D).second) { |
4789 | 0 | getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) |
4790 | 0 | << MangledName; |
4791 | 0 | getDiags().Report(OtherGD.getDecl()->getLocation(), |
4792 | 0 | diag::note_previous_definition); |
4793 | 0 | } |
4794 | 0 | } |
4795 | | |
4796 | | // Make sure the result is of the correct type. |
4797 | 0 | if (Entry->getType()->getAddressSpace() != TargetAS) |
4798 | 0 | return llvm::ConstantExpr::getAddrSpaceCast( |
4799 | 0 | Entry, llvm::PointerType::get(Ty->getContext(), TargetAS)); |
4800 | | |
4801 | | // (If global is requested for a definition, we always need to create a new |
4802 | | // global, not just return a bitcast.) |
4803 | 0 | if (!IsForDefinition) |
4804 | 0 | return Entry; |
4805 | 0 | } |
4806 | | |
4807 | 0 | auto DAddrSpace = GetGlobalVarAddressSpace(D); |
4808 | |
|
4809 | 0 | auto *GV = new llvm::GlobalVariable( |
4810 | 0 | getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, |
4811 | 0 | MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, |
4812 | 0 | getContext().getTargetAddressSpace(DAddrSpace)); |
4813 | | |
4814 | | // If we already created a global with the same mangled name (but different |
4815 | | // type) before, take its name and remove it from its parent. |
4816 | 0 | if (Entry) { |
4817 | 0 | GV->takeName(Entry); |
4818 | |
|
4819 | 0 | if (!Entry->use_empty()) { |
4820 | 0 | Entry->replaceAllUsesWith(GV); |
4821 | 0 | } |
4822 | |
|
4823 | 0 | Entry->eraseFromParent(); |
4824 | 0 | } |
4825 | | |
4826 | | // This is the first use or definition of a mangled name. If there is a |
4827 | | // deferred decl with this name, remember that we need to emit it at the end |
4828 | | // of the file. |
4829 | 0 | auto DDI = DeferredDecls.find(MangledName); |
4830 | 0 | if (DDI != DeferredDecls.end()) { |
4831 | | // Move the potentially referenced deferred decl to the DeferredDeclsToEmit |
4832 | | // list, and remove it from DeferredDecls (since we don't need it anymore). |
4833 | 0 | addDeferredDeclToEmit(DDI->second); |
4834 | 0 | DeferredDecls.erase(DDI); |
4835 | 0 | } |
4836 | | |
4837 | | // Handle things which are present even on external declarations. |
4838 | 0 | if (D) { |
4839 | 0 | if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) |
4840 | 0 | getOpenMPRuntime().registerTargetGlobalVariable(D, GV); |
4841 | | |
4842 | | // FIXME: This code is overly simple and should be merged with other global |
4843 | | // handling. |
4844 | 0 | GV->setConstant(D->getType().isConstantStorage(getContext(), false, false)); |
4845 | |
|
4846 | 0 | GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); |
4847 | |
|
4848 | 0 | setLinkageForGV(GV, D); |
4849 | |
|
4850 | 0 | if (D->getTLSKind()) { |
4851 | 0 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) |
4852 | 0 | CXXThreadLocals.push_back(D); |
4853 | 0 | setTLSMode(GV, *D); |
4854 | 0 | } |
4855 | |
|
4856 | 0 | setGVProperties(GV, D); |
4857 | | |
4858 | | // If required by the ABI, treat declarations of static data members with |
4859 | | // inline initializers as definitions. |
4860 | 0 | if (getContext().isMSStaticDataMemberInlineDefinition(D)) { |
4861 | 0 | EmitGlobalVarDefinition(D); |
4862 | 0 | } |
4863 | | |
4864 | | // Emit section information for extern variables. |
4865 | 0 | if (D->hasExternalStorage()) { |
4866 | 0 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) |
4867 | 0 | GV->setSection(SA->getName()); |
4868 | 0 | } |
4869 | | |
4870 | | // Handle XCore specific ABI requirements. |
4871 | 0 | if (getTriple().getArch() == llvm::Triple::xcore && |
4872 | 0 | D->getLanguageLinkage() == CLanguageLinkage && |
4873 | 0 | D->getType().isConstant(Context) && |
4874 | 0 | isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) |
4875 | 0 | GV->setSection(".cp.rodata"); |
4876 | | |
4877 | | // Handle code model attribute |
4878 | 0 | if (const auto *CMA = D->getAttr<CodeModelAttr>()) |
4879 | 0 | GV->setCodeModel(CMA->getModel()); |
4880 | | |
4881 | | // Check if we a have a const declaration with an initializer, we may be |
4882 | | // able to emit it as available_externally to expose it's value to the |
4883 | | // optimizer. |
4884 | 0 | if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && |
4885 | 0 | D->getType().isConstQualified() && !GV->hasInitializer() && |
4886 | 0 | !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { |
4887 | 0 | const auto *Record = |
4888 | 0 | Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); |
4889 | 0 | bool HasMutableFields = Record && Record->hasMutableFields(); |
4890 | 0 | if (!HasMutableFields) { |
4891 | 0 | const VarDecl *InitDecl; |
4892 | 0 | const Expr *InitExpr = D->getAnyInitializer(InitDecl); |
4893 | 0 | if (InitExpr) { |
4894 | 0 | ConstantEmitter emitter(*this); |
4895 | 0 | llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); |
4896 | 0 | if (Init) { |
4897 | 0 | auto *InitType = Init->getType(); |
4898 | 0 | if (GV->getValueType() != InitType) { |
4899 | | // The type of the initializer does not match the definition. |
4900 | | // This happens when an initializer has a different type from |
4901 | | // the type of the global (because of padding at the end of a |
4902 | | // structure for instance). |
4903 | 0 | GV->setName(StringRef()); |
4904 | | // Make a new global with the correct type, this is now guaranteed |
4905 | | // to work. |
4906 | 0 | auto *NewGV = cast<llvm::GlobalVariable>( |
4907 | 0 | GetAddrOfGlobalVar(D, InitType, IsForDefinition) |
4908 | 0 | ->stripPointerCasts()); |
4909 | | |
4910 | | // Erase the old global, since it is no longer used. |
4911 | 0 | GV->eraseFromParent(); |
4912 | 0 | GV = NewGV; |
4913 | 0 | } else { |
4914 | 0 | GV->setInitializer(Init); |
4915 | 0 | GV->setConstant(true); |
4916 | 0 | GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); |
4917 | 0 | } |
4918 | 0 | emitter.finalize(GV); |
4919 | 0 | } |
4920 | 0 | } |
4921 | 0 | } |
4922 | 0 | } |
4923 | 0 | } |
4924 | |
|
4925 | 0 | if (D && |
4926 | 0 | D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) { |
4927 | 0 | getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); |
4928 | | // External HIP managed variables needed to be recorded for transformation |
4929 | | // in both device and host compilations. |
4930 | 0 | if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && |
4931 | 0 | D->hasExternalStorage()) |
4932 | 0 | getCUDARuntime().handleVarRegistration(D, *GV); |
4933 | 0 | } |
4934 | |
|
4935 | 0 | if (D) |
4936 | 0 | SanitizerMD->reportGlobal(GV, *D); |
4937 | |
|
4938 | 0 | LangAS ExpectedAS = |
4939 | 0 | D ? D->getType().getAddressSpace() |
4940 | 0 | : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); |
4941 | 0 | assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); |
4942 | 0 | if (DAddrSpace != ExpectedAS) { |
4943 | 0 | return getTargetCodeGenInfo().performAddrSpaceCast( |
4944 | 0 | *this, GV, DAddrSpace, ExpectedAS, |
4945 | 0 | llvm::PointerType::get(getLLVMContext(), TargetAS)); |
4946 | 0 | } |
4947 | | |
4948 | 0 | return GV; |
4949 | 0 | } |
4950 | | |
4951 | | llvm::Constant * |
4952 | 0 | CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { |
4953 | 0 | const Decl *D = GD.getDecl(); |
4954 | |
|
4955 | 0 | if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) |
4956 | 0 | return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, |
4957 | 0 | /*DontDefer=*/false, IsForDefinition); |
4958 | | |
4959 | 0 | if (isa<CXXMethodDecl>(D)) { |
4960 | 0 | auto FInfo = |
4961 | 0 | &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); |
4962 | 0 | auto Ty = getTypes().GetFunctionType(*FInfo); |
4963 | 0 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, |
4964 | 0 | IsForDefinition); |
4965 | 0 | } |
4966 | | |
4967 | 0 | if (isa<FunctionDecl>(D)) { |
4968 | 0 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4969 | 0 | llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); |
4970 | 0 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, |
4971 | 0 | IsForDefinition); |
4972 | 0 | } |
4973 | | |
4974 | 0 | return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); |
4975 | 0 | } |
4976 | | |
4977 | | llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( |
4978 | | StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, |
4979 | 0 | llvm::Align Alignment) { |
4980 | 0 | llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); |
4981 | 0 | llvm::GlobalVariable *OldGV = nullptr; |
4982 | |
|
4983 | 0 | if (GV) { |
4984 | | // Check if the variable has the right type. |
4985 | 0 | if (GV->getValueType() == Ty) |
4986 | 0 | return GV; |
4987 | | |
4988 | | // Because C++ name mangling, the only way we can end up with an already |
4989 | | // existing global with the same name is if it has been declared extern "C". |
4990 | 0 | assert(GV->isDeclaration() && "Declaration has wrong type!"); |
4991 | 0 | OldGV = GV; |
4992 | 0 | } |
4993 | | |
4994 | | // Create a new variable. |
4995 | 0 | GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, |
4996 | 0 | Linkage, nullptr, Name); |
4997 | |
|
4998 | 0 | if (OldGV) { |
4999 | | // Replace occurrences of the old variable if needed. |
5000 | 0 | GV->takeName(OldGV); |
5001 | |
|
5002 | 0 | if (!OldGV->use_empty()) { |
5003 | 0 | OldGV->replaceAllUsesWith(GV); |
5004 | 0 | } |
5005 | |
|
5006 | 0 | OldGV->eraseFromParent(); |
5007 | 0 | } |
5008 | |
|
5009 | 0 | if (supportsCOMDAT() && GV->isWeakForLinker() && |
5010 | 0 | !GV->hasAvailableExternallyLinkage()) |
5011 | 0 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); |
5012 | |
|
5013 | 0 | GV->setAlignment(Alignment); |
5014 | |
|
5015 | 0 | return GV; |
5016 | 0 | } |
5017 | | |
5018 | | /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the |
5019 | | /// given global variable. If Ty is non-null and if the global doesn't exist, |
5020 | | /// then it will be created with the specified type instead of whatever the |
5021 | | /// normal requested type would be. If IsForDefinition is true, it is guaranteed |
5022 | | /// that an actual global with type Ty will be returned, not conversion of a |
5023 | | /// variable with the same mangled name but some other type. |
5024 | | llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, |
5025 | | llvm::Type *Ty, |
5026 | 0 | ForDefinition_t IsForDefinition) { |
5027 | 0 | assert(D->hasGlobalStorage() && "Not a global variable"); |
5028 | 0 | QualType ASTTy = D->getType(); |
5029 | 0 | if (!Ty) |
5030 | 0 | Ty = getTypes().ConvertTypeForMem(ASTTy); |
5031 | |
|
5032 | 0 | StringRef MangledName = getMangledName(D); |
5033 | 0 | return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, |
5034 | 0 | IsForDefinition); |
5035 | 0 | } |
5036 | | |
5037 | | /// CreateRuntimeVariable - Create a new runtime global variable with the |
5038 | | /// specified type and name. |
5039 | | llvm::Constant * |
5040 | | CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, |
5041 | 0 | StringRef Name) { |
5042 | 0 | LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global |
5043 | 0 | : LangAS::Default; |
5044 | 0 | auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); |
5045 | 0 | setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); |
5046 | 0 | return Ret; |
5047 | 0 | } |
5048 | | |
5049 | 0 | void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { |
5050 | 0 | assert(!D->getInit() && "Cannot emit definite definitions here!"); |
5051 | | |
5052 | 0 | StringRef MangledName = getMangledName(D); |
5053 | 0 | llvm::GlobalValue *GV = GetGlobalValue(MangledName); |
5054 | | |
5055 | | // We already have a definition, not declaration, with the same mangled name. |
5056 | | // Emitting of declaration is not required (and actually overwrites emitted |
5057 | | // definition). |
5058 | 0 | if (GV && !GV->isDeclaration()) |
5059 | 0 | return; |
5060 | | |
5061 | | // If we have not seen a reference to this variable yet, place it into the |
5062 | | // deferred declarations table to be emitted if needed later. |
5063 | 0 | if (!MustBeEmitted(D) && !GV) { |
5064 | 0 | DeferredDecls[MangledName] = D; |
5065 | 0 | return; |
5066 | 0 | } |
5067 | | |
5068 | | // The tentative definition is the only definition. |
5069 | 0 | EmitGlobalVarDefinition(D); |
5070 | 0 | } |
5071 | | |
5072 | 0 | void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { |
5073 | 0 | EmitExternalVarDeclaration(D); |
5074 | 0 | } |
5075 | | |
5076 | 0 | CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { |
5077 | 0 | return Context.toCharUnitsFromBits( |
5078 | 0 | getDataLayout().getTypeStoreSizeInBits(Ty)); |
5079 | 0 | } |
5080 | | |
5081 | 0 | LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { |
5082 | 0 | if (LangOpts.OpenCL) { |
5083 | 0 | LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; |
5084 | 0 | assert(AS == LangAS::opencl_global || |
5085 | 0 | AS == LangAS::opencl_global_device || |
5086 | 0 | AS == LangAS::opencl_global_host || |
5087 | 0 | AS == LangAS::opencl_constant || |
5088 | 0 | AS == LangAS::opencl_local || |
5089 | 0 | AS >= LangAS::FirstTargetAddressSpace); |
5090 | 0 | return AS; |
5091 | 0 | } |
5092 | | |
5093 | 0 | if (LangOpts.SYCLIsDevice && |
5094 | 0 | (!D || D->getType().getAddressSpace() == LangAS::Default)) |
5095 | 0 | return LangAS::sycl_global; |
5096 | | |
5097 | 0 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { |
5098 | 0 | if (D) { |
5099 | 0 | if (D->hasAttr<CUDAConstantAttr>()) |
5100 | 0 | return LangAS::cuda_constant; |
5101 | 0 | if (D->hasAttr<CUDASharedAttr>()) |
5102 | 0 | return LangAS::cuda_shared; |
5103 | 0 | if (D->hasAttr<CUDADeviceAttr>()) |
5104 | 0 | return LangAS::cuda_device; |
5105 | 0 | if (D->getType().isConstQualified()) |
5106 | 0 | return LangAS::cuda_constant; |
5107 | 0 | } |
5108 | 0 | return LangAS::cuda_device; |
5109 | 0 | } |
5110 | | |
5111 | 0 | if (LangOpts.OpenMP) { |
5112 | 0 | LangAS AS; |
5113 | 0 | if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) |
5114 | 0 | return AS; |
5115 | 0 | } |
5116 | 0 | return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); |
5117 | 0 | } |
5118 | | |
5119 | 46 | LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { |
5120 | | // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. |
5121 | 46 | if (LangOpts.OpenCL) |
5122 | 0 | return LangAS::opencl_constant; |
5123 | 46 | if (LangOpts.SYCLIsDevice) |
5124 | 0 | return LangAS::sycl_global; |
5125 | 46 | if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) |
5126 | | // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) |
5127 | | // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up |
5128 | | // with OpVariable instructions with Generic storage class which is not |
5129 | | // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V |
5130 | | // UniformConstant storage class is not viable as pointers to it may not be |
5131 | | // casted to Generic pointers which are used to model HIP's "flat" pointers. |
5132 | 0 | return LangAS::cuda_device; |
5133 | 46 | if (auto AS = getTarget().getConstantAddressSpace()) |
5134 | 46 | return *AS; |
5135 | 0 | return LangAS::Default; |
5136 | 46 | } |
5137 | | |
5138 | | // In address space agnostic languages, string literals are in default address |
5139 | | // space in AST. However, certain targets (e.g. amdgcn) request them to be |
5140 | | // emitted in constant address space in LLVM IR. To be consistent with other |
5141 | | // parts of AST, string literal global variables in constant address space |
5142 | | // need to be casted to default address space before being put into address |
5143 | | // map and referenced by other part of CodeGen. |
5144 | | // In OpenCL, string literals are in constant address space in AST, therefore |
5145 | | // they should not be casted to default address space. |
5146 | | static llvm::Constant * |
5147 | | castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, |
5148 | 0 | llvm::GlobalVariable *GV) { |
5149 | 0 | llvm::Constant *Cast = GV; |
5150 | 0 | if (!CGM.getLangOpts().OpenCL) { |
5151 | 0 | auto AS = CGM.GetGlobalConstantAddressSpace(); |
5152 | 0 | if (AS != LangAS::Default) |
5153 | 0 | Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( |
5154 | 0 | CGM, GV, AS, LangAS::Default, |
5155 | 0 | llvm::PointerType::get( |
5156 | 0 | CGM.getLLVMContext(), |
5157 | 0 | CGM.getContext().getTargetAddressSpace(LangAS::Default))); |
5158 | 0 | } |
5159 | 0 | return Cast; |
5160 | 0 | } |
5161 | | |
5162 | | template<typename SomeDecl> |
5163 | | void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, |
5164 | 0 | llvm::GlobalValue *GV) { |
5165 | 0 | if (!getLangOpts().CPlusPlus) |
5166 | 0 | return; |
5167 | | |
5168 | | // Must have 'used' attribute, or else inline assembly can't rely on |
5169 | | // the name existing. |
5170 | 0 | if (!D->template hasAttr<UsedAttr>()) |
5171 | 0 | return; |
5172 | | |
5173 | | // Must have internal linkage and an ordinary name. |
5174 | 0 | if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal) |
5175 | 0 | return; |
5176 | | |
5177 | | // Must be in an extern "C" context. Entities declared directly within |
5178 | | // a record are not extern "C" even if the record is in such a context. |
5179 | 0 | const SomeDecl *First = D->getFirstDecl(); |
5180 | 0 | if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) |
5181 | 0 | return; |
5182 | | |
5183 | | // OK, this is an internal linkage entity inside an extern "C" linkage |
5184 | | // specification. Make a note of that so we can give it the "expected" |
5185 | | // mangled name if nothing else is using that name. |
5186 | 0 | std::pair<StaticExternCMap::iterator, bool> R = |
5187 | 0 | StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); |
5188 | | |
5189 | | // If we have multiple internal linkage entities with the same name |
5190 | | // in extern "C" regions, none of them gets that name. |
5191 | 0 | if (!R.second) |
5192 | 0 | R.first->second = nullptr; |
5193 | 0 | } Unexecuted instantiation: void clang::CodeGen::CodeGenModule::MaybeHandleStaticInExternC<clang::VarDecl>(clang::VarDecl const*, llvm::GlobalValue*) Unexecuted instantiation: void clang::CodeGen::CodeGenModule::MaybeHandleStaticInExternC<clang::FunctionDecl>(clang::FunctionDecl const*, llvm::GlobalValue*) |
5194 | | |
5195 | 0 | static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { |
5196 | 0 | if (!CGM.supportsCOMDAT()) |
5197 | 0 | return false; |
5198 | | |
5199 | 0 | if (D.hasAttr<SelectAnyAttr>()) |
5200 | 0 | return true; |
5201 | | |
5202 | 0 | GVALinkage Linkage; |
5203 | 0 | if (auto *VD = dyn_cast<VarDecl>(&D)) |
5204 | 0 | Linkage = CGM.getContext().GetGVALinkageForVariable(VD); |
5205 | 0 | else |
5206 | 0 | Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); |
5207 | |
|
5208 | 0 | switch (Linkage) { |
5209 | 0 | case GVA_Internal: |
5210 | 0 | case GVA_AvailableExternally: |
5211 | 0 | case GVA_StrongExternal: |
5212 | 0 | return false; |
5213 | 0 | case GVA_DiscardableODR: |
5214 | 0 | case GVA_StrongODR: |
5215 | 0 | return true; |
5216 | 0 | } |
5217 | 0 | llvm_unreachable("No such linkage"); |
5218 | 0 | } |
5219 | | |
5220 | 0 | bool CodeGenModule::supportsCOMDAT() const { |
5221 | 0 | return getTriple().supportsCOMDAT(); |
5222 | 0 | } |
5223 | | |
5224 | | void CodeGenModule::maybeSetTrivialComdat(const Decl &D, |
5225 | 0 | llvm::GlobalObject &GO) { |
5226 | 0 | if (!shouldBeInCOMDAT(*this, D)) |
5227 | 0 | return; |
5228 | 0 | GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); |
5229 | 0 | } |
5230 | | |
5231 | | /// Pass IsTentative as true if you want to create a tentative definition. |
5232 | | void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, |
5233 | 0 | bool IsTentative) { |
5234 | | // OpenCL global variables of sampler type are translated to function calls, |
5235 | | // therefore no need to be translated. |
5236 | 0 | QualType ASTTy = D->getType(); |
5237 | 0 | if (getLangOpts().OpenCL && ASTTy->isSamplerT()) |
5238 | 0 | return; |
5239 | | |
5240 | | // If this is OpenMP device, check if it is legal to emit this global |
5241 | | // normally. |
5242 | 0 | if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime && |
5243 | 0 | OpenMPRuntime->emitTargetGlobalVariable(D)) |
5244 | 0 | return; |
5245 | | |
5246 | 0 | llvm::TrackingVH<llvm::Constant> Init; |
5247 | 0 | bool NeedsGlobalCtor = false; |
5248 | | // Whether the definition of the variable is available externally. |
5249 | | // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable |
5250 | | // since this is the job for its original source. |
5251 | 0 | bool IsDefinitionAvailableExternally = |
5252 | 0 | getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally; |
5253 | 0 | bool NeedsGlobalDtor = |
5254 | 0 | !IsDefinitionAvailableExternally && |
5255 | 0 | D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; |
5256 | |
|
5257 | 0 | const VarDecl *InitDecl; |
5258 | 0 | const Expr *InitExpr = D->getAnyInitializer(InitDecl); |
5259 | |
|
5260 | 0 | std::optional<ConstantEmitter> emitter; |
5261 | | |
5262 | | // CUDA E.2.4.1 "__shared__ variables cannot have an initialization |
5263 | | // as part of their declaration." Sema has already checked for |
5264 | | // error cases, so we just need to set Init to UndefValue. |
5265 | 0 | bool IsCUDASharedVar = |
5266 | 0 | getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); |
5267 | | // Shadows of initialized device-side global variables are also left |
5268 | | // undefined. |
5269 | | // Managed Variables should be initialized on both host side and device side. |
5270 | 0 | bool IsCUDAShadowVar = |
5271 | 0 | !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && |
5272 | 0 | (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || |
5273 | 0 | D->hasAttr<CUDASharedAttr>()); |
5274 | 0 | bool IsCUDADeviceShadowVar = |
5275 | 0 | getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && |
5276 | 0 | (D->getType()->isCUDADeviceBuiltinSurfaceType() || |
5277 | 0 | D->getType()->isCUDADeviceBuiltinTextureType()); |
5278 | 0 | if (getLangOpts().CUDA && |
5279 | 0 | (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) |
5280 | 0 | Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); |
5281 | 0 | else if (D->hasAttr<LoaderUninitializedAttr>()) |
5282 | 0 | Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); |
5283 | 0 | else if (!InitExpr) { |
5284 | | // This is a tentative definition; tentative definitions are |
5285 | | // implicitly initialized with { 0 }. |
5286 | | // |
5287 | | // Note that tentative definitions are only emitted at the end of |
5288 | | // a translation unit, so they should never have incomplete |
5289 | | // type. In addition, EmitTentativeDefinition makes sure that we |
5290 | | // never attempt to emit a tentative definition if a real one |
5291 | | // exists. A use may still exists, however, so we still may need |
5292 | | // to do a RAUW. |
5293 | 0 | assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); |
5294 | 0 | Init = EmitNullConstant(D->getType()); |
5295 | 0 | } else { |
5296 | 0 | initializedGlobalDecl = GlobalDecl(D); |
5297 | 0 | emitter.emplace(*this); |
5298 | 0 | llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); |
5299 | 0 | if (!Initializer) { |
5300 | 0 | QualType T = InitExpr->getType(); |
5301 | 0 | if (D->getType()->isReferenceType()) |
5302 | 0 | T = D->getType(); |
5303 | |
|
5304 | 0 | if (getLangOpts().CPlusPlus) { |
5305 | 0 | if (InitDecl->hasFlexibleArrayInit(getContext())) |
5306 | 0 | ErrorUnsupported(D, "flexible array initializer"); |
5307 | 0 | Init = EmitNullConstant(T); |
5308 | |
|
5309 | 0 | if (!IsDefinitionAvailableExternally) |
5310 | 0 | NeedsGlobalCtor = true; |
5311 | 0 | } else { |
5312 | 0 | ErrorUnsupported(D, "static initializer"); |
5313 | 0 | Init = llvm::UndefValue::get(getTypes().ConvertType(T)); |
5314 | 0 | } |
5315 | 0 | } else { |
5316 | 0 | Init = Initializer; |
5317 | | // We don't need an initializer, so remove the entry for the delayed |
5318 | | // initializer position (just in case this entry was delayed) if we |
5319 | | // also don't need to register a destructor. |
5320 | 0 | if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) |
5321 | 0 | DelayedCXXInitPosition.erase(D); |
5322 | |
|
5323 | 0 | #ifndef NDEBUG |
5324 | 0 | CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + |
5325 | 0 | InitDecl->getFlexibleArrayInitChars(getContext()); |
5326 | 0 | CharUnits CstSize = CharUnits::fromQuantity( |
5327 | 0 | getDataLayout().getTypeAllocSize(Init->getType())); |
5328 | 0 | assert(VarSize == CstSize && "Emitted constant has unexpected size"); |
5329 | 0 | #endif |
5330 | 0 | } |
5331 | 0 | } |
5332 | | |
5333 | 0 | llvm::Type* InitType = Init->getType(); |
5334 | 0 | llvm::Constant *Entry = |
5335 | 0 | GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); |
5336 | | |
5337 | | // Strip off pointer casts if we got them. |
5338 | 0 | Entry = Entry->stripPointerCasts(); |
5339 | | |
5340 | | // Entry is now either a Function or GlobalVariable. |
5341 | 0 | auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); |
5342 | | |
5343 | | // We have a definition after a declaration with the wrong type. |
5344 | | // We must make a new GlobalVariable* and update everything that used OldGV |
5345 | | // (a declaration or tentative definition) with the new GlobalVariable* |
5346 | | // (which will be a definition). |
5347 | | // |
5348 | | // This happens if there is a prototype for a global (e.g. |
5349 | | // "extern int x[];") and then a definition of a different type (e.g. |
5350 | | // "int x[10];"). This also happens when an initializer has a different type |
5351 | | // from the type of the global (this happens with unions). |
5352 | 0 | if (!GV || GV->getValueType() != InitType || |
5353 | 0 | GV->getType()->getAddressSpace() != |
5354 | 0 | getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { |
5355 | | |
5356 | | // Move the old entry aside so that we'll create a new one. |
5357 | 0 | Entry->setName(StringRef()); |
5358 | | |
5359 | | // Make a new global with the correct type, this is now guaranteed to work. |
5360 | 0 | GV = cast<llvm::GlobalVariable>( |
5361 | 0 | GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) |
5362 | 0 | ->stripPointerCasts()); |
5363 | | |
5364 | | // Replace all uses of the old global with the new global |
5365 | 0 | llvm::Constant *NewPtrForOldDecl = |
5366 | 0 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, |
5367 | 0 | Entry->getType()); |
5368 | 0 | Entry->replaceAllUsesWith(NewPtrForOldDecl); |
5369 | | |
5370 | | // Erase the old global, since it is no longer used. |
5371 | 0 | cast<llvm::GlobalValue>(Entry)->eraseFromParent(); |
5372 | 0 | } |
5373 | |
|
5374 | 0 | MaybeHandleStaticInExternC(D, GV); |
5375 | |
|
5376 | 0 | if (D->hasAttr<AnnotateAttr>()) |
5377 | 0 | AddGlobalAnnotations(D, GV); |
5378 | | |
5379 | | // Set the llvm linkage type as appropriate. |
5380 | 0 | llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D); |
5381 | | |
5382 | | // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on |
5383 | | // the device. [...]" |
5384 | | // CUDA B.2.2 "The __constant__ qualifier, optionally used together with |
5385 | | // __device__, declares a variable that: [...] |
5386 | | // Is accessible from all the threads within the grid and from the host |
5387 | | // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() |
5388 | | // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." |
5389 | 0 | if (LangOpts.CUDA) { |
5390 | 0 | if (LangOpts.CUDAIsDevice) { |
5391 | 0 | if (Linkage != llvm::GlobalValue::InternalLinkage && |
5392 | 0 | (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || |
5393 | 0 | D->getType()->isCUDADeviceBuiltinSurfaceType() || |
5394 | 0 | D->getType()->isCUDADeviceBuiltinTextureType())) |
5395 | 0 | GV->setExternallyInitialized(true); |
5396 | 0 | } else { |
5397 | 0 | getCUDARuntime().internalizeDeviceSideVar(D, Linkage); |
5398 | 0 | } |
5399 | 0 | getCUDARuntime().handleVarRegistration(D, *GV); |
5400 | 0 | } |
5401 | |
|
5402 | 0 | GV->setInitializer(Init); |
5403 | 0 | if (emitter) |
5404 | 0 | emitter->finalize(GV); |
5405 | | |
5406 | | // If it is safe to mark the global 'constant', do so now. |
5407 | 0 | GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && |
5408 | 0 | D->getType().isConstantStorage(getContext(), true, true)); |
5409 | | |
5410 | | // If it is in a read-only section, mark it 'constant'. |
5411 | 0 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { |
5412 | 0 | const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; |
5413 | 0 | if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) |
5414 | 0 | GV->setConstant(true); |
5415 | 0 | } |
5416 | |
|
5417 | 0 | CharUnits AlignVal = getContext().getDeclAlign(D); |
5418 | | // Check for alignment specifed in an 'omp allocate' directive. |
5419 | 0 | if (std::optional<CharUnits> AlignValFromAllocate = |
5420 | 0 | getOMPAllocateAlignment(D)) |
5421 | 0 | AlignVal = *AlignValFromAllocate; |
5422 | 0 | GV->setAlignment(AlignVal.getAsAlign()); |
5423 | | |
5424 | | // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper |
5425 | | // function is only defined alongside the variable, not also alongside |
5426 | | // callers. Normally, all accesses to a thread_local go through the |
5427 | | // thread-wrapper in order to ensure initialization has occurred, underlying |
5428 | | // variable will never be used other than the thread-wrapper, so it can be |
5429 | | // converted to internal linkage. |
5430 | | // |
5431 | | // However, if the variable has the 'constinit' attribute, it _can_ be |
5432 | | // referenced directly, without calling the thread-wrapper, so the linkage |
5433 | | // must not be changed. |
5434 | | // |
5435 | | // Additionally, if the variable isn't plain external linkage, e.g. if it's |
5436 | | // weak or linkonce, the de-duplication semantics are important to preserve, |
5437 | | // so we don't change the linkage. |
5438 | 0 | if (D->getTLSKind() == VarDecl::TLS_Dynamic && |
5439 | 0 | Linkage == llvm::GlobalValue::ExternalLinkage && |
5440 | 0 | Context.getTargetInfo().getTriple().isOSDarwin() && |
5441 | 0 | !D->hasAttr<ConstInitAttr>()) |
5442 | 0 | Linkage = llvm::GlobalValue::InternalLinkage; |
5443 | |
|
5444 | 0 | GV->setLinkage(Linkage); |
5445 | 0 | if (D->hasAttr<DLLImportAttr>()) |
5446 | 0 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); |
5447 | 0 | else if (D->hasAttr<DLLExportAttr>()) |
5448 | 0 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); |
5449 | 0 | else |
5450 | 0 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); |
5451 | |
|
5452 | 0 | if (Linkage == llvm::GlobalVariable::CommonLinkage) { |
5453 | | // common vars aren't constant even if declared const. |
5454 | 0 | GV->setConstant(false); |
5455 | | // Tentative definition of global variables may be initialized with |
5456 | | // non-zero null pointers. In this case they should have weak linkage |
5457 | | // since common linkage must have zero initializer and must not have |
5458 | | // explicit section therefore cannot have non-zero initial value. |
5459 | 0 | if (!GV->getInitializer()->isNullValue()) |
5460 | 0 | GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); |
5461 | 0 | } |
5462 | |
|
5463 | 0 | setNonAliasAttributes(D, GV); |
5464 | |
|
5465 | 0 | if (D->getTLSKind() && !GV->isThreadLocal()) { |
5466 | 0 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) |
5467 | 0 | CXXThreadLocals.push_back(D); |
5468 | 0 | setTLSMode(GV, *D); |
5469 | 0 | } |
5470 | |
|
5471 | 0 | maybeSetTrivialComdat(*D, *GV); |
5472 | | |
5473 | | // Emit the initializer function if necessary. |
5474 | 0 | if (NeedsGlobalCtor || NeedsGlobalDtor) |
5475 | 0 | EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); |
5476 | |
|
5477 | 0 | SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); |
5478 | | |
5479 | | // Emit global variable debug information. |
5480 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
5481 | 0 | if (getCodeGenOpts().hasReducedDebugInfo()) |
5482 | 0 | DI->EmitGlobalVariable(GV, D); |
5483 | 0 | } |
5484 | | |
5485 | 0 | void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { |
5486 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
5487 | 0 | if (getCodeGenOpts().hasReducedDebugInfo()) { |
5488 | 0 | QualType ASTTy = D->getType(); |
5489 | 0 | llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); |
5490 | 0 | llvm::Constant *GV = |
5491 | 0 | GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); |
5492 | 0 | DI->EmitExternalVariable( |
5493 | 0 | cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); |
5494 | 0 | } |
5495 | 0 | } |
5496 | | |
5497 | | static bool isVarDeclStrongDefinition(const ASTContext &Context, |
5498 | | CodeGenModule &CGM, const VarDecl *D, |
5499 | 0 | bool NoCommon) { |
5500 | | // Don't give variables common linkage if -fno-common was specified unless it |
5501 | | // was overridden by a NoCommon attribute. |
5502 | 0 | if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) |
5503 | 0 | return true; |
5504 | | |
5505 | | // C11 6.9.2/2: |
5506 | | // A declaration of an identifier for an object that has file scope without |
5507 | | // an initializer, and without a storage-class specifier or with the |
5508 | | // storage-class specifier static, constitutes a tentative definition. |
5509 | 0 | if (D->getInit() || D->hasExternalStorage()) |
5510 | 0 | return true; |
5511 | | |
5512 | | // A variable cannot be both common and exist in a section. |
5513 | 0 | if (D->hasAttr<SectionAttr>()) |
5514 | 0 | return true; |
5515 | | |
5516 | | // A variable cannot be both common and exist in a section. |
5517 | | // We don't try to determine which is the right section in the front-end. |
5518 | | // If no specialized section name is applicable, it will resort to default. |
5519 | 0 | if (D->hasAttr<PragmaClangBSSSectionAttr>() || |
5520 | 0 | D->hasAttr<PragmaClangDataSectionAttr>() || |
5521 | 0 | D->hasAttr<PragmaClangRelroSectionAttr>() || |
5522 | 0 | D->hasAttr<PragmaClangRodataSectionAttr>()) |
5523 | 0 | return true; |
5524 | | |
5525 | | // Thread local vars aren't considered common linkage. |
5526 | 0 | if (D->getTLSKind()) |
5527 | 0 | return true; |
5528 | | |
5529 | | // Tentative definitions marked with WeakImportAttr are true definitions. |
5530 | 0 | if (D->hasAttr<WeakImportAttr>()) |
5531 | 0 | return true; |
5532 | | |
5533 | | // A variable cannot be both common and exist in a comdat. |
5534 | 0 | if (shouldBeInCOMDAT(CGM, *D)) |
5535 | 0 | return true; |
5536 | | |
5537 | | // Declarations with a required alignment do not have common linkage in MSVC |
5538 | | // mode. |
5539 | 0 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
5540 | 0 | if (D->hasAttr<AlignedAttr>()) |
5541 | 0 | return true; |
5542 | 0 | QualType VarType = D->getType(); |
5543 | 0 | if (Context.isAlignmentRequired(VarType)) |
5544 | 0 | return true; |
5545 | | |
5546 | 0 | if (const auto *RT = VarType->getAs<RecordType>()) { |
5547 | 0 | const RecordDecl *RD = RT->getDecl(); |
5548 | 0 | for (const FieldDecl *FD : RD->fields()) { |
5549 | 0 | if (FD->isBitField()) |
5550 | 0 | continue; |
5551 | 0 | if (FD->hasAttr<AlignedAttr>()) |
5552 | 0 | return true; |
5553 | 0 | if (Context.isAlignmentRequired(FD->getType())) |
5554 | 0 | return true; |
5555 | 0 | } |
5556 | 0 | } |
5557 | 0 | } |
5558 | | |
5559 | | // Microsoft's link.exe doesn't support alignments greater than 32 bytes for |
5560 | | // common symbols, so symbols with greater alignment requirements cannot be |
5561 | | // common. |
5562 | | // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two |
5563 | | // alignments for common symbols via the aligncomm directive, so this |
5564 | | // restriction only applies to MSVC environments. |
5565 | 0 | if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && |
5566 | 0 | Context.getTypeAlignIfKnown(D->getType()) > |
5567 | 0 | Context.toBits(CharUnits::fromQuantity(32))) |
5568 | 0 | return true; |
5569 | | |
5570 | 0 | return false; |
5571 | 0 | } |
5572 | | |
5573 | | llvm::GlobalValue::LinkageTypes |
5574 | | CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D, |
5575 | 0 | GVALinkage Linkage) { |
5576 | 0 | if (Linkage == GVA_Internal) |
5577 | 0 | return llvm::Function::InternalLinkage; |
5578 | | |
5579 | 0 | if (D->hasAttr<WeakAttr>()) |
5580 | 0 | return llvm::GlobalVariable::WeakAnyLinkage; |
5581 | | |
5582 | 0 | if (const auto *FD = D->getAsFunction()) |
5583 | 0 | if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) |
5584 | 0 | return llvm::GlobalVariable::LinkOnceAnyLinkage; |
5585 | | |
5586 | | // We are guaranteed to have a strong definition somewhere else, |
5587 | | // so we can use available_externally linkage. |
5588 | 0 | if (Linkage == GVA_AvailableExternally) |
5589 | 0 | return llvm::GlobalValue::AvailableExternallyLinkage; |
5590 | | |
5591 | | // Note that Apple's kernel linker doesn't support symbol |
5592 | | // coalescing, so we need to avoid linkonce and weak linkages there. |
5593 | | // Normally, this means we just map to internal, but for explicit |
5594 | | // instantiations we'll map to external. |
5595 | | |
5596 | | // In C++, the compiler has to emit a definition in every translation unit |
5597 | | // that references the function. We should use linkonce_odr because |
5598 | | // a) if all references in this translation unit are optimized away, we |
5599 | | // don't need to codegen it. b) if the function persists, it needs to be |
5600 | | // merged with other definitions. c) C++ has the ODR, so we know the |
5601 | | // definition is dependable. |
5602 | 0 | if (Linkage == GVA_DiscardableODR) |
5603 | 0 | return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage |
5604 | 0 | : llvm::Function::InternalLinkage; |
5605 | | |
5606 | | // An explicit instantiation of a template has weak linkage, since |
5607 | | // explicit instantiations can occur in multiple translation units |
5608 | | // and must all be equivalent. However, we are not allowed to |
5609 | | // throw away these explicit instantiations. |
5610 | | // |
5611 | | // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, |
5612 | | // so say that CUDA templates are either external (for kernels) or internal. |
5613 | | // This lets llvm perform aggressive inter-procedural optimizations. For |
5614 | | // -fgpu-rdc case, device function calls across multiple TU's are allowed, |
5615 | | // therefore we need to follow the normal linkage paradigm. |
5616 | 0 | if (Linkage == GVA_StrongODR) { |
5617 | 0 | if (getLangOpts().AppleKext) |
5618 | 0 | return llvm::Function::ExternalLinkage; |
5619 | 0 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && |
5620 | 0 | !getLangOpts().GPURelocatableDeviceCode) |
5621 | 0 | return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage |
5622 | 0 | : llvm::Function::InternalLinkage; |
5623 | 0 | return llvm::Function::WeakODRLinkage; |
5624 | 0 | } |
5625 | | |
5626 | | // C++ doesn't have tentative definitions and thus cannot have common |
5627 | | // linkage. |
5628 | 0 | if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && |
5629 | 0 | !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), |
5630 | 0 | CodeGenOpts.NoCommon)) |
5631 | 0 | return llvm::GlobalVariable::CommonLinkage; |
5632 | | |
5633 | | // selectany symbols are externally visible, so use weak instead of |
5634 | | // linkonce. MSVC optimizes away references to const selectany globals, so |
5635 | | // all definitions should be the same and ODR linkage should be used. |
5636 | | // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx |
5637 | 0 | if (D->hasAttr<SelectAnyAttr>()) |
5638 | 0 | return llvm::GlobalVariable::WeakODRLinkage; |
5639 | | |
5640 | | // Otherwise, we have strong external linkage. |
5641 | 0 | assert(Linkage == GVA_StrongExternal); |
5642 | 0 | return llvm::GlobalVariable::ExternalLinkage; |
5643 | 0 | } |
5644 | | |
5645 | | llvm::GlobalValue::LinkageTypes |
5646 | 0 | CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) { |
5647 | 0 | GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); |
5648 | 0 | return getLLVMLinkageForDeclarator(VD, Linkage); |
5649 | 0 | } |
5650 | | |
5651 | | /// Replace the uses of a function that was declared with a non-proto type. |
5652 | | /// We want to silently drop extra arguments from call sites |
5653 | | static void replaceUsesOfNonProtoConstant(llvm::Constant *old, |
5654 | 0 | llvm::Function *newFn) { |
5655 | | // Fast path. |
5656 | 0 | if (old->use_empty()) return; |
5657 | | |
5658 | 0 | llvm::Type *newRetTy = newFn->getReturnType(); |
5659 | 0 | SmallVector<llvm::Value*, 4> newArgs; |
5660 | |
|
5661 | 0 | for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); |
5662 | 0 | ui != ue; ) { |
5663 | 0 | llvm::Value::use_iterator use = ui++; // Increment before the use is erased. |
5664 | 0 | llvm::User *user = use->getUser(); |
5665 | | |
5666 | | // Recognize and replace uses of bitcasts. Most calls to |
5667 | | // unprototyped functions will use bitcasts. |
5668 | 0 | if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { |
5669 | 0 | if (bitcast->getOpcode() == llvm::Instruction::BitCast) |
5670 | 0 | replaceUsesOfNonProtoConstant(bitcast, newFn); |
5671 | 0 | continue; |
5672 | 0 | } |
5673 | | |
5674 | | // Recognize calls to the function. |
5675 | 0 | llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); |
5676 | 0 | if (!callSite) continue; |
5677 | 0 | if (!callSite->isCallee(&*use)) |
5678 | 0 | continue; |
5679 | | |
5680 | | // If the return types don't match exactly, then we can't |
5681 | | // transform this call unless it's dead. |
5682 | 0 | if (callSite->getType() != newRetTy && !callSite->use_empty()) |
5683 | 0 | continue; |
5684 | | |
5685 | | // Get the call site's attribute list. |
5686 | 0 | SmallVector<llvm::AttributeSet, 8> newArgAttrs; |
5687 | 0 | llvm::AttributeList oldAttrs = callSite->getAttributes(); |
5688 | | |
5689 | | // If the function was passed too few arguments, don't transform. |
5690 | 0 | unsigned newNumArgs = newFn->arg_size(); |
5691 | 0 | if (callSite->arg_size() < newNumArgs) |
5692 | 0 | continue; |
5693 | | |
5694 | | // If extra arguments were passed, we silently drop them. |
5695 | | // If any of the types mismatch, we don't transform. |
5696 | 0 | unsigned argNo = 0; |
5697 | 0 | bool dontTransform = false; |
5698 | 0 | for (llvm::Argument &A : newFn->args()) { |
5699 | 0 | if (callSite->getArgOperand(argNo)->getType() != A.getType()) { |
5700 | 0 | dontTransform = true; |
5701 | 0 | break; |
5702 | 0 | } |
5703 | | |
5704 | | // Add any parameter attributes. |
5705 | 0 | newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); |
5706 | 0 | argNo++; |
5707 | 0 | } |
5708 | 0 | if (dontTransform) |
5709 | 0 | continue; |
5710 | | |
5711 | | // Okay, we can transform this. Create the new call instruction and copy |
5712 | | // over the required information. |
5713 | 0 | newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); |
5714 | | |
5715 | | // Copy over any operand bundles. |
5716 | 0 | SmallVector<llvm::OperandBundleDef, 1> newBundles; |
5717 | 0 | callSite->getOperandBundlesAsDefs(newBundles); |
5718 | |
|
5719 | 0 | llvm::CallBase *newCall; |
5720 | 0 | if (isa<llvm::CallInst>(callSite)) { |
5721 | 0 | newCall = |
5722 | 0 | llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); |
5723 | 0 | } else { |
5724 | 0 | auto *oldInvoke = cast<llvm::InvokeInst>(callSite); |
5725 | 0 | newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), |
5726 | 0 | oldInvoke->getUnwindDest(), newArgs, |
5727 | 0 | newBundles, "", callSite); |
5728 | 0 | } |
5729 | 0 | newArgs.clear(); // for the next iteration |
5730 | |
|
5731 | 0 | if (!newCall->getType()->isVoidTy()) |
5732 | 0 | newCall->takeName(callSite); |
5733 | 0 | newCall->setAttributes( |
5734 | 0 | llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), |
5735 | 0 | oldAttrs.getRetAttrs(), newArgAttrs)); |
5736 | 0 | newCall->setCallingConv(callSite->getCallingConv()); |
5737 | | |
5738 | | // Finally, remove the old call, replacing any uses with the new one. |
5739 | 0 | if (!callSite->use_empty()) |
5740 | 0 | callSite->replaceAllUsesWith(newCall); |
5741 | | |
5742 | | // Copy debug location attached to CI. |
5743 | 0 | if (callSite->getDebugLoc()) |
5744 | 0 | newCall->setDebugLoc(callSite->getDebugLoc()); |
5745 | |
|
5746 | 0 | callSite->eraseFromParent(); |
5747 | 0 | } |
5748 | 0 | } |
5749 | | |
5750 | | /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we |
5751 | | /// implement a function with no prototype, e.g. "int foo() {}". If there are |
5752 | | /// existing call uses of the old function in the module, this adjusts them to |
5753 | | /// call the new function directly. |
5754 | | /// |
5755 | | /// This is not just a cleanup: the always_inline pass requires direct calls to |
5756 | | /// functions to be able to inline them. If there is a bitcast in the way, it |
5757 | | /// won't inline them. Instcombine normally deletes these calls, but it isn't |
5758 | | /// run at -O0. |
5759 | | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, |
5760 | 0 | llvm::Function *NewFn) { |
5761 | | // If we're redefining a global as a function, don't transform it. |
5762 | 0 | if (!isa<llvm::Function>(Old)) return; |
5763 | | |
5764 | 0 | replaceUsesOfNonProtoConstant(Old, NewFn); |
5765 | 0 | } |
5766 | | |
5767 | 0 | void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { |
5768 | 0 | auto DK = VD->isThisDeclarationADefinition(); |
5769 | 0 | if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) |
5770 | 0 | return; |
5771 | | |
5772 | 0 | TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); |
5773 | | // If we have a definition, this might be a deferred decl. If the |
5774 | | // instantiation is explicit, make sure we emit it at the end. |
5775 | 0 | if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) |
5776 | 0 | GetAddrOfGlobalVar(VD); |
5777 | |
|
5778 | 0 | EmitTopLevelDecl(VD); |
5779 | 0 | } |
5780 | | |
5781 | | void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, |
5782 | 0 | llvm::GlobalValue *GV) { |
5783 | 0 | const auto *D = cast<FunctionDecl>(GD.getDecl()); |
5784 | | |
5785 | | // Compute the function info and LLVM type. |
5786 | 0 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
5787 | 0 | llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); |
5788 | | |
5789 | | // Get or create the prototype for the function. |
5790 | 0 | if (!GV || (GV->getValueType() != Ty)) |
5791 | 0 | GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, |
5792 | 0 | /*DontDefer=*/true, |
5793 | 0 | ForDefinition)); |
5794 | | |
5795 | | // Already emitted. |
5796 | 0 | if (!GV->isDeclaration()) |
5797 | 0 | return; |
5798 | | |
5799 | | // We need to set linkage and visibility on the function before |
5800 | | // generating code for it because various parts of IR generation |
5801 | | // want to propagate this information down (e.g. to local static |
5802 | | // declarations). |
5803 | 0 | auto *Fn = cast<llvm::Function>(GV); |
5804 | 0 | setFunctionLinkage(GD, Fn); |
5805 | | |
5806 | | // FIXME: this is redundant with part of setFunctionDefinitionAttributes |
5807 | 0 | setGVProperties(Fn, GD); |
5808 | |
|
5809 | 0 | MaybeHandleStaticInExternC(D, Fn); |
5810 | |
|
5811 | 0 | maybeSetTrivialComdat(*D, *Fn); |
5812 | |
|
5813 | 0 | CodeGenFunction(*this).GenerateCode(GD, Fn, FI); |
5814 | |
|
5815 | 0 | setNonAliasAttributes(GD, Fn); |
5816 | 0 | SetLLVMFunctionAttributesForDefinition(D, Fn); |
5817 | |
|
5818 | 0 | if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) |
5819 | 0 | AddGlobalCtor(Fn, CA->getPriority()); |
5820 | 0 | if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) |
5821 | 0 | AddGlobalDtor(Fn, DA->getPriority(), true); |
5822 | 0 | if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>()) |
5823 | 0 | getOpenMPRuntime().emitDeclareTargetFunction(D, GV); |
5824 | 0 | } |
5825 | | |
5826 | 0 | void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { |
5827 | 0 | const auto *D = cast<ValueDecl>(GD.getDecl()); |
5828 | 0 | const AliasAttr *AA = D->getAttr<AliasAttr>(); |
5829 | 0 | assert(AA && "Not an alias?"); |
5830 | | |
5831 | 0 | StringRef MangledName = getMangledName(GD); |
5832 | |
|
5833 | 0 | if (AA->getAliasee() == MangledName) { |
5834 | 0 | Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; |
5835 | 0 | return; |
5836 | 0 | } |
5837 | | |
5838 | | // If there is a definition in the module, then it wins over the alias. |
5839 | | // This is dubious, but allow it to be safe. Just ignore the alias. |
5840 | 0 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); |
5841 | 0 | if (Entry && !Entry->isDeclaration()) |
5842 | 0 | return; |
5843 | | |
5844 | 0 | Aliases.push_back(GD); |
5845 | |
|
5846 | 0 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); |
5847 | | |
5848 | | // Create a reference to the named value. This ensures that it is emitted |
5849 | | // if a deferred decl. |
5850 | 0 | llvm::Constant *Aliasee; |
5851 | 0 | llvm::GlobalValue::LinkageTypes LT; |
5852 | 0 | if (isa<llvm::FunctionType>(DeclTy)) { |
5853 | 0 | Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, |
5854 | 0 | /*ForVTable=*/false); |
5855 | 0 | LT = getFunctionLinkage(GD); |
5856 | 0 | } else { |
5857 | 0 | Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, |
5858 | 0 | /*D=*/nullptr); |
5859 | 0 | if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) |
5860 | 0 | LT = getLLVMLinkageVarDefinition(VD); |
5861 | 0 | else |
5862 | 0 | LT = getFunctionLinkage(GD); |
5863 | 0 | } |
5864 | | |
5865 | | // Create the new alias itself, but don't set a name yet. |
5866 | 0 | unsigned AS = Aliasee->getType()->getPointerAddressSpace(); |
5867 | 0 | auto *GA = |
5868 | 0 | llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); |
5869 | |
|
5870 | 0 | if (Entry) { |
5871 | 0 | if (GA->getAliasee() == Entry) { |
5872 | 0 | Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; |
5873 | 0 | return; |
5874 | 0 | } |
5875 | | |
5876 | 0 | assert(Entry->isDeclaration()); |
5877 | | |
5878 | | // If there is a declaration in the module, then we had an extern followed |
5879 | | // by the alias, as in: |
5880 | | // extern int test6(); |
5881 | | // ... |
5882 | | // int test6() __attribute__((alias("test7"))); |
5883 | | // |
5884 | | // Remove it and replace uses of it with the alias. |
5885 | 0 | GA->takeName(Entry); |
5886 | |
|
5887 | 0 | Entry->replaceAllUsesWith(GA); |
5888 | 0 | Entry->eraseFromParent(); |
5889 | 0 | } else { |
5890 | 0 | GA->setName(MangledName); |
5891 | 0 | } |
5892 | | |
5893 | | // Set attributes which are particular to an alias; this is a |
5894 | | // specialization of the attributes which may be set on a global |
5895 | | // variable/function. |
5896 | 0 | if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || |
5897 | 0 | D->isWeakImported()) { |
5898 | 0 | GA->setLinkage(llvm::Function::WeakAnyLinkage); |
5899 | 0 | } |
5900 | |
|
5901 | 0 | if (const auto *VD = dyn_cast<VarDecl>(D)) |
5902 | 0 | if (VD->getTLSKind()) |
5903 | 0 | setTLSMode(GA, *VD); |
5904 | |
|
5905 | 0 | SetCommonAttributes(GD, GA); |
5906 | | |
5907 | | // Emit global alias debug information. |
5908 | 0 | if (isa<VarDecl>(D)) |
5909 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
5910 | 0 | DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); |
5911 | 0 | } |
5912 | | |
5913 | 0 | void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { |
5914 | 0 | const auto *D = cast<ValueDecl>(GD.getDecl()); |
5915 | 0 | const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); |
5916 | 0 | assert(IFA && "Not an ifunc?"); |
5917 | | |
5918 | 0 | StringRef MangledName = getMangledName(GD); |
5919 | |
|
5920 | 0 | if (IFA->getResolver() == MangledName) { |
5921 | 0 | Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; |
5922 | 0 | return; |
5923 | 0 | } |
5924 | | |
5925 | | // Report an error if some definition overrides ifunc. |
5926 | 0 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); |
5927 | 0 | if (Entry && !Entry->isDeclaration()) { |
5928 | 0 | GlobalDecl OtherGD; |
5929 | 0 | if (lookupRepresentativeDecl(MangledName, OtherGD) && |
5930 | 0 | DiagnosedConflictingDefinitions.insert(GD).second) { |
5931 | 0 | Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) |
5932 | 0 | << MangledName; |
5933 | 0 | Diags.Report(OtherGD.getDecl()->getLocation(), |
5934 | 0 | diag::note_previous_definition); |
5935 | 0 | } |
5936 | 0 | return; |
5937 | 0 | } |
5938 | | |
5939 | 0 | Aliases.push_back(GD); |
5940 | |
|
5941 | 0 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); |
5942 | 0 | llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); |
5943 | 0 | llvm::Constant *Resolver = |
5944 | 0 | GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, |
5945 | 0 | /*ForVTable=*/false); |
5946 | 0 | llvm::GlobalIFunc *GIF = |
5947 | 0 | llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, |
5948 | 0 | "", Resolver, &getModule()); |
5949 | 0 | if (Entry) { |
5950 | 0 | if (GIF->getResolver() == Entry) { |
5951 | 0 | Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; |
5952 | 0 | return; |
5953 | 0 | } |
5954 | 0 | assert(Entry->isDeclaration()); |
5955 | | |
5956 | | // If there is a declaration in the module, then we had an extern followed |
5957 | | // by the ifunc, as in: |
5958 | | // extern int test(); |
5959 | | // ... |
5960 | | // int test() __attribute__((ifunc("resolver"))); |
5961 | | // |
5962 | | // Remove it and replace uses of it with the ifunc. |
5963 | 0 | GIF->takeName(Entry); |
5964 | |
|
5965 | 0 | Entry->replaceAllUsesWith(GIF); |
5966 | 0 | Entry->eraseFromParent(); |
5967 | 0 | } else |
5968 | 0 | GIF->setName(MangledName); |
5969 | 0 | if (auto *F = dyn_cast<llvm::Function>(Resolver)) { |
5970 | 0 | F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); |
5971 | 0 | } |
5972 | 0 | SetCommonAttributes(GD, GIF); |
5973 | 0 | } |
5974 | | |
5975 | | llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, |
5976 | 0 | ArrayRef<llvm::Type*> Tys) { |
5977 | 0 | return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, |
5978 | 0 | Tys); |
5979 | 0 | } |
5980 | | |
5981 | | static llvm::StringMapEntry<llvm::GlobalVariable *> & |
5982 | | GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, |
5983 | | const StringLiteral *Literal, bool TargetIsLSB, |
5984 | 0 | bool &IsUTF16, unsigned &StringLength) { |
5985 | 0 | StringRef String = Literal->getString(); |
5986 | 0 | unsigned NumBytes = String.size(); |
5987 | | |
5988 | | // Check for simple case. |
5989 | 0 | if (!Literal->containsNonAsciiOrNull()) { |
5990 | 0 | StringLength = NumBytes; |
5991 | 0 | return *Map.insert(std::make_pair(String, nullptr)).first; |
5992 | 0 | } |
5993 | | |
5994 | | // Otherwise, convert the UTF8 literals into a string of shorts. |
5995 | 0 | IsUTF16 = true; |
5996 | |
|
5997 | 0 | SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. |
5998 | 0 | const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); |
5999 | 0 | llvm::UTF16 *ToPtr = &ToBuf[0]; |
6000 | |
|
6001 | 0 | (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, |
6002 | 0 | ToPtr + NumBytes, llvm::strictConversion); |
6003 | | |
6004 | | // ConvertUTF8toUTF16 returns the length in ToPtr. |
6005 | 0 | StringLength = ToPtr - &ToBuf[0]; |
6006 | | |
6007 | | // Add an explicit null. |
6008 | 0 | *ToPtr = 0; |
6009 | 0 | return *Map.insert(std::make_pair( |
6010 | 0 | StringRef(reinterpret_cast<const char *>(ToBuf.data()), |
6011 | 0 | (StringLength + 1) * 2), |
6012 | 0 | nullptr)).first; |
6013 | 0 | } |
6014 | | |
6015 | | ConstantAddress |
6016 | 0 | CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { |
6017 | 0 | unsigned StringLength = 0; |
6018 | 0 | bool isUTF16 = false; |
6019 | 0 | llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = |
6020 | 0 | GetConstantCFStringEntry(CFConstantStringMap, Literal, |
6021 | 0 | getDataLayout().isLittleEndian(), isUTF16, |
6022 | 0 | StringLength); |
6023 | |
|
6024 | 0 | if (auto *C = Entry.second) |
6025 | 0 | return ConstantAddress( |
6026 | 0 | C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); |
6027 | | |
6028 | 0 | llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); |
6029 | 0 | llvm::Constant *Zeros[] = { Zero, Zero }; |
6030 | |
|
6031 | 0 | const ASTContext &Context = getContext(); |
6032 | 0 | const llvm::Triple &Triple = getTriple(); |
6033 | |
|
6034 | 0 | const auto CFRuntime = getLangOpts().CFRuntime; |
6035 | 0 | const bool IsSwiftABI = |
6036 | 0 | static_cast<unsigned>(CFRuntime) >= |
6037 | 0 | static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); |
6038 | 0 | const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; |
6039 | | |
6040 | | // If we don't already have it, get __CFConstantStringClassReference. |
6041 | 0 | if (!CFConstantStringClassRef) { |
6042 | 0 | const char *CFConstantStringClassName = "__CFConstantStringClassReference"; |
6043 | 0 | llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); |
6044 | 0 | Ty = llvm::ArrayType::get(Ty, 0); |
6045 | |
|
6046 | 0 | switch (CFRuntime) { |
6047 | 0 | default: break; |
6048 | 0 | case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; |
6049 | 0 | case LangOptions::CoreFoundationABI::Swift5_0: |
6050 | 0 | CFConstantStringClassName = |
6051 | 0 | Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" |
6052 | 0 | : "$s10Foundation19_NSCFConstantStringCN"; |
6053 | 0 | Ty = IntPtrTy; |
6054 | 0 | break; |
6055 | 0 | case LangOptions::CoreFoundationABI::Swift4_2: |
6056 | 0 | CFConstantStringClassName = |
6057 | 0 | Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" |
6058 | 0 | : "$S10Foundation19_NSCFConstantStringCN"; |
6059 | 0 | Ty = IntPtrTy; |
6060 | 0 | break; |
6061 | 0 | case LangOptions::CoreFoundationABI::Swift4_1: |
6062 | 0 | CFConstantStringClassName = |
6063 | 0 | Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" |
6064 | 0 | : "__T010Foundation19_NSCFConstantStringCN"; |
6065 | 0 | Ty = IntPtrTy; |
6066 | 0 | break; |
6067 | 0 | } |
6068 | | |
6069 | 0 | llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); |
6070 | |
|
6071 | 0 | if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { |
6072 | 0 | llvm::GlobalValue *GV = nullptr; |
6073 | |
|
6074 | 0 | if ((GV = dyn_cast<llvm::GlobalValue>(C))) { |
6075 | 0 | IdentifierInfo &II = Context.Idents.get(GV->getName()); |
6076 | 0 | TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); |
6077 | 0 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); |
6078 | |
|
6079 | 0 | const VarDecl *VD = nullptr; |
6080 | 0 | for (const auto *Result : DC->lookup(&II)) |
6081 | 0 | if ((VD = dyn_cast<VarDecl>(Result))) |
6082 | 0 | break; |
6083 | |
|
6084 | 0 | if (Triple.isOSBinFormatELF()) { |
6085 | 0 | if (!VD) |
6086 | 0 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
6087 | 0 | } else { |
6088 | 0 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
6089 | 0 | if (!VD || !VD->hasAttr<DLLExportAttr>()) |
6090 | 0 | GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
6091 | 0 | else |
6092 | 0 | GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); |
6093 | 0 | } |
6094 | |
|
6095 | 0 | setDSOLocal(GV); |
6096 | 0 | } |
6097 | 0 | } |
6098 | | |
6099 | | // Decay array -> ptr |
6100 | 0 | CFConstantStringClassRef = |
6101 | 0 | IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) |
6102 | 0 | : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); |
6103 | 0 | } |
6104 | | |
6105 | 0 | QualType CFTy = Context.getCFConstantStringType(); |
6106 | |
|
6107 | 0 | auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); |
6108 | |
|
6109 | 0 | ConstantInitBuilder Builder(*this); |
6110 | 0 | auto Fields = Builder.beginStruct(STy); |
6111 | | |
6112 | | // Class pointer. |
6113 | 0 | Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); |
6114 | | |
6115 | | // Flags. |
6116 | 0 | if (IsSwiftABI) { |
6117 | 0 | Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); |
6118 | 0 | Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); |
6119 | 0 | } else { |
6120 | 0 | Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); |
6121 | 0 | } |
6122 | | |
6123 | | // String pointer. |
6124 | 0 | llvm::Constant *C = nullptr; |
6125 | 0 | if (isUTF16) { |
6126 | 0 | auto Arr = llvm::ArrayRef( |
6127 | 0 | reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), |
6128 | 0 | Entry.first().size() / 2); |
6129 | 0 | C = llvm::ConstantDataArray::get(VMContext, Arr); |
6130 | 0 | } else { |
6131 | 0 | C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); |
6132 | 0 | } |
6133 | | |
6134 | | // Note: -fwritable-strings doesn't make the backing store strings of |
6135 | | // CFStrings writable. |
6136 | 0 | auto *GV = |
6137 | 0 | new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, |
6138 | 0 | llvm::GlobalValue::PrivateLinkage, C, ".str"); |
6139 | 0 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
6140 | | // Don't enforce the target's minimum global alignment, since the only use |
6141 | | // of the string is via this class initializer. |
6142 | 0 | CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) |
6143 | 0 | : Context.getTypeAlignInChars(Context.CharTy); |
6144 | 0 | GV->setAlignment(Align.getAsAlign()); |
6145 | | |
6146 | | // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. |
6147 | | // Without it LLVM can merge the string with a non unnamed_addr one during |
6148 | | // LTO. Doing that changes the section it ends in, which surprises ld64. |
6149 | 0 | if (Triple.isOSBinFormatMachO()) |
6150 | 0 | GV->setSection(isUTF16 ? "__TEXT,__ustring" |
6151 | 0 | : "__TEXT,__cstring,cstring_literals"); |
6152 | | // Make sure the literal ends up in .rodata to allow for safe ICF and for |
6153 | | // the static linker to adjust permissions to read-only later on. |
6154 | 0 | else if (Triple.isOSBinFormatELF()) |
6155 | 0 | GV->setSection(".rodata"); |
6156 | | |
6157 | | // String. |
6158 | 0 | llvm::Constant *Str = |
6159 | 0 | llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); |
6160 | |
|
6161 | 0 | Fields.add(Str); |
6162 | | |
6163 | | // String length. |
6164 | 0 | llvm::IntegerType *LengthTy = |
6165 | 0 | llvm::IntegerType::get(getModule().getContext(), |
6166 | 0 | Context.getTargetInfo().getLongWidth()); |
6167 | 0 | if (IsSwiftABI) { |
6168 | 0 | if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || |
6169 | 0 | CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) |
6170 | 0 | LengthTy = Int32Ty; |
6171 | 0 | else |
6172 | 0 | LengthTy = IntPtrTy; |
6173 | 0 | } |
6174 | 0 | Fields.addInt(LengthTy, StringLength); |
6175 | | |
6176 | | // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is |
6177 | | // properly aligned on 32-bit platforms. |
6178 | 0 | CharUnits Alignment = |
6179 | 0 | IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); |
6180 | | |
6181 | | // The struct. |
6182 | 0 | GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, |
6183 | 0 | /*isConstant=*/false, |
6184 | 0 | llvm::GlobalVariable::PrivateLinkage); |
6185 | 0 | GV->addAttribute("objc_arc_inert"); |
6186 | 0 | switch (Triple.getObjectFormat()) { |
6187 | 0 | case llvm::Triple::UnknownObjectFormat: |
6188 | 0 | llvm_unreachable("unknown file format"); |
6189 | 0 | case llvm::Triple::DXContainer: |
6190 | 0 | case llvm::Triple::GOFF: |
6191 | 0 | case llvm::Triple::SPIRV: |
6192 | 0 | case llvm::Triple::XCOFF: |
6193 | 0 | llvm_unreachable("unimplemented"); |
6194 | 0 | case llvm::Triple::COFF: |
6195 | 0 | case llvm::Triple::ELF: |
6196 | 0 | case llvm::Triple::Wasm: |
6197 | 0 | GV->setSection("cfstring"); |
6198 | 0 | break; |
6199 | 0 | case llvm::Triple::MachO: |
6200 | 0 | GV->setSection("__DATA,__cfstring"); |
6201 | 0 | break; |
6202 | 0 | } |
6203 | 0 | Entry.second = GV; |
6204 | |
|
6205 | 0 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
6206 | 0 | } |
6207 | | |
6208 | 0 | bool CodeGenModule::getExpressionLocationsEnabled() const { |
6209 | 0 | return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; |
6210 | 0 | } |
6211 | | |
6212 | 0 | QualType CodeGenModule::getObjCFastEnumerationStateType() { |
6213 | 0 | if (ObjCFastEnumerationStateType.isNull()) { |
6214 | 0 | RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); |
6215 | 0 | D->startDefinition(); |
6216 | |
|
6217 | 0 | QualType FieldTypes[] = { |
6218 | 0 | Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()), |
6219 | 0 | Context.getPointerType(Context.UnsignedLongTy), |
6220 | 0 | Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5), |
6221 | 0 | nullptr, ArraySizeModifier::Normal, 0)}; |
6222 | |
|
6223 | 0 | for (size_t i = 0; i < 4; ++i) { |
6224 | 0 | FieldDecl *Field = FieldDecl::Create(Context, |
6225 | 0 | D, |
6226 | 0 | SourceLocation(), |
6227 | 0 | SourceLocation(), nullptr, |
6228 | 0 | FieldTypes[i], /*TInfo=*/nullptr, |
6229 | 0 | /*BitWidth=*/nullptr, |
6230 | 0 | /*Mutable=*/false, |
6231 | 0 | ICIS_NoInit); |
6232 | 0 | Field->setAccess(AS_public); |
6233 | 0 | D->addDecl(Field); |
6234 | 0 | } |
6235 | |
|
6236 | 0 | D->completeDefinition(); |
6237 | 0 | ObjCFastEnumerationStateType = Context.getTagDeclType(D); |
6238 | 0 | } |
6239 | |
|
6240 | 0 | return ObjCFastEnumerationStateType; |
6241 | 0 | } |
6242 | | |
6243 | | llvm::Constant * |
6244 | 0 | CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { |
6245 | 0 | assert(!E->getType()->isPointerType() && "Strings are always arrays"); |
6246 | | |
6247 | | // Don't emit it as the address of the string, emit the string data itself |
6248 | | // as an inline array. |
6249 | 0 | if (E->getCharByteWidth() == 1) { |
6250 | 0 | SmallString<64> Str(E->getString()); |
6251 | | |
6252 | | // Resize the string to the right size, which is indicated by its type. |
6253 | 0 | const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); |
6254 | 0 | assert(CAT && "String literal not of constant array type!"); |
6255 | 0 | Str.resize(CAT->getSize().getZExtValue()); |
6256 | 0 | return llvm::ConstantDataArray::getString(VMContext, Str, false); |
6257 | 0 | } |
6258 | | |
6259 | 0 | auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); |
6260 | 0 | llvm::Type *ElemTy = AType->getElementType(); |
6261 | 0 | unsigned NumElements = AType->getNumElements(); |
6262 | | |
6263 | | // Wide strings have either 2-byte or 4-byte elements. |
6264 | 0 | if (ElemTy->getPrimitiveSizeInBits() == 16) { |
6265 | 0 | SmallVector<uint16_t, 32> Elements; |
6266 | 0 | Elements.reserve(NumElements); |
6267 | |
|
6268 | 0 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) |
6269 | 0 | Elements.push_back(E->getCodeUnit(i)); |
6270 | 0 | Elements.resize(NumElements); |
6271 | 0 | return llvm::ConstantDataArray::get(VMContext, Elements); |
6272 | 0 | } |
6273 | | |
6274 | 0 | assert(ElemTy->getPrimitiveSizeInBits() == 32); |
6275 | 0 | SmallVector<uint32_t, 32> Elements; |
6276 | 0 | Elements.reserve(NumElements); |
6277 | |
|
6278 | 0 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) |
6279 | 0 | Elements.push_back(E->getCodeUnit(i)); |
6280 | 0 | Elements.resize(NumElements); |
6281 | 0 | return llvm::ConstantDataArray::get(VMContext, Elements); |
6282 | 0 | } |
6283 | | |
6284 | | static llvm::GlobalVariable * |
6285 | | GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, |
6286 | | CodeGenModule &CGM, StringRef GlobalName, |
6287 | 0 | CharUnits Alignment) { |
6288 | 0 | unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( |
6289 | 0 | CGM.GetGlobalConstantAddressSpace()); |
6290 | |
|
6291 | 0 | llvm::Module &M = CGM.getModule(); |
6292 | | // Create a global variable for this string |
6293 | 0 | auto *GV = new llvm::GlobalVariable( |
6294 | 0 | M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, |
6295 | 0 | nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); |
6296 | 0 | GV->setAlignment(Alignment.getAsAlign()); |
6297 | 0 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
6298 | 0 | if (GV->isWeakForLinker()) { |
6299 | 0 | assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); |
6300 | 0 | GV->setComdat(M.getOrInsertComdat(GV->getName())); |
6301 | 0 | } |
6302 | 0 | CGM.setDSOLocal(GV); |
6303 | |
|
6304 | 0 | return GV; |
6305 | 0 | } |
6306 | | |
6307 | | /// GetAddrOfConstantStringFromLiteral - Return a pointer to a |
6308 | | /// constant array for the given string literal. |
6309 | | ConstantAddress |
6310 | | CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, |
6311 | 0 | StringRef Name) { |
6312 | 0 | CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); |
6313 | |
|
6314 | 0 | llvm::Constant *C = GetConstantArrayFromStringLiteral(S); |
6315 | 0 | llvm::GlobalVariable **Entry = nullptr; |
6316 | 0 | if (!LangOpts.WritableStrings) { |
6317 | 0 | Entry = &ConstantStringMap[C]; |
6318 | 0 | if (auto GV = *Entry) { |
6319 | 0 | if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) |
6320 | 0 | GV->setAlignment(Alignment.getAsAlign()); |
6321 | 0 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), |
6322 | 0 | GV->getValueType(), Alignment); |
6323 | 0 | } |
6324 | 0 | } |
6325 | | |
6326 | 0 | SmallString<256> MangledNameBuffer; |
6327 | 0 | StringRef GlobalVariableName; |
6328 | 0 | llvm::GlobalValue::LinkageTypes LT; |
6329 | | |
6330 | | // Mangle the string literal if that's how the ABI merges duplicate strings. |
6331 | | // Don't do it if they are writable, since we don't want writes in one TU to |
6332 | | // affect strings in another. |
6333 | 0 | if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && |
6334 | 0 | !LangOpts.WritableStrings) { |
6335 | 0 | llvm::raw_svector_ostream Out(MangledNameBuffer); |
6336 | 0 | getCXXABI().getMangleContext().mangleStringLiteral(S, Out); |
6337 | 0 | LT = llvm::GlobalValue::LinkOnceODRLinkage; |
6338 | 0 | GlobalVariableName = MangledNameBuffer; |
6339 | 0 | } else { |
6340 | 0 | LT = llvm::GlobalValue::PrivateLinkage; |
6341 | 0 | GlobalVariableName = Name; |
6342 | 0 | } |
6343 | |
|
6344 | 0 | auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); |
6345 | |
|
6346 | 0 | CGDebugInfo *DI = getModuleDebugInfo(); |
6347 | 0 | if (DI && getCodeGenOpts().hasReducedDebugInfo()) |
6348 | 0 | DI->AddStringLiteralDebugInfo(GV, S); |
6349 | |
|
6350 | 0 | if (Entry) |
6351 | 0 | *Entry = GV; |
6352 | |
|
6353 | 0 | SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); |
6354 | |
|
6355 | 0 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), |
6356 | 0 | GV->getValueType(), Alignment); |
6357 | 0 | } |
6358 | | |
6359 | | /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant |
6360 | | /// array for the given ObjCEncodeExpr node. |
6361 | | ConstantAddress |
6362 | 0 | CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { |
6363 | 0 | std::string Str; |
6364 | 0 | getContext().getObjCEncodingForType(E->getEncodedType(), Str); |
6365 | |
|
6366 | 0 | return GetAddrOfConstantCString(Str); |
6367 | 0 | } |
6368 | | |
6369 | | /// GetAddrOfConstantCString - Returns a pointer to a character array containing |
6370 | | /// the literal and a terminating '\0' character. |
6371 | | /// The result has pointer to array type. |
6372 | | ConstantAddress CodeGenModule::GetAddrOfConstantCString( |
6373 | 0 | const std::string &Str, const char *GlobalName) { |
6374 | 0 | StringRef StrWithNull(Str.c_str(), Str.size() + 1); |
6375 | 0 | CharUnits Alignment = |
6376 | 0 | getContext().getAlignOfGlobalVarInChars(getContext().CharTy); |
6377 | |
|
6378 | 0 | llvm::Constant *C = |
6379 | 0 | llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); |
6380 | | |
6381 | | // Don't share any string literals if strings aren't constant. |
6382 | 0 | llvm::GlobalVariable **Entry = nullptr; |
6383 | 0 | if (!LangOpts.WritableStrings) { |
6384 | 0 | Entry = &ConstantStringMap[C]; |
6385 | 0 | if (auto GV = *Entry) { |
6386 | 0 | if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) |
6387 | 0 | GV->setAlignment(Alignment.getAsAlign()); |
6388 | 0 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), |
6389 | 0 | GV->getValueType(), Alignment); |
6390 | 0 | } |
6391 | 0 | } |
6392 | | |
6393 | | // Get the default prefix if a name wasn't specified. |
6394 | 0 | if (!GlobalName) |
6395 | 0 | GlobalName = ".str"; |
6396 | | // Create a global variable for this. |
6397 | 0 | auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, |
6398 | 0 | GlobalName, Alignment); |
6399 | 0 | if (Entry) |
6400 | 0 | *Entry = GV; |
6401 | |
|
6402 | 0 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), |
6403 | 0 | GV->getValueType(), Alignment); |
6404 | 0 | } |
6405 | | |
6406 | | ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( |
6407 | 0 | const MaterializeTemporaryExpr *E, const Expr *Init) { |
6408 | 0 | assert((E->getStorageDuration() == SD_Static || |
6409 | 0 | E->getStorageDuration() == SD_Thread) && "not a global temporary"); |
6410 | 0 | const auto *VD = cast<VarDecl>(E->getExtendingDecl()); |
6411 | | |
6412 | | // If we're not materializing a subobject of the temporary, keep the |
6413 | | // cv-qualifiers from the type of the MaterializeTemporaryExpr. |
6414 | 0 | QualType MaterializedType = Init->getType(); |
6415 | 0 | if (Init == E->getSubExpr()) |
6416 | 0 | MaterializedType = E->getType(); |
6417 | |
|
6418 | 0 | CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); |
6419 | |
|
6420 | 0 | auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); |
6421 | 0 | if (!InsertResult.second) { |
6422 | | // We've seen this before: either we already created it or we're in the |
6423 | | // process of doing so. |
6424 | 0 | if (!InsertResult.first->second) { |
6425 | | // We recursively re-entered this function, probably during emission of |
6426 | | // the initializer. Create a placeholder. We'll clean this up in the |
6427 | | // outer call, at the end of this function. |
6428 | 0 | llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); |
6429 | 0 | InsertResult.first->second = new llvm::GlobalVariable( |
6430 | 0 | getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, |
6431 | 0 | nullptr); |
6432 | 0 | } |
6433 | 0 | return ConstantAddress(InsertResult.first->second, |
6434 | 0 | llvm::cast<llvm::GlobalVariable>( |
6435 | 0 | InsertResult.first->second->stripPointerCasts()) |
6436 | 0 | ->getValueType(), |
6437 | 0 | Align); |
6438 | 0 | } |
6439 | | |
6440 | | // FIXME: If an externally-visible declaration extends multiple temporaries, |
6441 | | // we need to give each temporary the same name in every translation unit (and |
6442 | | // we also need to make the temporaries externally-visible). |
6443 | 0 | SmallString<256> Name; |
6444 | 0 | llvm::raw_svector_ostream Out(Name); |
6445 | 0 | getCXXABI().getMangleContext().mangleReferenceTemporary( |
6446 | 0 | VD, E->getManglingNumber(), Out); |
6447 | |
|
6448 | 0 | APValue *Value = nullptr; |
6449 | 0 | if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) { |
6450 | | // If the initializer of the extending declaration is a constant |
6451 | | // initializer, we should have a cached constant initializer for this |
6452 | | // temporary. Note that this might have a different value from the value |
6453 | | // computed by evaluating the initializer if the surrounding constant |
6454 | | // expression modifies the temporary. |
6455 | 0 | Value = E->getOrCreateValue(false); |
6456 | 0 | } |
6457 | | |
6458 | | // Try evaluating it now, it might have a constant initializer. |
6459 | 0 | Expr::EvalResult EvalResult; |
6460 | 0 | if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && |
6461 | 0 | !EvalResult.hasSideEffects()) |
6462 | 0 | Value = &EvalResult.Val; |
6463 | |
|
6464 | 0 | LangAS AddrSpace = GetGlobalVarAddressSpace(VD); |
6465 | |
|
6466 | 0 | std::optional<ConstantEmitter> emitter; |
6467 | 0 | llvm::Constant *InitialValue = nullptr; |
6468 | 0 | bool Constant = false; |
6469 | 0 | llvm::Type *Type; |
6470 | 0 | if (Value) { |
6471 | | // The temporary has a constant initializer, use it. |
6472 | 0 | emitter.emplace(*this); |
6473 | 0 | InitialValue = emitter->emitForInitializer(*Value, AddrSpace, |
6474 | 0 | MaterializedType); |
6475 | 0 | Constant = |
6476 | 0 | MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value, |
6477 | 0 | /*ExcludeDtor*/ false); |
6478 | 0 | Type = InitialValue->getType(); |
6479 | 0 | } else { |
6480 | | // No initializer, the initialization will be provided when we |
6481 | | // initialize the declaration which performed lifetime extension. |
6482 | 0 | Type = getTypes().ConvertTypeForMem(MaterializedType); |
6483 | 0 | } |
6484 | | |
6485 | | // Create a global variable for this lifetime-extended temporary. |
6486 | 0 | llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD); |
6487 | 0 | if (Linkage == llvm::GlobalVariable::ExternalLinkage) { |
6488 | 0 | const VarDecl *InitVD; |
6489 | 0 | if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && |
6490 | 0 | isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { |
6491 | | // Temporaries defined inside a class get linkonce_odr linkage because the |
6492 | | // class can be defined in multiple translation units. |
6493 | 0 | Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; |
6494 | 0 | } else { |
6495 | | // There is no need for this temporary to have external linkage if the |
6496 | | // VarDecl has external linkage. |
6497 | 0 | Linkage = llvm::GlobalVariable::InternalLinkage; |
6498 | 0 | } |
6499 | 0 | } |
6500 | 0 | auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); |
6501 | 0 | auto *GV = new llvm::GlobalVariable( |
6502 | 0 | getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), |
6503 | 0 | /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); |
6504 | 0 | if (emitter) emitter->finalize(GV); |
6505 | | // Don't assign dllimport or dllexport to local linkage globals. |
6506 | 0 | if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { |
6507 | 0 | setGVProperties(GV, VD); |
6508 | 0 | if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) |
6509 | | // The reference temporary should never be dllexport. |
6510 | 0 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); |
6511 | 0 | } |
6512 | 0 | GV->setAlignment(Align.getAsAlign()); |
6513 | 0 | if (supportsCOMDAT() && GV->isWeakForLinker()) |
6514 | 0 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); |
6515 | 0 | if (VD->getTLSKind()) |
6516 | 0 | setTLSMode(GV, *VD); |
6517 | 0 | llvm::Constant *CV = GV; |
6518 | 0 | if (AddrSpace != LangAS::Default) |
6519 | 0 | CV = getTargetCodeGenInfo().performAddrSpaceCast( |
6520 | 0 | *this, GV, AddrSpace, LangAS::Default, |
6521 | 0 | llvm::PointerType::get( |
6522 | 0 | getLLVMContext(), |
6523 | 0 | getContext().getTargetAddressSpace(LangAS::Default))); |
6524 | | |
6525 | | // Update the map with the new temporary. If we created a placeholder above, |
6526 | | // replace it with the new global now. |
6527 | 0 | llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; |
6528 | 0 | if (Entry) { |
6529 | 0 | Entry->replaceAllUsesWith(CV); |
6530 | 0 | llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); |
6531 | 0 | } |
6532 | 0 | Entry = CV; |
6533 | |
|
6534 | 0 | return ConstantAddress(CV, Type, Align); |
6535 | 0 | } |
6536 | | |
6537 | | /// EmitObjCPropertyImplementations - Emit information for synthesized |
6538 | | /// properties for an implementation. |
6539 | | void CodeGenModule::EmitObjCPropertyImplementations(const |
6540 | 0 | ObjCImplementationDecl *D) { |
6541 | 0 | for (const auto *PID : D->property_impls()) { |
6542 | | // Dynamic is just for type-checking. |
6543 | 0 | if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { |
6544 | 0 | ObjCPropertyDecl *PD = PID->getPropertyDecl(); |
6545 | | |
6546 | | // Determine which methods need to be implemented, some may have |
6547 | | // been overridden. Note that ::isPropertyAccessor is not the method |
6548 | | // we want, that just indicates if the decl came from a |
6549 | | // property. What we want to know is if the method is defined in |
6550 | | // this implementation. |
6551 | 0 | auto *Getter = PID->getGetterMethodDecl(); |
6552 | 0 | if (!Getter || Getter->isSynthesizedAccessorStub()) |
6553 | 0 | CodeGenFunction(*this).GenerateObjCGetter( |
6554 | 0 | const_cast<ObjCImplementationDecl *>(D), PID); |
6555 | 0 | auto *Setter = PID->getSetterMethodDecl(); |
6556 | 0 | if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) |
6557 | 0 | CodeGenFunction(*this).GenerateObjCSetter( |
6558 | 0 | const_cast<ObjCImplementationDecl *>(D), PID); |
6559 | 0 | } |
6560 | 0 | } |
6561 | 0 | } |
6562 | | |
6563 | 0 | static bool needsDestructMethod(ObjCImplementationDecl *impl) { |
6564 | 0 | const ObjCInterfaceDecl *iface = impl->getClassInterface(); |
6565 | 0 | for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); |
6566 | 0 | ivar; ivar = ivar->getNextIvar()) |
6567 | 0 | if (ivar->getType().isDestructedType()) |
6568 | 0 | return true; |
6569 | | |
6570 | 0 | return false; |
6571 | 0 | } |
6572 | | |
6573 | | static bool AllTrivialInitializers(CodeGenModule &CGM, |
6574 | 0 | ObjCImplementationDecl *D) { |
6575 | 0 | CodeGenFunction CGF(CGM); |
6576 | 0 | for (ObjCImplementationDecl::init_iterator B = D->init_begin(), |
6577 | 0 | E = D->init_end(); B != E; ++B) { |
6578 | 0 | CXXCtorInitializer *CtorInitExp = *B; |
6579 | 0 | Expr *Init = CtorInitExp->getInit(); |
6580 | 0 | if (!CGF.isTrivialInitializer(Init)) |
6581 | 0 | return false; |
6582 | 0 | } |
6583 | 0 | return true; |
6584 | 0 | } |
6585 | | |
6586 | | /// EmitObjCIvarInitializations - Emit information for ivar initialization |
6587 | | /// for an implementation. |
6588 | 0 | void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { |
6589 | | // We might need a .cxx_destruct even if we don't have any ivar initializers. |
6590 | 0 | if (needsDestructMethod(D)) { |
6591 | 0 | IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); |
6592 | 0 | Selector cxxSelector = getContext().Selectors.getSelector(0, &II); |
6593 | 0 | ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( |
6594 | 0 | getContext(), D->getLocation(), D->getLocation(), cxxSelector, |
6595 | 0 | getContext().VoidTy, nullptr, D, |
6596 | 0 | /*isInstance=*/true, /*isVariadic=*/false, |
6597 | 0 | /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, |
6598 | 0 | /*isImplicitlyDeclared=*/true, |
6599 | 0 | /*isDefined=*/false, ObjCImplementationControl::Required); |
6600 | 0 | D->addInstanceMethod(DTORMethod); |
6601 | 0 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); |
6602 | 0 | D->setHasDestructors(true); |
6603 | 0 | } |
6604 | | |
6605 | | // If the implementation doesn't have any ivar initializers, we don't need |
6606 | | // a .cxx_construct. |
6607 | 0 | if (D->getNumIvarInitializers() == 0 || |
6608 | 0 | AllTrivialInitializers(*this, D)) |
6609 | 0 | return; |
6610 | | |
6611 | 0 | IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); |
6612 | 0 | Selector cxxSelector = getContext().Selectors.getSelector(0, &II); |
6613 | | // The constructor returns 'self'. |
6614 | 0 | ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( |
6615 | 0 | getContext(), D->getLocation(), D->getLocation(), cxxSelector, |
6616 | 0 | getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, |
6617 | 0 | /*isVariadic=*/false, |
6618 | 0 | /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, |
6619 | 0 | /*isImplicitlyDeclared=*/true, |
6620 | 0 | /*isDefined=*/false, ObjCImplementationControl::Required); |
6621 | 0 | D->addInstanceMethod(CTORMethod); |
6622 | 0 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); |
6623 | 0 | D->setHasNonZeroConstructors(true); |
6624 | 0 | } |
6625 | | |
6626 | | // EmitLinkageSpec - Emit all declarations in a linkage spec. |
6627 | 0 | void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { |
6628 | 0 | if (LSD->getLanguage() != LinkageSpecLanguageIDs::C && |
6629 | 0 | LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) { |
6630 | 0 | ErrorUnsupported(LSD, "linkage spec"); |
6631 | 0 | return; |
6632 | 0 | } |
6633 | | |
6634 | 0 | EmitDeclContext(LSD); |
6635 | 0 | } |
6636 | | |
6637 | 0 | void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { |
6638 | | // Device code should not be at top level. |
6639 | 0 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) |
6640 | 0 | return; |
6641 | | |
6642 | 0 | std::unique_ptr<CodeGenFunction> &CurCGF = |
6643 | 0 | GlobalTopLevelStmtBlockInFlight.first; |
6644 | | |
6645 | | // We emitted a top-level stmt but after it there is initialization. |
6646 | | // Stop squashing the top-level stmts into a single function. |
6647 | 0 | if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { |
6648 | 0 | CurCGF->FinishFunction(D->getEndLoc()); |
6649 | 0 | CurCGF = nullptr; |
6650 | 0 | } |
6651 | |
|
6652 | 0 | if (!CurCGF) { |
6653 | | // void __stmts__N(void) |
6654 | | // FIXME: Ask the ABI name mangler to pick a name. |
6655 | 0 | std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); |
6656 | 0 | FunctionArgList Args; |
6657 | 0 | QualType RetTy = getContext().VoidTy; |
6658 | 0 | const CGFunctionInfo &FnInfo = |
6659 | 0 | getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); |
6660 | 0 | llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); |
6661 | 0 | llvm::Function *Fn = llvm::Function::Create( |
6662 | 0 | FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); |
6663 | |
|
6664 | 0 | CurCGF.reset(new CodeGenFunction(*this)); |
6665 | 0 | GlobalTopLevelStmtBlockInFlight.second = D; |
6666 | 0 | CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, |
6667 | 0 | D->getBeginLoc(), D->getBeginLoc()); |
6668 | 0 | CXXGlobalInits.push_back(Fn); |
6669 | 0 | } |
6670 | |
|
6671 | 0 | CurCGF->EmitStmt(D->getStmt()); |
6672 | 0 | } |
6673 | | |
6674 | 0 | void CodeGenModule::EmitDeclContext(const DeclContext *DC) { |
6675 | 0 | for (auto *I : DC->decls()) { |
6676 | | // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope |
6677 | | // are themselves considered "top-level", so EmitTopLevelDecl on an |
6678 | | // ObjCImplDecl does not recursively visit them. We need to do that in |
6679 | | // case they're nested inside another construct (LinkageSpecDecl / |
6680 | | // ExportDecl) that does stop them from being considered "top-level". |
6681 | 0 | if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { |
6682 | 0 | for (auto *M : OID->methods()) |
6683 | 0 | EmitTopLevelDecl(M); |
6684 | 0 | } |
6685 | |
|
6686 | 0 | EmitTopLevelDecl(I); |
6687 | 0 | } |
6688 | 0 | } |
6689 | | |
6690 | | /// EmitTopLevelDecl - Emit code for a single top level declaration. |
6691 | 0 | void CodeGenModule::EmitTopLevelDecl(Decl *D) { |
6692 | | // Ignore dependent declarations. |
6693 | 0 | if (D->isTemplated()) |
6694 | 0 | return; |
6695 | | |
6696 | | // Consteval function shouldn't be emitted. |
6697 | 0 | if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction()) |
6698 | 0 | return; |
6699 | | |
6700 | 0 | switch (D->getKind()) { |
6701 | 0 | case Decl::CXXConversion: |
6702 | 0 | case Decl::CXXMethod: |
6703 | 0 | case Decl::Function: |
6704 | 0 | EmitGlobal(cast<FunctionDecl>(D)); |
6705 | | // Always provide some coverage mapping |
6706 | | // even for the functions that aren't emitted. |
6707 | 0 | AddDeferredUnusedCoverageMapping(D); |
6708 | 0 | break; |
6709 | | |
6710 | 0 | case Decl::CXXDeductionGuide: |
6711 | | // Function-like, but does not result in code emission. |
6712 | 0 | break; |
6713 | | |
6714 | 0 | case Decl::Var: |
6715 | 0 | case Decl::Decomposition: |
6716 | 0 | case Decl::VarTemplateSpecialization: |
6717 | 0 | EmitGlobal(cast<VarDecl>(D)); |
6718 | 0 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) |
6719 | 0 | for (auto *B : DD->bindings()) |
6720 | 0 | if (auto *HD = B->getHoldingVar()) |
6721 | 0 | EmitGlobal(HD); |
6722 | 0 | break; |
6723 | | |
6724 | | // Indirect fields from global anonymous structs and unions can be |
6725 | | // ignored; only the actual variable requires IR gen support. |
6726 | 0 | case Decl::IndirectField: |
6727 | 0 | break; |
6728 | | |
6729 | | // C++ Decls |
6730 | 0 | case Decl::Namespace: |
6731 | 0 | EmitDeclContext(cast<NamespaceDecl>(D)); |
6732 | 0 | break; |
6733 | 0 | case Decl::ClassTemplateSpecialization: { |
6734 | 0 | const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); |
6735 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6736 | 0 | if (Spec->getSpecializationKind() == |
6737 | 0 | TSK_ExplicitInstantiationDefinition && |
6738 | 0 | Spec->hasDefinition()) |
6739 | 0 | DI->completeTemplateDefinition(*Spec); |
6740 | 0 | } [[fallthrough]]; |
6741 | 0 | case Decl::CXXRecord: { |
6742 | 0 | CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); |
6743 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) { |
6744 | 0 | if (CRD->hasDefinition()) |
6745 | 0 | DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); |
6746 | 0 | if (auto *ES = D->getASTContext().getExternalSource()) |
6747 | 0 | if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) |
6748 | 0 | DI->completeUnusedClass(*CRD); |
6749 | 0 | } |
6750 | | // Emit any static data members, they may be definitions. |
6751 | 0 | for (auto *I : CRD->decls()) |
6752 | 0 | if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) |
6753 | 0 | EmitTopLevelDecl(I); |
6754 | 0 | break; |
6755 | 0 | } |
6756 | | // No code generation needed. |
6757 | 0 | case Decl::UsingShadow: |
6758 | 0 | case Decl::ClassTemplate: |
6759 | 0 | case Decl::VarTemplate: |
6760 | 0 | case Decl::Concept: |
6761 | 0 | case Decl::VarTemplatePartialSpecialization: |
6762 | 0 | case Decl::FunctionTemplate: |
6763 | 0 | case Decl::TypeAliasTemplate: |
6764 | 0 | case Decl::Block: |
6765 | 0 | case Decl::Empty: |
6766 | 0 | case Decl::Binding: |
6767 | 0 | break; |
6768 | 0 | case Decl::Using: // using X; [C++] |
6769 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6770 | 0 | DI->EmitUsingDecl(cast<UsingDecl>(*D)); |
6771 | 0 | break; |
6772 | 0 | case Decl::UsingEnum: // using enum X; [C++] |
6773 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6774 | 0 | DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); |
6775 | 0 | break; |
6776 | 0 | case Decl::NamespaceAlias: |
6777 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6778 | 0 | DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); |
6779 | 0 | break; |
6780 | 0 | case Decl::UsingDirective: // using namespace X; [C++] |
6781 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6782 | 0 | DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); |
6783 | 0 | break; |
6784 | 0 | case Decl::CXXConstructor: |
6785 | 0 | getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); |
6786 | 0 | break; |
6787 | 0 | case Decl::CXXDestructor: |
6788 | 0 | getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); |
6789 | 0 | break; |
6790 | | |
6791 | 0 | case Decl::StaticAssert: |
6792 | | // Nothing to do. |
6793 | 0 | break; |
6794 | | |
6795 | | // Objective-C Decls |
6796 | | |
6797 | | // Forward declarations, no (immediate) code generation. |
6798 | 0 | case Decl::ObjCInterface: |
6799 | 0 | case Decl::ObjCCategory: |
6800 | 0 | break; |
6801 | | |
6802 | 0 | case Decl::ObjCProtocol: { |
6803 | 0 | auto *Proto = cast<ObjCProtocolDecl>(D); |
6804 | 0 | if (Proto->isThisDeclarationADefinition()) |
6805 | 0 | ObjCRuntime->GenerateProtocol(Proto); |
6806 | 0 | break; |
6807 | 0 | } |
6808 | | |
6809 | 0 | case Decl::ObjCCategoryImpl: |
6810 | | // Categories have properties but don't support synthesize so we |
6811 | | // can ignore them here. |
6812 | 0 | ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); |
6813 | 0 | break; |
6814 | | |
6815 | 0 | case Decl::ObjCImplementation: { |
6816 | 0 | auto *OMD = cast<ObjCImplementationDecl>(D); |
6817 | 0 | EmitObjCPropertyImplementations(OMD); |
6818 | 0 | EmitObjCIvarInitializations(OMD); |
6819 | 0 | ObjCRuntime->GenerateClass(OMD); |
6820 | | // Emit global variable debug information. |
6821 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6822 | 0 | if (getCodeGenOpts().hasReducedDebugInfo()) |
6823 | 0 | DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( |
6824 | 0 | OMD->getClassInterface()), OMD->getLocation()); |
6825 | 0 | break; |
6826 | 0 | } |
6827 | 0 | case Decl::ObjCMethod: { |
6828 | 0 | auto *OMD = cast<ObjCMethodDecl>(D); |
6829 | | // If this is not a prototype, emit the body. |
6830 | 0 | if (OMD->getBody()) |
6831 | 0 | CodeGenFunction(*this).GenerateObjCMethod(OMD); |
6832 | 0 | break; |
6833 | 0 | } |
6834 | 0 | case Decl::ObjCCompatibleAlias: |
6835 | 0 | ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); |
6836 | 0 | break; |
6837 | | |
6838 | 0 | case Decl::PragmaComment: { |
6839 | 0 | const auto *PCD = cast<PragmaCommentDecl>(D); |
6840 | 0 | switch (PCD->getCommentKind()) { |
6841 | 0 | case PCK_Unknown: |
6842 | 0 | llvm_unreachable("unexpected pragma comment kind"); |
6843 | 0 | case PCK_Linker: |
6844 | 0 | AppendLinkerOptions(PCD->getArg()); |
6845 | 0 | break; |
6846 | 0 | case PCK_Lib: |
6847 | 0 | AddDependentLib(PCD->getArg()); |
6848 | 0 | break; |
6849 | 0 | case PCK_Compiler: |
6850 | 0 | case PCK_ExeStr: |
6851 | 0 | case PCK_User: |
6852 | 0 | break; // We ignore all of these. |
6853 | 0 | } |
6854 | 0 | break; |
6855 | 0 | } |
6856 | | |
6857 | 0 | case Decl::PragmaDetectMismatch: { |
6858 | 0 | const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); |
6859 | 0 | AddDetectMismatch(PDMD->getName(), PDMD->getValue()); |
6860 | 0 | break; |
6861 | 0 | } |
6862 | | |
6863 | 0 | case Decl::LinkageSpec: |
6864 | 0 | EmitLinkageSpec(cast<LinkageSpecDecl>(D)); |
6865 | 0 | break; |
6866 | | |
6867 | 0 | case Decl::FileScopeAsm: { |
6868 | | // File-scope asm is ignored during device-side CUDA compilation. |
6869 | 0 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) |
6870 | 0 | break; |
6871 | | // File-scope asm is ignored during device-side OpenMP compilation. |
6872 | 0 | if (LangOpts.OpenMPIsTargetDevice) |
6873 | 0 | break; |
6874 | | // File-scope asm is ignored during device-side SYCL compilation. |
6875 | 0 | if (LangOpts.SYCLIsDevice) |
6876 | 0 | break; |
6877 | 0 | auto *AD = cast<FileScopeAsmDecl>(D); |
6878 | 0 | getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); |
6879 | 0 | break; |
6880 | 0 | } |
6881 | | |
6882 | 0 | case Decl::TopLevelStmt: |
6883 | 0 | EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); |
6884 | 0 | break; |
6885 | | |
6886 | 0 | case Decl::Import: { |
6887 | 0 | auto *Import = cast<ImportDecl>(D); |
6888 | | |
6889 | | // If we've already imported this module, we're done. |
6890 | 0 | if (!ImportedModules.insert(Import->getImportedModule())) |
6891 | 0 | break; |
6892 | | |
6893 | | // Emit debug information for direct imports. |
6894 | 0 | if (!Import->getImportedOwningModule()) { |
6895 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6896 | 0 | DI->EmitImportDecl(*Import); |
6897 | 0 | } |
6898 | | |
6899 | | // For C++ standard modules we are done - we will call the module |
6900 | | // initializer for imported modules, and that will likewise call those for |
6901 | | // any imports it has. |
6902 | 0 | if (CXX20ModuleInits && Import->getImportedOwningModule() && |
6903 | 0 | !Import->getImportedOwningModule()->isModuleMapModule()) |
6904 | 0 | break; |
6905 | | |
6906 | | // For clang C++ module map modules the initializers for sub-modules are |
6907 | | // emitted here. |
6908 | | |
6909 | | // Find all of the submodules and emit the module initializers. |
6910 | 0 | llvm::SmallPtrSet<clang::Module *, 16> Visited; |
6911 | 0 | SmallVector<clang::Module *, 16> Stack; |
6912 | 0 | Visited.insert(Import->getImportedModule()); |
6913 | 0 | Stack.push_back(Import->getImportedModule()); |
6914 | |
|
6915 | 0 | while (!Stack.empty()) { |
6916 | 0 | clang::Module *Mod = Stack.pop_back_val(); |
6917 | 0 | if (!EmittedModuleInitializers.insert(Mod).second) |
6918 | 0 | continue; |
6919 | | |
6920 | 0 | for (auto *D : Context.getModuleInitializers(Mod)) |
6921 | 0 | EmitTopLevelDecl(D); |
6922 | | |
6923 | | // Visit the submodules of this module. |
6924 | 0 | for (auto *Submodule : Mod->submodules()) { |
6925 | | // Skip explicit children; they need to be explicitly imported to emit |
6926 | | // the initializers. |
6927 | 0 | if (Submodule->IsExplicit) |
6928 | 0 | continue; |
6929 | | |
6930 | 0 | if (Visited.insert(Submodule).second) |
6931 | 0 | Stack.push_back(Submodule); |
6932 | 0 | } |
6933 | 0 | } |
6934 | 0 | break; |
6935 | 0 | } |
6936 | | |
6937 | 0 | case Decl::Export: |
6938 | 0 | EmitDeclContext(cast<ExportDecl>(D)); |
6939 | 0 | break; |
6940 | | |
6941 | 0 | case Decl::OMPThreadPrivate: |
6942 | 0 | EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); |
6943 | 0 | break; |
6944 | | |
6945 | 0 | case Decl::OMPAllocate: |
6946 | 0 | EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); |
6947 | 0 | break; |
6948 | | |
6949 | 0 | case Decl::OMPDeclareReduction: |
6950 | 0 | EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); |
6951 | 0 | break; |
6952 | | |
6953 | 0 | case Decl::OMPDeclareMapper: |
6954 | 0 | EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); |
6955 | 0 | break; |
6956 | | |
6957 | 0 | case Decl::OMPRequires: |
6958 | 0 | EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); |
6959 | 0 | break; |
6960 | | |
6961 | 0 | case Decl::Typedef: |
6962 | 0 | case Decl::TypeAlias: // using foo = bar; [C++11] |
6963 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6964 | 0 | DI->EmitAndRetainType( |
6965 | 0 | getContext().getTypedefType(cast<TypedefNameDecl>(D))); |
6966 | 0 | break; |
6967 | | |
6968 | 0 | case Decl::Record: |
6969 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6970 | 0 | if (cast<RecordDecl>(D)->getDefinition()) |
6971 | 0 | DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); |
6972 | 0 | break; |
6973 | | |
6974 | 0 | case Decl::Enum: |
6975 | 0 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6976 | 0 | if (cast<EnumDecl>(D)->getDefinition()) |
6977 | 0 | DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); |
6978 | 0 | break; |
6979 | | |
6980 | 0 | case Decl::HLSLBuffer: |
6981 | 0 | getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); |
6982 | 0 | break; |
6983 | | |
6984 | 0 | default: |
6985 | | // Make sure we handled everything we should, every other kind is a |
6986 | | // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind |
6987 | | // function. Need to recode Decl::Kind to do that easily. |
6988 | 0 | assert(isa<TypeDecl>(D) && "Unsupported decl kind"); |
6989 | 0 | break; |
6990 | 0 | } |
6991 | 0 | } |
6992 | | |
6993 | 0 | void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { |
6994 | | // Do we need to generate coverage mapping? |
6995 | 0 | if (!CodeGenOpts.CoverageMapping) |
6996 | 0 | return; |
6997 | 0 | switch (D->getKind()) { |
6998 | 0 | case Decl::CXXConversion: |
6999 | 0 | case Decl::CXXMethod: |
7000 | 0 | case Decl::Function: |
7001 | 0 | case Decl::ObjCMethod: |
7002 | 0 | case Decl::CXXConstructor: |
7003 | 0 | case Decl::CXXDestructor: { |
7004 | 0 | if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) |
7005 | 0 | break; |
7006 | 0 | SourceManager &SM = getContext().getSourceManager(); |
7007 | 0 | if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) |
7008 | 0 | break; |
7009 | 0 | DeferredEmptyCoverageMappingDecls.try_emplace(D, true); |
7010 | 0 | break; |
7011 | 0 | } |
7012 | 0 | default: |
7013 | 0 | break; |
7014 | 0 | }; |
7015 | 0 | } |
7016 | | |
7017 | 0 | void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { |
7018 | | // Do we need to generate coverage mapping? |
7019 | 0 | if (!CodeGenOpts.CoverageMapping) |
7020 | 0 | return; |
7021 | 0 | if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { |
7022 | 0 | if (Fn->isTemplateInstantiation()) |
7023 | 0 | ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); |
7024 | 0 | } |
7025 | 0 | DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false); |
7026 | 0 | } |
7027 | | |
7028 | 0 | void CodeGenModule::EmitDeferredUnusedCoverageMappings() { |
7029 | | // We call takeVector() here to avoid use-after-free. |
7030 | | // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because |
7031 | | // we deserialize function bodies to emit coverage info for them, and that |
7032 | | // deserializes more declarations. How should we handle that case? |
7033 | 0 | for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { |
7034 | 0 | if (!Entry.second) |
7035 | 0 | continue; |
7036 | 0 | const Decl *D = Entry.first; |
7037 | 0 | switch (D->getKind()) { |
7038 | 0 | case Decl::CXXConversion: |
7039 | 0 | case Decl::CXXMethod: |
7040 | 0 | case Decl::Function: |
7041 | 0 | case Decl::ObjCMethod: { |
7042 | 0 | CodeGenPGO PGO(*this); |
7043 | 0 | GlobalDecl GD(cast<FunctionDecl>(D)); |
7044 | 0 | PGO.emitEmptyCounterMapping(D, getMangledName(GD), |
7045 | 0 | getFunctionLinkage(GD)); |
7046 | 0 | break; |
7047 | 0 | } |
7048 | 0 | case Decl::CXXConstructor: { |
7049 | 0 | CodeGenPGO PGO(*this); |
7050 | 0 | GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); |
7051 | 0 | PGO.emitEmptyCounterMapping(D, getMangledName(GD), |
7052 | 0 | getFunctionLinkage(GD)); |
7053 | 0 | break; |
7054 | 0 | } |
7055 | 0 | case Decl::CXXDestructor: { |
7056 | 0 | CodeGenPGO PGO(*this); |
7057 | 0 | GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); |
7058 | 0 | PGO.emitEmptyCounterMapping(D, getMangledName(GD), |
7059 | 0 | getFunctionLinkage(GD)); |
7060 | 0 | break; |
7061 | 0 | } |
7062 | 0 | default: |
7063 | 0 | break; |
7064 | 0 | }; |
7065 | 0 | } |
7066 | 0 | } |
7067 | | |
7068 | 0 | void CodeGenModule::EmitMainVoidAlias() { |
7069 | | // In order to transition away from "__original_main" gracefully, emit an |
7070 | | // alias for "main" in the no-argument case so that libc can detect when |
7071 | | // new-style no-argument main is in used. |
7072 | 0 | if (llvm::Function *F = getModule().getFunction("main")) { |
7073 | 0 | if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && |
7074 | 0 | F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { |
7075 | 0 | auto *GA = llvm::GlobalAlias::create("__main_void", F); |
7076 | 0 | GA->setVisibility(llvm::GlobalValue::HiddenVisibility); |
7077 | 0 | } |
7078 | 0 | } |
7079 | 0 | } |
7080 | | |
7081 | | /// Turns the given pointer into a constant. |
7082 | | static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, |
7083 | 0 | const void *Ptr) { |
7084 | 0 | uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); |
7085 | 0 | llvm::Type *i64 = llvm::Type::getInt64Ty(Context); |
7086 | 0 | return llvm::ConstantInt::get(i64, PtrInt); |
7087 | 0 | } |
7088 | | |
7089 | | static void EmitGlobalDeclMetadata(CodeGenModule &CGM, |
7090 | | llvm::NamedMDNode *&GlobalMetadata, |
7091 | | GlobalDecl D, |
7092 | 0 | llvm::GlobalValue *Addr) { |
7093 | 0 | if (!GlobalMetadata) |
7094 | 0 | GlobalMetadata = |
7095 | 0 | CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); |
7096 | | |
7097 | | // TODO: should we report variant information for ctors/dtors? |
7098 | 0 | llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), |
7099 | 0 | llvm::ConstantAsMetadata::get(GetPointerConstant( |
7100 | 0 | CGM.getLLVMContext(), D.getDecl()))}; |
7101 | 0 | GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); |
7102 | 0 | } |
7103 | | |
7104 | | bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, |
7105 | 0 | llvm::GlobalValue *CppFunc) { |
7106 | | // Store the list of ifuncs we need to replace uses in. |
7107 | 0 | llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; |
7108 | | // List of ConstantExprs that we should be able to delete when we're done |
7109 | | // here. |
7110 | 0 | llvm::SmallVector<llvm::ConstantExpr *> CEs; |
7111 | | |
7112 | | // It isn't valid to replace the extern-C ifuncs if all we find is itself! |
7113 | 0 | if (Elem == CppFunc) |
7114 | 0 | return false; |
7115 | | |
7116 | | // First make sure that all users of this are ifuncs (or ifuncs via a |
7117 | | // bitcast), and collect the list of ifuncs and CEs so we can work on them |
7118 | | // later. |
7119 | 0 | for (llvm::User *User : Elem->users()) { |
7120 | | // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an |
7121 | | // ifunc directly. In any other case, just give up, as we don't know what we |
7122 | | // could break by changing those. |
7123 | 0 | if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { |
7124 | 0 | if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) |
7125 | 0 | return false; |
7126 | | |
7127 | 0 | for (llvm::User *CEUser : ConstExpr->users()) { |
7128 | 0 | if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { |
7129 | 0 | IFuncs.push_back(IFunc); |
7130 | 0 | } else { |
7131 | 0 | return false; |
7132 | 0 | } |
7133 | 0 | } |
7134 | 0 | CEs.push_back(ConstExpr); |
7135 | 0 | } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { |
7136 | 0 | IFuncs.push_back(IFunc); |
7137 | 0 | } else { |
7138 | | // This user is one we don't know how to handle, so fail redirection. This |
7139 | | // will result in an ifunc retaining a resolver name that will ultimately |
7140 | | // fail to be resolved to a defined function. |
7141 | 0 | return false; |
7142 | 0 | } |
7143 | 0 | } |
7144 | | |
7145 | | // Now we know this is a valid case where we can do this alias replacement, we |
7146 | | // need to remove all of the references to Elem (and the bitcasts!) so we can |
7147 | | // delete it. |
7148 | 0 | for (llvm::GlobalIFunc *IFunc : IFuncs) |
7149 | 0 | IFunc->setResolver(nullptr); |
7150 | 0 | for (llvm::ConstantExpr *ConstExpr : CEs) |
7151 | 0 | ConstExpr->destroyConstant(); |
7152 | | |
7153 | | // We should now be out of uses for the 'old' version of this function, so we |
7154 | | // can erase it as well. |
7155 | 0 | Elem->eraseFromParent(); |
7156 | |
|
7157 | 0 | for (llvm::GlobalIFunc *IFunc : IFuncs) { |
7158 | | // The type of the resolver is always just a function-type that returns the |
7159 | | // type of the IFunc, so create that here. If the type of the actual |
7160 | | // resolver doesn't match, it just gets bitcast to the right thing. |
7161 | 0 | auto *ResolverTy = |
7162 | 0 | llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); |
7163 | 0 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
7164 | 0 | CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); |
7165 | 0 | IFunc->setResolver(Resolver); |
7166 | 0 | } |
7167 | 0 | return true; |
7168 | 0 | } |
7169 | | |
7170 | | /// For each function which is declared within an extern "C" region and marked |
7171 | | /// as 'used', but has internal linkage, create an alias from the unmangled |
7172 | | /// name to the mangled name if possible. People expect to be able to refer |
7173 | | /// to such functions with an unmangled name from inline assembly within the |
7174 | | /// same translation unit. |
7175 | 0 | void CodeGenModule::EmitStaticExternCAliases() { |
7176 | 0 | if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) |
7177 | 0 | return; |
7178 | 0 | for (auto &I : StaticExternCValues) { |
7179 | 0 | IdentifierInfo *Name = I.first; |
7180 | 0 | llvm::GlobalValue *Val = I.second; |
7181 | | |
7182 | | // If Val is null, that implies there were multiple declarations that each |
7183 | | // had a claim to the unmangled name. In this case, generation of the alias |
7184 | | // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. |
7185 | 0 | if (!Val) |
7186 | 0 | break; |
7187 | | |
7188 | 0 | llvm::GlobalValue *ExistingElem = |
7189 | 0 | getModule().getNamedValue(Name->getName()); |
7190 | | |
7191 | | // If there is either not something already by this name, or we were able to |
7192 | | // replace all uses from IFuncs, create the alias. |
7193 | 0 | if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) |
7194 | 0 | addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); |
7195 | 0 | } |
7196 | 0 | } |
7197 | | |
7198 | | bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, |
7199 | 0 | GlobalDecl &Result) const { |
7200 | 0 | auto Res = Manglings.find(MangledName); |
7201 | 0 | if (Res == Manglings.end()) |
7202 | 0 | return false; |
7203 | 0 | Result = Res->getValue(); |
7204 | 0 | return true; |
7205 | 0 | } |
7206 | | |
7207 | | /// Emits metadata nodes associating all the global values in the |
7208 | | /// current module with the Decls they came from. This is useful for |
7209 | | /// projects using IR gen as a subroutine. |
7210 | | /// |
7211 | | /// Since there's currently no way to associate an MDNode directly |
7212 | | /// with an llvm::GlobalValue, we create a global named metadata |
7213 | | /// with the name 'clang.global.decl.ptrs'. |
7214 | 0 | void CodeGenModule::EmitDeclMetadata() { |
7215 | 0 | llvm::NamedMDNode *GlobalMetadata = nullptr; |
7216 | |
|
7217 | 0 | for (auto &I : MangledDeclNames) { |
7218 | 0 | llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); |
7219 | | // Some mangled names don't necessarily have an associated GlobalValue |
7220 | | // in this module, e.g. if we mangled it for DebugInfo. |
7221 | 0 | if (Addr) |
7222 | 0 | EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); |
7223 | 0 | } |
7224 | 0 | } |
7225 | | |
7226 | | /// Emits metadata nodes for all the local variables in the current |
7227 | | /// function. |
7228 | 0 | void CodeGenFunction::EmitDeclMetadata() { |
7229 | 0 | if (LocalDeclMap.empty()) return; |
7230 | | |
7231 | 0 | llvm::LLVMContext &Context = getLLVMContext(); |
7232 | | |
7233 | | // Find the unique metadata ID for this name. |
7234 | 0 | unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); |
7235 | |
|
7236 | 0 | llvm::NamedMDNode *GlobalMetadata = nullptr; |
7237 | |
|
7238 | 0 | for (auto &I : LocalDeclMap) { |
7239 | 0 | const Decl *D = I.first; |
7240 | 0 | llvm::Value *Addr = I.second.getPointer(); |
7241 | 0 | if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { |
7242 | 0 | llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); |
7243 | 0 | Alloca->setMetadata( |
7244 | 0 | DeclPtrKind, llvm::MDNode::get( |
7245 | 0 | Context, llvm::ValueAsMetadata::getConstant(DAddr))); |
7246 | 0 | } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { |
7247 | 0 | GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); |
7248 | 0 | EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); |
7249 | 0 | } |
7250 | 0 | } |
7251 | 0 | } |
7252 | | |
7253 | 0 | void CodeGenModule::EmitVersionIdentMetadata() { |
7254 | 0 | llvm::NamedMDNode *IdentMetadata = |
7255 | 0 | TheModule.getOrInsertNamedMetadata("llvm.ident"); |
7256 | 0 | std::string Version = getClangFullVersion(); |
7257 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
7258 | |
|
7259 | 0 | llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; |
7260 | 0 | IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); |
7261 | 0 | } |
7262 | | |
7263 | 0 | void CodeGenModule::EmitCommandLineMetadata() { |
7264 | 0 | llvm::NamedMDNode *CommandLineMetadata = |
7265 | 0 | TheModule.getOrInsertNamedMetadata("llvm.commandline"); |
7266 | 0 | std::string CommandLine = getCodeGenOpts().RecordCommandLine; |
7267 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
7268 | |
|
7269 | 0 | llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; |
7270 | 0 | CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); |
7271 | 0 | } |
7272 | | |
7273 | 0 | void CodeGenModule::EmitCoverageFile() { |
7274 | 0 | llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); |
7275 | 0 | if (!CUNode) |
7276 | 0 | return; |
7277 | | |
7278 | 0 | llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); |
7279 | 0 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
7280 | 0 | auto *CoverageDataFile = |
7281 | 0 | llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); |
7282 | 0 | auto *CoverageNotesFile = |
7283 | 0 | llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); |
7284 | 0 | for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { |
7285 | 0 | llvm::MDNode *CU = CUNode->getOperand(i); |
7286 | 0 | llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; |
7287 | 0 | GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); |
7288 | 0 | } |
7289 | 0 | } |
7290 | | |
7291 | | llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, |
7292 | 0 | bool ForEH) { |
7293 | | // Return a bogus pointer if RTTI is disabled, unless it's for EH. |
7294 | | // FIXME: should we even be calling this method if RTTI is disabled |
7295 | | // and it's not for EH? |
7296 | 0 | if (!shouldEmitRTTI(ForEH)) |
7297 | 0 | return llvm::Constant::getNullValue(GlobalsInt8PtrTy); |
7298 | | |
7299 | 0 | if (ForEH && Ty->isObjCObjectPointerType() && |
7300 | 0 | LangOpts.ObjCRuntime.isGNUFamily()) |
7301 | 0 | return ObjCRuntime->GetEHType(Ty); |
7302 | | |
7303 | 0 | return getCXXABI().getAddrOfRTTIDescriptor(Ty); |
7304 | 0 | } |
7305 | | |
7306 | 0 | void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { |
7307 | | // Do not emit threadprivates in simd-only mode. |
7308 | 0 | if (LangOpts.OpenMP && LangOpts.OpenMPSimd) |
7309 | 0 | return; |
7310 | 0 | for (auto RefExpr : D->varlists()) { |
7311 | 0 | auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); |
7312 | 0 | bool PerformInit = |
7313 | 0 | VD->getAnyInitializer() && |
7314 | 0 | !VD->getAnyInitializer()->isConstantInitializer(getContext(), |
7315 | 0 | /*ForRef=*/false); |
7316 | |
|
7317 | 0 | Address Addr(GetAddrOfGlobalVar(VD), |
7318 | 0 | getTypes().ConvertTypeForMem(VD->getType()), |
7319 | 0 | getContext().getDeclAlign(VD)); |
7320 | 0 | if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( |
7321 | 0 | VD, Addr, RefExpr->getBeginLoc(), PerformInit)) |
7322 | 0 | CXXGlobalInits.push_back(InitFunction); |
7323 | 0 | } |
7324 | 0 | } |
7325 | | |
7326 | | llvm::Metadata * |
7327 | | CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, |
7328 | 0 | StringRef Suffix) { |
7329 | 0 | if (auto *FnType = T->getAs<FunctionProtoType>()) |
7330 | 0 | T = getContext().getFunctionType( |
7331 | 0 | FnType->getReturnType(), FnType->getParamTypes(), |
7332 | 0 | FnType->getExtProtoInfo().withExceptionSpec(EST_None)); |
7333 | |
|
7334 | 0 | llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; |
7335 | 0 | if (InternalId) |
7336 | 0 | return InternalId; |
7337 | | |
7338 | 0 | if (isExternallyVisible(T->getLinkage())) { |
7339 | 0 | std::string OutName; |
7340 | 0 | llvm::raw_string_ostream Out(OutName); |
7341 | 0 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
7342 | 0 | T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); |
7343 | |
|
7344 | 0 | if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) |
7345 | 0 | Out << ".normalized"; |
7346 | |
|
7347 | 0 | Out << Suffix; |
7348 | |
|
7349 | 0 | InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); |
7350 | 0 | } else { |
7351 | 0 | InternalId = llvm::MDNode::getDistinct(getLLVMContext(), |
7352 | 0 | llvm::ArrayRef<llvm::Metadata *>()); |
7353 | 0 | } |
7354 | |
|
7355 | 0 | return InternalId; |
7356 | 0 | } |
7357 | | |
7358 | 0 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { |
7359 | 0 | return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); |
7360 | 0 | } |
7361 | | |
7362 | | llvm::Metadata * |
7363 | 0 | CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { |
7364 | 0 | return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); |
7365 | 0 | } |
7366 | | |
7367 | | // Generalize pointer types to a void pointer with the qualifiers of the |
7368 | | // originally pointed-to type, e.g. 'const char *' and 'char * const *' |
7369 | | // generalize to 'const void *' while 'char *' and 'const char **' generalize to |
7370 | | // 'void *'. |
7371 | 0 | static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { |
7372 | 0 | if (!Ty->isPointerType()) |
7373 | 0 | return Ty; |
7374 | | |
7375 | 0 | return Ctx.getPointerType( |
7376 | 0 | QualType(Ctx.VoidTy).withCVRQualifiers( |
7377 | 0 | Ty->getPointeeType().getCVRQualifiers())); |
7378 | 0 | } |
7379 | | |
7380 | | // Apply type generalization to a FunctionType's return and argument types |
7381 | 0 | static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { |
7382 | 0 | if (auto *FnType = Ty->getAs<FunctionProtoType>()) { |
7383 | 0 | SmallVector<QualType, 8> GeneralizedParams; |
7384 | 0 | for (auto &Param : FnType->param_types()) |
7385 | 0 | GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); |
7386 | |
|
7387 | 0 | return Ctx.getFunctionType( |
7388 | 0 | GeneralizeType(Ctx, FnType->getReturnType()), |
7389 | 0 | GeneralizedParams, FnType->getExtProtoInfo()); |
7390 | 0 | } |
7391 | | |
7392 | 0 | if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) |
7393 | 0 | return Ctx.getFunctionNoProtoType( |
7394 | 0 | GeneralizeType(Ctx, FnType->getReturnType())); |
7395 | | |
7396 | 0 | llvm_unreachable("Encountered unknown FunctionType"); |
7397 | 0 | } |
7398 | | |
7399 | 0 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { |
7400 | 0 | return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), |
7401 | 0 | GeneralizedMetadataIdMap, ".generalized"); |
7402 | 0 | } |
7403 | | |
7404 | | /// Returns whether this module needs the "all-vtables" type identifier. |
7405 | 0 | bool CodeGenModule::NeedAllVtablesTypeId() const { |
7406 | | // Returns true if at least one of vtable-based CFI checkers is enabled and |
7407 | | // is not in the trapping mode. |
7408 | 0 | return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && |
7409 | 0 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || |
7410 | 0 | (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && |
7411 | 0 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || |
7412 | 0 | (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && |
7413 | 0 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || |
7414 | 0 | (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && |
7415 | 0 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); |
7416 | 0 | } |
7417 | | |
7418 | | void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, |
7419 | | CharUnits Offset, |
7420 | 0 | const CXXRecordDecl *RD) { |
7421 | 0 | llvm::Metadata *MD = |
7422 | 0 | CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); |
7423 | 0 | VTable->addTypeMetadata(Offset.getQuantity(), MD); |
7424 | |
|
7425 | 0 | if (CodeGenOpts.SanitizeCfiCrossDso) |
7426 | 0 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) |
7427 | 0 | VTable->addTypeMetadata(Offset.getQuantity(), |
7428 | 0 | llvm::ConstantAsMetadata::get(CrossDsoTypeId)); |
7429 | |
|
7430 | 0 | if (NeedAllVtablesTypeId()) { |
7431 | 0 | llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); |
7432 | 0 | VTable->addTypeMetadata(Offset.getQuantity(), MD); |
7433 | 0 | } |
7434 | 0 | } |
7435 | | |
7436 | 0 | llvm::SanitizerStatReport &CodeGenModule::getSanStats() { |
7437 | 0 | if (!SanStats) |
7438 | 0 | SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); |
7439 | |
|
7440 | 0 | return *SanStats; |
7441 | 0 | } |
7442 | | |
7443 | | llvm::Value * |
7444 | | CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, |
7445 | 0 | CodeGenFunction &CGF) { |
7446 | 0 | llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); |
7447 | 0 | auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); |
7448 | 0 | auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); |
7449 | 0 | auto *Call = CGF.EmitRuntimeCall( |
7450 | 0 | CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); |
7451 | 0 | return Call; |
7452 | 0 | } |
7453 | | |
7454 | | CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( |
7455 | 0 | QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { |
7456 | 0 | return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, |
7457 | 0 | /* forPointeeType= */ true); |
7458 | 0 | } |
7459 | | |
7460 | | CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, |
7461 | | LValueBaseInfo *BaseInfo, |
7462 | | TBAAAccessInfo *TBAAInfo, |
7463 | 0 | bool forPointeeType) { |
7464 | 0 | if (TBAAInfo) |
7465 | 0 | *TBAAInfo = getTBAAAccessInfo(T); |
7466 | | |
7467 | | // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But |
7468 | | // that doesn't return the information we need to compute BaseInfo. |
7469 | | |
7470 | | // Honor alignment typedef attributes even on incomplete types. |
7471 | | // We also honor them straight for C++ class types, even as pointees; |
7472 | | // there's an expressivity gap here. |
7473 | 0 | if (auto TT = T->getAs<TypedefType>()) { |
7474 | 0 | if (auto Align = TT->getDecl()->getMaxAlignment()) { |
7475 | 0 | if (BaseInfo) |
7476 | 0 | *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); |
7477 | 0 | return getContext().toCharUnitsFromBits(Align); |
7478 | 0 | } |
7479 | 0 | } |
7480 | | |
7481 | 0 | bool AlignForArray = T->isArrayType(); |
7482 | | |
7483 | | // Analyze the base element type, so we don't get confused by incomplete |
7484 | | // array types. |
7485 | 0 | T = getContext().getBaseElementType(T); |
7486 | |
|
7487 | 0 | if (T->isIncompleteType()) { |
7488 | | // We could try to replicate the logic from |
7489 | | // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the |
7490 | | // type is incomplete, so it's impossible to test. We could try to reuse |
7491 | | // getTypeAlignIfKnown, but that doesn't return the information we need |
7492 | | // to set BaseInfo. So just ignore the possibility that the alignment is |
7493 | | // greater than one. |
7494 | 0 | if (BaseInfo) |
7495 | 0 | *BaseInfo = LValueBaseInfo(AlignmentSource::Type); |
7496 | 0 | return CharUnits::One(); |
7497 | 0 | } |
7498 | | |
7499 | 0 | if (BaseInfo) |
7500 | 0 | *BaseInfo = LValueBaseInfo(AlignmentSource::Type); |
7501 | |
|
7502 | 0 | CharUnits Alignment; |
7503 | 0 | const CXXRecordDecl *RD; |
7504 | 0 | if (T.getQualifiers().hasUnaligned()) { |
7505 | 0 | Alignment = CharUnits::One(); |
7506 | 0 | } else if (forPointeeType && !AlignForArray && |
7507 | 0 | (RD = T->getAsCXXRecordDecl())) { |
7508 | | // For C++ class pointees, we don't know whether we're pointing at a |
7509 | | // base or a complete object, so we generally need to use the |
7510 | | // non-virtual alignment. |
7511 | 0 | Alignment = getClassPointerAlignment(RD); |
7512 | 0 | } else { |
7513 | 0 | Alignment = getContext().getTypeAlignInChars(T); |
7514 | 0 | } |
7515 | | |
7516 | | // Cap to the global maximum type alignment unless the alignment |
7517 | | // was somehow explicit on the type. |
7518 | 0 | if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { |
7519 | 0 | if (Alignment.getQuantity() > MaxAlign && |
7520 | 0 | !getContext().isAlignmentRequired(T)) |
7521 | 0 | Alignment = CharUnits::fromQuantity(MaxAlign); |
7522 | 0 | } |
7523 | 0 | return Alignment; |
7524 | 0 | } |
7525 | | |
7526 | 0 | bool CodeGenModule::stopAutoInit() { |
7527 | 0 | unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; |
7528 | 0 | if (StopAfter) { |
7529 | | // This number is positive only when -ftrivial-auto-var-init-stop-after=* is |
7530 | | // used |
7531 | 0 | if (NumAutoVarInit >= StopAfter) { |
7532 | 0 | return true; |
7533 | 0 | } |
7534 | 0 | if (!NumAutoVarInit) { |
7535 | 0 | unsigned DiagID = getDiags().getCustomDiagID( |
7536 | 0 | DiagnosticsEngine::Warning, |
7537 | 0 | "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " |
7538 | 0 | "number of times ftrivial-auto-var-init=%1 gets applied."); |
7539 | 0 | getDiags().Report(DiagID) |
7540 | 0 | << StopAfter |
7541 | 0 | << (getContext().getLangOpts().getTrivialAutoVarInit() == |
7542 | 0 | LangOptions::TrivialAutoVarInitKind::Zero |
7543 | 0 | ? "zero" |
7544 | 0 | : "pattern"); |
7545 | 0 | } |
7546 | 0 | ++NumAutoVarInit; |
7547 | 0 | } |
7548 | 0 | return false; |
7549 | 0 | } |
7550 | | |
7551 | | void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, |
7552 | 0 | const Decl *D) const { |
7553 | | // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers |
7554 | | // postfix beginning with '.' since the symbol name can be demangled. |
7555 | 0 | if (LangOpts.HIP) |
7556 | 0 | OS << (isa<VarDecl>(D) ? ".static." : ".intern."); |
7557 | 0 | else |
7558 | 0 | OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); |
7559 | | |
7560 | | // If the CUID is not specified we try to generate a unique postfix. |
7561 | 0 | if (getLangOpts().CUID.empty()) { |
7562 | 0 | SourceManager &SM = getContext().getSourceManager(); |
7563 | 0 | PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); |
7564 | 0 | assert(PLoc.isValid() && "Source location is expected to be valid."); |
7565 | | |
7566 | | // Get the hash of the user defined macros. |
7567 | 0 | llvm::MD5 Hash; |
7568 | 0 | llvm::MD5::MD5Result Result; |
7569 | 0 | for (const auto &Arg : PreprocessorOpts.Macros) |
7570 | 0 | Hash.update(Arg.first); |
7571 | 0 | Hash.final(Result); |
7572 | | |
7573 | | // Get the UniqueID for the file containing the decl. |
7574 | 0 | llvm::sys::fs::UniqueID ID; |
7575 | 0 | if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { |
7576 | 0 | PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); |
7577 | 0 | assert(PLoc.isValid() && "Source location is expected to be valid."); |
7578 | 0 | if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) |
7579 | 0 | SM.getDiagnostics().Report(diag::err_cannot_open_file) |
7580 | 0 | << PLoc.getFilename() << EC.message(); |
7581 | 0 | } |
7582 | 0 | OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) |
7583 | 0 | << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); |
7584 | 0 | } else { |
7585 | 0 | OS << getContext().getCUIDHash(); |
7586 | 0 | } |
7587 | 0 | } |
7588 | | |
7589 | 0 | void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { |
7590 | 0 | assert(DeferredDeclsToEmit.empty() && |
7591 | 0 | "Should have emitted all decls deferred to emit."); |
7592 | 0 | assert(NewBuilder->DeferredDecls.empty() && |
7593 | 0 | "Newly created module should not have deferred decls"); |
7594 | 0 | NewBuilder->DeferredDecls = std::move(DeferredDecls); |
7595 | 0 | assert(EmittedDeferredDecls.empty() && |
7596 | 0 | "Still have (unmerged) EmittedDeferredDecls deferred decls"); |
7597 | | |
7598 | 0 | assert(NewBuilder->DeferredVTables.empty() && |
7599 | 0 | "Newly created module should not have deferred vtables"); |
7600 | 0 | NewBuilder->DeferredVTables = std::move(DeferredVTables); |
7601 | |
|
7602 | 0 | assert(NewBuilder->MangledDeclNames.empty() && |
7603 | 0 | "Newly created module should not have mangled decl names"); |
7604 | 0 | assert(NewBuilder->Manglings.empty() && |
7605 | 0 | "Newly created module should not have manglings"); |
7606 | 0 | NewBuilder->Manglings = std::move(Manglings); |
7607 | |
|
7608 | 0 | NewBuilder->WeakRefReferences = std::move(WeakRefReferences); |
7609 | |
|
7610 | 0 | NewBuilder->TBAA = std::move(TBAA); |
7611 | |
|
7612 | 0 | NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); |
7613 | 0 | } |