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