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