Bug Summary

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