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