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