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