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