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