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