Bug Summary

File:clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 3552, column 27
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CodeGenModule.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/CodeGen -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp

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 "CGBlocks.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.h"
17#include "CGCall.h"
18#include "CGDebugInfo.h"
19#include "CGObjCRuntime.h"
20#include "CGOpenCLRuntime.h"
21#include "CGOpenMPRuntime.h"
22#include "CGOpenMPRuntimeAMDGCN.h"
23#include "CGOpenMPRuntimeNVPTX.h"
24#include "CodeGenFunction.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "CoverageMappingGen.h"
28#include "TargetInfo.h"
29#include "clang/AST/ASTContext.h"
30#include "clang/AST/CharUnits.h"
31#include "clang/AST/DeclCXX.h"
32#include "clang/AST/DeclObjC.h"
33#include "clang/AST/DeclTemplate.h"
34#include "clang/AST/Mangle.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/RecursiveASTVisitor.h"
37#include "clang/AST/StmtVisitor.h"
38#include "clang/Basic/Builtins.h"
39#include "clang/Basic/CharInfo.h"
40#include "clang/Basic/CodeGenOptions.h"
41#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/FileManager.h"
43#include "clang/Basic/Module.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/Version.h"
47#include "clang/CodeGen/ConstantInitBuilder.h"
48#include "clang/Frontend/FrontendDiagnostic.h"
49#include "llvm/ADT/StringSwitch.h"
50#include "llvm/ADT/Triple.h"
51#include "llvm/Analysis/TargetLibraryInfo.h"
52#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
53#include "llvm/IR/CallingConv.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/Intrinsics.h"
56#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/ProfileSummary.h"
59#include "llvm/ProfileData/InstrProfReader.h"
60#include "llvm/Support/CodeGen.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/ConvertUTF.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MD5.h"
65#include "llvm/Support/TimeProfiler.h"
66
67using namespace clang;
68using namespace CodeGen;
69
70static llvm::cl::opt<bool> LimitedCoverage(
71 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
72 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
73 llvm::cl::init(false));
74
75static const char AnnotationSection[] = "llvm.metadata";
76
77static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
78 switch (CGM.getContext().getCXXABIKind()) {
79 case TargetCXXABI::AppleARM64:
80 case TargetCXXABI::Fuchsia:
81 case TargetCXXABI::GenericAArch64:
82 case TargetCXXABI::GenericARM:
83 case TargetCXXABI::iOS:
84 case TargetCXXABI::WatchOS:
85 case TargetCXXABI::GenericMIPS:
86 case TargetCXXABI::GenericItanium:
87 case TargetCXXABI::WebAssembly:
88 case TargetCXXABI::XL:
89 return CreateItaniumCXXABI(CGM);
90 case TargetCXXABI::Microsoft:
91 return CreateMicrosoftCXXABI(CGM);
92 }
93
94 llvm_unreachable("invalid C++ ABI kind")::llvm::llvm_unreachable_internal("invalid C++ ABI kind", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 94)
;
95}
96
97CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
98 const PreprocessorOptions &PPO,
99 const CodeGenOptions &CGO, llvm::Module &M,
100 DiagnosticsEngine &diags,
101 CoverageSourceInfo *CoverageInfo)
102 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
103 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
104 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
105 VMContext(M.getContext()), Types(*this), VTables(*this),
106 SanitizerMD(new SanitizerMetadata(*this)) {
107
108 // Initialize the type cache.
109 llvm::LLVMContext &LLVMContext = M.getContext();
110 VoidTy = llvm::Type::getVoidTy(LLVMContext);
111 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
112 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
113 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
114 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
115 HalfTy = llvm::Type::getHalfTy(LLVMContext);
116 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
117 FloatTy = llvm::Type::getFloatTy(LLVMContext);
118 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
119 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
120 PointerAlignInBytes =
121 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
122 SizeSizeInBytes =
123 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
124 IntAlignInBytes =
125 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
126 CharTy =
127 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
128 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
129 IntPtrTy = llvm::IntegerType::get(LLVMContext,
130 C.getTargetInfo().getMaxPointerWidth());
131 Int8PtrTy = Int8Ty->getPointerTo(0);
132 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
133 AllocaInt8PtrTy = Int8Ty->getPointerTo(
134 M.getDataLayout().getAllocaAddrSpace());
135 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
136
137 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
138
139 if (LangOpts.ObjC)
140 createObjCRuntime();
141 if (LangOpts.OpenCL)
142 createOpenCLRuntime();
143 if (LangOpts.OpenMP)
144 createOpenMPRuntime();
145 if (LangOpts.CUDA)
146 createCUDARuntime();
147
148 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
149 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
150 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
151 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
152 getCXXABI().getMangleContext()));
153
154 // If debug info or coverage generation is enabled, create the CGDebugInfo
155 // object.
156 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
157 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
158 DebugInfo.reset(new CGDebugInfo(*this));
159
160 Block.GlobalUniqueCount = 0;
161
162 if (C.getLangOpts().ObjC)
163 ObjCData.reset(new ObjCEntrypoints());
164
165 if (CodeGenOpts.hasProfileClangUse()) {
166 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
167 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
168 if (auto E = ReaderOrErr.takeError()) {
169 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
170 "Could not read profile %0: %1");
171 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
172 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
173 << EI.message();
174 });
175 } else
176 PGOReader = std::move(ReaderOrErr.get());
177 }
178
179 // If coverage mapping generation is enabled, create the
180 // CoverageMappingModuleGen object.
181 if (CodeGenOpts.CoverageMapping)
182 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
183
184 // Generate the module name hash here if needed.
185 if (CodeGenOpts.UniqueInternalLinkageNames &&
186 !getModule().getSourceFileName().empty()) {
187 std::string Path = getModule().getSourceFileName();
188 // Check if a path substitution is needed from the MacroPrefixMap.
189 for (const auto &Entry : PPO.MacroPrefixMap)
190 if (Path.rfind(Entry.first, 0) != std::string::npos) {
191 Path = Entry.second + Path.substr(Entry.first.size());
192 break;
193 }
194 llvm::MD5 Md5;
195 Md5.update(Path);
196 llvm::MD5::MD5Result R;
197 Md5.final(R);
198 SmallString<32> Str;
199 llvm::MD5::stringifyResult(R, Str);
200 // Convert MD5hash to Decimal. Demangler suffixes can either contain
201 // numbers or characters but not both.
202 llvm::APInt IntHash(128, Str.str(), 16);
203 // Prepend "__uniq" before the hash for tools like profilers to understand
204 // that this symbol is of internal linkage type. The "__uniq" is the
205 // pre-determined prefix that is used to tell tools that this symbol was
206 // created with -funique-internal-linakge-symbols and the tools can strip or
207 // keep the prefix as needed.
208 ModuleNameHash = (Twine(".__uniq.") +
209 Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str();
210 }
211}
212
213CodeGenModule::~CodeGenModule() {}
214
215void CodeGenModule::createObjCRuntime() {
216 // This is just isGNUFamily(), but we want to force implementors of
217 // new ABIs to decide how best to do this.
218 switch (LangOpts.ObjCRuntime.getKind()) {
219 case ObjCRuntime::GNUstep:
220 case ObjCRuntime::GCC:
221 case ObjCRuntime::ObjFW:
222 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
223 return;
224
225 case ObjCRuntime::FragileMacOSX:
226 case ObjCRuntime::MacOSX:
227 case ObjCRuntime::iOS:
228 case ObjCRuntime::WatchOS:
229 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
230 return;
231 }
232 llvm_unreachable("bad runtime kind")::llvm::llvm_unreachable_internal("bad runtime kind", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 232)
;
233}
234
235void CodeGenModule::createOpenCLRuntime() {
236 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
237}
238
239void CodeGenModule::createOpenMPRuntime() {
240 // Select a specialized code generation class based on the target, if any.
241 // If it does not exist use the default implementation.
242 switch (getTriple().getArch()) {
243 case llvm::Triple::nvptx:
244 case llvm::Triple::nvptx64:
245 assert(getLangOpts().OpenMPIsDevice &&(static_cast <bool> (getLangOpts().OpenMPIsDevice &&
"OpenMP NVPTX is only prepared to deal with device code.") ?
void (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 246, __extension__ __PRETTY_FUNCTION__))
246 "OpenMP NVPTX is only prepared to deal with device code.")(static_cast <bool> (getLangOpts().OpenMPIsDevice &&
"OpenMP NVPTX is only prepared to deal with device code.") ?
void (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 246, __extension__ __PRETTY_FUNCTION__))
;
247 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
248 break;
249 case llvm::Triple::amdgcn:
250 assert(getLangOpts().OpenMPIsDevice &&(static_cast <bool> (getLangOpts().OpenMPIsDevice &&
"OpenMP AMDGCN is only prepared to deal with device code.") ?
void (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP AMDGCN is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 251, __extension__ __PRETTY_FUNCTION__))
251 "OpenMP AMDGCN is only prepared to deal with device code.")(static_cast <bool> (getLangOpts().OpenMPIsDevice &&
"OpenMP AMDGCN is only prepared to deal with device code.") ?
void (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP AMDGCN is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 251, __extension__ __PRETTY_FUNCTION__))
;
252 OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this));
253 break;
254 default:
255 if (LangOpts.OpenMPSimd)
256 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
257 else
258 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
259 break;
260 }
261}
262
263void CodeGenModule::createCUDARuntime() {
264 CUDARuntime.reset(CreateNVCUDARuntime(*this));
265}
266
267void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
268 Replacements[Name] = C;
269}
270
271void CodeGenModule::applyReplacements() {
272 for (auto &I : Replacements) {
273 StringRef MangledName = I.first();
274 llvm::Constant *Replacement = I.second;
275 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
276 if (!Entry)
277 continue;
278 auto *OldF = cast<llvm::Function>(Entry);
279 auto *NewF = dyn_cast<llvm::Function>(Replacement);
280 if (!NewF) {
281 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
282 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
283 } else {
284 auto *CE = cast<llvm::ConstantExpr>(Replacement);
285 assert(CE->getOpcode() == llvm::Instruction::BitCast ||(static_cast <bool> (CE->getOpcode() == llvm::Instruction
::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr
) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 286, __extension__ __PRETTY_FUNCTION__))
286 CE->getOpcode() == llvm::Instruction::GetElementPtr)(static_cast <bool> (CE->getOpcode() == llvm::Instruction
::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr
) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
288 }
289 }
290
291 // Replace old with new, but keep the old order.
292 OldF->replaceAllUsesWith(Replacement);
293 if (NewF) {
294 NewF->removeFromParent();
295 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
296 NewF);
297 }
298 OldF->eraseFromParent();
299 }
300}
301
302void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
303 GlobalValReplacements.push_back(std::make_pair(GV, C));
304}
305
306void CodeGenModule::applyGlobalValReplacements() {
307 for (auto &I : GlobalValReplacements) {
308 llvm::GlobalValue *GV = I.first;
309 llvm::Constant *C = I.second;
310
311 GV->replaceAllUsesWith(C);
312 GV->eraseFromParent();
313 }
314}
315
316// This is only used in aliases that we created and we know they have a
317// linear structure.
318static const llvm::GlobalObject *getAliasedGlobal(
319 const llvm::GlobalIndirectSymbol &GIS) {
320 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
321 const llvm::Constant *C = &GIS;
322 for (;;) {
323 C = C->stripPointerCasts();
324 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
325 return GO;
326 // stripPointerCasts will not walk over weak aliases.
327 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
328 if (!GIS2)
329 return nullptr;
330 if (!Visited.insert(GIS2).second)
331 return nullptr;
332 C = GIS2->getIndirectSymbol();
333 }
334}
335
336void CodeGenModule::checkAliases() {
337 // Check if the constructed aliases are well formed. It is really unfortunate
338 // that we have to do this in CodeGen, but we only construct mangled names
339 // and aliases during codegen.
340 bool Error = false;
341 DiagnosticsEngine &Diags = getDiags();
342 for (const GlobalDecl &GD : Aliases) {
343 const auto *D = cast<ValueDecl>(GD.getDecl());
344 SourceLocation Location;
345 bool IsIFunc = D->hasAttr<IFuncAttr>();
346 if (const Attr *A = D->getDefiningAttr())
347 Location = A->getLocation();
348 else
349 llvm_unreachable("Not an alias or ifunc?")::llvm::llvm_unreachable_internal("Not an alias or ifunc?", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 349)
;
350 StringRef MangledName = getMangledName(GD);
351 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
352 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
353 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
354 if (!GV) {
355 Error = true;
356 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
357 } else if (GV->isDeclaration()) {
358 Error = true;
359 Diags.Report(Location, diag::err_alias_to_undefined)
360 << IsIFunc << IsIFunc;
361 } else if (IsIFunc) {
362 // Check resolver function type.
363 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
364 GV->getType()->getPointerElementType());
365 assert(FTy)(static_cast <bool> (FTy) ? void (0) : __assert_fail ("FTy"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 365, __extension__ __PRETTY_FUNCTION__))
;
366 if (!FTy->getReturnType()->isPointerTy())
367 Diags.Report(Location, diag::err_ifunc_resolver_return);
368 }
369
370 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
371 llvm::GlobalValue *AliaseeGV;
372 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
373 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
374 else
375 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
376
377 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
378 StringRef AliasSection = SA->getName();
379 if (AliasSection != AliaseeGV->getSection())
380 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
381 << AliasSection << IsIFunc << IsIFunc;
382 }
383
384 // We have to handle alias to weak aliases in here. LLVM itself disallows
385 // this since the object semantics would not match the IL one. For
386 // compatibility with gcc we implement it by just pointing the alias
387 // to its aliasee's aliasee. We also warn, since the user is probably
388 // expecting the link to be weak.
389 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
390 if (GA->isInterposable()) {
391 Diags.Report(Location, diag::warn_alias_to_weak_alias)
392 << GV->getName() << GA->getName() << IsIFunc;
393 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
394 GA->getIndirectSymbol(), Alias->getType());
395 Alias->setIndirectSymbol(Aliasee);
396 }
397 }
398 }
399 if (!Error)
400 return;
401
402 for (const GlobalDecl &GD : Aliases) {
403 StringRef MangledName = getMangledName(GD);
404 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
405 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
406 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
407 Alias->eraseFromParent();
408 }
409}
410
411void CodeGenModule::clear() {
412 DeferredDeclsToEmit.clear();
413 if (OpenMPRuntime)
414 OpenMPRuntime->clear();
415}
416
417void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
418 StringRef MainFile) {
419 if (!hasDiagnostics())
420 return;
421 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
422 if (MainFile.empty())
423 MainFile = "<stdin>";
424 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
425 } else {
426 if (Mismatched > 0)
427 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
428
429 if (Missing > 0)
430 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
431 }
432}
433
434static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
435 llvm::Module &M) {
436 if (!LO.VisibilityFromDLLStorageClass)
437 return;
438
439 llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
440 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
441 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
442 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
443 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
444 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
445 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
446 CodeGenModule::GetLLVMVisibility(
447 LO.getExternDeclNoDLLStorageClassVisibility());
448
449 for (llvm::GlobalValue &GV : M.global_values()) {
450 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
451 continue;
452
453 // Reset DSO locality before setting the visibility. This removes
454 // any effects that visibility options and annotations may have
455 // had on the DSO locality. Setting the visibility will implicitly set
456 // appropriate globals to DSO Local; however, this will be pessimistic
457 // w.r.t. to the normal compiler IRGen.
458 GV.setDSOLocal(false);
459
460 if (GV.isDeclarationForLinker()) {
461 GV.setVisibility(GV.getDLLStorageClass() ==
462 llvm::GlobalValue::DLLImportStorageClass
463 ? ExternDeclDLLImportVisibility
464 : ExternDeclNoDLLStorageClassVisibility);
465 } else {
466 GV.setVisibility(GV.getDLLStorageClass() ==
467 llvm::GlobalValue::DLLExportStorageClass
468 ? DLLExportVisibility
469 : NoDLLStorageClassVisibility);
470 }
471
472 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
473 }
474}
475
476void CodeGenModule::Release() {
477 EmitDeferred();
478 EmitVTablesOpportunistically();
479 applyGlobalValReplacements();
480 applyReplacements();
481 checkAliases();
482 emitMultiVersionFunctions();
483 EmitCXXGlobalInitFunc();
484 EmitCXXGlobalCleanUpFunc();
485 registerGlobalDtorsWithAtExit();
486 EmitCXXThreadLocalInitFunc();
487 if (ObjCRuntime)
488 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
489 AddGlobalCtor(ObjCInitFunction);
490 if (Context.getLangOpts().CUDA && CUDARuntime) {
491 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
492 AddGlobalCtor(CudaCtorFunction);
493 }
494 if (OpenMPRuntime) {
495 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
496 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
497 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
498 }
499 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
500 OpenMPRuntime->clear();
501 }
502 if (PGOReader) {
503 getModule().setProfileSummary(
504 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
505 llvm::ProfileSummary::PSK_Instr);
506 if (PGOStats.hasDiagnostics())
507 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
508 }
509 EmitCtorList(GlobalCtors, "llvm.global_ctors");
510 EmitCtorList(GlobalDtors, "llvm.global_dtors");
511 EmitGlobalAnnotations();
512 EmitStaticExternCAliases();
513 EmitDeferredUnusedCoverageMappings();
514 CodeGenPGO(*this).setValueProfilingFlag(getModule());
515 if (CoverageMapping)
516 CoverageMapping->emit();
517 if (CodeGenOpts.SanitizeCfiCrossDso) {
518 CodeGenFunction(*this).EmitCfiCheckFail();
519 CodeGenFunction(*this).EmitCfiCheckStub();
520 }
521 emitAtAvailableLinkGuard();
522 if (Context.getTargetInfo().getTriple().isWasm() &&
523 !Context.getTargetInfo().getTriple().isOSEmscripten()) {
524 EmitMainVoidAlias();
525 }
526
527 // Emit reference of __amdgpu_device_library_preserve_asan_functions to
528 // preserve ASAN functions in bitcode libraries.
529 if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) {
530 auto *FT = llvm::FunctionType::get(VoidTy, {});
531 auto *F = llvm::Function::Create(
532 FT, llvm::GlobalValue::ExternalLinkage,
533 "__amdgpu_device_library_preserve_asan_functions", &getModule());
534 auto *Var = new llvm::GlobalVariable(
535 getModule(), FT->getPointerTo(),
536 /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
537 "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
538 llvm::GlobalVariable::NotThreadLocal);
539 addCompilerUsedGlobal(Var);
540 }
541
542 emitLLVMUsed();
543 if (SanStats)
544 SanStats->finish();
545
546 if (CodeGenOpts.Autolink &&
547 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
548 EmitModuleLinkOptions();
549 }
550
551 // On ELF we pass the dependent library specifiers directly to the linker
552 // without manipulating them. This is in contrast to other platforms where
553 // they are mapped to a specific linker option by the compiler. This
554 // difference is a result of the greater variety of ELF linkers and the fact
555 // that ELF linkers tend to handle libraries in a more complicated fashion
556 // than on other platforms. This forces us to defer handling the dependent
557 // libs to the linker.
558 //
559 // CUDA/HIP device and host libraries are different. Currently there is no
560 // way to differentiate dependent libraries for host or device. Existing
561 // usage of #pragma comment(lib, *) is intended for host libraries on
562 // Windows. Therefore emit llvm.dependent-libraries only for host.
563 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
564 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
565 for (auto *MD : ELFDependentLibraries)
566 NMD->addOperand(MD);
567 }
568
569 // Record mregparm value now so it is visible through rest of codegen.
570 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
571 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
572 CodeGenOpts.NumRegisterParameters);
573
574 if (CodeGenOpts.DwarfVersion) {
575 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
576 CodeGenOpts.DwarfVersion);
577 }
578
579 if (CodeGenOpts.Dwarf64)
580 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
581
582 if (Context.getLangOpts().SemanticInterposition)
583 // Require various optimization to respect semantic interposition.
584 getModule().setSemanticInterposition(1);
585
586 if (CodeGenOpts.EmitCodeView) {
587 // Indicate that we want CodeView in the metadata.
588 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
589 }
590 if (CodeGenOpts.CodeViewGHash) {
591 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
592 }
593 if (CodeGenOpts.ControlFlowGuard) {
594 // Function ID tables and checks for Control Flow Guard (cfguard=2).
595 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
596 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
597 // Function ID tables for Control Flow Guard (cfguard=1).
598 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
599 }
600 if (CodeGenOpts.EHContGuard) {
601 // Function ID tables for EH Continuation Guard.
602 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
603 }
604 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
605 // We don't support LTO with 2 with different StrictVTablePointers
606 // FIXME: we could support it by stripping all the information introduced
607 // by StrictVTablePointers.
608
609 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
610
611 llvm::Metadata *Ops[2] = {
612 llvm::MDString::get(VMContext, "StrictVTablePointers"),
613 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
614 llvm::Type::getInt32Ty(VMContext), 1))};
615
616 getModule().addModuleFlag(llvm::Module::Require,
617 "StrictVTablePointersRequirement",
618 llvm::MDNode::get(VMContext, Ops));
619 }
620 if (getModuleDebugInfo())
621 // We support a single version in the linked module. The LLVM
622 // parser will drop debug info with a different version number
623 // (and warn about it, too).
624 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
625 llvm::DEBUG_METADATA_VERSION);
626
627 // We need to record the widths of enums and wchar_t, so that we can generate
628 // the correct build attributes in the ARM backend. wchar_size is also used by
629 // TargetLibraryInfo.
630 uint64_t WCharWidth =
631 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
632 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
633
634 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
635 if ( Arch == llvm::Triple::arm
636 || Arch == llvm::Triple::armeb
637 || Arch == llvm::Triple::thumb
638 || Arch == llvm::Triple::thumbeb) {
639 // The minimum width of an enum in bytes
640 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
641 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
642 }
643
644 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
645 StringRef ABIStr = Target.getABI();
646 llvm::LLVMContext &Ctx = TheModule.getContext();
647 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
648 llvm::MDString::get(Ctx, ABIStr));
649 }
650
651 if (CodeGenOpts.SanitizeCfiCrossDso) {
652 // Indicate that we want cross-DSO control flow integrity checks.
653 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
654 }
655
656 if (CodeGenOpts.WholeProgramVTables) {
657 // Indicate whether VFE was enabled for this module, so that the
658 // vcall_visibility metadata added under whole program vtables is handled
659 // appropriately in the optimizer.
660 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
661 CodeGenOpts.VirtualFunctionElimination);
662 }
663
664 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
665 getModule().addModuleFlag(llvm::Module::Override,
666 "CFI Canonical Jump Tables",
667 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
668 }
669
670 if (CodeGenOpts.CFProtectionReturn &&
671 Target.checkCFProtectionReturnSupported(getDiags())) {
672 // Indicate that we want to instrument return control flow protection.
673 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
674 1);
675 }
676
677 if (CodeGenOpts.CFProtectionBranch &&
678 Target.checkCFProtectionBranchSupported(getDiags())) {
679 // Indicate that we want to instrument branch control flow protection.
680 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
681 1);
682 }
683
684 if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
685 Arch == llvm::Triple::aarch64_be) {
686 getModule().addModuleFlag(llvm::Module::Error,
687 "branch-target-enforcement",
688 LangOpts.BranchTargetEnforcement);
689
690 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
691 LangOpts.hasSignReturnAddress());
692
693 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
694 LangOpts.isSignReturnAddressScopeAll());
695
696 getModule().addModuleFlag(llvm::Module::Error,
697 "sign-return-address-with-bkey",
698 !LangOpts.isSignReturnAddressWithAKey());
699 }
700
701 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
702 llvm::LLVMContext &Ctx = TheModule.getContext();
703 getModule().addModuleFlag(
704 llvm::Module::Error, "MemProfProfileFilename",
705 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
706 }
707
708 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
709 // Indicate whether __nvvm_reflect should be configured to flush denormal
710 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
711 // property.)
712 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
713 CodeGenOpts.FP32DenormalMode.Output !=
714 llvm::DenormalMode::IEEE);
715 }
716
717 if (LangOpts.EHAsynch)
718 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
719
720 // Indicate whether this Module was compiled with -fopenmp
721 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
722 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
723 if (getLangOpts().OpenMPIsDevice)
724 getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
725 LangOpts.OpenMP);
726
727 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
728 if (LangOpts.OpenCL) {
729 EmitOpenCLMetadata();
730 // Emit SPIR version.
731 if (getTriple().isSPIR()) {
732 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
733 // opencl.spir.version named metadata.
734 // C++ is backwards compatible with OpenCL v2.0.
735 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
736 llvm::Metadata *SPIRVerElts[] = {
737 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
738 Int32Ty, Version / 100)),
739 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
740 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
741 llvm::NamedMDNode *SPIRVerMD =
742 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
743 llvm::LLVMContext &Ctx = TheModule.getContext();
744 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
745 }
746 }
747
748 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
749 assert(PLevel < 3 && "Invalid PIC Level")(static_cast <bool> (PLevel < 3 && "Invalid PIC Level"
) ? void (0) : __assert_fail ("PLevel < 3 && \"Invalid PIC Level\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 749, __extension__ __PRETTY_FUNCTION__))
;
750 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
751 if (Context.getLangOpts().PIE)
752 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
753 }
754
755 if (getCodeGenOpts().CodeModel.size() > 0) {
756 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
757 .Case("tiny", llvm::CodeModel::Tiny)
758 .Case("small", llvm::CodeModel::Small)
759 .Case("kernel", llvm::CodeModel::Kernel)
760 .Case("medium", llvm::CodeModel::Medium)
761 .Case("large", llvm::CodeModel::Large)
762 .Default(~0u);
763 if (CM != ~0u) {
764 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
765 getModule().setCodeModel(codeModel);
766 }
767 }
768
769 if (CodeGenOpts.NoPLT)
770 getModule().setRtLibUseGOT();
771 if (CodeGenOpts.UnwindTables)
772 getModule().setUwtable();
773
774 switch (CodeGenOpts.getFramePointer()) {
775 case CodeGenOptions::FramePointerKind::None:
776 // 0 ("none") is the default.
777 break;
778 case CodeGenOptions::FramePointerKind::NonLeaf:
779 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
780 break;
781 case CodeGenOptions::FramePointerKind::All:
782 getModule().setFramePointer(llvm::FramePointerKind::All);
783 break;
784 }
785
786 SimplifyPersonality();
787
788 if (getCodeGenOpts().EmitDeclMetadata)
789 EmitDeclMetadata();
790
791 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
792 EmitCoverageFile();
793
794 if (CGDebugInfo *DI = getModuleDebugInfo())
795 DI->finalize();
796
797 if (getCodeGenOpts().EmitVersionIdentMetadata)
798 EmitVersionIdentMetadata();
799
800 if (!getCodeGenOpts().RecordCommandLine.empty())
801 EmitCommandLineMetadata();
802
803 if (!getCodeGenOpts().StackProtectorGuard.empty())
804 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
805 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
806 getModule().setStackProtectorGuardReg(
807 getCodeGenOpts().StackProtectorGuardReg);
808 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX2147483647)
809 getModule().setStackProtectorGuardOffset(
810 getCodeGenOpts().StackProtectorGuardOffset);
811 if (getCodeGenOpts().StackAlignment)
812 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
813
814 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
815
816 EmitBackendOptionsMetadata(getCodeGenOpts());
817
818 // Set visibility from DLL storage class
819 // We do this at the end of LLVM IR generation; after any operation
820 // that might affect the DLL storage class or the visibility, and
821 // before anything that might act on these.
822 setVisibilityFromDLLStorageClass(LangOpts, getModule());
823}
824
825void CodeGenModule::EmitOpenCLMetadata() {
826 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
827 // opencl.ocl.version named metadata node.
828 // C++ is backwards compatible with OpenCL v2.0.
829 // FIXME: We might need to add CXX version at some point too?
830 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
831 llvm::Metadata *OCLVerElts[] = {
832 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
833 Int32Ty, Version / 100)),
834 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
835 Int32Ty, (Version % 100) / 10))};
836 llvm::NamedMDNode *OCLVerMD =
837 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
838 llvm::LLVMContext &Ctx = TheModule.getContext();
839 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
840}
841
842void CodeGenModule::EmitBackendOptionsMetadata(
843 const CodeGenOptions CodeGenOpts) {
844 switch (getTriple().getArch()) {
845 default:
846 break;
847 case llvm::Triple::riscv32:
848 case llvm::Triple::riscv64:
849 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
850 CodeGenOpts.SmallDataLimit);
851 break;
852 }
853}
854
855void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
856 // Make sure that this type is translated.
857 Types.UpdateCompletedType(TD);
858}
859
860void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
861 // Make sure that this type is translated.
862 Types.RefreshTypeCacheForClass(RD);
863}
864
865llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
866 if (!TBAA)
867 return nullptr;
868 return TBAA->getTypeInfo(QTy);
869}
870
871TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
872 if (!TBAA)
873 return TBAAAccessInfo();
874 if (getLangOpts().CUDAIsDevice) {
875 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
876 // access info.
877 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
878 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
879 nullptr)
880 return TBAAAccessInfo();
881 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
882 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
883 nullptr)
884 return TBAAAccessInfo();
885 }
886 }
887 return TBAA->getAccessInfo(AccessType);
888}
889
890TBAAAccessInfo
891CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
892 if (!TBAA)
893 return TBAAAccessInfo();
894 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
895}
896
897llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
898 if (!TBAA)
899 return nullptr;
900 return TBAA->getTBAAStructInfo(QTy);
901}
902
903llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
904 if (!TBAA)
905 return nullptr;
906 return TBAA->getBaseTypeInfo(QTy);
907}
908
909llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
910 if (!TBAA)
911 return nullptr;
912 return TBAA->getAccessTagInfo(Info);
913}
914
915TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
916 TBAAAccessInfo TargetInfo) {
917 if (!TBAA)
918 return TBAAAccessInfo();
919 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
920}
921
922TBAAAccessInfo
923CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
924 TBAAAccessInfo InfoB) {
925 if (!TBAA)
926 return TBAAAccessInfo();
927 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
928}
929
930TBAAAccessInfo
931CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
932 TBAAAccessInfo SrcInfo) {
933 if (!TBAA)
934 return TBAAAccessInfo();
935 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
936}
937
938void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
939 TBAAAccessInfo TBAAInfo) {
940 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
941 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
942}
943
944void CodeGenModule::DecorateInstructionWithInvariantGroup(
945 llvm::Instruction *I, const CXXRecordDecl *RD) {
946 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
947 llvm::MDNode::get(getLLVMContext(), {}));
948}
949
950void CodeGenModule::Error(SourceLocation loc, StringRef message) {
951 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
952 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
953}
954
955/// ErrorUnsupported - Print out an error that codegen doesn't support the
956/// specified stmt yet.
957void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
958 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
959 "cannot compile this %0 yet");
960 std::string Msg = Type;
961 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
962 << Msg << S->getSourceRange();
963}
964
965/// ErrorUnsupported - Print out an error that codegen doesn't support the
966/// specified decl yet.
967void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
968 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
969 "cannot compile this %0 yet");
970 std::string Msg = Type;
971 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
972}
973
974llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
975 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
976}
977
978void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
979 const NamedDecl *D) const {
980 if (GV->hasDLLImportStorageClass())
981 return;
982 // Internal definitions always have default visibility.
983 if (GV->hasLocalLinkage()) {
984 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
985 return;
986 }
987 if (!D)
988 return;
989 // Set visibility for definitions, and for declarations if requested globally
990 // or set explicitly.
991 LinkageInfo LV = D->getLinkageAndVisibility();
992 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
993 !GV->isDeclarationForLinker())
994 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
995}
996
997static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
998 llvm::GlobalValue *GV) {
999 if (GV->hasLocalLinkage())
1000 return true;
1001
1002 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1003 return true;
1004
1005 // DLLImport explicitly marks the GV as external.
1006 if (GV->hasDLLImportStorageClass())
1007 return false;
1008
1009 const llvm::Triple &TT = CGM.getTriple();
1010 if (TT.isWindowsGNUEnvironment()) {
1011 // In MinGW, variables without DLLImport can still be automatically
1012 // imported from a DLL by the linker; don't mark variables that
1013 // potentially could come from another DLL as DSO local.
1014
1015 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1016 // (and this actually happens in the public interface of libstdc++), so
1017 // such variables can't be marked as DSO local. (Native TLS variables
1018 // can't be dllimported at all, though.)
1019 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1020 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
1021 return false;
1022 }
1023
1024 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1025 // remain unresolved in the link, they can be resolved to zero, which is
1026 // outside the current DSO.
1027 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1028 return false;
1029
1030 // Every other GV is local on COFF.
1031 // Make an exception for windows OS in the triple: Some firmware builds use
1032 // *-win32-macho triples. This (accidentally?) produced windows relocations
1033 // without GOT tables in older clang versions; Keep this behaviour.
1034 // FIXME: even thread local variables?
1035 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1036 return true;
1037
1038 // Only handle COFF and ELF for now.
1039 if (!TT.isOSBinFormatELF())
1040 return false;
1041
1042 // If this is not an executable, don't assume anything is local.
1043 const auto &CGOpts = CGM.getCodeGenOpts();
1044 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1045 const auto &LOpts = CGM.getLangOpts();
1046 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1047 // On ELF, if -fno-semantic-interposition is specified and the target
1048 // supports local aliases, there will be neither CC1
1049 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1050 // dso_local on the function if using a local alias is preferable (can avoid
1051 // PLT indirection).
1052 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1053 return false;
1054 return !(CGM.getLangOpts().SemanticInterposition ||
1055 CGM.getLangOpts().HalfNoSemanticInterposition);
1056 }
1057
1058 // A definition cannot be preempted from an executable.
1059 if (!GV->isDeclarationForLinker())
1060 return true;
1061
1062 // Most PIC code sequences that assume that a symbol is local cannot produce a
1063 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1064 // depended, it seems worth it to handle it here.
1065 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1066 return false;
1067
1068 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1069 if (TT.isPPC64())
1070 return false;
1071
1072 if (CGOpts.DirectAccessExternalData) {
1073 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1074 // for non-thread-local variables. If the symbol is not defined in the
1075 // executable, a copy relocation will be needed at link time. dso_local is
1076 // excluded for thread-local variables because they generally don't support
1077 // copy relocations.
1078 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1079 if (!Var->isThreadLocal())
1080 return true;
1081
1082 // -fno-pic sets dso_local on a function declaration to allow direct
1083 // accesses when taking its address (similar to a data symbol). If the
1084 // function is not defined in the executable, a canonical PLT entry will be
1085 // needed at link time. -fno-direct-access-external-data can avoid the
1086 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1087 // it could just cause trouble without providing perceptible benefits.
1088 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1089 return true;
1090 }
1091
1092 // If we can use copy relocations we can assume it is local.
1093
1094 // Otherwise don't assume it is local.
1095 return false;
1096}
1097
1098void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1099 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1100}
1101
1102void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1103 GlobalDecl GD) const {
1104 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1105 // C++ destructors have a few C++ ABI specific special cases.
1106 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1107 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1108 return;
1109 }
1110 setDLLImportDLLExport(GV, D);
1111}
1112
1113void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1114 const NamedDecl *D) const {
1115 if (D && D->isExternallyVisible()) {
1116 if (D->hasAttr<DLLImportAttr>())
1117 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1118 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
1119 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1120 }
1121}
1122
1123void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1124 GlobalDecl GD) const {
1125 setDLLImportDLLExport(GV, GD);
1126 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1127}
1128
1129void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1130 const NamedDecl *D) const {
1131 setDLLImportDLLExport(GV, D);
1132 setGVPropertiesAux(GV, D);
1133}
1134
1135void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1136 const NamedDecl *D) const {
1137 setGlobalVisibility(GV, D);
1138 setDSOLocal(GV);
1139 GV->setPartition(CodeGenOpts.SymbolPartition);
1140}
1141
1142static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1143 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1144 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1145 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1146 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1147 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1148}
1149
1150llvm::GlobalVariable::ThreadLocalMode
1151CodeGenModule::GetDefaultLLVMTLSModel() const {
1152 switch (CodeGenOpts.getDefaultTLSModel()) {
1153 case CodeGenOptions::GeneralDynamicTLSModel:
1154 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1155 case CodeGenOptions::LocalDynamicTLSModel:
1156 return llvm::GlobalVariable::LocalDynamicTLSModel;
1157 case CodeGenOptions::InitialExecTLSModel:
1158 return llvm::GlobalVariable::InitialExecTLSModel;
1159 case CodeGenOptions::LocalExecTLSModel:
1160 return llvm::GlobalVariable::LocalExecTLSModel;
1161 }
1162 llvm_unreachable("Invalid TLS model!")::llvm::llvm_unreachable_internal("Invalid TLS model!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1162)
;
1163}
1164
1165void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1166 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!")(static_cast <bool> (D.getTLSKind() && "setting TLS mode on non-TLS var!"
) ? void (0) : __assert_fail ("D.getTLSKind() && \"setting TLS mode on non-TLS var!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1166, __extension__ __PRETTY_FUNCTION__))
;
1167
1168 llvm::GlobalValue::ThreadLocalMode TLM;
1169 TLM = GetDefaultLLVMTLSModel();
1170
1171 // Override the TLS model if it is explicitly specified.
1172 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1173 TLM = GetLLVMTLSModel(Attr->getModel());
1174 }
1175
1176 GV->setThreadLocalMode(TLM);
1177}
1178
1179static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1180 StringRef Name) {
1181 const TargetInfo &Target = CGM.getTarget();
1182 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1183}
1184
1185static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1186 const CPUSpecificAttr *Attr,
1187 unsigned CPUIndex,
1188 raw_ostream &Out) {
1189 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1190 // supported.
1191 if (Attr)
1192 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1193 else if (CGM.getTarget().supportsIFunc())
1194 Out << ".resolver";
1195}
1196
1197static void AppendTargetMangling(const CodeGenModule &CGM,
1198 const TargetAttr *Attr, raw_ostream &Out) {
1199 if (Attr->isDefaultVersion())
1200 return;
1201
1202 Out << '.';
1203 const TargetInfo &Target = CGM.getTarget();
1204 ParsedTargetAttr Info =
1205 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
1206 // Multiversioning doesn't allow "no-${feature}", so we can
1207 // only have "+" prefixes here.
1208 assert(LHS.startswith("+") && RHS.startswith("+") &&(static_cast <bool> (LHS.startswith("+") && RHS
.startswith("+") && "Features should always have a prefix."
) ? void (0) : __assert_fail ("LHS.startswith(\"+\") && RHS.startswith(\"+\") && \"Features should always have a prefix.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1209, __extension__ __PRETTY_FUNCTION__))
1209 "Features should always have a prefix.")(static_cast <bool> (LHS.startswith("+") && RHS
.startswith("+") && "Features should always have a prefix."
) ? void (0) : __assert_fail ("LHS.startswith(\"+\") && RHS.startswith(\"+\") && \"Features should always have a prefix.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1209, __extension__ __PRETTY_FUNCTION__))
;
1210 return Target.multiVersionSortPriority(LHS.substr(1)) >
1211 Target.multiVersionSortPriority(RHS.substr(1));
1212 });
1213
1214 bool IsFirst = true;
1215
1216 if (!Info.Architecture.empty()) {
1217 IsFirst = false;
1218 Out << "arch_" << Info.Architecture;
1219 }
1220
1221 for (StringRef Feat : Info.Features) {
1222 if (!IsFirst)
1223 Out << '_';
1224 IsFirst = false;
1225 Out << Feat.substr(1);
1226 }
1227}
1228
1229// Returns true if GD is a function decl with internal linkage and
1230// needs a unique suffix after the mangled name.
1231static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1232 CodeGenModule &CGM) {
1233 const Decl *D = GD.getDecl();
1234 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1235 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1236}
1237
1238static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1239 const NamedDecl *ND,
1240 bool OmitMultiVersionMangling = false) {
1241 SmallString<256> Buffer;
1242 llvm::raw_svector_ostream Out(Buffer);
1243 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1244 if (!CGM.getModuleNameHash().empty())
1245 MC.needsUniqueInternalLinkageNames();
1246 bool ShouldMangle = MC.shouldMangleDeclName(ND);
1247 if (ShouldMangle)
1248 MC.mangleName(GD.getWithDecl(ND), Out);
1249 else {
1250 IdentifierInfo *II = ND->getIdentifier();
1251 assert(II && "Attempt to mangle unnamed decl.")(static_cast <bool> (II && "Attempt to mangle unnamed decl."
) ? void (0) : __assert_fail ("II && \"Attempt to mangle unnamed decl.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1251, __extension__ __PRETTY_FUNCTION__))
;
1252 const auto *FD = dyn_cast<FunctionDecl>(ND);
1253
1254 if (FD &&
1255 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1256 Out << "__regcall3__" << II->getName();
1257 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1258 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1259 Out << "__device_stub__" << II->getName();
1260 } else {
1261 Out << II->getName();
1262 }
1263 }
1264
1265 // Check if the module name hash should be appended for internal linkage
1266 // symbols. This should come before multi-version target suffixes are
1267 // appended. This is to keep the name and module hash suffix of the
1268 // internal linkage function together. The unique suffix should only be
1269 // added when name mangling is done to make sure that the final name can
1270 // be properly demangled. For example, for C functions without prototypes,
1271 // name mangling is not done and the unique suffix should not be appeneded
1272 // then.
1273 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1274 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&(static_cast <bool> (CGM.getCodeGenOpts().UniqueInternalLinkageNames
&& "Hash computed when not explicitly requested") ? void
(0) : __assert_fail ("CGM.getCodeGenOpts().UniqueInternalLinkageNames && \"Hash computed when not explicitly requested\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1275, __extension__ __PRETTY_FUNCTION__))
1275 "Hash computed when not explicitly requested")(static_cast <bool> (CGM.getCodeGenOpts().UniqueInternalLinkageNames
&& "Hash computed when not explicitly requested") ? void
(0) : __assert_fail ("CGM.getCodeGenOpts().UniqueInternalLinkageNames && \"Hash computed when not explicitly requested\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1275, __extension__ __PRETTY_FUNCTION__))
;
1276 Out << CGM.getModuleNameHash();
1277 }
1278
1279 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1280 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1281 switch (FD->getMultiVersionKind()) {
1282 case MultiVersionKind::CPUDispatch:
1283 case MultiVersionKind::CPUSpecific:
1284 AppendCPUSpecificCPUDispatchMangling(CGM,
1285 FD->getAttr<CPUSpecificAttr>(),
1286 GD.getMultiVersionIndex(), Out);
1287 break;
1288 case MultiVersionKind::Target:
1289 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1290 break;
1291 case MultiVersionKind::None:
1292 llvm_unreachable("None multiversion type isn't valid here")::llvm::llvm_unreachable_internal("None multiversion type isn't valid here"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1292)
;
1293 }
1294 }
1295
1296 // Make unique name for device side static file-scope variable for HIP.
1297 if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
1298 CGM.getLangOpts().GPURelocatableDeviceCode &&
1299 CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
1300 CGM.printPostfixForExternalizedStaticVar(Out);
1301 return std::string(Out.str());
1302}
1303
1304void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1305 const FunctionDecl *FD) {
1306 if (!FD->isMultiVersion())
1307 return;
1308
1309 // Get the name of what this would be without the 'target' attribute. This
1310 // allows us to lookup the version that was emitted when this wasn't a
1311 // multiversion function.
1312 std::string NonTargetName =
1313 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1314 GlobalDecl OtherGD;
1315 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1316 assert(OtherGD.getCanonicalDecl()(static_cast <bool> (OtherGD.getCanonicalDecl() .getDecl
() ->getAsFunction() ->isMultiVersion() && "Other GD should now be a multiversioned function"
) ? void (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1320, __extension__ __PRETTY_FUNCTION__))
1317 .getDecl()(static_cast <bool> (OtherGD.getCanonicalDecl() .getDecl
() ->getAsFunction() ->isMultiVersion() && "Other GD should now be a multiversioned function"
) ? void (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1320, __extension__ __PRETTY_FUNCTION__))
1318 ->getAsFunction()(static_cast <bool> (OtherGD.getCanonicalDecl() .getDecl
() ->getAsFunction() ->isMultiVersion() && "Other GD should now be a multiversioned function"
) ? void (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1320, __extension__ __PRETTY_FUNCTION__))
1319 ->isMultiVersion() &&(static_cast <bool> (OtherGD.getCanonicalDecl() .getDecl
() ->getAsFunction() ->isMultiVersion() && "Other GD should now be a multiversioned function"
) ? void (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1320, __extension__ __PRETTY_FUNCTION__))
1320 "Other GD should now be a multiversioned function")(static_cast <bool> (OtherGD.getCanonicalDecl() .getDecl
() ->getAsFunction() ->isMultiVersion() && "Other GD should now be a multiversioned function"
) ? void (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1320, __extension__ __PRETTY_FUNCTION__))
;
1321 // OtherFD is the version of this function that was mangled BEFORE
1322 // becoming a MultiVersion function. It potentially needs to be updated.
1323 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1324 .getDecl()
1325 ->getAsFunction()
1326 ->getMostRecentDecl();
1327 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1328 // This is so that if the initial version was already the 'default'
1329 // version, we don't try to update it.
1330 if (OtherName != NonTargetName) {
1331 // Remove instead of erase, since others may have stored the StringRef
1332 // to this.
1333 const auto ExistingRecord = Manglings.find(NonTargetName);
1334 if (ExistingRecord != std::end(Manglings))
1335 Manglings.remove(&(*ExistingRecord));
1336 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1337 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1338 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1339 Entry->setName(OtherName);
1340 }
1341 }
1342}
1343
1344StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1345 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1346
1347 // Some ABIs don't have constructor variants. Make sure that base and
1348 // complete constructors get mangled the same.
1349 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1350 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1351 CXXCtorType OrigCtorType = GD.getCtorType();
1352 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete)(static_cast <bool> (OrigCtorType == Ctor_Base || OrigCtorType
== Ctor_Complete) ? void (0) : __assert_fail ("OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1352, __extension__ __PRETTY_FUNCTION__))
;
1353 if (OrigCtorType == Ctor_Base)
1354 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1355 }
1356 }
1357
1358 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1359 // static device variable depends on whether the variable is referenced by
1360 // a host or device host function. Therefore the mangled name cannot be
1361 // cached.
1362 if (!LangOpts.CUDAIsDevice ||
1363 !getContext().mayExternalizeStaticVar(GD.getDecl())) {
1364 auto FoundName = MangledDeclNames.find(CanonicalGD);
1365 if (FoundName != MangledDeclNames.end())
1366 return FoundName->second;
1367 }
1368
1369 // Keep the first result in the case of a mangling collision.
1370 const auto *ND = cast<NamedDecl>(GD.getDecl());
1371 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1372
1373 // Ensure either we have different ABIs between host and device compilations,
1374 // says host compilation following MSVC ABI but device compilation follows
1375 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1376 // mangling should be the same after name stubbing. The later checking is
1377 // very important as the device kernel name being mangled in host-compilation
1378 // is used to resolve the device binaries to be executed. Inconsistent naming
1379 // result in undefined behavior. Even though we cannot check that naming
1380 // directly between host- and device-compilations, the host- and
1381 // device-mangling in host compilation could help catching certain ones.
1382 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1383 getLangOpts().CUDAIsDevice ||(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1384 (getContext().getAuxTargetInfo() &&(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1385 (getContext().getAuxTargetInfo()->getCXXABI() !=(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1386 getContext().getTargetInfo().getCXXABI())) ||(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1387 getCUDARuntime().getDeviceSideName(ND) ==(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1388 getMangledNameImpl((static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1389 *this,(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1390 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
1391 ND))(static_cast <bool> (!isa<FunctionDecl>(ND) || !ND
->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice
|| (getContext().getAuxTargetInfo() && (getContext()
.getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo
().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind
::Kernel), ND)) ? void (0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1391, __extension__ __PRETTY_FUNCTION__))
;
1392
1393 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1394 return MangledDeclNames[CanonicalGD] = Result.first->first();
1395}
1396
1397StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1398 const BlockDecl *BD) {
1399 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1400 const Decl *D = GD.getDecl();
1401
1402 SmallString<256> Buffer;
1403 llvm::raw_svector_ostream Out(Buffer);
1404 if (!D)
1405 MangleCtx.mangleGlobalBlock(BD,
1406 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1407 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1408 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1409 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1410 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1411 else
1412 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1413
1414 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1415 return Result.first->first();
1416}
1417
1418llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1419 return getModule().getNamedValue(Name);
1420}
1421
1422/// AddGlobalCtor - Add a function to the list that will be called before
1423/// main() runs.
1424void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1425 llvm::Constant *AssociatedData) {
1426 // FIXME: Type coercion of void()* types.
1427 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1428}
1429
1430/// AddGlobalDtor - Add a function to the list that will be called
1431/// when the module is unloaded.
1432void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1433 bool IsDtorAttrFunc) {
1434 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1435 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
1436 DtorsUsingAtExit[Priority].push_back(Dtor);
1437 return;
1438 }
1439
1440 // FIXME: Type coercion of void()* types.
1441 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1442}
1443
1444void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1445 if (Fns.empty()) return;
1446
1447 // Ctor function type is void()*.
1448 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1449 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1450 TheModule.getDataLayout().getProgramAddressSpace());
1451
1452 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1453 llvm::StructType *CtorStructTy = llvm::StructType::get(
1454 Int32Ty, CtorPFTy, VoidPtrTy);
1455
1456 // Construct the constructor and destructor arrays.
1457 ConstantInitBuilder builder(*this);
1458 auto ctors = builder.beginArray(CtorStructTy);
1459 for (const auto &I : Fns) {
1460 auto ctor = ctors.beginStruct(CtorStructTy);
1461 ctor.addInt(Int32Ty, I.Priority);
1462 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1463 if (I.AssociatedData)
1464 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1465 else
1466 ctor.addNullPointer(VoidPtrTy);
1467 ctor.finishAndAddTo(ctors);
1468 }
1469
1470 auto list =
1471 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1472 /*constant*/ false,
1473 llvm::GlobalValue::AppendingLinkage);
1474
1475 // The LTO linker doesn't seem to like it when we set an alignment
1476 // on appending variables. Take it off as a workaround.
1477 list->setAlignment(llvm::None);
1478
1479 Fns.clear();
1480}
1481
1482llvm::GlobalValue::LinkageTypes
1483CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1484 const auto *D = cast<FunctionDecl>(GD.getDecl());
1485
1486 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1487
1488 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1489 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1490
1491 if (isa<CXXConstructorDecl>(D) &&
1492 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1493 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1494 // Our approach to inheriting constructors is fundamentally different from
1495 // that used by the MS ABI, so keep our inheriting constructor thunks
1496 // internal rather than trying to pick an unambiguous mangling for them.
1497 return llvm::GlobalValue::InternalLinkage;
1498 }
1499
1500 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1501}
1502
1503llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1504 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1505 if (!MDS) return nullptr;
1506
1507 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1508}
1509
1510void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1511 const CGFunctionInfo &Info,
1512 llvm::Function *F, bool IsThunk) {
1513 unsigned CallingConv;
1514 llvm::AttributeList PAL;
1515 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
1516 /*AttrOnCallSite=*/false, IsThunk);
1517 F->setAttributes(PAL);
1518 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1519}
1520
1521static void removeImageAccessQualifier(std::string& TyName) {
1522 std::string ReadOnlyQual("__read_only");
1523 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1524 if (ReadOnlyPos != std::string::npos)
1525 // "+ 1" for the space after access qualifier.
1526 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1527 else {
1528 std::string WriteOnlyQual("__write_only");
1529 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1530 if (WriteOnlyPos != std::string::npos)
1531 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1532 else {
1533 std::string ReadWriteQual("__read_write");
1534 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1535 if (ReadWritePos != std::string::npos)
1536 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1537 }
1538 }
1539}
1540
1541// Returns the address space id that should be produced to the
1542// kernel_arg_addr_space metadata. This is always fixed to the ids
1543// as specified in the SPIR 2.0 specification in order to differentiate
1544// for example in clGetKernelArgInfo() implementation between the address
1545// spaces with targets without unique mapping to the OpenCL address spaces
1546// (basically all single AS CPUs).
1547static unsigned ArgInfoAddressSpace(LangAS AS) {
1548 switch (AS) {
1549 case LangAS::opencl_global:
1550 return 1;
1551 case LangAS::opencl_constant:
1552 return 2;
1553 case LangAS::opencl_local:
1554 return 3;
1555 case LangAS::opencl_generic:
1556 return 4; // Not in SPIR 2.0 specs.
1557 case LangAS::opencl_global_device:
1558 return 5;
1559 case LangAS::opencl_global_host:
1560 return 6;
1561 default:
1562 return 0; // Assume private.
1563 }
1564}
1565
1566void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1567 const FunctionDecl *FD,
1568 CodeGenFunction *CGF) {
1569 assert(((FD && CGF) || (!FD && !CGF)) &&(static_cast <bool> (((FD && CGF) || (!FD &&
!CGF)) && "Incorrect use - FD and CGF should either be both null or not!"
) ? void (0) : __assert_fail ("((FD && CGF) || (!FD && !CGF)) && \"Incorrect use - FD and CGF should either be both null or not!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1570, __extension__ __PRETTY_FUNCTION__))
1570 "Incorrect use - FD and CGF should either be both null or not!")(static_cast <bool> (((FD && CGF) || (!FD &&
!CGF)) && "Incorrect use - FD and CGF should either be both null or not!"
) ? void (0) : __assert_fail ("((FD && CGF) || (!FD && !CGF)) && \"Incorrect use - FD and CGF should either be both null or not!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 1570, __extension__ __PRETTY_FUNCTION__))
;
1571 // Create MDNodes that represent the kernel arg metadata.
1572 // Each MDNode is a list in the form of "key", N number of values which is
1573 // the same number of values as their are kernel arguments.
1574
1575 const PrintingPolicy &Policy = Context.getPrintingPolicy();
1576
1577 // MDNode for the kernel argument address space qualifiers.
1578 SmallVector<llvm::Metadata *, 8> addressQuals;
1579
1580 // MDNode for the kernel argument access qualifiers (images only).
1581 SmallVector<llvm::Metadata *, 8> accessQuals;
1582
1583 // MDNode for the kernel argument type names.
1584 SmallVector<llvm::Metadata *, 8> argTypeNames;
1585
1586 // MDNode for the kernel argument base type names.
1587 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1588
1589 // MDNode for the kernel argument type qualifiers.
1590 SmallVector<llvm::Metadata *, 8> argTypeQuals;
1591
1592 // MDNode for the kernel argument names.
1593 SmallVector<llvm::Metadata *, 8> argNames;
1594
1595 if (FD && CGF)
1596 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1597 const ParmVarDecl *parm = FD->getParamDecl(i);
1598 QualType ty = parm->getType();
1599 std::string typeQuals;
1600
1601 // Get image and pipe access qualifier:
1602 if (ty->isImageType() || ty->isPipeType()) {
1603 const Decl *PDecl = parm;
1604 if (auto *TD = dyn_cast<TypedefType>(ty))
1605 PDecl = TD->getDecl();
1606 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1607 if (A && A->isWriteOnly())
1608 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1609 else if (A && A->isReadWrite())
1610 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1611 else
1612 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1613 } else
1614 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1615
1616 // Get argument name.
1617 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1618
1619 auto getTypeSpelling = [&](QualType Ty) {
1620 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
1621
1622 if (Ty.isCanonical()) {
1623 StringRef typeNameRef = typeName;
1624 // Turn "unsigned type" to "utype"
1625 if (typeNameRef.consume_front("unsigned "))
1626 return std::string("u") + typeNameRef.str();
1627 if (typeNameRef.consume_front("signed "))
1628 return typeNameRef.str();
1629 }
1630
1631 return typeName;
1632 };
1633
1634 if (ty->isPointerType()) {
1635 QualType pointeeTy = ty->getPointeeType();
1636
1637 // Get address qualifier.
1638 addressQuals.push_back(
1639 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1640 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1641
1642 // Get argument type name.
1643 std::string typeName = getTypeSpelling(pointeeTy) + "*";
1644 std::string baseTypeName =
1645 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
1646 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1647 argBaseTypeNames.push_back(
1648 llvm::MDString::get(VMContext, baseTypeName));
1649
1650 // Get argument type qualifiers:
1651 if (ty.isRestrictQualified())
1652 typeQuals = "restrict";
1653 if (pointeeTy.isConstQualified() ||
1654 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1655 typeQuals += typeQuals.empty() ? "const" : " const";
1656 if (pointeeTy.isVolatileQualified())
1657 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1658 } else {
1659 uint32_t AddrSpc = 0;
1660 bool isPipe = ty->isPipeType();
1661 if (ty->isImageType() || isPipe)
1662 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1663
1664 addressQuals.push_back(
1665 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1666
1667 // Get argument type name.
1668 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
1669 std::string typeName = getTypeSpelling(ty);
1670 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
1671
1672 // Remove access qualifiers on images
1673 // (as they are inseparable from type in clang implementation,
1674 // but OpenCL spec provides a special query to get access qualifier
1675 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1676 if (ty->isImageType()) {
1677 removeImageAccessQualifier(typeName);
1678 removeImageAccessQualifier(baseTypeName);
1679 }
1680
1681 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1682 argBaseTypeNames.push_back(
1683 llvm::MDString::get(VMContext, baseTypeName));
1684
1685 if (isPipe)
1686 typeQuals = "pipe";
1687 }
1688 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1689 }
1690
1691 Fn->setMetadata("kernel_arg_addr_space",
1692 llvm::MDNode::get(VMContext, addressQuals));
1693 Fn->setMetadata("kernel_arg_access_qual",
1694 llvm::MDNode::get(VMContext, accessQuals));
1695 Fn->setMetadata("kernel_arg_type",
1696 llvm::MDNode::get(VMContext, argTypeNames));
1697 Fn->setMetadata("kernel_arg_base_type",
1698 llvm::MDNode::get(VMContext, argBaseTypeNames));
1699 Fn->setMetadata("kernel_arg_type_qual",
1700 llvm::MDNode::get(VMContext, argTypeQuals));
1701 if (getCodeGenOpts().EmitOpenCLArgMetadata)
1702 Fn->setMetadata("kernel_arg_name",
1703 llvm::MDNode::get(VMContext, argNames));
1704}
1705
1706/// Determines whether the language options require us to model
1707/// unwind exceptions. We treat -fexceptions as mandating this
1708/// except under the fragile ObjC ABI with only ObjC exceptions
1709/// enabled. This means, for example, that C with -fexceptions
1710/// enables this.
1711static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1712 // If exceptions are completely disabled, obviously this is false.
1713 if (!LangOpts.Exceptions) return false;
1714
1715 // If C++ exceptions are enabled, this is true.
1716 if (LangOpts.CXXExceptions) return true;
1717
1718 // If ObjC exceptions are enabled, this depends on the ABI.
1719 if (LangOpts.ObjCExceptions) {
1720 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1721 }
1722
1723 return true;
1724}
1725
1726static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1727 const CXXMethodDecl *MD) {
1728 // Check that the type metadata can ever actually be used by a call.
1729 if (!CGM.getCodeGenOpts().LTOUnit ||
1730 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1731 return false;
1732
1733 // Only functions whose address can be taken with a member function pointer
1734 // need this sort of type metadata.
1735 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1736 !isa<CXXDestructorDecl>(MD);
1737}
1738
1739std::vector<const CXXRecordDecl *>
1740CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1741 llvm::SetVector<const CXXRecordDecl *> MostBases;
1742
1743 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1744 CollectMostBases = [&](const CXXRecordDecl *RD) {
1745 if (RD->getNumBases() == 0)
1746 MostBases.insert(RD);
1747 for (const CXXBaseSpecifier &B : RD->bases())
1748 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1749 };
1750 CollectMostBases(RD);
1751 return MostBases.takeVector();
1752}
1753
1754void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1755 llvm::Function *F) {
1756 llvm::AttrBuilder B;
1757
1758 if (CodeGenOpts.UnwindTables)
1759 B.addAttribute(llvm::Attribute::UWTable);
1760
1761 if (CodeGenOpts.StackClashProtector)
1762 B.addAttribute("probe-stack", "inline-asm");
1763
1764 if (!hasUnwindExceptions(LangOpts))
1765 B.addAttribute(llvm::Attribute::NoUnwind);
1766
1767 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1768 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1769 B.addAttribute(llvm::Attribute::StackProtect);
1770 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1771 B.addAttribute(llvm::Attribute::StackProtectStrong);
1772 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1773 B.addAttribute(llvm::Attribute::StackProtectReq);
1774 }
1775
1776 if (!D) {
1777 // If we don't have a declaration to control inlining, the function isn't
1778 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1779 // disabled, mark the function as noinline.
1780 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1781 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1782 B.addAttribute(llvm::Attribute::NoInline);
1783
1784 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1785 return;
1786 }
1787
1788 // Track whether we need to add the optnone LLVM attribute,
1789 // starting with the default for this optimization level.
1790 bool ShouldAddOptNone =
1791 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1792 // We can't add optnone in the following cases, it won't pass the verifier.
1793 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1794 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1795
1796 // Add optnone, but do so only if the function isn't always_inline.
1797 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1798 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1799 B.addAttribute(llvm::Attribute::OptimizeNone);
1800
1801 // OptimizeNone implies noinline; we should not be inlining such functions.
1802 B.addAttribute(llvm::Attribute::NoInline);
1803
1804 // We still need to handle naked functions even though optnone subsumes
1805 // much of their semantics.
1806 if (D->hasAttr<NakedAttr>())
1807 B.addAttribute(llvm::Attribute::Naked);
1808
1809 // OptimizeNone wins over OptimizeForSize and MinSize.
1810 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1811 F->removeFnAttr(llvm::Attribute::MinSize);
1812 } else if (D->hasAttr<NakedAttr>()) {
1813 // Naked implies noinline: we should not be inlining such functions.
1814 B.addAttribute(llvm::Attribute::Naked);
1815 B.addAttribute(llvm::Attribute::NoInline);
1816 } else if (D->hasAttr<NoDuplicateAttr>()) {
1817 B.addAttribute(llvm::Attribute::NoDuplicate);
1818 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1819 // Add noinline if the function isn't always_inline.
1820 B.addAttribute(llvm::Attribute::NoInline);
1821 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1822 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1823 // (noinline wins over always_inline, and we can't specify both in IR)
1824 B.addAttribute(llvm::Attribute::AlwaysInline);
1825 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1826 // If we're not inlining, then force everything that isn't always_inline to
1827 // carry an explicit noinline attribute.
1828 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1829 B.addAttribute(llvm::Attribute::NoInline);
1830 } else {
1831 // Otherwise, propagate the inline hint attribute and potentially use its
1832 // absence to mark things as noinline.
1833 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1834 // Search function and template pattern redeclarations for inline.
1835 auto CheckForInline = [](const FunctionDecl *FD) {
1836 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1837 return Redecl->isInlineSpecified();
1838 };
1839 if (any_of(FD->redecls(), CheckRedeclForInline))
1840 return true;
1841 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1842 if (!Pattern)
1843 return false;
1844 return any_of(Pattern->redecls(), CheckRedeclForInline);
1845 };
1846 if (CheckForInline(FD)) {
1847 B.addAttribute(llvm::Attribute::InlineHint);
1848 } else if (CodeGenOpts.getInlining() ==
1849 CodeGenOptions::OnlyHintInlining &&
1850 !FD->isInlined() &&
1851 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1852 B.addAttribute(llvm::Attribute::NoInline);
1853 }
1854 }
1855 }
1856
1857 // Add other optimization related attributes if we are optimizing this
1858 // function.
1859 if (!D->hasAttr<OptimizeNoneAttr>()) {
1860 if (D->hasAttr<ColdAttr>()) {
1861 if (!ShouldAddOptNone)
1862 B.addAttribute(llvm::Attribute::OptimizeForSize);
1863 B.addAttribute(llvm::Attribute::Cold);
1864 }
1865 if (D->hasAttr<HotAttr>())
1866 B.addAttribute(llvm::Attribute::Hot);
1867 if (D->hasAttr<MinSizeAttr>())
1868 B.addAttribute(llvm::Attribute::MinSize);
1869 }
1870
1871 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1872
1873 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1874 if (alignment)
1875 F->setAlignment(llvm::Align(alignment));
1876
1877 if (!D->hasAttr<AlignedAttr>())
1878 if (LangOpts.FunctionAlignment)
1879 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1880
1881 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1882 // reserve a bit for differentiating between virtual and non-virtual member
1883 // functions. If the current target's C++ ABI requires this and this is a
1884 // member function, set its alignment accordingly.
1885 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1886 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1887 F->setAlignment(llvm::Align(2));
1888 }
1889
1890 // In the cross-dso CFI mode with canonical jump tables, we want !type
1891 // attributes on definitions only.
1892 if (CodeGenOpts.SanitizeCfiCrossDso &&
1893 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1894 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1895 // Skip available_externally functions. They won't be codegen'ed in the
1896 // current module anyway.
1897 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1898 CreateFunctionTypeMetadataForIcall(FD, F);
1899 }
1900 }
1901
1902 // Emit type metadata on member functions for member function pointer checks.
1903 // These are only ever necessary on definitions; we're guaranteed that the
1904 // definition will be present in the LTO unit as a result of LTO visibility.
1905 auto *MD = dyn_cast<CXXMethodDecl>(D);
1906 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1907 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1908 llvm::Metadata *Id =
1909 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1910 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1911 F->addTypeMetadata(0, Id);
1912 }
1913 }
1914}
1915
1916void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
1917 llvm::Function *F) {
1918 if (D->hasAttr<StrictFPAttr>()) {
1919 llvm::AttrBuilder FuncAttrs;
1920 FuncAttrs.addAttribute("strictfp");
1921 F->addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1922 }
1923}
1924
1925void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1926 const Decl *D = GD.getDecl();
1927 if (dyn_cast_or_null<NamedDecl>(D))
1928 setGVProperties(GV, GD);
1929 else
1930 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1931
1932 if (D && D->hasAttr<UsedAttr>())
1933 addUsedOrCompilerUsedGlobal(GV);
1934
1935 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1936 const auto *VD = cast<VarDecl>(D);
1937 if (VD->getType().isConstQualified() &&
1938 VD->getStorageDuration() == SD_Static)
1939 addUsedOrCompilerUsedGlobal(GV);
1940 }
1941}
1942
1943bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
1944 llvm::AttrBuilder &Attrs) {
1945 // Add target-cpu and target-features attributes to functions. If
1946 // we have a decl for the function and it has a target attribute then
1947 // parse that and add it to the feature set.
1948 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1949 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
1950 std::vector<std::string> Features;
1951 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
1952 FD = FD ? FD->getMostRecentDecl() : FD;
1953 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1954 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1955 bool AddedAttr = false;
1956 if (TD || SD) {
1957 llvm::StringMap<bool> FeatureMap;
1958 getContext().getFunctionFeatureMap(FeatureMap, GD);
1959
1960 // Produce the canonical string for this set of features.
1961 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1962 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1963
1964 // Now add the target-cpu and target-features to the function.
1965 // While we populated the feature map above, we still need to
1966 // get and parse the target attribute so we can get the cpu for
1967 // the function.
1968 if (TD) {
1969 ParsedTargetAttr ParsedAttr = TD->parse();
1970 if (!ParsedAttr.Architecture.empty() &&
1971 getTarget().isValidCPUName(ParsedAttr.Architecture)) {
1972 TargetCPU = ParsedAttr.Architecture;
1973 TuneCPU = ""; // Clear the tune CPU.
1974 }
1975 if (!ParsedAttr.Tune.empty() &&
1976 getTarget().isValidCPUName(ParsedAttr.Tune))
1977 TuneCPU = ParsedAttr.Tune;
1978 }
1979 } else {
1980 // Otherwise just add the existing target cpu and target features to the
1981 // function.
1982 Features = getTarget().getTargetOpts().Features;
1983 }
1984
1985 if (!TargetCPU.empty()) {
1986 Attrs.addAttribute("target-cpu", TargetCPU);
1987 AddedAttr = true;
1988 }
1989 if (!TuneCPU.empty()) {
1990 Attrs.addAttribute("tune-cpu", TuneCPU);
1991 AddedAttr = true;
1992 }
1993 if (!Features.empty()) {
1994 llvm::sort(Features);
1995 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1996 AddedAttr = true;
1997 }
1998
1999 return AddedAttr;
2000}
2001
2002void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2003 llvm::GlobalObject *GO) {
2004 const Decl *D = GD.getDecl();
2005 SetCommonAttributes(GD, GO);
2006
2007 if (D) {
2008 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2009 if (D->hasAttr<RetainAttr>())
2010 addUsedGlobal(GV);
2011 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2012 GV->addAttribute("bss-section", SA->getName());
2013 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2014 GV->addAttribute("data-section", SA->getName());
2015 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2016 GV->addAttribute("rodata-section", SA->getName());
2017 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2018 GV->addAttribute("relro-section", SA->getName());
2019 }
2020
2021 if (auto *F = dyn_cast<llvm::Function>(GO)) {
2022 if (D->hasAttr<RetainAttr>())
2023 addUsedGlobal(F);
2024 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2025 if (!D->getAttr<SectionAttr>())
2026 F->addFnAttr("implicit-section-name", SA->getName());
2027
2028 llvm::AttrBuilder Attrs;
2029 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2030 // We know that GetCPUAndFeaturesAttributes will always have the
2031 // newest set, since it has the newest possible FunctionDecl, so the
2032 // new ones should replace the old.
2033 llvm::AttrBuilder RemoveAttrs;
2034 RemoveAttrs.addAttribute("target-cpu");
2035 RemoveAttrs.addAttribute("target-features");
2036 RemoveAttrs.addAttribute("tune-cpu");
2037 F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs);
2038 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
2039 }
2040 }
2041
2042 if (const auto *CSA = D->getAttr<CodeSegAttr>())
2043 GO->setSection(CSA->getName());
2044 else if (const auto *SA = D->getAttr<SectionAttr>())
2045 GO->setSection(SA->getName());
2046 }
2047
2048 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2049}
2050
2051void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2052 llvm::Function *F,
2053 const CGFunctionInfo &FI) {
2054 const Decl *D = GD.getDecl();
2055 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2056 SetLLVMFunctionAttributesForDefinition(D, F);
2057
2058 F->setLinkage(llvm::Function::InternalLinkage);
2059
2060 setNonAliasAttributes(GD, F);
2061}
2062
2063static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2064 // Set linkage and visibility in case we never see a definition.
2065 LinkageInfo LV = ND->getLinkageAndVisibility();
2066 // Don't set internal linkage on declarations.
2067 // "extern_weak" is overloaded in LLVM; we probably should have
2068 // separate linkage types for this.
2069 if (isExternallyVisible(LV.getLinkage()) &&
2070 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2071 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2072}
2073
2074void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2075 llvm::Function *F) {
2076 // Only if we are checking indirect calls.
2077 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2078 return;
2079
2080 // Non-static class methods are handled via vtable or member function pointer
2081 // checks elsewhere.
2082 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2083 return;
2084
2085 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2086 F->addTypeMetadata(0, MD);
2087 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2088
2089 // Emit a hash-based bit set entry for cross-DSO calls.
2090 if (CodeGenOpts.SanitizeCfiCrossDso)
2091 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2092 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2093}
2094
2095void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2096 bool IsIncompleteFunction,
2097 bool IsThunk) {
2098
2099 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2100 // If this is an intrinsic function, set the function's attributes
2101 // to the intrinsic's attributes.
2102 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2103 return;
2104 }
2105
2106 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2107
2108 if (!IsIncompleteFunction)
2109 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2110 IsThunk);
2111
2112 // Add the Returned attribute for "this", except for iOS 5 and earlier
2113 // where substantial code, including the libstdc++ dylib, was compiled with
2114 // GCC and does not actually return "this".
2115 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2116 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2117 assert(!F->arg_empty() &&(static_cast <bool> (!F->arg_empty() && F->
arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType
()) && "unexpected this return") ? void (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2120, __extension__ __PRETTY_FUNCTION__))
2118 F->arg_begin()->getType()(static_cast <bool> (!F->arg_empty() && F->
arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType
()) && "unexpected this return") ? void (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2120, __extension__ __PRETTY_FUNCTION__))
2119 ->canLosslesslyBitCastTo(F->getReturnType()) &&(static_cast <bool> (!F->arg_empty() && F->
arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType
()) && "unexpected this return") ? void (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2120, __extension__ __PRETTY_FUNCTION__))
2120 "unexpected this return")(static_cast <bool> (!F->arg_empty() && F->
arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType
()) && "unexpected this return") ? void (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2120, __extension__ __PRETTY_FUNCTION__))
;
2121 F->addAttribute(1, llvm::Attribute::Returned);
2122 }
2123
2124 // Only a few attributes are set on declarations; these may later be
2125 // overridden by a definition.
2126
2127 setLinkageForGV(F, FD);
2128 setGVProperties(F, FD);
2129
2130 // Setup target-specific attributes.
2131 if (!IsIncompleteFunction && F->isDeclaration())
2132 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2133
2134 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2135 F->setSection(CSA->getName());
2136 else if (const auto *SA = FD->getAttr<SectionAttr>())
2137 F->setSection(SA->getName());
2138
2139 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2140 if (FD->isInlineBuiltinDeclaration()) {
2141 const FunctionDecl *FDBody;
2142 bool HasBody = FD->hasBody(FDBody);
2143 (void)HasBody;
2144 assert(HasBody && "Inline builtin declarations should always have an "(static_cast <bool> (HasBody && "Inline builtin declarations should always have an "
"available body!") ? void (0) : __assert_fail ("HasBody && \"Inline builtin declarations should always have an \" \"available body!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2145, __extension__ __PRETTY_FUNCTION__))
2145 "available body!")(static_cast <bool> (HasBody && "Inline builtin declarations should always have an "
"available body!") ? void (0) : __assert_fail ("HasBody && \"Inline builtin declarations should always have an \" \"available body!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2145, __extension__ __PRETTY_FUNCTION__))
;
2146 if (shouldEmitFunction(FDBody))
2147 F->addAttribute(llvm::AttributeList::FunctionIndex,
2148 llvm::Attribute::NoBuiltin);
2149 }
2150
2151 if (FD->isReplaceableGlobalAllocationFunction()) {
2152 // A replaceable global allocation function does not act like a builtin by
2153 // default, only if it is invoked by a new-expression or delete-expression.
2154 F->addAttribute(llvm::AttributeList::FunctionIndex,
2155 llvm::Attribute::NoBuiltin);
2156 }
2157
2158 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2159 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2160 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2161 if (MD->isVirtual())
2162 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2163
2164 // Don't emit entries for function declarations in the cross-DSO mode. This
2165 // is handled with better precision by the receiving DSO. But if jump tables
2166 // are non-canonical then we need type metadata in order to produce the local
2167 // jump table.
2168 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2169 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2170 CreateFunctionTypeMetadataForIcall(FD, F);
2171
2172 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2173 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2174
2175 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2176 // Annotate the callback behavior as metadata:
2177 // - The callback callee (as argument number).
2178 // - The callback payloads (as argument numbers).
2179 llvm::LLVMContext &Ctx = F->getContext();
2180 llvm::MDBuilder MDB(Ctx);
2181
2182 // The payload indices are all but the first one in the encoding. The first
2183 // identifies the callback callee.
2184 int CalleeIdx = *CB->encoding_begin();
2185 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2186 F->addMetadata(llvm::LLVMContext::MD_callback,
2187 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2188 CalleeIdx, PayloadIndices,
2189 /* VarArgsArePassed */ false)}));
2190 }
2191}
2192
2193void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2194 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&(static_cast <bool> ((isa<llvm::Function>(GV) || !
GV->isDeclaration()) && "Only globals with definition can force usage."
) ? void (0) : __assert_fail ("(isa<llvm::Function>(GV) || !GV->isDeclaration()) && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2195, __extension__ __PRETTY_FUNCTION__))
2195 "Only globals with definition can force usage.")(static_cast <bool> ((isa<llvm::Function>(GV) || !
GV->isDeclaration()) && "Only globals with definition can force usage."
) ? void (0) : __assert_fail ("(isa<llvm::Function>(GV) || !GV->isDeclaration()) && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2195, __extension__ __PRETTY_FUNCTION__))
;
2196 LLVMUsed.emplace_back(GV);
2197}
2198
2199void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2200 assert(!GV->isDeclaration() &&(static_cast <bool> (!GV->isDeclaration() &&
"Only globals with definition can force usage.") ? void (0) :
__assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2201, __extension__ __PRETTY_FUNCTION__))
2201 "Only globals with definition can force usage.")(static_cast <bool> (!GV->isDeclaration() &&
"Only globals with definition can force usage.") ? void (0) :
__assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2201, __extension__ __PRETTY_FUNCTION__))
;
2202 LLVMCompilerUsed.emplace_back(GV);
2203}
2204
2205void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2206 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&(static_cast <bool> ((isa<llvm::Function>(GV) || !
GV->isDeclaration()) && "Only globals with definition can force usage."
) ? void (0) : __assert_fail ("(isa<llvm::Function>(GV) || !GV->isDeclaration()) && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2207, __extension__ __PRETTY_FUNCTION__))
2207 "Only globals with definition can force usage.")(static_cast <bool> ((isa<llvm::Function>(GV) || !
GV->isDeclaration()) && "Only globals with definition can force usage."
) ? void (0) : __assert_fail ("(isa<llvm::Function>(GV) || !GV->isDeclaration()) && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2207, __extension__ __PRETTY_FUNCTION__))
;
2208 if (getTriple().isOSBinFormatELF())
2209 LLVMCompilerUsed.emplace_back(GV);
2210 else
2211 LLVMUsed.emplace_back(GV);
2212}
2213
2214static void emitUsed(CodeGenModule &CGM, StringRef Name,
2215 std::vector<llvm::WeakTrackingVH> &List) {
2216 // Don't create llvm.used if there is no need.
2217 if (List.empty())
2218 return;
2219
2220 // Convert List to what ConstantArray needs.
2221 SmallVector<llvm::Constant*, 8> UsedArray;
2222 UsedArray.resize(List.size());
2223 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2224 UsedArray[i] =
2225 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2226 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2227 }
2228
2229 if (UsedArray.empty())
2230 return;
2231 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2232
2233 auto *GV = new llvm::GlobalVariable(
2234 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2235 llvm::ConstantArray::get(ATy, UsedArray), Name);
2236
2237 GV->setSection("llvm.metadata");
2238}
2239
2240void CodeGenModule::emitLLVMUsed() {
2241 emitUsed(*this, "llvm.used", LLVMUsed);
2242 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2243}
2244
2245void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2246 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2247 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2248}
2249
2250void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2251 llvm::SmallString<32> Opt;
2252 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2253 if (Opt.empty())
2254 return;
2255 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2256 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2257}
2258
2259void CodeGenModule::AddDependentLib(StringRef Lib) {
2260 auto &C = getLLVMContext();
2261 if (getTarget().getTriple().isOSBinFormatELF()) {
2262 ELFDependentLibraries.push_back(
2263 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2264 return;
2265 }
2266
2267 llvm::SmallString<24> Opt;
2268 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2269 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2270 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2271}
2272
2273/// Add link options implied by the given module, including modules
2274/// it depends on, using a postorder walk.
2275static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2276 SmallVectorImpl<llvm::MDNode *> &Metadata,
2277 llvm::SmallPtrSet<Module *, 16> &Visited) {
2278 // Import this module's parent.
2279 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2280 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2281 }
2282
2283 // Import this module's dependencies.
2284 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
2285 if (Visited.insert(Mod->Imports[I - 1]).second)
2286 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2287 }
2288
2289 // Add linker options to link against the libraries/frameworks
2290 // described by this module.
2291 llvm::LLVMContext &Context = CGM.getLLVMContext();
2292 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2293
2294 // For modules that use export_as for linking, use that module
2295 // name instead.
2296 if (Mod->UseExportAsModuleLinkName)
2297 return;
2298
2299 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2300 // Link against a framework. Frameworks are currently Darwin only, so we
2301 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2302 if (Mod->LinkLibraries[I-1].IsFramework) {
2303 llvm::Metadata *Args[2] = {
2304 llvm::MDString::get(Context, "-framework"),
2305 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2306
2307 Metadata.push_back(llvm::MDNode::get(Context, Args));
2308 continue;
2309 }
2310
2311 // Link against a library.
2312 if (IsELF) {
2313 llvm::Metadata *Args[2] = {
2314 llvm::MDString::get(Context, "lib"),
2315 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2316 };
2317 Metadata.push_back(llvm::MDNode::get(Context, Args));
2318 } else {
2319 llvm::SmallString<24> Opt;
2320 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2321 Mod->LinkLibraries[I - 1].Library, Opt);
2322 auto *OptString = llvm::MDString::get(Context, Opt);
2323 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2324 }
2325 }
2326}
2327
2328void CodeGenModule::EmitModuleLinkOptions() {
2329 // Collect the set of all of the modules we want to visit to emit link
2330 // options, which is essentially the imported modules and all of their
2331 // non-explicit child modules.
2332 llvm::SetVector<clang::Module *> LinkModules;
2333 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2334 SmallVector<clang::Module *, 16> Stack;
2335
2336 // Seed the stack with imported modules.
2337 for (Module *M : ImportedModules) {
2338 // Do not add any link flags when an implementation TU of a module imports
2339 // a header of that same module.
2340 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2341 !getLangOpts().isCompilingModule())
2342 continue;
2343 if (Visited.insert(M).second)
2344 Stack.push_back(M);
2345 }
2346
2347 // Find all of the modules to import, making a little effort to prune
2348 // non-leaf modules.
2349 while (!Stack.empty()) {
2350 clang::Module *Mod = Stack.pop_back_val();
2351
2352 bool AnyChildren = false;
2353
2354 // Visit the submodules of this module.
2355 for (const auto &SM : Mod->submodules()) {
2356 // Skip explicit children; they need to be explicitly imported to be
2357 // linked against.
2358 if (SM->IsExplicit)
2359 continue;
2360
2361 if (Visited.insert(SM).second) {
2362 Stack.push_back(SM);
2363 AnyChildren = true;
2364 }
2365 }
2366
2367 // We didn't find any children, so add this module to the list of
2368 // modules to link against.
2369 if (!AnyChildren) {
2370 LinkModules.insert(Mod);
2371 }
2372 }
2373
2374 // Add link options for all of the imported modules in reverse topological
2375 // order. We don't do anything to try to order import link flags with respect
2376 // to linker options inserted by things like #pragma comment().
2377 SmallVector<llvm::MDNode *, 16> MetadataArgs;
2378 Visited.clear();
2379 for (Module *M : LinkModules)
2380 if (Visited.insert(M).second)
2381 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2382 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2383 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2384
2385 // Add the linker options metadata flag.
2386 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2387 for (auto *MD : LinkerOptionsMetadata)
2388 NMD->addOperand(MD);
2389}
2390
2391void CodeGenModule::EmitDeferred() {
2392 // Emit deferred declare target declarations.
2393 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2394 getOpenMPRuntime().emitDeferredTargetDecls();
2395
2396 // Emit code for any potentially referenced deferred decls. Since a
2397 // previously unused static decl may become used during the generation of code
2398 // for a static function, iterate until no changes are made.
2399
2400 if (!DeferredVTables.empty()) {
2401 EmitDeferredVTables();
2402
2403 // Emitting a vtable doesn't directly cause more vtables to
2404 // become deferred, although it can cause functions to be
2405 // emitted that then need those vtables.
2406 assert(DeferredVTables.empty())(static_cast <bool> (DeferredVTables.empty()) ? void (0
) : __assert_fail ("DeferredVTables.empty()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2406, __extension__ __PRETTY_FUNCTION__))
;
2407 }
2408
2409 // Emit CUDA/HIP static device variables referenced by host code only.
2410 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2411 // needed for further handling.
2412 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2413 for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
2414 DeferredDeclsToEmit.push_back(V);
2415
2416 // Stop if we're out of both deferred vtables and deferred declarations.
2417 if (DeferredDeclsToEmit.empty())
2418 return;
2419
2420 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2421 // work, it will not interfere with this.
2422 std::vector<GlobalDecl> CurDeclsToEmit;
2423 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2424
2425 for (GlobalDecl &D : CurDeclsToEmit) {
2426 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2427 // to get GlobalValue with exactly the type we need, not something that
2428 // might had been created for another decl with the same mangled name but
2429 // different type.
2430 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2431 GetAddrOfGlobal(D, ForDefinition));
2432
2433 // In case of different address spaces, we may still get a cast, even with
2434 // IsForDefinition equal to true. Query mangled names table to get
2435 // GlobalValue.
2436 if (!GV)
2437 GV = GetGlobalValue(getMangledName(D));
2438
2439 // Make sure GetGlobalValue returned non-null.
2440 assert(GV)(static_cast <bool> (GV) ? void (0) : __assert_fail ("GV"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2440, __extension__ __PRETTY_FUNCTION__))
;
2441
2442 // Check to see if we've already emitted this. This is necessary
2443 // for a couple of reasons: first, decls can end up in the
2444 // deferred-decls queue multiple times, and second, decls can end
2445 // up with definitions in unusual ways (e.g. by an extern inline
2446 // function acquiring a strong function redefinition). Just
2447 // ignore these cases.
2448 if (!GV->isDeclaration())
2449 continue;
2450
2451 // If this is OpenMP, check if it is legal to emit this global normally.
2452 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2453 continue;
2454
2455 // Otherwise, emit the definition and move on to the next one.
2456 EmitGlobalDefinition(D, GV);
2457
2458 // If we found out that we need to emit more decls, do that recursively.
2459 // This has the advantage that the decls are emitted in a DFS and related
2460 // ones are close together, which is convenient for testing.
2461 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2462 EmitDeferred();
2463 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty())(static_cast <bool> (DeferredVTables.empty() &&
DeferredDeclsToEmit.empty()) ? void (0) : __assert_fail ("DeferredVTables.empty() && DeferredDeclsToEmit.empty()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2463, __extension__ __PRETTY_FUNCTION__))
;
2464 }
2465 }
2466}
2467
2468void CodeGenModule::EmitVTablesOpportunistically() {
2469 // Try to emit external vtables as available_externally if they have emitted
2470 // all inlined virtual functions. It runs after EmitDeferred() and therefore
2471 // is not allowed to create new references to things that need to be emitted
2472 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2473
2474 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())(static_cast <bool> ((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables
()) && "Only emit opportunistic vtables with optimizations"
) ? void (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2475, __extension__ __PRETTY_FUNCTION__))
2475 && "Only emit opportunistic vtables with optimizations")(static_cast <bool> ((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables
()) && "Only emit opportunistic vtables with optimizations"
) ? void (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2475, __extension__ __PRETTY_FUNCTION__))
;
2476
2477 for (const CXXRecordDecl *RD : OpportunisticVTables) {
2478 assert(getVTables().isVTableExternal(RD) &&(static_cast <bool> (getVTables().isVTableExternal(RD) &&
"This queue should only contain external vtables") ? void (0
) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2479, __extension__ __PRETTY_FUNCTION__))
2479 "This queue should only contain external vtables")(static_cast <bool> (getVTables().isVTableExternal(RD) &&
"This queue should only contain external vtables") ? void (0
) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2479, __extension__ __PRETTY_FUNCTION__))
;
2480 if (getCXXABI().canSpeculativelyEmitVTable(RD))
2481 VTables.GenerateClassData(RD);
2482 }
2483 OpportunisticVTables.clear();
2484}
2485
2486void CodeGenModule::EmitGlobalAnnotations() {
2487 if (Annotations.empty())
2488 return;
2489
2490 // Create a new global variable for the ConstantStruct in the Module.
2491 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2492 Annotations[0]->getType(), Annotations.size()), Annotations);
2493 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2494 llvm::GlobalValue::AppendingLinkage,
2495 Array, "llvm.global.annotations");
2496 gv->setSection(AnnotationSection);
2497}
2498
2499llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2500 llvm::Constant *&AStr = AnnotationStrings[Str];
2501 if (AStr)
2502 return AStr;
2503
2504 // Not found yet, create a new global.
2505 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2506 auto *gv =
2507 new llvm::GlobalVariable(getModule(), s->getType(), true,
2508 llvm::GlobalValue::PrivateLinkage, s, ".str");
2509 gv->setSection(AnnotationSection);
2510 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2511 AStr = gv;
2512 return gv;
2513}
2514
2515llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2516 SourceManager &SM = getContext().getSourceManager();
2517 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2518 if (PLoc.isValid())
2519 return EmitAnnotationString(PLoc.getFilename());
2520 return EmitAnnotationString(SM.getBufferName(Loc));
2521}
2522
2523llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2524 SourceManager &SM = getContext().getSourceManager();
2525 PresumedLoc PLoc = SM.getPresumedLoc(L);
2526 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2527 SM.getExpansionLineNumber(L);
2528 return llvm::ConstantInt::get(Int32Ty, LineNo);
2529}
2530
2531llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2532 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2533 if (Exprs.empty())
2534 return llvm::ConstantPointerNull::get(Int8PtrTy);
2535
2536 llvm::FoldingSetNodeID ID;
2537 for (Expr *E : Exprs) {
2538 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2539 }
2540 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2541 if (Lookup)
2542 return Lookup;
2543
2544 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2545 LLVMArgs.reserve(Exprs.size());
2546 ConstantEmitter ConstEmiter(*this);
2547 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2548 const auto *CE = cast<clang::ConstantExpr>(E);
2549 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2550 CE->getType());
2551 });
2552 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2553 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2554 llvm::GlobalValue::PrivateLinkage, Struct,
2555 ".args");
2556 GV->setSection(AnnotationSection);
2557 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2558 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
2559
2560 Lookup = Bitcasted;
2561 return Bitcasted;
2562}
2563
2564llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2565 const AnnotateAttr *AA,
2566 SourceLocation L) {
2567 // Get the globals for file name, annotation, and the line number.
2568 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2569 *UnitGV = EmitAnnotationUnit(L),
2570 *LineNoCst = EmitAnnotationLineNo(L),
2571 *Args = EmitAnnotationArgs(AA);
2572
2573 llvm::Constant *ASZeroGV = GV;
2574 if (GV->getAddressSpace() != 0) {
2575 ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2576 GV, GV->getValueType()->getPointerTo(0));
2577 }
2578
2579 // Create the ConstantStruct for the global annotation.
2580 llvm::Constant *Fields[] = {
2581 llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2582 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2583 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2584 LineNoCst,
2585 Args,
2586 };
2587 return llvm::ConstantStruct::getAnon(Fields);
2588}
2589
2590void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2591 llvm::GlobalValue *GV) {
2592 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute")(static_cast <bool> (D->hasAttr<AnnotateAttr>(
) && "no annotate attribute") ? void (0) : __assert_fail
("D->hasAttr<AnnotateAttr>() && \"no annotate attribute\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2592, __extension__ __PRETTY_FUNCTION__))
;
2593 // Get the struct elements for these annotations.
2594 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2595 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2596}
2597
2598bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
2599 SourceLocation Loc) const {
2600 const auto &NoSanitizeL = getContext().getNoSanitizeList();
2601 // NoSanitize by function name.
2602 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
2603 return true;
2604 // NoSanitize by location.
2605 if (Loc.isValid())
2606 return NoSanitizeL.containsLocation(Kind, Loc);
2607 // If location is unknown, this may be a compiler-generated function. Assume
2608 // it's located in the main file.
2609 auto &SM = Context.getSourceManager();
2610 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2611 return NoSanitizeL.containsFile(Kind, MainFile->getName());
2612 }
2613 return false;
2614}
2615
2616bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
2617 SourceLocation Loc, QualType Ty,
2618 StringRef Category) const {
2619 // For now globals can be ignored only in ASan and KASan.
2620 const SanitizerMask EnabledAsanMask =
2621 LangOpts.Sanitize.Mask &
2622 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2623 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2624 SanitizerKind::MemTag);
2625 if (!EnabledAsanMask)
2626 return false;
2627 const auto &NoSanitizeL = getContext().getNoSanitizeList();
2628 if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
2629 return true;
2630 if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
2631 return true;
2632 // Check global type.
2633 if (!Ty.isNull()) {
2634 // Drill down the array types: if global variable of a fixed type is
2635 // not sanitized, we also don't instrument arrays of them.
2636 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2637 Ty = AT->getElementType();
2638 Ty = Ty.getCanonicalType().getUnqualifiedType();
2639 // Only record types (classes, structs etc.) are ignored.
2640 if (Ty->isRecordType()) {
2641 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2642 if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
2643 return true;
2644 }
2645 }
2646 return false;
2647}
2648
2649bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2650 StringRef Category) const {
2651 const auto &XRayFilter = getContext().getXRayFilter();
2652 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2653 auto Attr = ImbueAttr::NONE;
2654 if (Loc.isValid())
2655 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2656 if (Attr == ImbueAttr::NONE)
2657 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2658 switch (Attr) {
2659 case ImbueAttr::NONE:
2660 return false;
2661 case ImbueAttr::ALWAYS:
2662 Fn->addFnAttr("function-instrument", "xray-always");
2663 break;
2664 case ImbueAttr::ALWAYS_ARG1:
2665 Fn->addFnAttr("function-instrument", "xray-always");
2666 Fn->addFnAttr("xray-log-args", "1");
2667 break;
2668 case ImbueAttr::NEVER:
2669 Fn->addFnAttr("function-instrument", "xray-never");
2670 break;
2671 }
2672 return true;
2673}
2674
2675bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2676 SourceLocation Loc) const {
2677 const auto &ProfileList = getContext().getProfileList();
2678 // If the profile list is empty, then instrument everything.
2679 if (ProfileList.isEmpty())
2680 return false;
2681 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2682 // First, check the function name.
2683 Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2684 if (V.hasValue())
2685 return *V;
2686 // Next, check the source location.
2687 if (Loc.isValid()) {
2688 Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2689 if (V.hasValue())
2690 return *V;
2691 }
2692 // If location is unknown, this may be a compiler-generated function. Assume
2693 // it's located in the main file.
2694 auto &SM = Context.getSourceManager();
2695 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2696 Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2697 if (V.hasValue())
2698 return *V;
2699 }
2700 return ProfileList.getDefault();
2701}
2702
2703bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2704 // Never defer when EmitAllDecls is specified.
2705 if (LangOpts.EmitAllDecls)
2706 return true;
2707
2708 if (CodeGenOpts.KeepStaticConsts) {
2709 const auto *VD = dyn_cast<VarDecl>(Global);
2710 if (VD && VD->getType().isConstQualified() &&
2711 VD->getStorageDuration() == SD_Static)
2712 return true;
2713 }
2714
2715 return getContext().DeclMustBeEmitted(Global);
2716}
2717
2718bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2719 // In OpenMP 5.0 variables and function may be marked as
2720 // device_type(host/nohost) and we should not emit them eagerly unless we sure
2721 // that they must be emitted on the host/device. To be sure we need to have
2722 // seen a declare target with an explicit mentioning of the function, we know
2723 // we have if the level of the declare target attribute is -1. Note that we
2724 // check somewhere else if we should emit this at all.
2725 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
2726 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
2727 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
2728 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
2729 return false;
2730 }
2731
2732 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2733 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2734 // Implicit template instantiations may change linkage if they are later
2735 // explicitly instantiated, so they should not be emitted eagerly.
2736 return false;
2737 }
2738 if (const auto *VD = dyn_cast<VarDecl>(Global))
2739 if (Context.getInlineVariableDefinitionKind(VD) ==
2740 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2741 // A definition of an inline constexpr static data member may change
2742 // linkage later if it's redeclared outside the class.
2743 return false;
2744 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2745 // codegen for global variables, because they may be marked as threadprivate.
2746 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2747 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2748 !isTypeConstant(Global->getType(), false) &&
2749 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2750 return false;
2751
2752 return true;
2753}
2754
2755ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2756 StringRef Name = getMangledName(GD);
2757
2758 // The UUID descriptor should be pointer aligned.
2759 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2760
2761 // Look for an existing global.
2762 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2763 return ConstantAddress(GV, Alignment);
2764
2765 ConstantEmitter Emitter(*this);
2766 llvm::Constant *Init;
2767
2768 APValue &V = GD->getAsAPValue();
2769 if (!V.isAbsent()) {
2770 // If possible, emit the APValue version of the initializer. In particular,
2771 // this gets the type of the constant right.
2772 Init = Emitter.emitForInitializer(
2773 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2774 } else {
2775 // As a fallback, directly construct the constant.
2776 // FIXME: This may get padding wrong under esoteric struct layout rules.
2777 // MSVC appears to create a complete type 'struct __s_GUID' that it
2778 // presumably uses to represent these constants.
2779 MSGuidDecl::Parts Parts = GD->getParts();
2780 llvm::Constant *Fields[4] = {
2781 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2782 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2783 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2784 llvm::ConstantDataArray::getRaw(
2785 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2786 Int8Ty)};
2787 Init = llvm::ConstantStruct::getAnon(Fields);
2788 }
2789
2790 auto *GV = new llvm::GlobalVariable(
2791 getModule(), Init->getType(),
2792 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2793 if (supportsCOMDAT())
2794 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2795 setDSOLocal(GV);
2796
2797 llvm::Constant *Addr = GV;
2798 if (!V.isAbsent()) {
2799 Emitter.finalize(GV);
2800 } else {
2801 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2802 Addr = llvm::ConstantExpr::getBitCast(
2803 GV, Ty->getPointerTo(GV->getAddressSpace()));
2804 }
2805 return ConstantAddress(Addr, Alignment);
2806}
2807
2808ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2809 const TemplateParamObjectDecl *TPO) {
2810 StringRef Name = getMangledName(TPO);
2811 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2812
2813 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2814 return ConstantAddress(GV, Alignment);
2815
2816 ConstantEmitter Emitter(*this);
2817 llvm::Constant *Init = Emitter.emitForInitializer(
2818 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2819
2820 if (!Init) {
2821 ErrorUnsupported(TPO, "template parameter object");
2822 return ConstantAddress::invalid();
2823 }
2824
2825 auto *GV = new llvm::GlobalVariable(
2826 getModule(), Init->getType(),
2827 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2828 if (supportsCOMDAT())
2829 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2830 Emitter.finalize(GV);
2831
2832 return ConstantAddress(GV, Alignment);
2833}
2834
2835ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2836 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2837 assert(AA && "No alias?")(static_cast <bool> (AA && "No alias?") ? void (
0) : __assert_fail ("AA && \"No alias?\"", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2837, __extension__ __PRETTY_FUNCTION__))
;
1
Assuming 'AA' is non-null
2
'?' condition is true
2838
2839 CharUnits Alignment = getContext().getDeclAlign(VD);
2840 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2841
2842 // See if there is already something with the target's name in the module.
2843 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2844 if (Entry) {
3
Assuming 'Entry' is null
4
Taking false branch
2845 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2846 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2847 return ConstantAddress(Ptr, Alignment);
2848 }
2849
2850 llvm::Constant *Aliasee;
2851 if (isa<llvm::FunctionType>(DeclTy))
5
Assuming 'DeclTy' is a 'FunctionType'
6
Taking true branch
2852 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
8
Calling 'CodeGenModule::GetOrCreateLLVMFunction'
2853 GlobalDecl(cast<FunctionDecl>(VD)),
7
'VD' is a 'FunctionDecl'
2854 /*ForVTable=*/false);
2855 else
2856 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0, nullptr);
2857
2858 auto *F = cast<llvm::GlobalValue>(Aliasee);
2859 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2860 WeakRefReferences.insert(F);
2861
2862 return ConstantAddress(Aliasee, Alignment);
2863}
2864
2865void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2866 const auto *Global = cast<ValueDecl>(GD.getDecl());
22
The object is a 'ValueDecl'
2867
2868 // Weak references don't produce any output by themselves.
2869 if (Global->hasAttr<WeakRefAttr>())
23
Taking false branch
2870 return;
2871
2872 // If this is an alias definition (which otherwise looks like a declaration)
2873 // emit it now.
2874 if (Global->hasAttr<AliasAttr>())
24
Taking false branch
2875 return EmitAliasDefinition(GD);
2876
2877 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2878 if (Global->hasAttr<IFuncAttr>())
25
Taking false branch
2879 return emitIFuncDefinition(GD);
2880
2881 // If this is a cpu_dispatch multiversion function, emit the resolver.
2882 if (Global->hasAttr<CPUDispatchAttr>())
26
Taking true branch
2883 return emitCPUDispatchDefinition(GD);
27
Calling 'CodeGenModule::emitCPUDispatchDefinition'
2884
2885 // If this is CUDA, be selective about which declarations we emit.
2886 if (LangOpts.CUDA) {
2887 if (LangOpts.CUDAIsDevice) {
2888 if (!Global->hasAttr<CUDADeviceAttr>() &&
2889 !Global->hasAttr<CUDAGlobalAttr>() &&
2890 !Global->hasAttr<CUDAConstantAttr>() &&
2891 !Global->hasAttr<CUDASharedAttr>() &&
2892 !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2893 !Global->getType()->isCUDADeviceBuiltinTextureType())
2894 return;
2895 } else {
2896 // We need to emit host-side 'shadows' for all global
2897 // device-side variables because the CUDA runtime needs their
2898 // size and host-side address in order to provide access to
2899 // their device-side incarnations.
2900
2901 // So device-only functions are the only things we skip.
2902 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2903 Global->hasAttr<CUDADeviceAttr>())
2904 return;
2905
2906 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&(static_cast <bool> ((isa<FunctionDecl>(Global) ||
isa<VarDecl>(Global)) && "Expected Variable or Function"
) ? void (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2907, __extension__ __PRETTY_FUNCTION__))
2907 "Expected Variable or Function")(static_cast <bool> ((isa<FunctionDecl>(Global) ||
isa<VarDecl>(Global)) && "Expected Variable or Function"
) ? void (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2907, __extension__ __PRETTY_FUNCTION__))
;
2908 }
2909 }
2910
2911 if (LangOpts.OpenMP) {
2912 // If this is OpenMP, check if it is legal to emit this global normally.
2913 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2914 return;
2915 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2916 if (MustBeEmitted(Global))
2917 EmitOMPDeclareReduction(DRD);
2918 return;
2919 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2920 if (MustBeEmitted(Global))
2921 EmitOMPDeclareMapper(DMD);
2922 return;
2923 }
2924 }
2925
2926 // Ignore declarations, they will be emitted on their first use.
2927 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2928 // Forward declarations are emitted lazily on first use.
2929 if (!FD->doesThisDeclarationHaveABody()) {
2930 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2931 return;
2932
2933 StringRef MangledName = getMangledName(GD);
2934
2935 // Compute the function info and LLVM type.
2936 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2937 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2938
2939 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2940 /*DontDefer=*/false);
2941 return;
2942 }
2943 } else {
2944 const auto *VD = cast<VarDecl>(Global);
2945 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.")(static_cast <bool> (VD->isFileVarDecl() && "Cannot emit local var decl as global."
) ? void (0) : __assert_fail ("VD->isFileVarDecl() && \"Cannot emit local var decl as global.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2945, __extension__ __PRETTY_FUNCTION__))
;
2946 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2947 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2948 if (LangOpts.OpenMP) {
2949 // Emit declaration of the must-be-emitted declare target variable.
2950 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2951 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2952 bool UnifiedMemoryEnabled =
2953 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2954 if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2955 !UnifiedMemoryEnabled) {
2956 (void)GetAddrOfGlobalVar(VD);
2957 } else {
2958 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||(static_cast <bool> (((*Res == OMPDeclareTargetDeclAttr
::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? void (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2961, __extension__ __PRETTY_FUNCTION__))
2959 (*Res == OMPDeclareTargetDeclAttr::MT_To &&(static_cast <bool> (((*Res == OMPDeclareTargetDeclAttr
::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? void (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2961, __extension__ __PRETTY_FUNCTION__))
2960 UnifiedMemoryEnabled)) &&(static_cast <bool> (((*Res == OMPDeclareTargetDeclAttr
::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? void (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2961, __extension__ __PRETTY_FUNCTION__))
2961 "Link clause or to clause with unified memory expected.")(static_cast <bool> (((*Res == OMPDeclareTargetDeclAttr
::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? void (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 2961, __extension__ __PRETTY_FUNCTION__))
;
2962 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2963 }
2964
2965 return;
2966 }
2967 }
2968 // If this declaration may have caused an inline variable definition to
2969 // change linkage, make sure that it's emitted.
2970 if (Context.getInlineVariableDefinitionKind(VD) ==
2971 ASTContext::InlineVariableDefinitionKind::Strong)
2972 GetAddrOfGlobalVar(VD);
2973 return;
2974 }
2975 }
2976
2977 // Defer code generation to first use when possible, e.g. if this is an inline
2978 // function. If the global must always be emitted, do it eagerly if possible
2979 // to benefit from cache locality.
2980 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2981 // Emit the definition if it can't be deferred.
2982 EmitGlobalDefinition(GD);
2983 return;
2984 }
2985
2986 // If we're deferring emission of a C++ variable with an
2987 // initializer, remember the order in which it appeared in the file.
2988 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2989 cast<VarDecl>(Global)->hasInit()) {
2990 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2991 CXXGlobalInits.push_back(nullptr);
2992 }
2993
2994 StringRef MangledName = getMangledName(GD);
2995 if (GetGlobalValue(MangledName) != nullptr) {
2996 // The value has already been used and should therefore be emitted.
2997 addDeferredDeclToEmit(GD);
2998 } else if (MustBeEmitted(Global)) {
2999 // The value must be emitted, but cannot be emitted eagerly.
3000 assert(!MayBeEmittedEagerly(Global))(static_cast <bool> (!MayBeEmittedEagerly(Global)) ? void
(0) : __assert_fail ("!MayBeEmittedEagerly(Global)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3000, __extension__ __PRETTY_FUNCTION__))
;
3001 addDeferredDeclToEmit(GD);
3002 } else {
3003 // Otherwise, remember that we saw a deferred decl with this name. The
3004 // first use of the mangled name will cause it to move into
3005 // DeferredDeclsToEmit.
3006 DeferredDecls[MangledName] = GD;
3007 }
3008}
3009
3010// Check if T is a class type with a destructor that's not dllimport.
3011static bool HasNonDllImportDtor(QualType T) {
3012 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3013 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3014 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3015 return true;
3016
3017 return false;
3018}
3019
3020namespace {
3021 struct FunctionIsDirectlyRecursive
3022 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3023 const StringRef Name;
3024 const Builtin::Context &BI;
3025 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3026 : Name(N), BI(C) {}
3027
3028 bool VisitCallExpr(const CallExpr *E) {
3029 const FunctionDecl *FD = E->getDirectCallee();
3030 if (!FD)
3031 return false;
3032 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3033 if (Attr && Name == Attr->getLabel())
3034 return true;
3035 unsigned BuiltinID = FD->getBuiltinID();
3036 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3037 return false;
3038 StringRef BuiltinName = BI.getName(BuiltinID);
3039 if (BuiltinName.startswith("__builtin_") &&
3040 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3041 return true;
3042 }
3043 return false;
3044 }
3045
3046 bool VisitStmt(const Stmt *S) {
3047 for (const Stmt *Child : S->children())
3048 if (Child && this->Visit(Child))
3049 return true;
3050 return false;
3051 }
3052 };
3053
3054 // Make sure we're not referencing non-imported vars or functions.
3055 struct DLLImportFunctionVisitor
3056 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3057 bool SafeToInline = true;
3058
3059 bool shouldVisitImplicitCode() const { return true; }
3060
3061 bool VisitVarDecl(VarDecl *VD) {
3062 if (VD->getTLSKind()) {
3063 // A thread-local variable cannot be imported.
3064 SafeToInline = false;
3065 return SafeToInline;
3066 }
3067
3068 // A variable definition might imply a destructor call.
3069 if (VD->isThisDeclarationADefinition())
3070 SafeToInline = !HasNonDllImportDtor(VD->getType());
3071
3072 return SafeToInline;
3073 }
3074
3075 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3076 if (const auto *D = E->getTemporary()->getDestructor())
3077 SafeToInline = D->hasAttr<DLLImportAttr>();
3078 return SafeToInline;
3079 }
3080
3081 bool VisitDeclRefExpr(DeclRefExpr *E) {
3082 ValueDecl *VD = E->getDecl();
3083 if (isa<FunctionDecl>(VD))
3084 SafeToInline = VD->hasAttr<DLLImportAttr>();
3085 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3086 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3087 return SafeToInline;
3088 }
3089
3090 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3091 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3092 return SafeToInline;
3093 }
3094
3095 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3096 CXXMethodDecl *M = E->getMethodDecl();
3097 if (!M) {
3098 // Call through a pointer to member function. This is safe to inline.
3099 SafeToInline = true;
3100 } else {
3101 SafeToInline = M->hasAttr<DLLImportAttr>();
3102 }
3103 return SafeToInline;
3104 }
3105
3106 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3107 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3108 return SafeToInline;
3109 }
3110
3111 bool VisitCXXNewExpr(CXXNewExpr *E) {
3112 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3113 return SafeToInline;
3114 }
3115 };
3116}
3117
3118// isTriviallyRecursive - Check if this function calls another
3119// decl that, because of the asm attribute or the other decl being a builtin,
3120// ends up pointing to itself.
3121bool
3122CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3123 StringRef Name;
3124 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3125 // asm labels are a special kind of mangling we have to support.
3126 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3127 if (!Attr)
3128 return false;
3129 Name = Attr->getLabel();
3130 } else {
3131 Name = FD->getName();
3132 }
3133
3134 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3135 const Stmt *Body = FD->getBody();
3136 return Body ? Walker.Visit(Body) : false;
3137}
3138
3139bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3140 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3141 return true;
3142 const auto *F = cast<FunctionDecl>(GD.getDecl());
3143 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3144 return false;
3145
3146 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3147 // Check whether it would be safe to inline this dllimport function.
3148 DLLImportFunctionVisitor Visitor;
3149 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3150 if (!Visitor.SafeToInline)
3151 return false;
3152
3153 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3154 // Implicit destructor invocations aren't captured in the AST, so the
3155 // check above can't see them. Check for them manually here.
3156 for (const Decl *Member : Dtor->getParent()->decls())
3157 if (isa<FieldDecl>(Member))
3158 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3159 return false;
3160 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3161 if (HasNonDllImportDtor(B.getType()))
3162 return false;
3163 }
3164 }
3165
3166 // PR9614. Avoid cases where the source code is lying to us. An available
3167 // externally function should have an equivalent function somewhere else,
3168 // but a function that calls itself through asm label/`__builtin_` trickery is
3169 // clearly not equivalent to the real implementation.
3170 // This happens in glibc's btowc and in some configure checks.
3171 return !isTriviallyRecursive(F);
3172}
3173
3174bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3175 return CodeGenOpts.OptimizationLevel > 0;
3176}
3177
3178void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3179 llvm::GlobalValue *GV) {
3180 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3181
3182 if (FD->isCPUSpecificMultiVersion()) {
3183 auto *Spec = FD->getAttr<CPUSpecificAttr>();
3184 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3185 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3186 // Requires multiple emits.
3187 } else
3188 EmitGlobalFunctionDefinition(GD, GV);
3189}
3190
3191void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3192 const auto *D = cast<ValueDecl>(GD.getDecl());
3193
3194 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3195 Context.getSourceManager(),
3196 "Generating code for declaration");
3197
3198 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3199 // At -O0, don't generate IR for functions with available_externally
3200 // linkage.
3201 if (!shouldEmitFunction(GD))
3202 return;
3203
3204 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3205 std::string Name;
3206 llvm::raw_string_ostream OS(Name);
3207 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3208 /*Qualified=*/true);
3209 return Name;
3210 });
3211
3212 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3213 // Make sure to emit the definition(s) before we emit the thunks.
3214 // This is necessary for the generation of certain thunks.
3215 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3216 ABI->emitCXXStructor(GD);
3217 else if (FD->isMultiVersion())
3218 EmitMultiVersionFunctionDefinition(GD, GV);
3219 else
3220 EmitGlobalFunctionDefinition(GD, GV);
3221
3222 if (Method->isVirtual())
3223 getVTables().EmitThunks(GD);
3224
3225 return;
3226 }
3227
3228 if (FD->isMultiVersion())
3229 return EmitMultiVersionFunctionDefinition(GD, GV);
3230 return EmitGlobalFunctionDefinition(GD, GV);
3231 }
3232
3233 if (const auto *VD = dyn_cast<VarDecl>(D))
3234 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3235
3236 llvm_unreachable("Invalid argument to EmitGlobalDefinition()")::llvm::llvm_unreachable_internal("Invalid argument to EmitGlobalDefinition()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3236)
;
3237}
3238
3239static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3240 llvm::Function *NewFn);
3241
3242static unsigned
3243TargetMVPriority(const TargetInfo &TI,
3244 const CodeGenFunction::MultiVersionResolverOption &RO) {
3245 unsigned Priority = 0;
3246 for (StringRef Feat : RO.Conditions.Features)
3247 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3248
3249 if (!RO.Conditions.Architecture.empty())
3250 Priority = std::max(
3251 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3252 return Priority;
3253}
3254
3255void CodeGenModule::emitMultiVersionFunctions() {
3256 std::vector<GlobalDecl> MVFuncsToEmit;
3257 MultiVersionFuncs.swap(MVFuncsToEmit);
3258 for (GlobalDecl GD : MVFuncsToEmit) {
3259 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3260 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3261 getContext().forEachMultiversionedFunctionVersion(
3262 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3263 GlobalDecl CurGD{
3264 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3265 StringRef MangledName = getMangledName(CurGD);
3266 llvm::Constant *Func = GetGlobalValue(MangledName);
3267 if (!Func) {
3268 if (CurFD->isDefined()) {
3269 EmitGlobalFunctionDefinition(CurGD, nullptr);
3270 Func = GetGlobalValue(MangledName);
3271 } else {
3272 const CGFunctionInfo &FI =
3273 getTypes().arrangeGlobalDeclaration(GD);
3274 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3275 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3276 /*DontDefer=*/false, ForDefinition);
3277 }
3278 assert(Func && "This should have just been created")(static_cast <bool> (Func && "This should have just been created"
) ? void (0) : __assert_fail ("Func && \"This should have just been created\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3278, __extension__ __PRETTY_FUNCTION__))
;
3279 }
3280
3281 const auto *TA = CurFD->getAttr<TargetAttr>();
3282 llvm::SmallVector<StringRef, 8> Feats;
3283 TA->getAddedFeatures(Feats);
3284
3285 Options.emplace_back(cast<llvm::Function>(Func),
3286 TA->getArchitecture(), Feats);
3287 });
3288
3289 llvm::Function *ResolverFunc;
3290 const TargetInfo &TI = getTarget();
3291
3292 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
3293 ResolverFunc = cast<llvm::Function>(
3294 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3295 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3296 } else {
3297 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3298 }
3299
3300 if (supportsCOMDAT())
3301 ResolverFunc->setComdat(
3302 getModule().getOrInsertComdat(ResolverFunc->getName()));
3303
3304 llvm::stable_sort(
3305 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3306 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3307 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3308 });
3309 CodeGenFunction CGF(*this);
3310 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3311 }
3312
3313 // Ensure that any additions to the deferred decls list caused by emitting a
3314 // variant are emitted. This can happen when the variant itself is inline and
3315 // calls a function without linkage.
3316 if (!MVFuncsToEmit.empty())
3317 EmitDeferred();
3318
3319 // Ensure that any additions to the multiversion funcs list from either the
3320 // deferred decls or the multiversion functions themselves are emitted.
3321 if (!MultiVersionFuncs.empty())
3322 emitMultiVersionFunctions();
3323}
3324
3325void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3326 const auto *FD = cast<FunctionDecl>(GD.getDecl());
28
The object is a 'FunctionDecl'
3327 assert(FD && "Not a FunctionDecl?")(static_cast <bool> (FD && "Not a FunctionDecl?"
) ? void (0) : __assert_fail ("FD && \"Not a FunctionDecl?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3327, __extension__ __PRETTY_FUNCTION__))
;
29
'?' condition is true
3328 const auto *DD = FD->getAttr<CPUDispatchAttr>();
3329 assert(DD && "Not a cpu_dispatch Function?")(static_cast <bool> (DD && "Not a cpu_dispatch Function?"
) ? void (0) : __assert_fail ("DD && \"Not a cpu_dispatch Function?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3329, __extension__ __PRETTY_FUNCTION__))
;
30
Assuming 'DD' is non-null
31
'?' condition is true
3330 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3331
3332 if (const auto *CXXFD
32.1
'CXXFD' is null
32.1
'CXXFD' is null
32.1
'CXXFD' is null
32.1
'CXXFD' is null
= dyn_cast<CXXMethodDecl>(FD)) {
32
Assuming 'FD' is not a 'CXXMethodDecl'
33
Taking false branch
3333 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3334 DeclTy = getTypes().GetFunctionType(FInfo);
3335 }
3336
3337 StringRef ResolverName = getMangledName(GD);
3338
3339 llvm::Type *ResolverType;
3340 GlobalDecl ResolverGD;
3341 if (getTarget().supportsIFunc())
34
Taking false branch
3342 ResolverType = llvm::FunctionType::get(
3343 llvm::PointerType::get(DeclTy,
3344 Context.getTargetAddressSpace(FD->getType())),
3345 false);
3346 else {
3347 ResolverType = DeclTy;
3348 ResolverGD = GD;
3349 }
3350
3351 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
35
The object is a 'Function'
3352 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3353 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3354 if (supportsCOMDAT())
36
Assuming the condition is false
37
Taking false branch
3355 ResolverFunc->setComdat(
3356 getModule().getOrInsertComdat(ResolverFunc->getName()));
3357
3358 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3359 const TargetInfo &Target = getTarget();
3360 unsigned Index = 0;
3361 for (const IdentifierInfo *II : DD->cpus()) {
38
Assuming '__begin1' is not equal to '__end1'
3362 // Get the name of the target function so we can look it up/create it.
3363 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3364 getCPUSpecificMangling(*this, II->getName());
3365
3366 llvm::Constant *Func = GetGlobalValue(MangledName);
3367
3368 if (!Func) {
39
Assuming 'Func' is null
40
Taking true branch
3369 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3370 if (ExistingDecl.getDecl() &&
41
Assuming the condition is false
3371 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3372 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3373 Func = GetGlobalValue(MangledName);
3374 } else {
3375 if (!ExistingDecl.getDecl())
42
Assuming the condition is false
43
Taking false branch
3376 ExistingDecl = GD.getWithMultiVersionIndex(Index);
3377
3378 Func = GetOrCreateLLVMFunction(
44
Calling 'CodeGenModule::GetOrCreateLLVMFunction'
3379 MangledName, DeclTy, ExistingDecl,
3380 /*ForVTable=*/false, /*DontDefer=*/true,
3381 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3382 }
3383 }
3384
3385 llvm::SmallVector<StringRef, 32> Features;
3386 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3387 llvm::transform(Features, Features.begin(),
3388 [](StringRef Str) { return Str.substr(1); });
3389 Features.erase(std::remove_if(
3390 Features.begin(), Features.end(), [&Target](StringRef Feat) {
3391 return !Target.validateCpuSupports(Feat);
3392 }), Features.end());
3393 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3394 ++Index;
3395 }
3396
3397 llvm::stable_sort(
3398 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3399 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3400 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3401 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3402 });
3403
3404 // If the list contains multiple 'default' versions, such as when it contains
3405 // 'pentium' and 'generic', don't emit the call to the generic one (since we
3406 // always run on at least a 'pentium'). We do this by deleting the 'least
3407 // advanced' (read, lowest mangling letter).
3408 while (Options.size() > 1 &&
3409 CodeGenFunction::GetX86CpuSupportsMask(
3410 (Options.end() - 2)->Conditions.Features) == 0) {
3411 StringRef LHSName = (Options.end() - 2)->Function->getName();
3412 StringRef RHSName = (Options.end() - 1)->Function->getName();
3413 if (LHSName.compare(RHSName) < 0)
3414 Options.erase(Options.end() - 2);
3415 else
3416 Options.erase(Options.end() - 1);
3417 }
3418
3419 CodeGenFunction CGF(*this);
3420 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3421
3422 if (getTarget().supportsIFunc()) {
3423 std::string AliasName = getMangledNameImpl(
3424 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3425 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3426 if (!AliasFunc) {
3427 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3428 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3429 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3430 auto *GA = llvm::GlobalAlias::create(
3431 DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3432 GA->setLinkage(llvm::Function::WeakODRLinkage);
3433 SetCommonAttributes(GD, GA);
3434 }
3435 }
3436}
3437
3438/// If a dispatcher for the specified mangled name is not in the module, create
3439/// and return an llvm Function with the specified type.
3440llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3441 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3442 std::string MangledName =
3443 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3444
3445 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3446 // a separate resolver).
3447 std::string ResolverName = MangledName;
3448 if (getTarget().supportsIFunc())
3449 ResolverName += ".ifunc";
3450 else if (FD->isTargetMultiVersion())
3451 ResolverName += ".resolver";
3452
3453 // If this already exists, just return that one.
3454 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3455 return ResolverGV;
3456
3457 // Since this is the first time we've created this IFunc, make sure
3458 // that we put this multiversioned function into the list to be
3459 // replaced later if necessary (target multiversioning only).
3460 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3461 MultiVersionFuncs.push_back(GD);
3462
3463 if (getTarget().supportsIFunc()) {
3464 llvm::Type *ResolverType = llvm::FunctionType::get(
3465 llvm::PointerType::get(
3466 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3467 false);
3468 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3469 MangledName + ".resolver", ResolverType, GlobalDecl{},
3470 /*ForVTable=*/false);
3471 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3472 DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3473 GIF->setName(ResolverName);
3474 SetCommonAttributes(FD, GIF);
3475
3476 return GIF;
3477 }
3478
3479 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3480 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3481 assert(isa<llvm::GlobalValue>(Resolver) &&(static_cast <bool> (isa<llvm::GlobalValue>(Resolver
) && "Resolver should be created for the first time")
? void (0) : __assert_fail ("isa<llvm::GlobalValue>(Resolver) && \"Resolver should be created for the first time\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3482, __extension__ __PRETTY_FUNCTION__))
3482 "Resolver should be created for the first time")(static_cast <bool> (isa<llvm::GlobalValue>(Resolver
) && "Resolver should be created for the first time")
? void (0) : __assert_fail ("isa<llvm::GlobalValue>(Resolver) && \"Resolver should be created for the first time\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3482, __extension__ __PRETTY_FUNCTION__))
;
3483 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3484 return Resolver;
3485}
3486
3487/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3488/// module, create and return an llvm Function with the specified type. If there
3489/// is something in the module with the specified name, return it potentially
3490/// bitcasted to the right type.
3491///
3492/// If D is non-null, it specifies a decl that correspond to this. This is used
3493/// to set the attributes on the function when it is first created.
3494llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3495 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3496 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3497 ForDefinition_t IsForDefinition) {
3498 const Decl *D = GD.getDecl();
45
Calling 'GlobalDecl::getDecl'
57
Returning from 'GlobalDecl::getDecl'
58
'D' initialized here
3499
3500 // Any attempts to use a MultiVersion function should result in retrieving
3501 // the iFunc instead. Name Mangling will handle the rest of the changes.
3502 if (const FunctionDecl *FD
9.1
'FD' is non-null
60.1
'FD' is null
9.1
'FD' is non-null
60.1
'FD' is null
9.1
'FD' is non-null
60.1
'FD' is null
9.1
'FD' is non-null
60.1
'FD' is null
= cast_or_null<FunctionDecl>(D)) {
9
Assuming 'D' is a 'FunctionDecl'
10
Taking true branch
59
Assuming null pointer is passed into cast
60
Assuming pointer value is null
61
Taking false branch
3503 // For the device mark the function as one that should be emitted.
3504 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
11
Assuming field 'OpenMPIsDevice' is not equal to 0
14
Taking true branch
3505 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
12
Assuming the condition is true
13
Assuming the condition is true
3506 !DontDefer
13.1
'DontDefer' is false
13.1
'DontDefer' is false
13.1
'DontDefer' is false
13.1
'DontDefer' is false
&& !IsForDefinition
13.2
'IsForDefinition' is 0
13.2
'IsForDefinition' is 0
13.2
'IsForDefinition' is 0
13.2
'IsForDefinition' is 0
) {
3507 if (const FunctionDecl *FDDef = FD->getDefinition()) {
15
Assuming 'FDDef' is non-null
16
Taking true branch
3508 GlobalDecl GDDef;
3509 if (const auto *CD
17.1
'CD' is null
17.1
'CD' is null
17.1
'CD' is null
17.1
'CD' is null
= dyn_cast<CXXConstructorDecl>(FDDef))
17
Assuming 'FDDef' is not a 'CXXConstructorDecl'
18
Taking false branch
3510 GDDef = GlobalDecl(CD, GD.getCtorType());
3511 else if (const auto *DD
19.1
'DD' is null
19.1
'DD' is null
19.1
'DD' is null
19.1
'DD' is null
= dyn_cast<CXXDestructorDecl>(FDDef))
19
Assuming 'FDDef' is not a 'CXXDestructorDecl'
20
Taking false branch
3512 GDDef = GlobalDecl(DD, GD.getDtorType());
3513 else
3514 GDDef = GlobalDecl(FDDef);
3515 EmitGlobal(GDDef);
21
Calling 'CodeGenModule::EmitGlobal'
3516 }
3517 }
3518
3519 if (FD->isMultiVersion()) {
3520 if (FD->hasAttr<TargetAttr>())
3521 UpdateMultiVersionNames(GD, FD);
3522 if (!IsForDefinition)
3523 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3524 }
3525 }
3526
3527 // Lookup the entry, lazily creating it if necessary.
3528 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3529 if (Entry) {
62
Assuming 'Entry' is non-null
63
Taking true branch
3530 if (WeakRefReferences.erase(Entry)) {
64
Assuming the condition is false
65
Taking false branch
3531 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3532 if (FD && !FD->hasAttr<WeakAttr>())
3533 Entry->setLinkage(llvm::Function::ExternalLinkage);
3534 }
3535
3536 // Handle dropped DLL attributes.
3537 if (D
65.1
'D' is null
65.1
'D' is null
65.1
'D' is null
65.1
'D' is null
&& !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3538 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3539 setDSOLocal(Entry);
3540 }
3541
3542 // If there are two attempts to define the same mangled name, issue an
3543 // error.
3544 if (IsForDefinition
65.2
'IsForDefinition' is 1
65.2
'IsForDefinition' is 1
65.2
'IsForDefinition' is 1
65.2
'IsForDefinition' is 1
&& !Entry->isDeclaration()) {
66
Assuming the condition is true
67
Taking true branch
3545 GlobalDecl OtherGD;
3546 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3547 // to make sure that we issue an error only once.
3548 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
68
Assuming the condition is true
70
Assuming the condition is true
71
Taking true branch
3549 (GD.getCanonicalDecl().getDecl() !=
69
Assuming the condition is true
3550 OtherGD.getCanonicalDecl().getDecl()) &&
3551 DiagnosedConflictingDefinitions.insert(GD).second) {
3552 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
72
Called C++ object pointer is null
3553 << MangledName;
3554 getDiags().Report(OtherGD.getDecl()->getLocation(),
3555 diag::note_previous_definition);
3556 }
3557 }
3558
3559 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3560 (Entry->getValueType() == Ty)) {
3561 return Entry;
3562 }
3563
3564 // Make sure the result is of the correct type.
3565 // (If function is requested for a definition, we always need to create a new
3566 // function, not just return a bitcast.)
3567 if (!IsForDefinition)
3568 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3569 }
3570
3571 // This function doesn't have a complete type (for example, the return
3572 // type is an incomplete struct). Use a fake type instead, and make
3573 // sure not to try to set attributes.
3574 bool IsIncompleteFunction = false;
3575
3576 llvm::FunctionType *FTy;
3577 if (isa<llvm::FunctionType>(Ty)) {
3578 FTy = cast<llvm::FunctionType>(Ty);
3579 } else {
3580 FTy = llvm::FunctionType::get(VoidTy, false);
3581 IsIncompleteFunction = true;
3582 }
3583
3584 llvm::Function *F =
3585 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3586 Entry ? StringRef() : MangledName, &getModule());
3587
3588 // If we already created a function with the same mangled name (but different
3589 // type) before, take its name and add it to the list of functions to be
3590 // replaced with F at the end of CodeGen.
3591 //
3592 // This happens if there is a prototype for a function (e.g. "int f()") and
3593 // then a definition of a different type (e.g. "int f(int x)").
3594 if (Entry) {
3595 F->takeName(Entry);
3596
3597 // This might be an implementation of a function without a prototype, in
3598 // which case, try to do special replacement of calls which match the new
3599 // prototype. The really key thing here is that we also potentially drop
3600 // arguments from the call site so as to make a direct call, which makes the
3601 // inliner happier and suppresses a number of optimizer warnings (!) about
3602 // dropping arguments.
3603 if (!Entry->use_empty()) {
3604 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3605 Entry->removeDeadConstantUsers();
3606 }
3607
3608 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3609 F, Entry->getValueType()->getPointerTo());
3610 addGlobalValReplacement(Entry, BC);
3611 }
3612
3613 assert(F->getName() == MangledName && "name was uniqued!")(static_cast <bool> (F->getName() == MangledName &&
"name was uniqued!") ? void (0) : __assert_fail ("F->getName() == MangledName && \"name was uniqued!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3613, __extension__ __PRETTY_FUNCTION__))
;
3614 if (D)
3615 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3616 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3617 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3618 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3619 }
3620
3621 if (!DontDefer) {
3622 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3623 // each other bottoming out with the base dtor. Therefore we emit non-base
3624 // dtors on usage, even if there is no dtor definition in the TU.
3625 if (D && isa<CXXDestructorDecl>(D) &&
3626 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3627 GD.getDtorType()))
3628 addDeferredDeclToEmit(GD);
3629
3630 // This is the first use or definition of a mangled name. If there is a
3631 // deferred decl with this name, remember that we need to emit it at the end
3632 // of the file.
3633 auto DDI = DeferredDecls.find(MangledName);
3634 if (DDI != DeferredDecls.end()) {
3635 // Move the potentially referenced deferred decl to the
3636 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3637 // don't need it anymore).
3638 addDeferredDeclToEmit(DDI->second);
3639 DeferredDecls.erase(DDI);
3640
3641 // Otherwise, there are cases we have to worry about where we're
3642 // using a declaration for which we must emit a definition but where
3643 // we might not find a top-level definition:
3644 // - member functions defined inline in their classes
3645 // - friend functions defined inline in some class
3646 // - special member functions with implicit definitions
3647 // If we ever change our AST traversal to walk into class methods,
3648 // this will be unnecessary.
3649 //
3650 // We also don't emit a definition for a function if it's going to be an
3651 // entry in a vtable, unless it's already marked as used.
3652 } else if (getLangOpts().CPlusPlus && D) {
3653 // Look for a declaration that's lexically in a record.
3654 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3655 FD = FD->getPreviousDecl()) {
3656 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3657 if (FD->doesThisDeclarationHaveABody()) {
3658 addDeferredDeclToEmit(GD.getWithDecl(FD));
3659 break;
3660 }
3661 }
3662 }
3663 }
3664 }
3665
3666 // Make sure the result is of the requested type.
3667 if (!IsIncompleteFunction) {
3668 assert(F->getFunctionType() == Ty)(static_cast <bool> (F->getFunctionType() == Ty) ? void
(0) : __assert_fail ("F->getFunctionType() == Ty", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3668, __extension__ __PRETTY_FUNCTION__))
;
3669 return F;
3670 }
3671
3672 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3673 return llvm::ConstantExpr::getBitCast(F, PTy);
3674}
3675
3676/// GetAddrOfFunction - Return the address of the given function. If Ty is
3677/// non-null, then this function will use the specified type if it has to
3678/// create it (this occurs when we see a definition of the function).
3679llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3680 llvm::Type *Ty,
3681 bool ForVTable,
3682 bool DontDefer,
3683 ForDefinition_t IsForDefinition) {
3684 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&(static_cast <bool> (!cast<FunctionDecl>(GD.getDecl
())->isConsteval() && "consteval function should never be emitted"
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(GD.getDecl())->isConsteval() && \"consteval function should never be emitted\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3685, __extension__ __PRETTY_FUNCTION__))
3685 "consteval function should never be emitted")(static_cast <bool> (!cast<FunctionDecl>(GD.getDecl
())->isConsteval() && "consteval function should never be emitted"
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(GD.getDecl())->isConsteval() && \"consteval function should never be emitted\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 3685, __extension__ __PRETTY_FUNCTION__))
;
3686 // If there was no specific requested type, just convert it now.
3687 if (!Ty) {
3688 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3689 Ty = getTypes().ConvertType(FD->getType());
3690 }
3691
3692 // Devirtualized destructor calls may come through here instead of via
3693 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3694 // of the complete destructor when necessary.
3695 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3696 if (getTarget().getCXXABI().isMicrosoft() &&
3697 GD.getDtorType() == Dtor_Complete &&
3698 DD->getParent()->getNumVBases() == 0)
3699 GD = GlobalDecl(DD, Dtor_Base);
3700 }
3701
3702 StringRef MangledName = getMangledName(GD);
3703 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3704 /*IsThunk=*/false, llvm::AttributeList(),
3705 IsForDefinition);
3706 // Returns kernel handle for HIP kernel stub function.
3707 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
3708 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
3709 auto *Handle = getCUDARuntime().getKernelHandle(
3710 cast<llvm::Function>(F->stripPointerCasts()), GD);
3711 if (IsForDefinition)
3712 return F;
3713 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3714 }
3715 return F;
3716}
3717
3718static const FunctionDecl *
3719GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3720 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3721 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3722
3723 IdentifierInfo &CII = C.Idents.get(Name);
3724 for (const auto *Result : DC->lookup(&CII))
3725 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3726 return FD;
3727
3728 if (!C.getLangOpts().CPlusPlus)
3729 return nullptr;
3730
3731 // Demangle the premangled name from getTerminateFn()
3732 IdentifierInfo &CXXII =
3733 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3734 ? C.Idents.get("terminate")
3735 : C.Idents.get(Name);
3736
3737 for (const auto &N : {"__cxxabiv1", "std"}) {
3738 IdentifierInfo &NS = C.Idents.get(N);
3739 for (const auto *Result : DC->lookup(&NS)) {
3740 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3741 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3742 for (const auto *Result : LSD->lookup(&NS))
3743 if ((ND = dyn_cast<NamespaceDecl>(Result)))
3744 break;
3745
3746 if (ND)
3747 for (const auto *Result : ND->lookup(&CXXII))
3748 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3749 return FD;
3750 }
3751 }
3752
3753 return nullptr;
3754}
3755
3756/// CreateRuntimeFunction - Create a new runtime function with the specified
3757/// type and name.
3758llvm::FunctionCallee
3759CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3760 llvm::AttributeList ExtraAttrs, bool Local,
3761 bool AssumeConvergent) {
3762 if (AssumeConvergent) {
3763 ExtraAttrs =
3764 ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3765 llvm::Attribute::Convergent);
3766 }
3767
3768 llvm::Constant *C =
3769 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3770 /*DontDefer=*/false, /*IsThunk=*/false,
3771 ExtraAttrs);
3772
3773 if (auto *F = dyn_cast<llvm::Function>(C)) {
3774 if (F->empty()) {
3775 F->setCallingConv(getRuntimeCC());
3776
3777 // In Windows Itanium environments, try to mark runtime functions
3778 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3779 // will link their standard library statically or dynamically. Marking
3780 // functions imported when they are not imported can cause linker errors
3781 // and warnings.
3782 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3783 !getCodeGenOpts().LTOVisibilityPublicStd) {
3784 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3785 if (!FD || FD->hasAttr<DLLImportAttr>()) {
3786 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3787 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3788 }
3789 }
3790 setDSOLocal(F);
3791 }
3792 }
3793
3794 return {FTy, C};
3795}
3796
3797/// isTypeConstant - Determine whether an object of this type can be emitted
3798/// as a constant.
3799///
3800/// If ExcludeCtor is true, the duration when the object's constructor runs
3801/// will not be considered. The caller will need to verify that the object is
3802/// not written to during its construction.
3803bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3804 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3805 return false;
3806
3807 if (Context.getLangOpts().CPlusPlus) {
3808 if (const CXXRecordDecl *Record
3809 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3810 return ExcludeCtor && !Record->hasMutableFields() &&
3811 Record->hasTrivialDestructor();
3812 }
3813
3814 return true;
3815}
3816
3817/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3818/// create and return an llvm GlobalVariable with the specified type and address
3819/// space. If there is something in the module with the specified name, return
3820/// it potentially bitcasted to the right type.
3821///
3822/// If D is non-null, it specifies a decl that correspond to this. This is used
3823/// to set the attributes on the global when it is first created.
3824///
3825/// If IsForDefinition is true, it is guaranteed that an actual global with
3826/// type Ty will be returned, not conversion of a variable with the same
3827/// mangled name but some other type.
3828llvm::Constant *
3829CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
3830 unsigned AddrSpace, const VarDecl *D,
3831 ForDefinition_t IsForDefinition) {
3832 // Lookup the entry, lazily creating it if necessary.
3833 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3834 if (Entry) {
3835 if (WeakRefReferences.erase(Entry)) {
3836 if (D && !D->hasAttr<WeakAttr>())
3837 Entry->setLinkage(llvm::Function::ExternalLinkage);
3838 }
3839
3840 // Handle dropped DLL attributes.
3841 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3842 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3843
3844 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3845 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3846
3847 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == AddrSpace)
3848 return Entry;
3849
3850 // If there are two attempts to define the same mangled name, issue an
3851 // error.
3852 if (IsForDefinition && !Entry->isDeclaration()) {
3853 GlobalDecl OtherGD;
3854 const VarDecl *OtherD;
3855
3856 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3857 // to make sure that we issue an error only once.
3858 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3859 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3860 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3861 OtherD->hasInit() &&
3862 DiagnosedConflictingDefinitions.insert(D).second) {
3863 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3864 << MangledName;
3865 getDiags().Report(OtherGD.getDecl()->getLocation(),
3866 diag::note_previous_definition);
3867 }
3868 }
3869
3870 // Make sure the result is of the correct type.
3871 if (Entry->getType()->getAddressSpace() != AddrSpace) {
3872 return llvm::ConstantExpr::getAddrSpaceCast(Entry,
3873 Ty->getPointerTo(AddrSpace));
3874 }
3875
3876 // (If global is requested for a definition, we always need to create a new
3877 // global, not just return a bitcast.)
3878 if (!IsForDefinition)
3879 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(AddrSpace));
3880 }
3881
3882 auto DAddrSpace = GetGlobalVarAddressSpace(D);
3883 auto TargetAddrSpace = getContext().getTargetAddressSpace(DAddrSpace);
3884
3885 auto *GV = new llvm::GlobalVariable(
3886 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
3887 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
3888 TargetAddrSpace);
3889
3890 // If we already created a global with the same mangled name (but different
3891 // type) before, take its name and remove it from its parent.
3892 if (Entry) {
3893 GV->takeName(Entry);
3894
3895 if (!Entry->use_empty()) {
3896 llvm::Constant *NewPtrForOldDecl =
3897 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3898 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3899 }
3900
3901 Entry->eraseFromParent();
3902 }
3903
3904 // This is the first use or definition of a mangled name. If there is a
3905 // deferred decl with this name, remember that we need to emit it at the end
3906 // of the file.
3907 auto DDI = DeferredDecls.find(MangledName);
3908 if (DDI != DeferredDecls.end()) {
3909 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3910 // list, and remove it from DeferredDecls (since we don't need it anymore).
3911 addDeferredDeclToEmit(DDI->second);
3912 DeferredDecls.erase(DDI);
3913 }
3914
3915 // Handle things which are present even on external declarations.
3916 if (D) {
3917 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3918 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3919
3920 // FIXME: This code is overly simple and should be merged with other global
3921 // handling.
3922 GV->setConstant(isTypeConstant(D->getType(), false));
3923
3924 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3925
3926 setLinkageForGV(GV, D);
3927
3928 if (D->getTLSKind()) {
3929 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3930 CXXThreadLocals.push_back(D);
3931 setTLSMode(GV, *D);
3932 }
3933
3934 setGVProperties(GV, D);
3935
3936 // If required by the ABI, treat declarations of static data members with
3937 // inline initializers as definitions.
3938 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3939 EmitGlobalVarDefinition(D);
3940 }
3941
3942 // Emit section information for extern variables.
3943 if (D->hasExternalStorage()) {
3944 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3945 GV->setSection(SA->getName());
3946 }
3947
3948 // Handle XCore specific ABI requirements.
3949 if (getTriple().getArch() == llvm::Triple::xcore &&
3950 D->getLanguageLinkage() == CLanguageLinkage &&
3951 D->getType().isConstant(Context) &&
3952 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3953 GV->setSection(".cp.rodata");
3954
3955 // Check if we a have a const declaration with an initializer, we may be
3956 // able to emit it as available_externally to expose it's value to the
3957 // optimizer.
3958 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3959 D->getType().isConstQualified() && !GV->hasInitializer() &&
3960 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3961 const auto *Record =
3962 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3963 bool HasMutableFields = Record && Record->hasMutableFields();
3964 if (!HasMutableFields) {
3965 const VarDecl *InitDecl;
3966 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3967 if (InitExpr) {
3968 ConstantEmitter emitter(*this);
3969 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3970 if (Init) {
3971 auto *InitType = Init->getType();
3972 if (GV->getValueType() != InitType) {
3973 // The type of the initializer does not match the definition.
3974 // This happens when an initializer has a different type from
3975 // the type of the global (because of padding at the end of a
3976 // structure for instance).
3977 GV->setName(StringRef());
3978 // Make a new global with the correct type, this is now guaranteed
3979 // to work.
3980 auto *NewGV = cast<llvm::GlobalVariable>(
3981 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3982 ->stripPointerCasts());
3983
3984 // Erase the old global, since it is no longer used.
3985 GV->eraseFromParent();
3986 GV = NewGV;
3987 } else {
3988 GV->setInitializer(Init);
3989 GV->setConstant(true);
3990 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3991 }
3992 emitter.finalize(GV);
3993 }
3994 }
3995 }
3996 }
3997 }
3998
3999 if (GV->isDeclaration()) {
4000 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4001 // External HIP managed variables needed to be recorded for transformation
4002 // in both device and host compilations.
4003 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4004 D->hasExternalStorage())
4005 getCUDARuntime().handleVarRegistration(D, *GV);
4006 }
4007
4008 LangAS ExpectedAS =
4009 D ? D->getType().getAddressSpace()
4010 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4011 assert(getContext().getTargetAddressSpace(ExpectedAS) == AddrSpace)(static_cast <bool> (getContext().getTargetAddressSpace
(ExpectedAS) == AddrSpace) ? void (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == AddrSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4011, __extension__ __PRETTY_FUNCTION__))
;
4012 if (DAddrSpace != ExpectedAS) {
4013 return getTargetCodeGenInfo().performAddrSpaceCast(
4014 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(AddrSpace));
4015 }
4016
4017 return GV;
4018}
4019
4020llvm::Constant *
4021CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4022 const Decl *D = GD.getDecl();
4023
4024 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4025 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4026 /*DontDefer=*/false, IsForDefinition);
4027
4028 if (isa<CXXMethodDecl>(D)) {
4029 auto FInfo =
4030 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4031 auto Ty = getTypes().GetFunctionType(*FInfo);
4032 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4033 IsForDefinition);
4034 }
4035
4036 if (isa<FunctionDecl>(D)) {
4037 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4038 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4039 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4040 IsForDefinition);
4041 }
4042
4043 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4044}
4045
4046llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4047 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4048 unsigned Alignment) {
4049 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4050 llvm::GlobalVariable *OldGV = nullptr;
4051
4052 if (GV) {
4053 // Check if the variable has the right type.
4054 if (GV->getValueType() == Ty)
4055 return GV;
4056
4057 // Because C++ name mangling, the only way we can end up with an already
4058 // existing global with the same name is if it has been declared extern "C".
4059 assert(GV->isDeclaration() && "Declaration has wrong type!")(static_cast <bool> (GV->isDeclaration() && "Declaration has wrong type!"
) ? void (0) : __assert_fail ("GV->isDeclaration() && \"Declaration has wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4059, __extension__ __PRETTY_FUNCTION__))
;
4060 OldGV = GV;
4061 }
4062
4063 // Create a new variable.
4064 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4065 Linkage, nullptr, Name);
4066
4067 if (OldGV) {
4068 // Replace occurrences of the old variable if needed.
4069 GV->takeName(OldGV);
4070
4071 if (!OldGV->use_empty()) {
4072 llvm::Constant *NewPtrForOldDecl =
4073 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4074 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4075 }
4076
4077 OldGV->eraseFromParent();
4078 }
4079
4080 if (supportsCOMDAT() && GV->isWeakForLinker() &&
4081 !GV->hasAvailableExternallyLinkage())
4082 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4083
4084 GV->setAlignment(llvm::MaybeAlign(Alignment));
4085
4086 return GV;
4087}
4088
4089/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4090/// given global variable. If Ty is non-null and if the global doesn't exist,
4091/// then it will be created with the specified type instead of whatever the
4092/// normal requested type would be. If IsForDefinition is true, it is guaranteed
4093/// that an actual global with type Ty will be returned, not conversion of a
4094/// variable with the same mangled name but some other type.
4095llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4096 llvm::Type *Ty,
4097 ForDefinition_t IsForDefinition) {
4098 assert(D->hasGlobalStorage() && "Not a global variable")(static_cast <bool> (D->hasGlobalStorage() &&
"Not a global variable") ? void (0) : __assert_fail ("D->hasGlobalStorage() && \"Not a global variable\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4098, __extension__ __PRETTY_FUNCTION__))
;
4099 QualType ASTTy = D->getType();
4100 if (!Ty)
4101 Ty = getTypes().ConvertTypeForMem(ASTTy);
4102
4103 StringRef MangledName = getMangledName(D);
4104 return GetOrCreateLLVMGlobal(MangledName, Ty,
4105 getContext().getTargetAddressSpace(ASTTy), D,
4106 IsForDefinition);
4107}
4108
4109/// CreateRuntimeVariable - Create a new runtime global variable with the
4110/// specified type and name.
4111llvm::Constant *
4112CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4113 StringRef Name) {
4114 auto AddrSpace =
4115 getContext().getLangOpts().OpenCL
4116 ? getContext().getTargetAddressSpace(LangAS::opencl_global)
4117 : 0;
4118 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4119 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4120 return Ret;
4121}
4122
4123void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4124 assert(!D->getInit() && "Cannot emit definite definitions here!")(static_cast <bool> (!D->getInit() && "Cannot emit definite definitions here!"
) ? void (0) : __assert_fail ("!D->getInit() && \"Cannot emit definite definitions here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4124, __extension__ __PRETTY_FUNCTION__))
;
4125
4126 StringRef MangledName = getMangledName(D);
4127 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4128
4129 // We already have a definition, not declaration, with the same mangled name.
4130 // Emitting of declaration is not required (and actually overwrites emitted
4131 // definition).
4132 if (GV && !GV->isDeclaration())
4133 return;
4134
4135 // If we have not seen a reference to this variable yet, place it into the
4136 // deferred declarations table to be emitted if needed later.
4137 if (!MustBeEmitted(D) && !GV) {
4138 DeferredDecls[MangledName] = D;
4139 return;
4140 }
4141
4142 // The tentative definition is the only definition.
4143 EmitGlobalVarDefinition(D);
4144}
4145
4146void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4147 EmitExternalVarDeclaration(D);
4148}
4149
4150CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4151 return Context.toCharUnitsFromBits(
4152 getDataLayout().getTypeStoreSizeInBits(Ty));
4153}
4154
4155LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4156 LangAS AddrSpace = LangAS::Default;
4157 if (LangOpts.OpenCL) {
4158 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4159 assert(AddrSpace == LangAS::opencl_global ||(static_cast <bool> (AddrSpace == LangAS::opencl_global
|| AddrSpace == LangAS::opencl_global_device || AddrSpace ==
LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant
|| AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS
::FirstTargetAddressSpace) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
4160 AddrSpace == LangAS::opencl_global_device ||(static_cast <bool> (AddrSpace == LangAS::opencl_global
|| AddrSpace == LangAS::opencl_global_device || AddrSpace ==
LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant
|| AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS
::FirstTargetAddressSpace) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
4161 AddrSpace == LangAS::opencl_global_host ||(static_cast <bool> (AddrSpace == LangAS::opencl_global
|| AddrSpace == LangAS::opencl_global_device || AddrSpace ==
LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant
|| AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS
::FirstTargetAddressSpace) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
4162 AddrSpace == LangAS::opencl_constant ||(static_cast <bool> (AddrSpace == LangAS::opencl_global
|| AddrSpace == LangAS::opencl_global_device || AddrSpace ==
LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant
|| AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS
::FirstTargetAddressSpace) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
4163 AddrSpace == LangAS::opencl_local ||(static_cast <bool> (AddrSpace == LangAS::opencl_global
|| AddrSpace == LangAS::opencl_global_device || AddrSpace ==
LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant
|| AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS
::FirstTargetAddressSpace) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
4164 AddrSpace >= LangAS::FirstTargetAddressSpace)(static_cast <bool> (AddrSpace == LangAS::opencl_global
|| AddrSpace == LangAS::opencl_global_device || AddrSpace ==
LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant
|| AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS
::FirstTargetAddressSpace) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
;
4165 return AddrSpace;
4166 }
4167
4168 if (LangOpts.SYCLIsDevice &&
4169 (!D || D->getType().getAddressSpace() == LangAS::Default))
4170 return LangAS::sycl_global;
4171
4172 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4173 if (D && D->hasAttr<CUDAConstantAttr>())
4174 return LangAS::cuda_constant;
4175 else if (D && D->hasAttr<CUDASharedAttr>())
4176 return LangAS::cuda_shared;
4177 else if (D && D->hasAttr<CUDADeviceAttr>())
4178 return LangAS::cuda_device;
4179 else if (D && D->getType().isConstQualified())
4180 return LangAS::cuda_constant;
4181 else
4182 return LangAS::cuda_device;
4183 }
4184
4185 if (LangOpts.OpenMP) {
4186 LangAS AS;
4187 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4188 return AS;
4189 }
4190 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4191}
4192
4193LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4194 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4195 if (LangOpts.OpenCL)
4196 return LangAS::opencl_constant;
4197 if (LangOpts.SYCLIsDevice)
4198 return LangAS::sycl_global;
4199 if (auto AS = getTarget().getConstantAddressSpace())
4200 return AS.getValue();
4201 return LangAS::Default;
4202}
4203
4204// In address space agnostic languages, string literals are in default address
4205// space in AST. However, certain targets (e.g. amdgcn) request them to be
4206// emitted in constant address space in LLVM IR. To be consistent with other
4207// parts of AST, string literal global variables in constant address space
4208// need to be casted to default address space before being put into address
4209// map and referenced by other part of CodeGen.
4210// In OpenCL, string literals are in constant address space in AST, therefore
4211// they should not be casted to default address space.
4212static llvm::Constant *
4213castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4214 llvm::GlobalVariable *GV) {
4215 llvm::Constant *Cast = GV;
4216 if (!CGM.getLangOpts().OpenCL) {
4217 auto AS = CGM.GetGlobalConstantAddressSpace();
4218 if (AS != LangAS::Default)
4219 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4220 CGM, GV, AS, LangAS::Default,
4221 GV->getValueType()->getPointerTo(
4222 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4223 }
4224 return Cast;
4225}
4226
4227template<typename SomeDecl>
4228void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4229 llvm::GlobalValue *GV) {
4230 if (!getLangOpts().CPlusPlus)
4231 return;
4232
4233 // Must have 'used' attribute, or else inline assembly can't rely on
4234 // the name existing.
4235 if (!D->template hasAttr<UsedAttr>())
4236 return;
4237
4238 // Must have internal linkage and an ordinary name.
4239 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4240 return;
4241
4242 // Must be in an extern "C" context. Entities declared directly within
4243 // a record are not extern "C" even if the record is in such a context.
4244 const SomeDecl *First = D->getFirstDecl();
4245 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4246 return;
4247
4248 // OK, this is an internal linkage entity inside an extern "C" linkage
4249 // specification. Make a note of that so we can give it the "expected"
4250 // mangled name if nothing else is using that name.
4251 std::pair<StaticExternCMap::iterator, bool> R =
4252 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4253
4254 // If we have multiple internal linkage entities with the same name
4255 // in extern "C" regions, none of them gets that name.
4256 if (!R.second)
4257 R.first->second = nullptr;
4258}
4259
4260static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4261 if (!CGM.supportsCOMDAT())
4262 return false;
4263
4264 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
4265 // them being "merged" by the COMDAT Folding linker optimization.
4266 if (D.hasAttr<CUDAGlobalAttr>())
4267 return false;
4268
4269 if (D.hasAttr<SelectAnyAttr>())
4270 return true;
4271
4272 GVALinkage Linkage;
4273 if (auto *VD = dyn_cast<VarDecl>(&D))
4274 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4275 else
4276 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4277
4278 switch (Linkage) {
4279 case GVA_Internal:
4280 case GVA_AvailableExternally:
4281 case GVA_StrongExternal:
4282 return false;
4283 case GVA_DiscardableODR:
4284 case GVA_StrongODR:
4285 return true;
4286 }
4287 llvm_unreachable("No such linkage")::llvm::llvm_unreachable_internal("No such linkage", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4287)
;
4288}
4289
4290void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4291 llvm::GlobalObject &GO) {
4292 if (!shouldBeInCOMDAT(*this, D))
4293 return;
4294 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4295}
4296
4297/// Pass IsTentative as true if you want to create a tentative definition.
4298void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4299 bool IsTentative) {
4300 // OpenCL global variables of sampler type are translated to function calls,
4301 // therefore no need to be translated.
4302 QualType ASTTy = D->getType();
4303 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4304 return;
4305
4306 // If this is OpenMP device, check if it is legal to emit this global
4307 // normally.
4308 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4309 OpenMPRuntime->emitTargetGlobalVariable(D))
4310 return;
4311
4312 llvm::TrackingVH<llvm::Constant> Init;
4313 bool NeedsGlobalCtor = false;
4314 bool NeedsGlobalDtor =
4315 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4316
4317 const VarDecl *InitDecl;
4318 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4319
4320 Optional<ConstantEmitter> emitter;
4321
4322 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4323 // as part of their declaration." Sema has already checked for
4324 // error cases, so we just need to set Init to UndefValue.
4325 bool IsCUDASharedVar =
4326 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4327 // Shadows of initialized device-side global variables are also left
4328 // undefined.
4329 // Managed Variables should be initialized on both host side and device side.
4330 bool IsCUDAShadowVar =
4331 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4332 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4333 D->hasAttr<CUDASharedAttr>());
4334 bool IsCUDADeviceShadowVar =
4335 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4336 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4337 D->getType()->isCUDADeviceBuiltinTextureType());
4338 if (getLangOpts().CUDA &&
4339 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4340 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4341 else if (D->hasAttr<LoaderUninitializedAttr>())
4342 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4343 else if (!InitExpr) {
4344 // This is a tentative definition; tentative definitions are
4345 // implicitly initialized with { 0 }.
4346 //
4347 // Note that tentative definitions are only emitted at the end of
4348 // a translation unit, so they should never have incomplete
4349 // type. In addition, EmitTentativeDefinition makes sure that we
4350 // never attempt to emit a tentative definition if a real one
4351 // exists. A use may still exists, however, so we still may need
4352 // to do a RAUW.
4353 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type")(static_cast <bool> (!ASTTy->isIncompleteType() &&
"Unexpected incomplete type") ? void (0) : __assert_fail ("!ASTTy->isIncompleteType() && \"Unexpected incomplete type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4353, __extension__ __PRETTY_FUNCTION__))
;
4354 Init = EmitNullConstant(D->getType());
4355 } else {
4356 initializedGlobalDecl = GlobalDecl(D);
4357 emitter.emplace(*this);
4358 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4359 if (!Initializer) {
4360 QualType T = InitExpr->getType();
4361 if (D->getType()->isReferenceType())
4362 T = D->getType();
4363
4364 if (getLangOpts().CPlusPlus) {
4365 Init = EmitNullConstant(T);
4366 NeedsGlobalCtor = true;
4367 } else {
4368 ErrorUnsupported(D, "static initializer");
4369 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4370 }
4371 } else {
4372 Init = Initializer;
4373 // We don't need an initializer, so remove the entry for the delayed
4374 // initializer position (just in case this entry was delayed) if we
4375 // also don't need to register a destructor.
4376 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4377 DelayedCXXInitPosition.erase(D);
4378 }
4379 }
4380
4381 llvm::Type* InitType = Init->getType();
4382 llvm::Constant *Entry =
4383 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4384
4385 // Strip off pointer casts if we got them.
4386 Entry = Entry->stripPointerCasts();
4387
4388 // Entry is now either a Function or GlobalVariable.
4389 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4390
4391 // We have a definition after a declaration with the wrong type.
4392 // We must make a new GlobalVariable* and update everything that used OldGV
4393 // (a declaration or tentative definition) with the new GlobalVariable*
4394 // (which will be a definition).
4395 //
4396 // This happens if there is a prototype for a global (e.g.
4397 // "extern int x[];") and then a definition of a different type (e.g.
4398 // "int x[10];"). This also happens when an initializer has a different type
4399 // from the type of the global (this happens with unions).
4400 if (!GV || GV->getValueType() != InitType ||
4401 GV->getType()->getAddressSpace() !=
4402 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4403
4404 // Move the old entry aside so that we'll create a new one.
4405 Entry->setName(StringRef());
4406
4407 // Make a new global with the correct type, this is now guaranteed to work.
4408 GV = cast<llvm::GlobalVariable>(
4409 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4410 ->stripPointerCasts());
4411
4412 // Replace all uses of the old global with the new global
4413 llvm::Constant *NewPtrForOldDecl =
4414 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4415 Entry->getType());
4416 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4417
4418 // Erase the old global, since it is no longer used.
4419 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4420 }
4421
4422 MaybeHandleStaticInExternC(D, GV);
4423
4424 if (D->hasAttr<AnnotateAttr>())
4425 AddGlobalAnnotations(D, GV);
4426
4427 // Set the llvm linkage type as appropriate.
4428 llvm::GlobalValue::LinkageTypes Linkage =
4429 getLLVMLinkageVarDefinition(D, GV->isConstant());
4430
4431 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4432 // the device. [...]"
4433 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4434 // __device__, declares a variable that: [...]
4435 // Is accessible from all the threads within the grid and from the host
4436 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4437 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4438 if (GV && LangOpts.CUDA) {
4439 if (LangOpts.CUDAIsDevice) {
4440 if (Linkage != llvm::GlobalValue::InternalLinkage &&
4441 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4442 GV->setExternallyInitialized(true);
4443 } else {
4444 getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4445 }
4446 getCUDARuntime().handleVarRegistration(D, *GV);
4447 }
4448
4449 GV->setInitializer(Init);
4450 if (emitter)
4451 emitter->finalize(GV);
4452
4453 // If it is safe to mark the global 'constant', do so now.
4454 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4455 isTypeConstant(D->getType(), true));
4456
4457 // If it is in a read-only section, mark it 'constant'.
4458 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4459 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4460 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4461 GV->setConstant(true);
4462 }
4463
4464 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4465
4466 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4467 // function is only defined alongside the variable, not also alongside
4468 // callers. Normally, all accesses to a thread_local go through the
4469 // thread-wrapper in order to ensure initialization has occurred, underlying
4470 // variable will never be used other than the thread-wrapper, so it can be
4471 // converted to internal linkage.
4472 //
4473 // However, if the variable has the 'constinit' attribute, it _can_ be
4474 // referenced directly, without calling the thread-wrapper, so the linkage
4475 // must not be changed.
4476 //
4477 // Additionally, if the variable isn't plain external linkage, e.g. if it's
4478 // weak or linkonce, the de-duplication semantics are important to preserve,
4479 // so we don't change the linkage.
4480 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4481 Linkage == llvm::GlobalValue::ExternalLinkage &&
4482 Context.getTargetInfo().getTriple().isOSDarwin() &&
4483 !D->hasAttr<ConstInitAttr>())
4484 Linkage = llvm::GlobalValue::InternalLinkage;
4485
4486 GV->setLinkage(Linkage);
4487 if (D->hasAttr<DLLImportAttr>())
4488 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4489 else if (D->hasAttr<DLLExportAttr>())
4490 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4491 else
4492 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4493
4494 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4495 // common vars aren't constant even if declared const.
4496 GV->setConstant(false);
4497 // Tentative definition of global variables may be initialized with
4498 // non-zero null pointers. In this case they should have weak linkage
4499 // since common linkage must have zero initializer and must not have
4500 // explicit section therefore cannot have non-zero initial value.
4501 if (!GV->getInitializer()->isNullValue())
4502 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4503 }
4504
4505 setNonAliasAttributes(D, GV);
4506
4507 if (D->getTLSKind() && !GV->isThreadLocal()) {
4508 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4509 CXXThreadLocals.push_back(D);
4510 setTLSMode(GV, *D);
4511 }
4512
4513 maybeSetTrivialComdat(*D, *GV);
4514
4515 // Emit the initializer function if necessary.
4516 if (NeedsGlobalCtor || NeedsGlobalDtor)
4517 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4518
4519 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4520
4521 // Emit global variable debug information.
4522 if (CGDebugInfo *DI = getModuleDebugInfo())
4523 if (getCodeGenOpts().hasReducedDebugInfo())
4524 DI->EmitGlobalVariable(GV, D);
4525}
4526
4527void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4528 if (CGDebugInfo *DI = getModuleDebugInfo())
4529 if (getCodeGenOpts().hasReducedDebugInfo()) {
4530 QualType ASTTy = D->getType();
4531 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4532 llvm::Constant *GV = GetOrCreateLLVMGlobal(
4533 D->getName(), Ty, getContext().getTargetAddressSpace(ASTTy), D);
4534 DI->EmitExternalVariable(
4535 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4536 }
4537}
4538
4539static bool isVarDeclStrongDefinition(const ASTContext &Context,
4540 CodeGenModule &CGM, const VarDecl *D,
4541 bool NoCommon) {
4542 // Don't give variables common linkage if -fno-common was specified unless it
4543 // was overridden by a NoCommon attribute.
4544 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4545 return true;
4546
4547 // C11 6.9.2/2:
4548 // A declaration of an identifier for an object that has file scope without
4549 // an initializer, and without a storage-class specifier or with the
4550 // storage-class specifier static, constitutes a tentative definition.
4551 if (D->getInit() || D->hasExternalStorage())
4552 return true;
4553
4554 // A variable cannot be both common and exist in a section.
4555 if (D->hasAttr<SectionAttr>())
4556 return true;
4557
4558 // A variable cannot be both common and exist in a section.
4559 // We don't try to determine which is the right section in the front-end.
4560 // If no specialized section name is applicable, it will resort to default.
4561 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4562 D->hasAttr<PragmaClangDataSectionAttr>() ||
4563 D->hasAttr<PragmaClangRelroSectionAttr>() ||
4564 D->hasAttr<PragmaClangRodataSectionAttr>())
4565 return true;
4566
4567 // Thread local vars aren't considered common linkage.
4568 if (D->getTLSKind())
4569 return true;
4570
4571 // Tentative definitions marked with WeakImportAttr are true definitions.
4572 if (D->hasAttr<WeakImportAttr>())
4573 return true;
4574
4575 // A variable cannot be both common and exist in a comdat.
4576 if (shouldBeInCOMDAT(CGM, *D))
4577 return true;
4578
4579 // Declarations with a required alignment do not have common linkage in MSVC
4580 // mode.
4581 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4582 if (D->hasAttr<AlignedAttr>())
4583 return true;
4584 QualType VarType = D->getType();
4585 if (Context.isAlignmentRequired(VarType))
4586 return true;
4587
4588 if (const auto *RT = VarType->getAs<RecordType>()) {
4589 const RecordDecl *RD = RT->getDecl();
4590 for (const FieldDecl *FD : RD->fields()) {
4591 if (FD->isBitField())
4592 continue;
4593 if (FD->hasAttr<AlignedAttr>())
4594 return true;
4595 if (Context.isAlignmentRequired(FD->getType()))
4596 return true;
4597 }
4598 }
4599 }
4600
4601 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4602 // common symbols, so symbols with greater alignment requirements cannot be
4603 // common.
4604 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4605 // alignments for common symbols via the aligncomm directive, so this
4606 // restriction only applies to MSVC environments.
4607 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4608 Context.getTypeAlignIfKnown(D->getType()) >
4609 Context.toBits(CharUnits::fromQuantity(32)))
4610 return true;
4611
4612 return false;
4613}
4614
4615llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4616 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4617 if (Linkage == GVA_Internal)
4618 return llvm::Function::InternalLinkage;
4619
4620 if (D->hasAttr<WeakAttr>()) {
4621 if (IsConstantVariable)
4622 return llvm::GlobalVariable::WeakODRLinkage;
4623 else
4624 return llvm::GlobalVariable::WeakAnyLinkage;
4625 }
4626
4627 if (const auto *FD = D->getAsFunction())
4628 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4629 return llvm::GlobalVariable::LinkOnceAnyLinkage;
4630
4631 // We are guaranteed to have a strong definition somewhere else,
4632 // so we can use available_externally linkage.
4633 if (Linkage == GVA_AvailableExternally)
4634 return llvm::GlobalValue::AvailableExternallyLinkage;
4635
4636 // Note that Apple's kernel linker doesn't support symbol
4637 // coalescing, so we need to avoid linkonce and weak linkages there.
4638 // Normally, this means we just map to internal, but for explicit
4639 // instantiations we'll map to external.
4640
4641 // In C++, the compiler has to emit a definition in every translation unit
4642 // that references the function. We should use linkonce_odr because
4643 // a) if all references in this translation unit are optimized away, we
4644 // don't need to codegen it. b) if the function persists, it needs to be
4645 // merged with other definitions. c) C++ has the ODR, so we know the
4646 // definition is dependable.
4647 if (Linkage == GVA_DiscardableODR)
4648 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4649 : llvm::Function::InternalLinkage;
4650
4651 // An explicit instantiation of a template has weak linkage, since
4652 // explicit instantiations can occur in multiple translation units
4653 // and must all be equivalent. However, we are not allowed to
4654 // throw away these explicit instantiations.
4655 //
4656 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4657 // so say that CUDA templates are either external (for kernels) or internal.
4658 // This lets llvm perform aggressive inter-procedural optimizations. For
4659 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4660 // therefore we need to follow the normal linkage paradigm.
4661 if (Linkage == GVA_StrongODR) {
4662 if (getLangOpts().AppleKext)
4663 return llvm::Function::ExternalLinkage;
4664 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4665 !getLangOpts().GPURelocatableDeviceCode)
4666 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4667 : llvm::Function::InternalLinkage;
4668 return llvm::Function::WeakODRLinkage;
4669 }
4670
4671 // C++ doesn't have tentative definitions and thus cannot have common
4672 // linkage.
4673 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4674 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4675 CodeGenOpts.NoCommon))
4676 return llvm::GlobalVariable::CommonLinkage;
4677
4678 // selectany symbols are externally visible, so use weak instead of
4679 // linkonce. MSVC optimizes away references to const selectany globals, so
4680 // all definitions should be the same and ODR linkage should be used.
4681 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4682 if (D->hasAttr<SelectAnyAttr>())
4683 return llvm::GlobalVariable::WeakODRLinkage;
4684
4685 // Otherwise, we have strong external linkage.
4686 assert(Linkage == GVA_StrongExternal)(static_cast <bool> (Linkage == GVA_StrongExternal) ? void
(0) : __assert_fail ("Linkage == GVA_StrongExternal", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4686, __extension__ __PRETTY_FUNCTION__))
;
4687 return llvm::GlobalVariable::ExternalLinkage;
4688}
4689
4690llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4691 const VarDecl *VD, bool IsConstant) {
4692 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4693 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4694}
4695
4696/// Replace the uses of a function that was declared with a non-proto type.
4697/// We want to silently drop extra arguments from call sites
4698static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4699 llvm::Function *newFn) {
4700 // Fast path.
4701 if (old->use_empty()) return;
4702
4703 llvm::Type *newRetTy = newFn->getReturnType();
4704 SmallVector<llvm::Value*, 4> newArgs;
4705
4706 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4707 ui != ue; ) {
4708 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4709 llvm::User *user = use->getUser();
4710
4711 // Recognize and replace uses of bitcasts. Most calls to
4712 // unprototyped functions will use bitcasts.
4713 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4714 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4715 replaceUsesOfNonProtoConstant(bitcast, newFn);
4716 continue;
4717 }
4718
4719 // Recognize calls to the function.
4720 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4721 if (!callSite) continue;
4722 if (!callSite->isCallee(&*use))
4723 continue;
4724
4725 // If the return types don't match exactly, then we can't
4726 // transform this call unless it's dead.
4727 if (callSite->getType() != newRetTy && !callSite->use_empty())
4728 continue;
4729
4730 // Get the call site's attribute list.
4731 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4732 llvm::AttributeList oldAttrs = callSite->getAttributes();
4733
4734 // If the function was passed too few arguments, don't transform.
4735 unsigned newNumArgs = newFn->arg_size();
4736 if (callSite->arg_size() < newNumArgs)
4737 continue;
4738
4739 // If extra arguments were passed, we silently drop them.
4740 // If any of the types mismatch, we don't transform.
4741 unsigned argNo = 0;
4742 bool dontTransform = false;
4743 for (llvm::Argument &A : newFn->args()) {
4744 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4745 dontTransform = true;
4746 break;
4747 }
4748
4749 // Add any parameter attributes.
4750 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4751 argNo++;
4752 }
4753 if (dontTransform)
4754 continue;
4755
4756 // Okay, we can transform this. Create the new call instruction and copy
4757 // over the required information.
4758 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4759
4760 // Copy over any operand bundles.
4761 SmallVector<llvm::OperandBundleDef, 1> newBundles;
4762 callSite->getOperandBundlesAsDefs(newBundles);
4763
4764 llvm::CallBase *newCall;
4765 if (dyn_cast<llvm::CallInst>(callSite)) {
4766 newCall =
4767 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4768 } else {
4769 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4770 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4771 oldInvoke->getUnwindDest(), newArgs,
4772 newBundles, "", callSite);
4773 }
4774 newArgs.clear(); // for the next iteration
4775
4776 if (!newCall->getType()->isVoidTy())
4777 newCall->takeName(callSite);
4778 newCall->setAttributes(llvm::AttributeList::get(
4779 newFn->getContext(), oldAttrs.getFnAttributes(),
4780 oldAttrs.getRetAttributes(), newArgAttrs));
4781 newCall->setCallingConv(callSite->getCallingConv());
4782
4783 // Finally, remove the old call, replacing any uses with the new one.
4784 if (!callSite->use_empty())
4785 callSite->replaceAllUsesWith(newCall);
4786
4787 // Copy debug location attached to CI.
4788 if (callSite->getDebugLoc())
4789 newCall->setDebugLoc(callSite->getDebugLoc());
4790
4791 callSite->eraseFromParent();
4792 }
4793}
4794
4795/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4796/// implement a function with no prototype, e.g. "int foo() {}". If there are
4797/// existing call uses of the old function in the module, this adjusts them to
4798/// call the new function directly.
4799///
4800/// This is not just a cleanup: the always_inline pass requires direct calls to
4801/// functions to be able to inline them. If there is a bitcast in the way, it
4802/// won't inline them. Instcombine normally deletes these calls, but it isn't
4803/// run at -O0.
4804static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4805 llvm::Function *NewFn) {
4806 // If we're redefining a global as a function, don't transform it.
4807 if (!isa<llvm::Function>(Old)) return;
4808
4809 replaceUsesOfNonProtoConstant(Old, NewFn);
4810}
4811
4812void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4813 auto DK = VD->isThisDeclarationADefinition();
4814 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4815 return;
4816
4817 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4818 // If we have a definition, this might be a deferred decl. If the
4819 // instantiation is explicit, make sure we emit it at the end.
4820 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4821 GetAddrOfGlobalVar(VD);
4822
4823 EmitTopLevelDecl(VD);
4824}
4825
4826void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4827 llvm::GlobalValue *GV) {
4828 const auto *D = cast<FunctionDecl>(GD.getDecl());
4829
4830 // Compute the function info and LLVM type.
4831 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4832 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4833
4834 // Get or create the prototype for the function.
4835 if (!GV || (GV->getValueType() != Ty))
4836 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4837 /*DontDefer=*/true,
4838 ForDefinition));
4839
4840 // Already emitted.
4841 if (!GV->isDeclaration())
4842 return;
4843
4844 // We need to set linkage and visibility on the function before
4845 // generating code for it because various parts of IR generation
4846 // want to propagate this information down (e.g. to local static
4847 // declarations).
4848 auto *Fn = cast<llvm::Function>(GV);
4849 setFunctionLinkage(GD, Fn);
4850
4851 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4852 setGVProperties(Fn, GD);
4853
4854 MaybeHandleStaticInExternC(D, Fn);
4855
4856 maybeSetTrivialComdat(*D, *Fn);
4857
4858 // Set CodeGen attributes that represent floating point environment.
4859 setLLVMFunctionFEnvAttributes(D, Fn);
4860
4861 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4862
4863 setNonAliasAttributes(GD, Fn);
4864 SetLLVMFunctionAttributesForDefinition(D, Fn);
4865
4866 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4867 AddGlobalCtor(Fn, CA->getPriority());
4868 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4869 AddGlobalDtor(Fn, DA->getPriority(), true);
4870 if (D->hasAttr<AnnotateAttr>())
4871 AddGlobalAnnotations(D, Fn);
4872}
4873
4874void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4875 const auto *D = cast<ValueDecl>(GD.getDecl());
4876 const AliasAttr *AA = D->getAttr<AliasAttr>();
4877 assert(AA && "Not an alias?")(static_cast <bool> (AA && "Not an alias?") ? void
(0) : __assert_fail ("AA && \"Not an alias?\"", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4877, __extension__ __PRETTY_FUNCTION__))
;
4878
4879 StringRef MangledName = getMangledName(GD);
4880
4881 if (AA->getAliasee() == MangledName) {
4882 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4883 return;
4884 }
4885
4886 // If there is a definition in the module, then it wins over the alias.
4887 // This is dubious, but allow it to be safe. Just ignore the alias.
4888 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4889 if (Entry && !Entry->isDeclaration())
4890 return;
4891
4892 Aliases.push_back(GD);
4893
4894 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4895
4896 // Create a reference to the named value. This ensures that it is emitted
4897 // if a deferred decl.
4898 llvm::Constant *Aliasee;
4899 llvm::GlobalValue::LinkageTypes LT;
4900 if (isa<llvm::FunctionType>(DeclTy)) {
4901 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4902 /*ForVTable=*/false);
4903 LT = getFunctionLinkage(GD);
4904 } else {
4905 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0,
4906 /*D=*/nullptr);
4907 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4908 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4909 else
4910 LT = getFunctionLinkage(GD);
4911 }
4912
4913 // Create the new alias itself, but don't set a name yet.
4914 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4915 auto *GA =
4916 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4917
4918 if (Entry) {
4919 if (GA->getAliasee() == Entry) {
4920 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4921 return;
4922 }
4923
4924 assert(Entry->isDeclaration())(static_cast <bool> (Entry->isDeclaration()) ? void (
0) : __assert_fail ("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4924, __extension__ __PRETTY_FUNCTION__))
;
4925
4926 // If there is a declaration in the module, then we had an extern followed
4927 // by the alias, as in:
4928 // extern int test6();
4929 // ...
4930 // int test6() __attribute__((alias("test7")));
4931 //
4932 // Remove it and replace uses of it with the alias.
4933 GA->takeName(Entry);
4934
4935 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4936 Entry->getType()));
4937 Entry->eraseFromParent();
4938 } else {
4939 GA->setName(MangledName);
4940 }
4941
4942 // Set attributes which are particular to an alias; this is a
4943 // specialization of the attributes which may be set on a global
4944 // variable/function.
4945 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4946 D->isWeakImported()) {
4947 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4948 }
4949
4950 if (const auto *VD = dyn_cast<VarDecl>(D))
4951 if (VD->getTLSKind())
4952 setTLSMode(GA, *VD);
4953
4954 SetCommonAttributes(GD, GA);
4955}
4956
4957void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4958 const auto *D = cast<ValueDecl>(GD.getDecl());
4959 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4960 assert(IFA && "Not an ifunc?")(static_cast <bool> (IFA && "Not an ifunc?") ? void
(0) : __assert_fail ("IFA && \"Not an ifunc?\"", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4960, __extension__ __PRETTY_FUNCTION__))
;
4961
4962 StringRef MangledName = getMangledName(GD);
4963
4964 if (IFA->getResolver() == MangledName) {
4965 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4966 return;
4967 }
4968
4969 // Report an error if some definition overrides ifunc.
4970 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4971 if (Entry && !Entry->isDeclaration()) {
4972 GlobalDecl OtherGD;
4973 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4974 DiagnosedConflictingDefinitions.insert(GD).second) {
4975 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4976 << MangledName;
4977 Diags.Report(OtherGD.getDecl()->getLocation(),
4978 diag::note_previous_definition);
4979 }
4980 return;
4981 }
4982
4983 Aliases.push_back(GD);
4984
4985 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4986 llvm::Constant *Resolver =
4987 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4988 /*ForVTable=*/false);
4989 llvm::GlobalIFunc *GIF =
4990 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4991 "", Resolver, &getModule());
4992 if (Entry) {
4993 if (GIF->getResolver() == Entry) {
4994 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4995 return;
4996 }
4997 assert(Entry->isDeclaration())(static_cast <bool> (Entry->isDeclaration()) ? void (
0) : __assert_fail ("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 4997, __extension__ __PRETTY_FUNCTION__))
;
4998
4999 // If there is a declaration in the module, then we had an extern followed
5000 // by the ifunc, as in:
5001 // extern int test();
5002 // ...
5003 // int test() __attribute__((ifunc("resolver")));
5004 //
5005 // Remove it and replace uses of it with the ifunc.
5006 GIF->takeName(Entry);
5007
5008 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5009 Entry->getType()));
5010 Entry->eraseFromParent();
5011 } else
5012 GIF->setName(MangledName);
5013
5014 SetCommonAttributes(GD, GIF);
5015}
5016
5017llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5018 ArrayRef<llvm::Type*> Tys) {
5019 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5020 Tys);
5021}
5022
5023static llvm::StringMapEntry<llvm::GlobalVariable *> &
5024GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5025 const StringLiteral *Literal, bool TargetIsLSB,
5026 bool &IsUTF16, unsigned &StringLength) {
5027 StringRef String = Literal->getString();
5028 unsigned NumBytes = String.size();
5029
5030 // Check for simple case.
5031 if (!Literal->containsNonAsciiOrNull()) {
5032 StringLength = NumBytes;
5033 return *Map.insert(std::make_pair(String, nullptr)).first;
5034 }
5035
5036 // Otherwise, convert the UTF8 literals into a string of shorts.
5037 IsUTF16 = true;
5038
5039 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5040 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5041 llvm::UTF16 *ToPtr = &ToBuf[0];
5042
5043 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5044 ToPtr + NumBytes, llvm::strictConversion);
5045
5046 // ConvertUTF8toUTF16 returns the length in ToPtr.
5047 StringLength = ToPtr - &ToBuf[0];
5048
5049 // Add an explicit null.
5050 *ToPtr = 0;
5051 return *Map.insert(std::make_pair(
5052 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5053 (StringLength + 1) * 2),
5054 nullptr)).first;
5055}
5056
5057ConstantAddress
5058CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5059 unsigned StringLength = 0;
5060 bool isUTF16 = false;
5061 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5062 GetConstantCFStringEntry(CFConstantStringMap, Literal,
5063 getDataLayout().isLittleEndian(), isUTF16,
5064 StringLength);
5065
5066 if (auto *C = Entry.second)
5067 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
5068
5069 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5070 llvm::Constant *Zeros[] = { Zero, Zero };
5071
5072 const ASTContext &Context = getContext();
5073 const llvm::Triple &Triple = getTriple();
5074
5075 const auto CFRuntime = getLangOpts().CFRuntime;
5076 const bool IsSwiftABI =
5077 static_cast<unsigned>(CFRuntime) >=
5078 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5079 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5080
5081 // If we don't already have it, get __CFConstantStringClassReference.
5082 if (!CFConstantStringClassRef) {
5083 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5084 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5085 Ty = llvm::ArrayType::get(Ty, 0);
5086
5087 switch (CFRuntime) {
5088 default: break;
5089 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH[[gnu::fallthrough]];
5090 case LangOptions::CoreFoundationABI::Swift5_0:
5091 CFConstantStringClassName =
5092 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5093 : "$s10Foundation19_NSCFConstantStringCN";
5094 Ty = IntPtrTy;
5095 break;
5096 case LangOptions::CoreFoundationABI::Swift4_2:
5097 CFConstantStringClassName =
5098 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5099 : "$S10Foundation19_NSCFConstantStringCN";
5100 Ty = IntPtrTy;
5101 break;
5102 case LangOptions::CoreFoundationABI::Swift4_1:
5103 CFConstantStringClassName =
5104 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5105 : "__T010Foundation19_NSCFConstantStringCN";
5106 Ty = IntPtrTy;
5107 break;
5108 }
5109
5110 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5111
5112 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5113 llvm::GlobalValue *GV = nullptr;
5114
5115 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5116 IdentifierInfo &II = Context.Idents.get(GV->getName());
5117 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5118 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5119
5120 const VarDecl *VD = nullptr;
5121 for (const auto *Result : DC->lookup(&II))
5122 if ((VD = dyn_cast<VarDecl>(Result)))
5123 break;
5124
5125 if (Triple.isOSBinFormatELF()) {
5126 if (!VD)
5127 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5128 } else {
5129 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5130 if (!VD || !VD->hasAttr<DLLExportAttr>())
5131 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5132 else
5133 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5134 }
5135
5136 setDSOLocal(GV);
5137 }
5138 }
5139
5140 // Decay array -> ptr
5141 CFConstantStringClassRef =
5142 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5143 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5144 }
5145
5146 QualType CFTy = Context.getCFConstantStringType();
5147
5148 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5149
5150 ConstantInitBuilder Builder(*this);
5151 auto Fields = Builder.beginStruct(STy);
5152
5153 // Class pointer.
5154 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
5155
5156 // Flags.
5157 if (IsSwiftABI) {
5158 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5159 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5160 } else {
5161 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5162 }
5163
5164 // String pointer.
5165 llvm::Constant *C = nullptr;
5166 if (isUTF16) {
5167 auto Arr = llvm::makeArrayRef(
5168 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5169 Entry.first().size() / 2);
5170 C = llvm::ConstantDataArray::get(VMContext, Arr);
5171 } else {
5172 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5173 }
5174
5175 // Note: -fwritable-strings doesn't make the backing store strings of
5176 // CFStrings writable. (See <rdar://problem/10657500>)
5177 auto *GV =
5178 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5179 llvm::GlobalValue::PrivateLinkage, C, ".str");
5180 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5181 // Don't enforce the target's minimum global alignment, since the only use
5182 // of the string is via this class initializer.
5183 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5184 : Context.getTypeAlignInChars(Context.CharTy);
5185 GV->setAlignment(Align.getAsAlign());
5186
5187 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5188 // Without it LLVM can merge the string with a non unnamed_addr one during
5189 // LTO. Doing that changes the section it ends in, which surprises ld64.
5190 if (Triple.isOSBinFormatMachO())
5191 GV->setSection(isUTF16 ? "__TEXT,__ustring"
5192 : "__TEXT,__cstring,cstring_literals");
5193 // Make sure the literal ends up in .rodata to allow for safe ICF and for
5194 // the static linker to adjust permissions to read-only later on.
5195 else if (Triple.isOSBinFormatELF())
5196 GV->setSection(".rodata");
5197
5198 // String.
5199 llvm::Constant *Str =
5200 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5201
5202 if (isUTF16)
5203 // Cast the UTF16 string to the correct type.
5204 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5205 Fields.add(Str);
5206
5207 // String length.
5208 llvm::IntegerType *LengthTy =
5209 llvm::IntegerType::get(getModule().getContext(),
5210 Context.getTargetInfo().getLongWidth());
5211 if (IsSwiftABI) {
5212 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5213 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5214 LengthTy = Int32Ty;
5215 else
5216 LengthTy = IntPtrTy;
5217 }
5218 Fields.addInt(LengthTy, StringLength);
5219
5220 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5221 // properly aligned on 32-bit platforms.
5222 CharUnits Alignment =
5223 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5224
5225 // The struct.
5226 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5227 /*isConstant=*/false,
5228 llvm::GlobalVariable::PrivateLinkage);
5229 GV->addAttribute("objc_arc_inert");
5230 switch (Triple.getObjectFormat()) {
5231 case llvm::Triple::UnknownObjectFormat:
5232 llvm_unreachable("unknown file format")::llvm::llvm_unreachable_internal("unknown file format", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5232)
;
5233 case llvm::Triple::GOFF:
5234 llvm_unreachable("GOFF is not yet implemented")::llvm::llvm_unreachable_internal("GOFF is not yet implemented"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5234)
;
5235 case llvm::Triple::XCOFF:
5236 llvm_unreachable("XCOFF is not yet implemented")::llvm::llvm_unreachable_internal("XCOFF is not yet implemented"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5236)
;
5237 case llvm::Triple::COFF:
5238 case llvm::Triple::ELF:
5239 case llvm::Triple::Wasm:
5240 GV->setSection("cfstring");
5241 break;
5242 case llvm::Triple::MachO:
5243 GV->setSection("__DATA,__cfstring");
5244 break;
5245 }
5246 Entry.second = GV;
5247
5248 return ConstantAddress(GV, Alignment);
5249}
5250
5251bool CodeGenModule::getExpressionLocationsEnabled() const {
5252 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5253}
5254
5255QualType CodeGenModule::getObjCFastEnumerationStateType() {
5256 if (ObjCFastEnumerationStateType.isNull()) {
5257 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5258 D->startDefinition();
5259
5260 QualType FieldTypes[] = {
5261 Context.UnsignedLongTy,
5262 Context.getPointerType(Context.getObjCIdType()),
5263 Context.getPointerType(Context.UnsignedLongTy),
5264 Context.getConstantArrayType(Context.UnsignedLongTy,
5265 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5266 };
5267
5268 for (size_t i = 0; i < 4; ++i) {
5269 FieldDecl *Field = FieldDecl::Create(Context,
5270 D,
5271 SourceLocation(),
5272 SourceLocation(), nullptr,
5273 FieldTypes[i], /*TInfo=*/nullptr,
5274 /*BitWidth=*/nullptr,
5275 /*Mutable=*/false,
5276 ICIS_NoInit);
5277 Field->setAccess(AS_public);
5278 D->addDecl(Field);
5279 }
5280
5281 D->completeDefinition();
5282 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5283 }
5284
5285 return ObjCFastEnumerationStateType;
5286}
5287
5288llvm::Constant *
5289CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5290 assert(!E->getType()->isPointerType() && "Strings are always arrays")(static_cast <bool> (!E->getType()->isPointerType
() && "Strings are always arrays") ? void (0) : __assert_fail
("!E->getType()->isPointerType() && \"Strings are always arrays\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5290, __extension__ __PRETTY_FUNCTION__))
;
5291
5292 // Don't emit it as the address of the string, emit the string data itself
5293 // as an inline array.
5294 if (E->getCharByteWidth() == 1) {
5295 SmallString<64> Str(E->getString());
5296
5297 // Resize the string to the right size, which is indicated by its type.
5298 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5299 Str.resize(CAT->getSize().getZExtValue());
5300 return llvm::ConstantDataArray::getString(VMContext, Str, false);
5301 }
5302
5303 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5304 llvm::Type *ElemTy = AType->getElementType();
5305 unsigned NumElements = AType->getNumElements();
5306
5307 // Wide strings have either 2-byte or 4-byte elements.
5308 if (ElemTy->getPrimitiveSizeInBits() == 16) {
5309 SmallVector<uint16_t, 32> Elements;
5310 Elements.reserve(NumElements);
5311
5312 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5313 Elements.push_back(E->getCodeUnit(i));
5314 Elements.resize(NumElements);
5315 return llvm::ConstantDataArray::get(VMContext, Elements);
5316 }
5317
5318 assert(ElemTy->getPrimitiveSizeInBits() == 32)(static_cast <bool> (ElemTy->getPrimitiveSizeInBits(
) == 32) ? void (0) : __assert_fail ("ElemTy->getPrimitiveSizeInBits() == 32"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5318, __extension__ __PRETTY_FUNCTION__))
;
5319 SmallVector<uint32_t, 32> Elements;
5320 Elements.reserve(NumElements);
5321
5322 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5323 Elements.push_back(E->getCodeUnit(i));
5324 Elements.resize(NumElements);
5325 return llvm::ConstantDataArray::get(VMContext, Elements);
5326}
5327
5328static llvm::GlobalVariable *
5329GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5330 CodeGenModule &CGM, StringRef GlobalName,
5331 CharUnits Alignment) {
5332 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5333 CGM.GetGlobalConstantAddressSpace());
5334
5335 llvm::Module &M = CGM.getModule();
5336 // Create a global variable for this string
5337 auto *GV = new llvm::GlobalVariable(
5338 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5339 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5340 GV->setAlignment(Alignment.getAsAlign());
5341 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5342 if (GV->isWeakForLinker()) {
5343 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals")(static_cast <bool> (CGM.supportsCOMDAT() && "Only COFF uses weak string literals"
) ? void (0) : __assert_fail ("CGM.supportsCOMDAT() && \"Only COFF uses weak string literals\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5343, __extension__ __PRETTY_FUNCTION__))
;
5344 GV->setComdat(M.getOrInsertComdat(GV->getName()));
5345 }
5346 CGM.setDSOLocal(GV);
5347
5348 return GV;
5349}
5350
5351/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5352/// constant array for the given string literal.
5353ConstantAddress
5354CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5355 StringRef Name) {
5356 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5357
5358 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5359 llvm::GlobalVariable **Entry = nullptr;
5360 if (!LangOpts.WritableStrings) {
5361 Entry = &ConstantStringMap[C];
5362 if (auto GV = *Entry) {
5363 if (Alignment.getQuantity() > GV->getAlignment())
5364 GV->setAlignment(Alignment.getAsAlign());
5365 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5366 Alignment);
5367 }
5368 }
5369
5370 SmallString<256> MangledNameBuffer;
5371 StringRef GlobalVariableName;
5372 llvm::GlobalValue::LinkageTypes LT;
5373
5374 // Mangle the string literal if that's how the ABI merges duplicate strings.
5375 // Don't do it if they are writable, since we don't want writes in one TU to
5376 // affect strings in another.
5377 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5378 !LangOpts.WritableStrings) {
5379 llvm::raw_svector_ostream Out(MangledNameBuffer);
5380 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5381 LT = llvm::GlobalValue::LinkOnceODRLinkage;
5382 GlobalVariableName = MangledNameBuffer;
5383 } else {
5384 LT = llvm::GlobalValue::PrivateLinkage;
5385 GlobalVariableName = Name;
5386 }
5387
5388 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5389 if (Entry)
5390 *Entry = GV;
5391
5392 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5393 QualType());
5394
5395 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5396 Alignment);
5397}
5398
5399/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5400/// array for the given ObjCEncodeExpr node.
5401ConstantAddress
5402CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5403 std::string Str;
5404 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5405
5406 return GetAddrOfConstantCString(Str);
5407}
5408
5409/// GetAddrOfConstantCString - Returns a pointer to a character array containing
5410/// the literal and a terminating '\0' character.
5411/// The result has pointer to array type.
5412ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5413 const std::string &Str, const char *GlobalName) {
5414 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5415 CharUnits Alignment =
5416 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5417
5418 llvm::Constant *C =
5419 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5420
5421 // Don't share any string literals if strings aren't constant.
5422 llvm::GlobalVariable **Entry = nullptr;
5423 if (!LangOpts.WritableStrings) {
5424 Entry = &ConstantStringMap[C];
5425 if (auto GV = *Entry) {
5426 if (Alignment.getQuantity() > GV->getAlignment())
5427 GV->setAlignment(Alignment.getAsAlign());
5428 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5429 Alignment);
5430 }
5431 }
5432
5433 // Get the default prefix if a name wasn't specified.
5434 if (!GlobalName)
5435 GlobalName = ".str";
5436 // Create a global variable for this.
5437 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5438 GlobalName, Alignment);
5439 if (Entry)
5440 *Entry = GV;
5441
5442 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5443 Alignment);
5444}
5445
5446ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5447 const MaterializeTemporaryExpr *E, const Expr *Init) {
5448 assert((E->getStorageDuration() == SD_Static ||(static_cast <bool> ((E->getStorageDuration() == SD_Static
|| E->getStorageDuration() == SD_Thread) && "not a global temporary"
) ? void (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5449, __extension__ __PRETTY_FUNCTION__))
5449 E->getStorageDuration() == SD_Thread) && "not a global temporary")(static_cast <bool> ((E->getStorageDuration() == SD_Static
|| E->getStorageDuration() == SD_Thread) && "not a global temporary"
) ? void (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5449, __extension__ __PRETTY_FUNCTION__))
;
5450 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5451
5452 // If we're not materializing a subobject of the temporary, keep the
5453 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5454 QualType MaterializedType = Init->getType();
5455 if (Init == E->getSubExpr())
5456 MaterializedType = E->getType();
5457
5458 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5459
5460 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5461 if (!InsertResult.second) {
5462 // We've seen this before: either we already created it or we're in the
5463 // process of doing so.
5464 if (!InsertResult.first->second) {
5465 // We recursively re-entered this function, probably during emission of
5466 // the initializer. Create a placeholder. We'll clean this up in the
5467 // outer call, at the end of this function.
5468 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5469 InsertResult.first->second = new llvm::GlobalVariable(
5470 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5471 nullptr);
5472 }
5473 return ConstantAddress(InsertResult.first->second, Align);
5474 }
5475
5476 // FIXME: If an externally-visible declaration extends multiple temporaries,
5477 // we need to give each temporary the same name in every translation unit (and
5478 // we also need to make the temporaries externally-visible).
5479 SmallString<256> Name;
5480 llvm::raw_svector_ostream Out(Name);
5481 getCXXABI().getMangleContext().mangleReferenceTemporary(
5482 VD, E->getManglingNumber(), Out);
5483
5484 APValue *Value = nullptr;
5485 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5486 // If the initializer of the extending declaration is a constant
5487 // initializer, we should have a cached constant initializer for this
5488 // temporary. Note that this might have a different value from the value
5489 // computed by evaluating the initializer if the surrounding constant
5490 // expression modifies the temporary.
5491 Value = E->getOrCreateValue(false);
5492 }
5493
5494 // Try evaluating it now, it might have a constant initializer.
5495 Expr::EvalResult EvalResult;
5496 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5497 !EvalResult.hasSideEffects())
5498 Value = &EvalResult.Val;
5499
5500 LangAS AddrSpace =
5501 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5502
5503 Optional<ConstantEmitter> emitter;
5504 llvm::Constant *InitialValue = nullptr;
5505 bool Constant = false;
5506 llvm::Type *Type;
5507 if (Value) {
5508 // The temporary has a constant initializer, use it.
5509 emitter.emplace(*this);
5510 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5511 MaterializedType);
5512 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5513 Type = InitialValue->getType();
5514 } else {
5515 // No initializer, the initialization will be provided when we
5516 // initialize the declaration which performed lifetime extension.
5517 Type = getTypes().ConvertTypeForMem(MaterializedType);
5518 }
5519
5520 // Create a global variable for this lifetime-extended temporary.
5521 llvm::GlobalValue::LinkageTypes Linkage =
5522 getLLVMLinkageVarDefinition(VD, Constant);
5523 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5524 const VarDecl *InitVD;
5525 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5526 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5527 // Temporaries defined inside a class get linkonce_odr linkage because the
5528 // class can be defined in multiple translation units.
5529 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5530 } else {
5531 // There is no need for this temporary to have external linkage if the
5532 // VarDecl has external linkage.
5533 Linkage = llvm::GlobalVariable::InternalLinkage;
5534 }
5535 }
5536 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5537 auto *GV = new llvm::GlobalVariable(
5538 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5539 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5540 if (emitter) emitter->finalize(GV);
5541 setGVProperties(GV, VD);
5542 GV->setAlignment(Align.getAsAlign());
5543 if (supportsCOMDAT() && GV->isWeakForLinker())
5544 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5545 if (VD->getTLSKind())
5546 setTLSMode(GV, *VD);
5547 llvm::Constant *CV = GV;
5548 if (AddrSpace != LangAS::Default)
5549 CV = getTargetCodeGenInfo().performAddrSpaceCast(
5550 *this, GV, AddrSpace, LangAS::Default,
5551 Type->getPointerTo(
5552 getContext().getTargetAddressSpace(LangAS::Default)));
5553
5554 // Update the map with the new temporary. If we created a placeholder above,
5555 // replace it with the new global now.
5556 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5557 if (Entry) {
5558 Entry->replaceAllUsesWith(
5559 llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5560 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5561 }
5562 Entry = CV;
5563
5564 return ConstantAddress(CV, Align);
5565}
5566
5567/// EmitObjCPropertyImplementations - Emit information for synthesized
5568/// properties for an implementation.
5569void CodeGenModule::EmitObjCPropertyImplementations(const
5570 ObjCImplementationDecl *D) {
5571 for (const auto *PID : D->property_impls()) {
5572 // Dynamic is just for type-checking.
5573 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5574 ObjCPropertyDecl *PD = PID->getPropertyDecl();
5575
5576 // Determine which methods need to be implemented, some may have
5577 // been overridden. Note that ::isPropertyAccessor is not the method
5578 // we want, that just indicates if the decl came from a
5579 // property. What we want to know is if the method is defined in
5580 // this implementation.
5581 auto *Getter = PID->getGetterMethodDecl();
5582 if (!Getter || Getter->isSynthesizedAccessorStub())
5583 CodeGenFunction(*this).GenerateObjCGetter(
5584 const_cast<ObjCImplementationDecl *>(D), PID);
5585 auto *Setter = PID->getSetterMethodDecl();
5586 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5587 CodeGenFunction(*this).GenerateObjCSetter(
5588 const_cast<ObjCImplementationDecl *>(D), PID);
5589 }
5590 }
5591}
5592
5593static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5594 const ObjCInterfaceDecl *iface = impl->getClassInterface();
5595 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5596 ivar; ivar = ivar->getNextIvar())
5597 if (ivar->getType().isDestructedType())
5598 return true;
5599
5600 return false;
5601}
5602
5603static bool AllTrivialInitializers(CodeGenModule &CGM,
5604 ObjCImplementationDecl *D) {
5605 CodeGenFunction CGF(CGM);
5606 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5607 E = D->init_end(); B != E; ++B) {
5608 CXXCtorInitializer *CtorInitExp = *B;
5609 Expr *Init = CtorInitExp->getInit();
5610 if (!CGF.isTrivialInitializer(Init))
5611 return false;
5612 }
5613 return true;
5614}
5615
5616/// EmitObjCIvarInitializations - Emit information for ivar initialization
5617/// for an implementation.
5618void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5619 // We might need a .cxx_destruct even if we don't have any ivar initializers.
5620 if (needsDestructMethod(D)) {
5621 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5622 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5623 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5624 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5625 getContext().VoidTy, nullptr, D,
5626 /*isInstance=*/true, /*isVariadic=*/false,
5627 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5628 /*isImplicitlyDeclared=*/true,
5629 /*isDefined=*/false, ObjCMethodDecl::Required);
5630 D->addInstanceMethod(DTORMethod);
5631 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5632 D->setHasDestructors(true);
5633 }
5634
5635 // If the implementation doesn't have any ivar initializers, we don't need
5636 // a .cxx_construct.
5637 if (D->getNumIvarInitializers() == 0 ||
5638 AllTrivialInitializers(*this, D))
5639 return;
5640
5641 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5642 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5643 // The constructor returns 'self'.
5644 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5645 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5646 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5647 /*isVariadic=*/false,
5648 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5649 /*isImplicitlyDeclared=*/true,
5650 /*isDefined=*/false, ObjCMethodDecl::Required);
5651 D->addInstanceMethod(CTORMethod);
5652 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5653 D->setHasNonZeroConstructors(true);
5654}
5655
5656// EmitLinkageSpec - Emit all declarations in a linkage spec.
5657void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5658 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5659 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5660 ErrorUnsupported(LSD, "linkage spec");
5661 return;
5662 }
5663
5664 EmitDeclContext(LSD);
5665}
5666
5667void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5668 for (auto *I : DC->decls()) {
5669 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5670 // are themselves considered "top-level", so EmitTopLevelDecl on an
5671 // ObjCImplDecl does not recursively visit them. We need to do that in
5672 // case they're nested inside another construct (LinkageSpecDecl /
5673 // ExportDecl) that does stop them from being considered "top-level".
5674 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5675 for (auto *M : OID->methods())
5676 EmitTopLevelDecl(M);
5677 }
5678
5679 EmitTopLevelDecl(I);
5680 }
5681}
5682
5683/// EmitTopLevelDecl - Emit code for a single top level declaration.
5684void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5685 // Ignore dependent declarations.
5686 if (D->isTemplated())
5687 return;
5688
5689 // Consteval function shouldn't be emitted.
5690 if (auto *FD = dyn_cast<FunctionDecl>(D))
5691 if (FD->isConsteval())
5692 return;
5693
5694 switch (D->getKind()) {
5695 case Decl::CXXConversion:
5696 case Decl::CXXMethod:
5697 case Decl::Function:
5698 EmitGlobal(cast<FunctionDecl>(D));
5699 // Always provide some coverage mapping
5700 // even for the functions that aren't emitted.
5701 AddDeferredUnusedCoverageMapping(D);
5702 break;
5703
5704 case Decl::CXXDeductionGuide:
5705 // Function-like, but does not result in code emission.
5706 break;
5707
5708 case Decl::Var:
5709 case Decl::Decomposition:
5710 case Decl::VarTemplateSpecialization:
5711 EmitGlobal(cast<VarDecl>(D));
5712 if (auto *DD = dyn_cast<DecompositionDecl>(D))
5713 for (auto *B : DD->bindings())
5714 if (auto *HD = B->getHoldingVar())
5715 EmitGlobal(HD);
5716 break;
5717
5718 // Indirect fields from global anonymous structs and unions can be
5719 // ignored; only the actual variable requires IR gen support.
5720 case Decl::IndirectField:
5721 break;
5722
5723 // C++ Decls
5724 case Decl::Namespace:
5725 EmitDeclContext(cast<NamespaceDecl>(D));
5726 break;
5727 case Decl::ClassTemplateSpecialization: {
5728 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5729 if (CGDebugInfo *DI = getModuleDebugInfo())
5730 if (Spec->getSpecializationKind() ==
5731 TSK_ExplicitInstantiationDefinition &&
5732 Spec->hasDefinition())
5733 DI->completeTemplateDefinition(*Spec);
5734 } LLVM_FALLTHROUGH[[gnu::fallthrough]];
5735 case Decl::CXXRecord: {
5736 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5737 if (CGDebugInfo *DI = getModuleDebugInfo()) {
5738 if (CRD->hasDefinition())
5739 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5740 if (auto *ES = D->getASTContext().getExternalSource())
5741 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5742 DI->completeUnusedClass(*CRD);
5743 }
5744 // Emit any static data members, they may be definitions.
5745 for (auto *I : CRD->decls())
5746 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5747 EmitTopLevelDecl(I);
5748 break;
5749 }
5750 // No code generation needed.
5751 case Decl::UsingShadow:
5752 case Decl::ClassTemplate:
5753 case Decl::VarTemplate:
5754 case Decl::Concept:
5755 case Decl::VarTemplatePartialSpecialization:
5756 case Decl::FunctionTemplate:
5757 case Decl::TypeAliasTemplate:
5758 case Decl::Block:
5759 case Decl::Empty:
5760 case Decl::Binding:
5761 break;
5762 case Decl::Using: // using X; [C++]
5763 if (CGDebugInfo *DI = getModuleDebugInfo())
5764 DI->EmitUsingDecl(cast<UsingDecl>(*D));
5765 break;
5766 case Decl::UsingEnum: // using enum X; [C++]
5767 if (CGDebugInfo *DI = getModuleDebugInfo())
5768 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
5769 break;
5770 case Decl::NamespaceAlias:
5771 if (CGDebugInfo *DI = getModuleDebugInfo())
5772 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5773 break;
5774 case Decl::UsingDirective: // using namespace X; [C++]
5775 if (CGDebugInfo *DI = getModuleDebugInfo())
5776 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5777 break;
5778 case Decl::CXXConstructor:
5779 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5780 break;
5781 case Decl::CXXDestructor:
5782 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5783 break;
5784
5785 case Decl::StaticAssert:
5786 // Nothing to do.
5787 break;
5788
5789 // Objective-C Decls
5790
5791 // Forward declarations, no (immediate) code generation.
5792 case Decl::ObjCInterface:
5793 case Decl::ObjCCategory:
5794 break;
5795
5796 case Decl::ObjCProtocol: {
5797 auto *Proto = cast<ObjCProtocolDecl>(D);
5798 if (Proto->isThisDeclarationADefinition())
5799 ObjCRuntime->GenerateProtocol(Proto);
5800 break;
5801 }
5802
5803 case Decl::ObjCCategoryImpl:
5804 // Categories have properties but don't support synthesize so we
5805 // can ignore them here.
5806 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5807 break;
5808
5809 case Decl::ObjCImplementation: {
5810 auto *OMD = cast<ObjCImplementationDecl>(D);
5811 EmitObjCPropertyImplementations(OMD);
5812 EmitObjCIvarInitializations(OMD);
5813 ObjCRuntime->GenerateClass(OMD);
5814 // Emit global variable debug information.
5815 if (CGDebugInfo *DI = getModuleDebugInfo())
5816 if (getCodeGenOpts().hasReducedDebugInfo())
5817 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5818 OMD->getClassInterface()), OMD->getLocation());
5819 break;
5820 }
5821 case Decl::ObjCMethod: {
5822 auto *OMD = cast<ObjCMethodDecl>(D);
5823 // If this is not a prototype, emit the body.
5824 if (OMD->getBody())
5825 CodeGenFunction(*this).GenerateObjCMethod(OMD);
5826 break;
5827 }
5828 case Decl::ObjCCompatibleAlias:
5829 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5830 break;
5831
5832 case Decl::PragmaComment: {
5833 const auto *PCD = cast<PragmaCommentDecl>(D);
5834 switch (PCD->getCommentKind()) {
5835 case PCK_Unknown:
5836 llvm_unreachable("unexpected pragma comment kind")::llvm::llvm_unreachable_internal("unexpected pragma comment kind"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5836)
;
5837 case PCK_Linker:
5838 AppendLinkerOptions(PCD->getArg());
5839 break;
5840 case PCK_Lib:
5841 AddDependentLib(PCD->getArg());
5842 break;
5843 case PCK_Compiler:
5844 case PCK_ExeStr:
5845 case PCK_User:
5846 break; // We ignore all of these.
5847 }
5848 break;
5849 }
5850
5851 case Decl::PragmaDetectMismatch: {
5852 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5853 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5854 break;
5855 }
5856
5857 case Decl::LinkageSpec:
5858 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5859 break;
5860
5861 case Decl::FileScopeAsm: {
5862 // File-scope asm is ignored during device-side CUDA compilation.
5863 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5864 break;
5865 // File-scope asm is ignored during device-side OpenMP compilation.
5866 if (LangOpts.OpenMPIsDevice)
5867 break;
5868 // File-scope asm is ignored during device-side SYCL compilation.
5869 if (LangOpts.SYCLIsDevice)
5870 break;
5871 auto *AD = cast<FileScopeAsmDecl>(D);
5872 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5873 break;
5874 }
5875
5876 case Decl::Import: {
5877 auto *Import = cast<ImportDecl>(D);
5878
5879 // If we've already imported this module, we're done.
5880 if (!ImportedModules.insert(Import->getImportedModule()))
5881 break;
5882
5883 // Emit debug information for direct imports.
5884 if (!Import->getImportedOwningModule()) {
5885 if (CGDebugInfo *DI = getModuleDebugInfo())
5886 DI->EmitImportDecl(*Import);
5887 }
5888
5889 // Find all of the submodules and emit the module initializers.
5890 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5891 SmallVector<clang::Module *, 16> Stack;
5892 Visited.insert(Import->getImportedModule());
5893 Stack.push_back(Import->getImportedModule());
5894
5895 while (!Stack.empty()) {
5896 clang::Module *Mod = Stack.pop_back_val();
5897 if (!EmittedModuleInitializers.insert(Mod).second)
5898 continue;
5899
5900 for (auto *D : Context.getModuleInitializers(Mod))
5901 EmitTopLevelDecl(D);
5902
5903 // Visit the submodules of this module.
5904 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5905 SubEnd = Mod->submodule_end();
5906 Sub != SubEnd; ++Sub) {
5907 // Skip explicit children; they need to be explicitly imported to emit
5908 // the initializers.
5909 if ((*Sub)->IsExplicit)
5910 continue;
5911
5912 if (Visited.insert(*Sub).second)
5913 Stack.push_back(*Sub);
5914 }
5915 }
5916 break;
5917 }
5918
5919 case Decl::Export:
5920 EmitDeclContext(cast<ExportDecl>(D));
5921 break;
5922
5923 case Decl::OMPThreadPrivate:
5924 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5925 break;
5926
5927 case Decl::OMPAllocate:
5928 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
5929 break;
5930
5931 case Decl::OMPDeclareReduction:
5932 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5933 break;
5934
5935 case Decl::OMPDeclareMapper:
5936 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5937 break;
5938
5939 case Decl::OMPRequires:
5940 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5941 break;
5942
5943 case Decl::Typedef:
5944 case Decl::TypeAlias: // using foo = bar; [C++11]
5945 if (CGDebugInfo *DI = getModuleDebugInfo())
5946 DI->EmitAndRetainType(
5947 getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5948 break;
5949
5950 case Decl::Record:
5951 if (CGDebugInfo *DI = getModuleDebugInfo())
5952 if (cast<RecordDecl>(D)->getDefinition())
5953 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5954 break;
5955
5956 case Decl::Enum:
5957 if (CGDebugInfo *DI = getModuleDebugInfo())
5958 if (cast<EnumDecl>(D)->getDefinition())
5959 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5960 break;
5961
5962 default:
5963 // Make sure we handled everything we should, every other kind is a
5964 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5965 // function. Need to recode Decl::Kind to do that easily.
5966 assert(isa<TypeDecl>(D) && "Unsupported decl kind")(static_cast <bool> (isa<TypeDecl>(D) && "Unsupported decl kind"
) ? void (0) : __assert_fail ("isa<TypeDecl>(D) && \"Unsupported decl kind\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 5966, __extension__ __PRETTY_FUNCTION__))
;
5967 break;
5968 }
5969}
5970
5971void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5972 // Do we need to generate coverage mapping?
5973 if (!CodeGenOpts.CoverageMapping)
5974 return;
5975 switch (D->getKind()) {
5976 case Decl::CXXConversion:
5977 case Decl::CXXMethod:
5978 case Decl::Function:
5979 case Decl::ObjCMethod:
5980 case Decl::CXXConstructor:
5981 case Decl::CXXDestructor: {
5982 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5983 break;
5984 SourceManager &SM = getContext().getSourceManager();
5985 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5986 break;
5987 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5988 if (I == DeferredEmptyCoverageMappingDecls.end())
5989 DeferredEmptyCoverageMappingDecls[D] = true;
5990 break;
5991 }
5992 default:
5993 break;
5994 };
5995}
5996
5997void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5998 // Do we need to generate coverage mapping?
5999 if (!CodeGenOpts.CoverageMapping)
6000 return;
6001 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6002 if (Fn->isTemplateInstantiation())
6003 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6004 }
6005 auto I = DeferredEmptyCoverageMappingDecls.find(D);
6006 if (I == DeferredEmptyCoverageMappingDecls.end())
6007 DeferredEmptyCoverageMappingDecls[D] = false;
6008 else
6009 I->second = false;
6010}
6011
6012void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6013 // We call takeVector() here to avoid use-after-free.
6014 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6015 // we deserialize function bodies to emit coverage info for them, and that
6016 // deserializes more declarations. How should we handle that case?
6017 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6018 if (!Entry.second)
6019 continue;
6020 const Decl *D = Entry.first;
6021 switch (D->getKind()) {
6022 case Decl::CXXConversion:
6023 case Decl::CXXMethod:
6024 case Decl::Function:
6025 case Decl::ObjCMethod: {
6026 CodeGenPGO PGO(*this);
6027 GlobalDecl GD(cast<FunctionDecl>(D));
6028 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6029 getFunctionLinkage(GD));
6030 break;
6031 }
6032 case Decl::CXXConstructor: {
6033 CodeGenPGO PGO(*this);
6034 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6035 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6036 getFunctionLinkage(GD));
6037 break;
6038 }
6039 case Decl::CXXDestructor: {
6040 CodeGenPGO PGO(*this);
6041 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6042 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6043 getFunctionLinkage(GD));
6044 break;
6045 }
6046 default:
6047 break;
6048 };
6049 }
6050}
6051
6052void CodeGenModule::EmitMainVoidAlias() {
6053 // In order to transition away from "__original_main" gracefully, emit an
6054 // alias for "main" in the no-argument case so that libc can detect when
6055 // new-style no-argument main is in used.
6056 if (llvm::Function *F = getModule().getFunction("main")) {
6057 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6058 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
6059 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
6060 }
6061}
6062
6063/// Turns the given pointer into a constant.
6064static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6065 const void *Ptr) {
6066 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6067 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6068 return llvm::ConstantInt::get(i64, PtrInt);
6069}
6070
6071static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6072 llvm::NamedMDNode *&GlobalMetadata,
6073 GlobalDecl D,
6074 llvm::GlobalValue *Addr) {
6075 if (!GlobalMetadata)
6076 GlobalMetadata =
6077 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6078
6079 // TODO: should we report variant information for ctors/dtors?
6080 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6081 llvm::ConstantAsMetadata::get(GetPointerConstant(
6082 CGM.getLLVMContext(), D.getDecl()))};
6083 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6084}
6085
6086/// For each function which is declared within an extern "C" region and marked
6087/// as 'used', but has internal linkage, create an alias from the unmangled
6088/// name to the mangled name if possible. People expect to be able to refer
6089/// to such functions with an unmangled name from inline assembly within the
6090/// same translation unit.
6091void CodeGenModule::EmitStaticExternCAliases() {
6092 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6093 return;
6094 for (auto &I : StaticExternCValues) {
6095 IdentifierInfo *Name = I.first;
6096 llvm::GlobalValue *Val = I.second;
6097 if (Val && !getModule().getNamedValue(Name->getName()))
6098 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6099 }
6100}
6101
6102bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6103 GlobalDecl &Result) const {
6104 auto Res = Manglings.find(MangledName);
6105 if (Res == Manglings.end())
6106 return false;
6107 Result = Res->getValue();
6108 return true;
6109}
6110
6111/// Emits metadata nodes associating all the global values in the
6112/// current module with the Decls they came from. This is useful for
6113/// projects using IR gen as a subroutine.
6114///
6115/// Since there's currently no way to associate an MDNode directly
6116/// with an llvm::GlobalValue, we create a global named metadata
6117/// with the name 'clang.global.decl.ptrs'.
6118void CodeGenModule::EmitDeclMetadata() {
6119 llvm::NamedMDNode *GlobalMetadata = nullptr;
6120
6121 for (auto &I : MangledDeclNames) {
6122 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6123 // Some mangled names don't necessarily have an associated GlobalValue
6124 // in this module, e.g. if we mangled it for DebugInfo.
6125 if (Addr)
6126 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6127 }
6128}
6129
6130/// Emits metadata nodes for all the local variables in the current
6131/// function.
6132void CodeGenFunction::EmitDeclMetadata() {
6133 if (LocalDeclMap.empty()) return;
6134
6135 llvm::LLVMContext &Context = getLLVMContext();
6136
6137 // Find the unique metadata ID for this name.
6138 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6139
6140 llvm::NamedMDNode *GlobalMetadata = nullptr;
6141
6142 for (auto &I : LocalDeclMap) {
6143 const Decl *D = I.first;
6144 llvm::Value *Addr = I.second.getPointer();
6145 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6146 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6147 Alloca->setMetadata(
6148 DeclPtrKind, llvm::MDNode::get(
6149 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6150 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6151 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6152 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6153 }
6154 }
6155}
6156
6157void CodeGenModule::EmitVersionIdentMetadata() {
6158 llvm::NamedMDNode *IdentMetadata =
6159 TheModule.getOrInsertNamedMetadata("llvm.ident");
6160 std::string Version = getClangFullVersion();
6161 llvm::LLVMContext &Ctx = TheModule.getContext();
6162
6163 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6164 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6165}
6166
6167void CodeGenModule::EmitCommandLineMetadata() {
6168 llvm::NamedMDNode *CommandLineMetadata =
6169 TheModule.getOrInsertNamedMetadata("llvm.commandline");
6170 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6171 llvm::LLVMContext &Ctx = TheModule.getContext();
6172
6173 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6174 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6175}
6176
6177void CodeGenModule::EmitCoverageFile() {
6178 if (getCodeGenOpts().CoverageDataFile.empty() &&
6179 getCodeGenOpts().CoverageNotesFile.empty())
6180 return;
6181
6182 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6183 if (!CUNode)
6184 return;
6185
6186 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6187 llvm::LLVMContext &Ctx = TheModule.getContext();
6188 auto *CoverageDataFile =
6189 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6190 auto *CoverageNotesFile =
6191 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6192 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6193 llvm::MDNode *CU = CUNode->getOperand(i);
6194 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6195 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6196 }
6197}
6198
6199llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6200 bool ForEH) {
6201 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6202 // FIXME: should we even be calling this method if RTTI is disabled
6203 // and it's not for EH?
6204 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6205 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6206 getTriple().isNVPTX()))
6207 return llvm::Constant::getNullValue(Int8PtrTy);
6208
6209 if (ForEH && Ty->isObjCObjectPointerType() &&
6210 LangOpts.ObjCRuntime.isGNUFamily())
6211 return ObjCRuntime->GetEHType(Ty);
6212
6213 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6214}
6215
6216void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6217 // Do not emit threadprivates in simd-only mode.
6218 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6219 return;
6220 for (auto RefExpr : D->varlists()) {
6221 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6222 bool PerformInit =
6223 VD->getAnyInitializer() &&
6224 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6225 /*ForRef=*/false);
6226
6227 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
6228 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6229 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6230 CXXGlobalInits.push_back(InitFunction);
6231 }
6232}
6233
6234llvm::Metadata *
6235CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6236 StringRef Suffix) {
6237 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6238 if (InternalId)
6239 return InternalId;
6240
6241 if (isExternallyVisible(T->getLinkage())) {
6242 std::string OutName;
6243 llvm::raw_string_ostream Out(OutName);
6244 getCXXABI().getMangleContext().mangleTypeName(T, Out);
6245 Out << Suffix;
6246
6247 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6248 } else {
6249 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6250 llvm::ArrayRef<llvm::Metadata *>());
6251 }
6252
6253 return InternalId;
6254}
6255
6256llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6257 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6258}
6259
6260llvm::Metadata *
6261CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6262 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6263}
6264
6265// Generalize pointer types to a void pointer with the qualifiers of the
6266// originally pointed-to type, e.g. 'const char *' and 'char * const *'
6267// generalize to 'const void *' while 'char *' and 'const char **' generalize to
6268// 'void *'.
6269static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6270 if (!Ty->isPointerType())
6271 return Ty;
6272
6273 return Ctx.getPointerType(
6274 QualType(Ctx.VoidTy).withCVRQualifiers(
6275 Ty->getPointeeType().getCVRQualifiers()));
6276}
6277
6278// Apply type generalization to a FunctionType's return and argument types
6279static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6280 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6281 SmallVector<QualType, 8> GeneralizedParams;
6282 for (auto &Param : FnType->param_types())
6283 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6284
6285 return Ctx.getFunctionType(
6286 GeneralizeType(Ctx, FnType->getReturnType()),
6287 GeneralizedParams, FnType->getExtProtoInfo());
6288 }
6289
6290 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6291 return Ctx.getFunctionNoProtoType(
6292 GeneralizeType(Ctx, FnType->getReturnType()));
6293
6294 llvm_unreachable("Encountered unknown FunctionType")::llvm::llvm_unreachable_internal("Encountered unknown FunctionType"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/CodeGen/CodeGenModule.cpp"
, 6294)
;
6295}
6296
6297llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6298 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6299 GeneralizedMetadataIdMap, ".generalized");
6300}
6301
6302/// Returns whether this module needs the "all-vtables" type identifier.
6303bool CodeGenModule::NeedAllVtablesTypeId() const {
6304 // Returns true if at least one of vtable-based CFI checkers is enabled and
6305 // is not in the trapping mode.
6306 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6307 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6308 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6309 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6310 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6311 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6312 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6313 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6314}
6315
6316void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6317 CharUnits Offset,
6318 const CXXRecordDecl *RD) {
6319 llvm::Metadata *MD =
6320 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6321 VTable->addTypeMetadata(Offset.getQuantity(), MD);
6322
6323 if (CodeGenOpts.SanitizeCfiCrossDso)
6324 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6325 VTable->addTypeMetadata(Offset.getQuantity(),
6326 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6327
6328 if (NeedAllVtablesTypeId()) {
6329 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6330 VTable->addTypeMetadata(Offset.getQuantity(), MD);
6331 }
6332}
6333
6334llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6335 if (!SanStats)
6336 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6337
6338 return *SanStats;
6339}
6340
6341llvm::Value *
6342CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6343 CodeGenFunction &CGF) {
6344 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6345 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6346 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6347 auto *Call = CGF.EmitRuntimeCall(
6348 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6349 return Call;
6350}
6351
6352CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6353 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6354 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6355 /* forPointeeType= */ true);
6356}
6357
6358CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6359 LValueBaseInfo *BaseInfo,
6360 TBAAAccessInfo *TBAAInfo,
6361 bool forPointeeType) {
6362 if (TBAAInfo)
6363 *TBAAInfo = getTBAAAccessInfo(T);
6364
6365 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6366 // that doesn't return the information we need to compute BaseInfo.
6367
6368 // Honor alignment typedef attributes even on incomplete types.
6369 // We also honor them straight for C++ class types, even as pointees;
6370 // there's an expressivity gap here.
6371 if (auto TT = T->getAs<TypedefType>()) {
6372 if (auto Align = TT->getDecl()->getMaxAlignment()) {
6373 if (BaseInfo)
6374 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6375 return getContext().toCharUnitsFromBits(Align);
6376 }
6377 }
6378
6379 bool AlignForArray = T->isArrayType();
6380
6381 // Analyze the base element type, so we don't get confused by incomplete
6382 // array types.
6383 T = getContext().getBaseElementType(T);
6384
6385 if (T->isIncompleteType()) {
6386 // We could try to replicate the logic from
6387 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6388 // type is incomplete, so it's impossible to test. We could try to reuse
6389 // getTypeAlignIfKnown, but that doesn't return the information we need
6390 // to set BaseInfo. So just ignore the possibility that the alignment is
6391 // greater than one.
6392 if (BaseInfo)
6393 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6394 return CharUnits::One();
6395 }
6396
6397 if (BaseInfo)
6398 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6399
6400 CharUnits Alignment;
6401 const CXXRecordDecl *RD;
6402 if (T.getQualifiers().hasUnaligned()) {
6403 Alignment = CharUnits::One();
6404 } else if (forPointeeType && !AlignForArray &&
6405 (RD = T->getAsCXXRecordDecl())) {
6406 // For C++ class pointees, we don't know whether we're pointing at a
6407 // base or a complete object, so we generally need to use the
6408 // non-virtual alignment.
6409 Alignment = getClassPointerAlignment(RD);
6410 } else {
6411 Alignment = getContext().getTypeAlignInChars(T);
6412 }
6413
6414 // Cap to the global maximum type alignment unless the alignment
6415 // was somehow explicit on the type.
6416 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6417 if (Alignment.getQuantity() > MaxAlign &&
6418 !getContext().isAlignmentRequired(T))
6419 Alignment = CharUnits::fromQuantity(MaxAlign);
6420 }
6421 return Alignment;
6422}
6423
6424bool CodeGenModule::stopAutoInit() {
6425 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6426 if (StopAfter) {
6427 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6428 // used
6429 if (NumAutoVarInit >= StopAfter) {
6430 return true;
6431 }
6432 if (!NumAutoVarInit) {
6433 unsigned DiagID = getDiags().getCustomDiagID(
6434 DiagnosticsEngine::Warning,
6435 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6436 "number of times ftrivial-auto-var-init=%1 gets applied.");
6437 getDiags().Report(DiagID)
6438 << StopAfter
6439 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6440 LangOptions::TrivialAutoVarInitKind::Zero
6441 ? "zero"
6442 : "pattern");
6443 }
6444 ++NumAutoVarInit;
6445 }
6446 return false;
6447}
6448
6449void CodeGenModule::printPostfixForExternalizedStaticVar(
6450 llvm::raw_ostream &OS) const {
6451 OS << ".static." << getContext().getCUIDHash();
6452}

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h

1//===- GlobalDecl.h - Global declaration holder -----------------*- C++ -*-===//
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// A GlobalDecl can hold either a regular variable/function or a C++ ctor/dtor
10// together with its type.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_GLOBALDECL_H
15#define LLVM_CLANG_AST_GLOBALDECL_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/Basic/ABI.h"
22#include "clang/Basic/LLVM.h"
23#include "llvm/ADT/DenseMapInfo.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/type_traits.h"
27#include <cassert>
28
29namespace clang {
30
31enum class DynamicInitKind : unsigned {
32 NoStub = 0,
33 Initializer,
34 AtExit,
35 GlobalArrayDestructor
36};
37
38enum class KernelReferenceKind : unsigned {
39 Kernel = 0,
40 Stub = 1,
41};
42
43/// GlobalDecl - represents a global declaration. This can either be a
44/// CXXConstructorDecl and the constructor type (Base, Complete).
45/// a CXXDestructorDecl and the destructor type (Base, Complete),
46/// a FunctionDecl and the kernel reference type (Kernel, Stub), or
47/// a VarDecl, a FunctionDecl or a BlockDecl.
48///
49/// When a new type of GlobalDecl is added, the following places should
50/// be updated to convert a Decl* to a GlobalDecl:
51/// PredefinedExpr::ComputeName() in lib/AST/Expr.cpp.
52/// getParentOfLocalEntity() in lib/AST/ItaniumMangle.cpp
53/// ASTNameGenerator::Implementation::writeFuncOrVarName in lib/AST/Mangle.cpp
54///
55class GlobalDecl {
56 llvm::PointerIntPair<const Decl *, 3> Value;
57 unsigned MultiVersionIndex = 0;
58
59 void Init(const Decl *D) {
60 assert(!isa<CXXConstructorDecl>(D) && "Use other ctor with ctor decls!")(static_cast <bool> (!isa<CXXConstructorDecl>(D) &&
"Use other ctor with ctor decls!") ? void (0) : __assert_fail
("!isa<CXXConstructorDecl>(D) && \"Use other ctor with ctor decls!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 60, __extension__ __PRETTY_FUNCTION__))
;
61 assert(!isa<CXXDestructorDecl>(D) && "Use other ctor with dtor decls!")(static_cast <bool> (!isa<CXXDestructorDecl>(D) &&
"Use other ctor with dtor decls!") ? void (0) : __assert_fail
("!isa<CXXDestructorDecl>(D) && \"Use other ctor with dtor decls!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 61, __extension__ __PRETTY_FUNCTION__))
;
62 assert(!D->hasAttr<CUDAGlobalAttr>() && "Use other ctor with GPU kernels!")(static_cast <bool> (!D->hasAttr<CUDAGlobalAttr>
() && "Use other ctor with GPU kernels!") ? void (0) :
__assert_fail ("!D->hasAttr<CUDAGlobalAttr>() && \"Use other ctor with GPU kernels!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 62, __extension__ __PRETTY_FUNCTION__))
;
63
64 Value.setPointer(D);
65 }
66
67public:
68 GlobalDecl() = default;
69 GlobalDecl(const VarDecl *D) { Init(D);}
70 GlobalDecl(const FunctionDecl *D, unsigned MVIndex = 0)
71 : MultiVersionIndex(MVIndex) {
72 if (!D->hasAttr<CUDAGlobalAttr>()) {
73 Init(D);
74 return;
75 }
76 Value.setPointerAndInt(D, unsigned(getDefaultKernelReference(D)));
77 }
78 GlobalDecl(const FunctionDecl *D, KernelReferenceKind Kind)
79 : Value(D, unsigned(Kind)) {
80 assert(D->hasAttr<CUDAGlobalAttr>() && "Decl is not a GPU kernel!")(static_cast <bool> (D->hasAttr<CUDAGlobalAttr>
() && "Decl is not a GPU kernel!") ? void (0) : __assert_fail
("D->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 80, __extension__ __PRETTY_FUNCTION__))
;
81 }
82 GlobalDecl(const NamedDecl *D) { Init(D); }
83 GlobalDecl(const BlockDecl *D) { Init(D); }
84 GlobalDecl(const CapturedDecl *D) { Init(D); }
85 GlobalDecl(const ObjCMethodDecl *D) { Init(D); }
86 GlobalDecl(const OMPDeclareReductionDecl *D) { Init(D); }
87 GlobalDecl(const OMPDeclareMapperDecl *D) { Init(D); }
88 GlobalDecl(const CXXConstructorDecl *D, CXXCtorType Type) : Value(D, Type) {}
89 GlobalDecl(const CXXDestructorDecl *D, CXXDtorType Type) : Value(D, Type) {}
90 GlobalDecl(const VarDecl *D, DynamicInitKind StubKind)
91 : Value(D, unsigned(StubKind)) {}
92
93 GlobalDecl getCanonicalDecl() const {
94 GlobalDecl CanonGD;
95 CanonGD.Value.setPointer(Value.getPointer()->getCanonicalDecl());
96 CanonGD.Value.setInt(Value.getInt());
97 CanonGD.MultiVersionIndex = MultiVersionIndex;
98
99 return CanonGD;
100 }
101
102 const Decl *getDecl() const { return Value.getPointer(); }
46
Calling 'PointerIntPair::getPointer'
55
Returning from 'PointerIntPair::getPointer'
56
Returning pointer
103
104 CXXCtorType getCtorType() const {
105 assert(isa<CXXConstructorDecl>(getDecl()) && "Decl is not a ctor!")(static_cast <bool> (isa<CXXConstructorDecl>(getDecl
()) && "Decl is not a ctor!") ? void (0) : __assert_fail
("isa<CXXConstructorDecl>(getDecl()) && \"Decl is not a ctor!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 105, __extension__ __PRETTY_FUNCTION__))
;
106 return static_cast<CXXCtorType>(Value.getInt());
107 }
108
109 CXXDtorType getDtorType() const {
110 assert(isa<CXXDestructorDecl>(getDecl()) && "Decl is not a dtor!")(static_cast <bool> (isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a dtor!") ? void (0) : __assert_fail
("isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a dtor!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 110, __extension__ __PRETTY_FUNCTION__))
;
111 return static_cast<CXXDtorType>(Value.getInt());
112 }
113
114 DynamicInitKind getDynamicInitKind() const {
115 assert(isa<VarDecl>(getDecl()) &&(static_cast <bool> (isa<VarDecl>(getDecl()) &&
cast<VarDecl>(getDecl())->hasGlobalStorage() &&
"Decl is not a global variable!") ? void (0) : __assert_fail
("isa<VarDecl>(getDecl()) && cast<VarDecl>(getDecl())->hasGlobalStorage() && \"Decl is not a global variable!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 117, __extension__ __PRETTY_FUNCTION__))
116 cast<VarDecl>(getDecl())->hasGlobalStorage() &&(static_cast <bool> (isa<VarDecl>(getDecl()) &&
cast<VarDecl>(getDecl())->hasGlobalStorage() &&
"Decl is not a global variable!") ? void (0) : __assert_fail
("isa<VarDecl>(getDecl()) && cast<VarDecl>(getDecl())->hasGlobalStorage() && \"Decl is not a global variable!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 117, __extension__ __PRETTY_FUNCTION__))
117 "Decl is not a global variable!")(static_cast <bool> (isa<VarDecl>(getDecl()) &&
cast<VarDecl>(getDecl())->hasGlobalStorage() &&
"Decl is not a global variable!") ? void (0) : __assert_fail
("isa<VarDecl>(getDecl()) && cast<VarDecl>(getDecl())->hasGlobalStorage() && \"Decl is not a global variable!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 117, __extension__ __PRETTY_FUNCTION__))
;
118 return static_cast<DynamicInitKind>(Value.getInt());
119 }
120
121 unsigned getMultiVersionIndex() const {
122 assert(isa<FunctionDecl>((static_cast <bool> (isa<FunctionDecl>( getDecl()
) && !cast<FunctionDecl>(getDecl())->hasAttr
<CUDAGlobalAttr>() && !isa<CXXConstructorDecl
>(getDecl()) && !isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a plain FunctionDecl!") ? void (0
) : __assert_fail ("isa<FunctionDecl>( getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 127, __extension__ __PRETTY_FUNCTION__))
123 getDecl()) &&(static_cast <bool> (isa<FunctionDecl>( getDecl()
) && !cast<FunctionDecl>(getDecl())->hasAttr
<CUDAGlobalAttr>() && !isa<CXXConstructorDecl
>(getDecl()) && !isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a plain FunctionDecl!") ? void (0
) : __assert_fail ("isa<FunctionDecl>( getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 127, __extension__ __PRETTY_FUNCTION__))
124 !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() &&(static_cast <bool> (isa<FunctionDecl>( getDecl()
) && !cast<FunctionDecl>(getDecl())->hasAttr
<CUDAGlobalAttr>() && !isa<CXXConstructorDecl
>(getDecl()) && !isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a plain FunctionDecl!") ? void (0
) : __assert_fail ("isa<FunctionDecl>( getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 127, __extension__ __PRETTY_FUNCTION__))
125 !isa<CXXConstructorDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>( getDecl()
) && !cast<FunctionDecl>(getDecl())->hasAttr
<CUDAGlobalAttr>() && !isa<CXXConstructorDecl
>(getDecl()) && !isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a plain FunctionDecl!") ? void (0
) : __assert_fail ("isa<FunctionDecl>( getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 127, __extension__ __PRETTY_FUNCTION__))
126 !isa<CXXDestructorDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>( getDecl()
) && !cast<FunctionDecl>(getDecl())->hasAttr
<CUDAGlobalAttr>() && !isa<CXXConstructorDecl
>(getDecl()) && !isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a plain FunctionDecl!") ? void (0
) : __assert_fail ("isa<FunctionDecl>( getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 127, __extension__ __PRETTY_FUNCTION__))
127 "Decl is not a plain FunctionDecl!")(static_cast <bool> (isa<FunctionDecl>( getDecl()
) && !cast<FunctionDecl>(getDecl())->hasAttr
<CUDAGlobalAttr>() && !isa<CXXConstructorDecl
>(getDecl()) && !isa<CXXDestructorDecl>(getDecl
()) && "Decl is not a plain FunctionDecl!") ? void (0
) : __assert_fail ("isa<FunctionDecl>( getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 127, __extension__ __PRETTY_FUNCTION__))
;
128 return MultiVersionIndex;
129 }
130
131 KernelReferenceKind getKernelReferenceKind() const {
132 assert(isa<FunctionDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && "Decl is not a GPU kernel!") ?
void (0) : __assert_fail ("isa<FunctionDecl>(getDecl()) && cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 134, __extension__ __PRETTY_FUNCTION__))
133 cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && "Decl is not a GPU kernel!") ?
void (0) : __assert_fail ("isa<FunctionDecl>(getDecl()) && cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 134, __extension__ __PRETTY_FUNCTION__))
134 "Decl is not a GPU kernel!")(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && "Decl is not a GPU kernel!") ?
void (0) : __assert_fail ("isa<FunctionDecl>(getDecl()) && cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 134, __extension__ __PRETTY_FUNCTION__))
;
135 return static_cast<KernelReferenceKind>(Value.getInt());
136 }
137
138 friend bool operator==(const GlobalDecl &LHS, const GlobalDecl &RHS) {
139 return LHS.Value == RHS.Value &&
140 LHS.MultiVersionIndex == RHS.MultiVersionIndex;
141 }
142
143 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
144
145 explicit operator bool() const { return getAsOpaquePtr(); }
146
147 static GlobalDecl getFromOpaquePtr(void *P) {
148 GlobalDecl GD;
149 GD.Value.setFromOpaqueValue(P);
150 return GD;
151 }
152
153 static KernelReferenceKind getDefaultKernelReference(const FunctionDecl *D) {
154 return D->getLangOpts().CUDAIsDevice ? KernelReferenceKind::Kernel
155 : KernelReferenceKind::Stub;
156 }
157
158 GlobalDecl getWithDecl(const Decl *D) {
159 GlobalDecl Result(*this);
160 Result.Value.setPointer(D);
161 return Result;
162 }
163
164 GlobalDecl getWithCtorType(CXXCtorType Type) {
165 assert(isa<CXXConstructorDecl>(getDecl()))(static_cast <bool> (isa<CXXConstructorDecl>(getDecl
())) ? void (0) : __assert_fail ("isa<CXXConstructorDecl>(getDecl())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 165, __extension__ __PRETTY_FUNCTION__))
;
166 GlobalDecl Result(*this);
167 Result.Value.setInt(Type);
168 return Result;
169 }
170
171 GlobalDecl getWithDtorType(CXXDtorType Type) {
172 assert(isa<CXXDestructorDecl>(getDecl()))(static_cast <bool> (isa<CXXDestructorDecl>(getDecl
())) ? void (0) : __assert_fail ("isa<CXXDestructorDecl>(getDecl())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 172, __extension__ __PRETTY_FUNCTION__))
;
173 GlobalDecl Result(*this);
174 Result.Value.setInt(Type);
175 return Result;
176 }
177
178 GlobalDecl getWithMultiVersionIndex(unsigned Index) {
179 assert(isa<FunctionDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& !cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && !isa<CXXConstructorDecl>
(getDecl()) && !isa<CXXDestructorDecl>(getDecl(
)) && "Decl is not a plain FunctionDecl!") ? void (0)
: __assert_fail ("isa<FunctionDecl>(getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 183, __extension__ __PRETTY_FUNCTION__))
180 !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& !cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && !isa<CXXConstructorDecl>
(getDecl()) && !isa<CXXDestructorDecl>(getDecl(
)) && "Decl is not a plain FunctionDecl!") ? void (0)
: __assert_fail ("isa<FunctionDecl>(getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 183, __extension__ __PRETTY_FUNCTION__))
181 !isa<CXXConstructorDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& !cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && !isa<CXXConstructorDecl>
(getDecl()) && !isa<CXXDestructorDecl>(getDecl(
)) && "Decl is not a plain FunctionDecl!") ? void (0)
: __assert_fail ("isa<FunctionDecl>(getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 183, __extension__ __PRETTY_FUNCTION__))
182 !isa<CXXDestructorDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& !cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && !isa<CXXConstructorDecl>
(getDecl()) && !isa<CXXDestructorDecl>(getDecl(
)) && "Decl is not a plain FunctionDecl!") ? void (0)
: __assert_fail ("isa<FunctionDecl>(getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 183, __extension__ __PRETTY_FUNCTION__))
183 "Decl is not a plain FunctionDecl!")(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& !cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && !isa<CXXConstructorDecl>
(getDecl()) && !isa<CXXDestructorDecl>(getDecl(
)) && "Decl is not a plain FunctionDecl!") ? void (0)
: __assert_fail ("isa<FunctionDecl>(getDecl()) && !cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && !isa<CXXConstructorDecl>(getDecl()) && !isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a plain FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 183, __extension__ __PRETTY_FUNCTION__))
;
184 GlobalDecl Result(*this);
185 Result.MultiVersionIndex = Index;
186 return Result;
187 }
188
189 GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind) {
190 assert(isa<FunctionDecl>(getDecl()) &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && "Decl is not a GPU kernel!") ?
void (0) : __assert_fail ("isa<FunctionDecl>(getDecl()) && cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 192, __extension__ __PRETTY_FUNCTION__))
191 cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() &&(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && "Decl is not a GPU kernel!") ?
void (0) : __assert_fail ("isa<FunctionDecl>(getDecl()) && cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 192, __extension__ __PRETTY_FUNCTION__))
192 "Decl is not a GPU kernel!")(static_cast <bool> (isa<FunctionDecl>(getDecl())
&& cast<FunctionDecl>(getDecl())->hasAttr<
CUDAGlobalAttr>() && "Decl is not a GPU kernel!") ?
void (0) : __assert_fail ("isa<FunctionDecl>(getDecl()) && cast<FunctionDecl>(getDecl())->hasAttr<CUDAGlobalAttr>() && \"Decl is not a GPU kernel!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/GlobalDecl.h"
, 192, __extension__ __PRETTY_FUNCTION__))
;
193 GlobalDecl Result(*this);
194 Result.Value.setInt(unsigned(Kind));
195 return Result;
196 }
197};
198
199} // namespace clang
200
201namespace llvm {
202
203 template<> struct DenseMapInfo<clang::GlobalDecl> {
204 static inline clang::GlobalDecl getEmptyKey() {
205 return clang::GlobalDecl();
206 }
207
208 static inline clang::GlobalDecl getTombstoneKey() {
209 return clang::GlobalDecl::
210 getFromOpaquePtr(reinterpret_cast<void*>(-1));
211 }
212
213 static unsigned getHashValue(clang::GlobalDecl GD) {
214 return DenseMapInfo<void*>::getHashValue(GD.getAsOpaquePtr());
215 }
216
217 static bool isEqual(clang::GlobalDecl LHS,
218 clang::GlobalDecl RHS) {
219 return LHS == RHS;
220 }
221 };
222
223} // namespace llvm
224
225#endif // LLVM_CLANG_AST_GLOBALDECL_H

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===//
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 file defines the PointerIntPair class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_POINTERINTPAIR_H
14#define LLVM_ADT_POINTERINTPAIR_H
15
16#include "llvm/Support/Compiler.h"
17#include "llvm/Support/PointerLikeTypeTraits.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <cstdint>
21#include <limits>
22
23namespace llvm {
24
25template <typename T> struct DenseMapInfo;
26template <typename PointerT, unsigned IntBits, typename PtrTraits>
27struct PointerIntPairInfo;
28
29/// PointerIntPair - This class implements a pair of a pointer and small
30/// integer. It is designed to represent this in the space required by one
31/// pointer by bitmangling the integer into the low part of the pointer. This
32/// can only be done for small integers: typically up to 3 bits, but it depends
33/// on the number of bits available according to PointerLikeTypeTraits for the
34/// type.
35///
36/// Note that PointerIntPair always puts the IntVal part in the highest bits
37/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
38/// the bool into bit #2, not bit #0, which allows the low two bits to be used
39/// for something else. For example, this allows:
40/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
41/// ... and the two bools will land in different bits.
42template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
43 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
44 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
45class PointerIntPair {
46 // Used by MSVC visualizer and generally helpful for debugging/visualizing.
47 using InfoTy = Info;
48 intptr_t Value = 0;
49
50public:
51 constexpr PointerIntPair() = default;
52
53 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
54 setPointerAndInt(PtrVal, IntVal);
55 }
56
57 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
58
59 PointerTy getPointer() const { return Info::getPointer(Value); }
47
Calling 'PointerIntPairInfo::getPointer'
53
Returning from 'PointerIntPairInfo::getPointer'
54
Returning pointer
60
61 IntType getInt() const { return (IntType)Info::getInt(Value); }
62
63 void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
64 Value = Info::updatePointer(Value, PtrVal);
65 }
66
67 void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& {
68 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
69 }
70
71 void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
72 Value = Info::updatePointer(0, PtrVal);
73 }
74
75 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& {
76 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
77 static_cast<intptr_t>(IntVal));
78 }
79
80 PointerTy const *getAddrOfPointer() const {
81 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
82 }
83
84 PointerTy *getAddrOfPointer() {
85 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&(static_cast <bool> (Value == reinterpret_cast<intptr_t
>(getPointer()) && "Can only return the address if IntBits is cleared and "
"PtrTraits doesn't change the pointer") ? void (0) : __assert_fail
("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __extension__ __PRETTY_FUNCTION__))
86 "Can only return the address if IntBits is cleared and "(static_cast <bool> (Value == reinterpret_cast<intptr_t
>(getPointer()) && "Can only return the address if IntBits is cleared and "
"PtrTraits doesn't change the pointer") ? void (0) : __assert_fail
("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __extension__ __PRETTY_FUNCTION__))
87 "PtrTraits doesn't change the pointer")(static_cast <bool> (Value == reinterpret_cast<intptr_t
>(getPointer()) && "Can only return the address if IntBits is cleared and "
"PtrTraits doesn't change the pointer") ? void (0) : __assert_fail
("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __extension__ __PRETTY_FUNCTION__))
;
88 return reinterpret_cast<PointerTy *>(&Value);
89 }
90
91 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
92
93 void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& {
94 Value = reinterpret_cast<intptr_t>(Val);
95 }
96
97 static PointerIntPair getFromOpaqueValue(void *V) {
98 PointerIntPair P;
99 P.setFromOpaqueValue(V);
100 return P;
101 }
102
103 // Allow PointerIntPairs to be created from const void * if and only if the
104 // pointer type could be created from a const void *.
105 static PointerIntPair getFromOpaqueValue(const void *V) {
106 (void)PtrTraits::getFromVoidPointer(V);
107 return getFromOpaqueValue(const_cast<void *>(V));
108 }
109
110 bool operator==(const PointerIntPair &RHS) const {
111 return Value == RHS.Value;
112 }
113
114 bool operator!=(const PointerIntPair &RHS) const {
115 return Value != RHS.Value;
116 }
117
118 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
119 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
120
121 bool operator<=(const PointerIntPair &RHS) const {
122 return Value <= RHS.Value;
123 }
124
125 bool operator>=(const PointerIntPair &RHS) const {
126 return Value >= RHS.Value;
127 }
128};
129
130// Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable
131// when compiled with gcc 4.9.
132template <typename PointerTy, unsigned IntBits, typename IntType,
133 typename PtrTraits,
134 typename Info>
135struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type {
136#ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE
137 static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value,
138 "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable");
139#endif
140};
141
142
143template <typename PointerT, unsigned IntBits, typename PtrTraits>
144struct PointerIntPairInfo {
145 static_assert(PtrTraits::NumLowBitsAvailable <
146 std::numeric_limits<uintptr_t>::digits,
147 "cannot use a pointer type that has all bits free");
148 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
149 "PointerIntPair with integer size too large for pointer");
150 enum MaskAndShiftConstants : uintptr_t {
151 /// PointerBitMask - The bits that come from the pointer.
152 PointerBitMask =
153 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
154
155 /// IntShift - The number of low bits that we reserve for other uses, and
156 /// keep zero.
157 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
158
159 /// IntMask - This is the unshifted mask for valid bits of the int type.
160 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
161
162 // ShiftedIntMask - This is the bits for the integer shifted in place.
163 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
164 };
165
166 static PointerT getPointer(intptr_t Value) {
167 return PtrTraits::getFromVoidPointer(
48
Calling 'PointerLikeTypeTraits::getFromVoidPointer'
51
Returning from 'PointerLikeTypeTraits::getFromVoidPointer'
52
Returning pointer
168 reinterpret_cast<void *>(Value & PointerBitMask));
169 }
170
171 static intptr_t getInt(intptr_t Value) {
172 return (Value >> IntShift) & IntMask;
173 }
174
175 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
176 intptr_t PtrWord =
177 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
178 assert((PtrWord & ~PointerBitMask) == 0 &&(static_cast <bool> ((PtrWord & ~PointerBitMask) ==
0 && "Pointer is not sufficiently aligned") ? void (
0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __extension__ __PRETTY_FUNCTION__))
179 "Pointer is not sufficiently aligned")(static_cast <bool> ((PtrWord & ~PointerBitMask) ==
0 && "Pointer is not sufficiently aligned") ? void (
0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __extension__ __PRETTY_FUNCTION__))
;
180 // Preserve all low bits, just update the pointer.
181 return PtrWord | (OrigValue & ~PointerBitMask);
182 }
183
184 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
185 intptr_t IntWord = static_cast<intptr_t>(Int);
186 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(static_cast <bool> ((IntWord & ~IntMask) == 0 &&
"Integer too large for field") ? void (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerIntPair.h"
, 186, __extension__ __PRETTY_FUNCTION__))
;
187
188 // Preserve all bits other than the ones we are updating.
189 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
190 }
191};
192
193// Provide specialization of DenseMapInfo for PointerIntPair.
194template <typename PointerTy, unsigned IntBits, typename IntType>
195struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> {
196 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
197
198 static Ty getEmptyKey() {
199 uintptr_t Val = static_cast<uintptr_t>(-1);
200 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
201 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
202 }
203
204 static Ty getTombstoneKey() {
205 uintptr_t Val = static_cast<uintptr_t>(-2);
206 Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
207 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
208 }
209
210 static unsigned getHashValue(Ty V) {
211 uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
212 return unsigned(IV) ^ unsigned(IV >> 9);
213 }
214
215 static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
216};
217
218// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
219template <typename PointerTy, unsigned IntBits, typename IntType,
220 typename PtrTraits>
221struct PointerLikeTypeTraits<
222 PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> {
223 static inline void *
224 getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
225 return P.getOpaqueValue();
226 }
227
228 static inline PointerIntPair<PointerTy, IntBits, IntType>
229 getFromVoidPointer(void *P) {
230 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
231 }
232
233 static inline PointerIntPair<PointerTy, IntBits, IntType>
234 getFromVoidPointer(const void *P) {
235 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
236 }
237
238 static constexpr int NumLowBitsAvailable =
239 PtrTraits::NumLowBitsAvailable - IntBits;
240};
241
242} // end namespace llvm
243
244#endif // LLVM_ADT_POINTERINTPAIR_H

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/PointerLikeTypeTraits.h

1//===- llvm/Support/PointerLikeTypeTraits.h - Pointer Traits ----*- C++ -*-===//
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 file defines the PointerLikeTypeTraits class. This allows data
10// structures to reason about pointers and other things that are pointer sized.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_POINTERLIKETYPETRAITS_H
15#define LLVM_SUPPORT_POINTERLIKETYPETRAITS_H
16
17#include "llvm/Support/DataTypes.h"
18#include <cassert>
19#include <type_traits>
20
21namespace llvm {
22
23/// A traits type that is used to handle pointer types and things that are just
24/// wrappers for pointers as a uniform entity.
25template <typename T> struct PointerLikeTypeTraits;
26
27namespace detail {
28/// A tiny meta function to compute the log2 of a compile time constant.
29template <size_t N>
30struct ConstantLog2
31 : std::integral_constant<size_t, ConstantLog2<N / 2>::value + 1> {};
32template <> struct ConstantLog2<1> : std::integral_constant<size_t, 0> {};
33
34// Provide a trait to check if T is pointer-like.
35template <typename T, typename U = void> struct HasPointerLikeTypeTraits {
36 static const bool value = false;
37};
38
39// sizeof(T) is valid only for a complete T.
40template <typename T>
41struct HasPointerLikeTypeTraits<
42 T, decltype((sizeof(PointerLikeTypeTraits<T>) + sizeof(T)), void())> {
43 static const bool value = true;
44};
45
46template <typename T> struct IsPointerLike {
47 static const bool value = HasPointerLikeTypeTraits<T>::value;
48};
49
50template <typename T> struct IsPointerLike<T *> {
51 static const bool value = true;
52};
53} // namespace detail
54
55// Provide PointerLikeTypeTraits for non-cvr pointers.
56template <typename T> struct PointerLikeTypeTraits<T *> {
57 static inline void *getAsVoidPointer(T *P) { return P; }
58 static inline T *getFromVoidPointer(void *P) { return static_cast<T *>(P); }
59
60 static constexpr int NumLowBitsAvailable =
61 detail::ConstantLog2<alignof(T)>::value;
62};
63
64template <> struct PointerLikeTypeTraits<void *> {
65 static inline void *getAsVoidPointer(void *P) { return P; }
66 static inline void *getFromVoidPointer(void *P) { return P; }
67
68 /// Note, we assume here that void* is related to raw malloc'ed memory and
69 /// that malloc returns objects at least 4-byte aligned. However, this may be
70 /// wrong, or pointers may be from something other than malloc. In this case,
71 /// you should specify a real typed pointer or avoid this template.
72 ///
73 /// All clients should use assertions to do a run-time check to ensure that
74 /// this is actually true.
75 static constexpr int NumLowBitsAvailable = 2;
76};
77
78// Provide PointerLikeTypeTraits for const things.
79template <typename T> struct PointerLikeTypeTraits<const T> {
80 typedef PointerLikeTypeTraits<T> NonConst;
81
82 static inline const void *getAsVoidPointer(const T P) {
83 return NonConst::getAsVoidPointer(P);
84 }
85 static inline const T getFromVoidPointer(const void *P) {
86 return NonConst::getFromVoidPointer(const_cast<void *>(P));
87 }
88 static constexpr int NumLowBitsAvailable = NonConst::NumLowBitsAvailable;
89};
90
91// Provide PointerLikeTypeTraits for const pointers.
92template <typename T> struct PointerLikeTypeTraits<const T *> {
93 typedef PointerLikeTypeTraits<T *> NonConst;
94
95 static inline const void *getAsVoidPointer(const T *P) {
96 return NonConst::getAsVoidPointer(const_cast<T *>(P));
97 }
98 static inline const T *getFromVoidPointer(const void *P) {
99 return NonConst::getFromVoidPointer(const_cast<void *>(P));
49
Passing value via 1st parameter 'P'
50
Returning pointer
100 }
101 static constexpr int NumLowBitsAvailable = NonConst::NumLowBitsAvailable;
102};
103
104// Provide PointerLikeTypeTraits for uintptr_t.
105template <> struct PointerLikeTypeTraits<uintptr_t> {
106 static inline void *getAsVoidPointer(uintptr_t P) {
107 return reinterpret_cast<void *>(P);
108 }
109 static inline uintptr_t getFromVoidPointer(void *P) {
110 return reinterpret_cast<uintptr_t>(P);
111 }
112 // No bits are available!
113 static constexpr int NumLowBitsAvailable = 0;
114};
115
116/// Provide suitable custom traits struct for function pointers.
117///
118/// Function pointers can't be directly given these traits as functions can't
119/// have their alignment computed with `alignof` and we need different casting.
120///
121/// To rely on higher alignment for a specialized use, you can provide a
122/// customized form of this template explicitly with higher alignment, and
123/// potentially use alignment attributes on functions to satisfy that.
124template <int Alignment, typename FunctionPointerT>
125struct FunctionPointerLikeTypeTraits {
126 static constexpr int NumLowBitsAvailable =
127 detail::ConstantLog2<Alignment>::value;
128 static inline void *getAsVoidPointer(FunctionPointerT P) {
129 assert((reinterpret_cast<uintptr_t>(P) &(static_cast <bool> ((reinterpret_cast<uintptr_t>
(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0
&& "Alignment not satisfied for an actual function pointer!"
) ? void (0) : __assert_fail ("(reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 && \"Alignment not satisfied for an actual function pointer!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/PointerLikeTypeTraits.h"
, 131, __extension__ __PRETTY_FUNCTION__))
130 ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 &&(static_cast <bool> ((reinterpret_cast<uintptr_t>
(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0
&& "Alignment not satisfied for an actual function pointer!"
) ? void (0) : __assert_fail ("(reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 && \"Alignment not satisfied for an actual function pointer!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/PointerLikeTypeTraits.h"
, 131, __extension__ __PRETTY_FUNCTION__))
131 "Alignment not satisfied for an actual function pointer!")(static_cast <bool> ((reinterpret_cast<uintptr_t>
(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0
&& "Alignment not satisfied for an actual function pointer!"
) ? void (0) : __assert_fail ("(reinterpret_cast<uintptr_t>(P) & ~((uintptr_t)-1 << NumLowBitsAvailable)) == 0 && \"Alignment not satisfied for an actual function pointer!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/PointerLikeTypeTraits.h"
, 131, __extension__ __PRETTY_FUNCTION__))
;
132 return reinterpret_cast<void *>(P);
133 }
134 static inline FunctionPointerT getFromVoidPointer(void *P) {
135 return reinterpret_cast<FunctionPointerT>(P);
136 }
137};
138
139/// Provide a default specialization for function pointers that assumes 4-byte
140/// alignment.
141///
142/// We assume here that functions used with this are always at least 4-byte
143/// aligned. This means that, for example, thumb functions won't work or systems
144/// with weird unaligned function pointers won't work. But all practical systems
145/// we support satisfy this requirement.
146template <typename ReturnT, typename... ParamTs>
147struct PointerLikeTypeTraits<ReturnT (*)(ParamTs...)>
148 : FunctionPointerLikeTypeTraits<4, ReturnT (*)(ParamTs...)> {};
149
150} // end namespace llvm
151
152#endif