Bug Summary

File:clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 4149, column 17
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 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -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 -o /tmp/scan-build-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/CodeGen/CodeGenModule.cpp

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