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