Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CodeGenModule.cpp

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