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