Bug Summary

File:tools/clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 3483, column 7
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-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337103/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337103/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337103/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337103/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337103/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-15-073923-5500-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/CodeGen/CodeGenModule.cpp

/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/CodeGen/CodeGenModule.cpp

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

/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
60 }
61};
62
63/// Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
107 return isa_impl<To, From>::doit(*Val);
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
2
Within the expansion of the macro 'assert':
256 return cast_convert_val<X, Y*,
3
Calling 'cast_convert_val::doit'
4
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H