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