Bug Summary

File:tools/clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 4186, 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~svn326246/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326246/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326246/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326246/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/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~svn326246/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-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-28-041547-14988-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/CodeGen/CodeGenModule.cpp

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

/build/llvm-toolchain-snapshot-7~svn326246/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));
5
Calling 'simplify_type::getSimplifiedValue'
6
Returning from 'simplify_type::getSimplifiedValue'
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);
12
Calling 'VarDecl::classof'
19
Returning from 'VarDecl::classof'
60 }
61};
62
63/// \brief 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~svn326246/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~svn326246/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~svn326246/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~svn326246/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
10
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
107 return isa_impl<To, From>::doit(*Val);
11
Calling 'isa_impl::doit'
20
Returning from 'isa_impl::doit'
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~svn326246/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,
8
Calling 'isa_impl_wrap::doit'
22
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
4
Calling 'simplify_type::getSimplifiedValue'
7
Returning from 'simplify_type::getSimplifiedValue'
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);
9
Calling 'isa_impl_cl::doit'
21
Returning from 'isa_impl_cl::doit'
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,
3
Calling 'isa_impl_wrap::doit'
23
Returning from 'isa_impl_wrap::doit'
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~svn326246/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~svn326246/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~svn326246/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
2
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
256 return cast_convert_val<X, Y*,
24
Calling 'cast_convert_val::doit'
25
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~svn326246/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~svn326246/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~svn326246/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~svn326246/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

/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- 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 Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class LLVM_ALIGNAS(8)alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 // FIXME: Remove string version.
314 std::string getQualifiedNameAsString() const;
315
316 /// Appends a human-readable name for this declaration into the given stream.
317 ///
318 /// This is the method invoked by Sema when displaying a NamedDecl
319 /// in a diagnostic. It does not necessarily produce the same
320 /// result as printName(); for example, class template
321 /// specializations are printed with their template arguments.
322 virtual void getNameForDiagnostic(raw_ostream &OS,
323 const PrintingPolicy &Policy,
324 bool Qualified) const;
325
326 /// Determine whether this declaration, if known to be well-formed within
327 /// its context, will replace the declaration OldD if introduced into scope.
328 ///
329 /// A declaration will replace another declaration if, for example, it is
330 /// a redeclaration of the same variable or function, but not if it is a
331 /// declaration of a different kind (function vs. class) or an overloaded
332 /// function.
333 ///
334 /// \param IsKnownNewer \c true if this declaration is known to be newer
335 /// than \p OldD (for instance, if this declaration is newly-created).
336 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
337
338 /// Determine whether this declaration has linkage.
339 bool hasLinkage() const;
340
341 using Decl::isModulePrivate;
342 using Decl::setModulePrivate;
343
344 /// Determine whether this declaration is a C++ class member.
345 bool isCXXClassMember() const {
346 const DeclContext *DC = getDeclContext();
347
348 // C++0x [class.mem]p1:
349 // The enumerators of an unscoped enumeration defined in
350 // the class are members of the class.
351 if (isa<EnumDecl>(DC))
352 DC = DC->getRedeclContext();
353
354 return DC->isRecord();
355 }
356
357 /// Determine whether the given declaration is an instance member of
358 /// a C++ class.
359 bool isCXXInstanceMember() const;
360
361 /// Determine what kind of linkage this entity has.
362 ///
363 /// This is not the linkage as defined by the standard or the codegen notion
364 /// of linkage. It is just an implementation detail that is used to compute
365 /// those.
366 Linkage getLinkageInternal() const;
367
368 /// Get the linkage from a semantic point of view. Entities in
369 /// anonymous namespaces are external (in c++98).
370 Linkage getFormalLinkage() const {
371 return clang::getFormalLinkage(getLinkageInternal());
372 }
373
374 /// True if this decl has external linkage.
375 bool hasExternalFormalLinkage() const {
376 return isExternalFormalLinkage(getLinkageInternal());
377 }
378
379 bool isExternallyVisible() const {
380 return clang::isExternallyVisible(getLinkageInternal());
381 }
382
383 /// Determine whether this declaration can be redeclared in a
384 /// different translation unit.
385 bool isExternallyDeclarable() const {
386 return isExternallyVisible() && !getOwningModuleForLinkage();
387 }
388
389 /// Determines the visibility of this entity.
390 Visibility getVisibility() const {
391 return getLinkageAndVisibility().getVisibility();
392 }
393
394 /// Determines the linkage and visibility of this entity.
395 LinkageInfo getLinkageAndVisibility() const;
396
397 /// Kinds of explicit visibility.
398 enum ExplicitVisibilityKind {
399 /// Do an LV computation for, ultimately, a type.
400 /// Visibility may be restricted by type visibility settings and
401 /// the visibility of template arguments.
402 VisibilityForType,
403
404 /// Do an LV computation for, ultimately, a non-type declaration.
405 /// Visibility may be restricted by value visibility settings and
406 /// the visibility of template arguments.
407 VisibilityForValue
408 };
409
410 /// If visibility was explicitly specified for this
411 /// declaration, return that visibility.
412 Optional<Visibility>
413 getExplicitVisibility(ExplicitVisibilityKind kind) const;
414
415 /// True if the computed linkage is valid. Used for consistency
416 /// checking. Should always return true.
417 bool isLinkageValid() const;
418
419 /// True if something has required us to compute the linkage
420 /// of this declaration.
421 ///
422 /// Language features which can retroactively change linkage (like a
423 /// typedef name for linkage purposes) may need to consider this,
424 /// but hopefully only in transitory ways during parsing.
425 bool hasLinkageBeenComputed() const {
426 return hasCachedLinkage();
427 }
428
429 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
430 /// the underlying named decl.
431 NamedDecl *getUnderlyingDecl() {
432 // Fast-path the common case.
433 if (this->getKind() != UsingShadow &&
434 this->getKind() != ConstructorUsingShadow &&
435 this->getKind() != ObjCCompatibleAlias &&
436 this->getKind() != NamespaceAlias)
437 return this;
438
439 return getUnderlyingDeclImpl();
440 }
441 const NamedDecl *getUnderlyingDecl() const {
442 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
443 }
444
445 NamedDecl *getMostRecentDecl() {
446 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
447 }
448 const NamedDecl *getMostRecentDecl() const {
449 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
450 }
451
452 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
453
454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
455 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
456};
457
458inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
459 ND.printName(OS);
460 return OS;
461}
462
463/// Represents the declaration of a label. Labels also have a
464/// corresponding LabelStmt, which indicates the position that the label was
465/// defined at. For normal labels, the location of the decl is the same as the
466/// location of the statement. For GNU local labels (__label__), the decl
467/// location is where the __label__ is.
468class LabelDecl : public NamedDecl {
469 LabelStmt *TheStmt;
470 StringRef MSAsmName;
471 bool MSAsmNameResolved = false;
472
473 /// For normal labels, this is the same as the main declaration
474 /// label, i.e., the location of the identifier; for GNU local labels,
475 /// this is the location of the __label__ keyword.
476 SourceLocation LocStart;
477
478 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
479 LabelStmt *S, SourceLocation StartL)
480 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
481
482 void anchor() override;
483
484public:
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II);
487 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
488 SourceLocation IdentL, IdentifierInfo *II,
489 SourceLocation GnuLabelL);
490 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
491
492 LabelStmt *getStmt() const { return TheStmt; }
493 void setStmt(LabelStmt *T) { TheStmt = T; }
494
495 bool isGnuLocal() const { return LocStart != getLocation(); }
496 void setLocStart(SourceLocation L) { LocStart = L; }
497
498 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
499 return SourceRange(LocStart, getLocation());
500 }
501
502 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
503 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
504 void setMSAsmLabel(StringRef Name);
505 StringRef getMSAsmLabel() const { return MSAsmName; }
506 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
507
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classofKind(Kind K) { return K == Label; }
511};
512
513/// Represent a C++ namespace.
514class NamespaceDecl : public NamedDecl, public DeclContext,
515 public Redeclarable<NamespaceDecl>
516{
517 /// The starting location of the source range, pointing
518 /// to either the namespace or the inline keyword.
519 SourceLocation LocStart;
520
521 /// The ending location of the source range.
522 SourceLocation RBraceLoc;
523
524 /// A pointer to either the anonymous namespace that lives just inside
525 /// this namespace or to the first namespace in the chain (the latter case
526 /// only when this is not the first in the chain), along with a
527 /// boolean value indicating whether this is an inline namespace.
528 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
529
530 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
531 SourceLocation StartLoc, SourceLocation IdLoc,
532 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
533
534 using redeclarable_base = Redeclarable<NamespaceDecl>;
535
536 NamespaceDecl *getNextRedeclarationImpl() override;
537 NamespaceDecl *getPreviousDeclImpl() override;
538 NamespaceDecl *getMostRecentDeclImpl() override;
539
540public:
541 friend class ASTDeclReader;
542 friend class ASTDeclWriter;
543
544 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
545 bool Inline, SourceLocation StartLoc,
546 SourceLocation IdLoc, IdentifierInfo *Id,
547 NamespaceDecl *PrevDecl);
548
549 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
550
551 using redecl_range = redeclarable_base::redecl_range;
552 using redecl_iterator = redeclarable_base::redecl_iterator;
553
554 using redeclarable_base::redecls_begin;
555 using redeclarable_base::redecls_end;
556 using redeclarable_base::redecls;
557 using redeclarable_base::getPreviousDecl;
558 using redeclarable_base::getMostRecentDecl;
559 using redeclarable_base::isFirstDecl;
560
561 /// Returns true if this is an anonymous namespace declaration.
562 ///
563 /// For example:
564 /// \code
565 /// namespace {
566 /// ...
567 /// };
568 /// \endcode
569 /// q.v. C++ [namespace.unnamed]
570 bool isAnonymousNamespace() const {
571 return !getIdentifier();
572 }
573
574 /// Returns true if this is an inline namespace declaration.
575 bool isInline() const {
576 return AnonOrFirstNamespaceAndInline.getInt();
577 }
578
579 /// Set whether this is an inline namespace declaration.
580 void setInline(bool Inline) {
581 AnonOrFirstNamespaceAndInline.setInt(Inline);
582 }
583
584 /// Get the original (first) namespace declaration.
585 NamespaceDecl *getOriginalNamespace();
586
587 /// Get the original (first) namespace declaration.
588 const NamespaceDecl *getOriginalNamespace() const;
589
590 /// Return true if this declaration is an original (first) declaration
591 /// of the namespace. This is false for non-original (subsequent) namespace
592 /// declarations and anonymous namespaces.
593 bool isOriginalNamespace() const;
594
595 /// Retrieve the anonymous namespace nested inside this namespace,
596 /// if any.
597 NamespaceDecl *getAnonymousNamespace() const {
598 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
599 }
600
601 void setAnonymousNamespace(NamespaceDecl *D) {
602 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
603 }
604
605 /// Retrieves the canonical declaration of this namespace.
606 NamespaceDecl *getCanonicalDecl() override {
607 return getOriginalNamespace();
608 }
609 const NamespaceDecl *getCanonicalDecl() const {
610 return getOriginalNamespace();
611 }
612
613 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
614 return SourceRange(LocStart, RBraceLoc);
615 }
616
617 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
618 SourceLocation getRBraceLoc() const { return RBraceLoc; }
619 void setLocStart(SourceLocation L) { LocStart = L; }
620 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
621
622 // Implement isa/cast/dyncast/etc.
623 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
624 static bool classofKind(Kind K) { return K == Namespace; }
625 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
626 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
627 }
628 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
629 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
630 }
631};
632
633/// Represent the declaration of a variable (in which case it is
634/// an lvalue) a function (in which case it is a function designator) or
635/// an enum constant.
636class ValueDecl : public NamedDecl {
637 QualType DeclType;
638
639 void anchor() override;
640
641protected:
642 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
643 DeclarationName N, QualType T)
644 : NamedDecl(DK, DC, L, N), DeclType(T) {}
645
646public:
647 QualType getType() const { return DeclType; }
648 void setType(QualType newType) { DeclType = newType; }
649
650 /// Determine whether this symbol is weakly-imported,
651 /// or declared with the weak or weak-ref attr.
652 bool isWeak() const;
653
654 // Implement isa/cast/dyncast/etc.
655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
656 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
657};
658
659/// A struct with extended info about a syntactic
660/// name qualifier, to be used for the case of out-of-line declarations.
661struct QualifierInfo {
662 NestedNameSpecifierLoc QualifierLoc;
663
664 /// The number of "outer" template parameter lists.
665 /// The count includes all of the template parameter lists that were matched
666 /// against the template-ids occurring into the NNS and possibly (in the
667 /// case of an explicit specialization) a final "template <>".
668 unsigned NumTemplParamLists = 0;
669
670 /// A new-allocated array of size NumTemplParamLists,
671 /// containing pointers to the "outer" template parameter lists.
672 /// It includes all of the template parameter lists that were matched
673 /// against the template-ids occurring into the NNS and possibly (in the
674 /// case of an explicit specialization) a final "template <>".
675 TemplateParameterList** TemplParamLists = nullptr;
676
677 QualifierInfo() = default;
678 QualifierInfo(const QualifierInfo &) = delete;
679 QualifierInfo& operator=(const QualifierInfo &) = delete;
680
681 /// Sets info about "outer" template parameter lists.
682 void setTemplateParameterListsInfo(ASTContext &Context,
683 ArrayRef<TemplateParameterList *> TPLists);
684};
685
686/// Represents a ValueDecl that came out of a declarator.
687/// Contains type source information through TypeSourceInfo.
688class DeclaratorDecl : public ValueDecl {
689 // A struct representing both a TInfo and a syntactic qualifier,
690 // to be used for the (uncommon) case of out-of-line declarations.
691 struct ExtInfo : public QualifierInfo {
692 TypeSourceInfo *TInfo;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 unsigned getNumTemplateParameterLists() const {
760 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761 }
762
763 TemplateParameterList *getTemplateParameterList(unsigned index) const {
764 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 return getExtInfo()->TemplParamLists[index];
766 }
767
768 void setTemplateParameterListsInfo(ASTContext &Context,
769 ArrayRef<TemplateParameterList *> TPLists);
770
771 SourceLocation getTypeSpecStartLoc() const;
772
773 // Implement isa/cast/dyncast/etc.
774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775 static bool classofKind(Kind K) {
776 return K >= firstDeclarator && K <= lastDeclarator;
777 }
778};
779
780/// Structure used to store a statement, the constant value to
781/// which it was evaluated (if any), and whether or not the statement
782/// is an integral constant expression (if known).
783struct EvaluatedStmt {
784 /// Whether this statement was already evaluated.
785 bool WasEvaluated : 1;
786
787 /// Whether this statement is being evaluated.
788 bool IsEvaluating : 1;
789
790 /// Whether we already checked whether this statement was an
791 /// integral constant expression.
792 bool CheckedICE : 1;
793
794 /// Whether we are checking whether this statement is an
795 /// integral constant expression.
796 bool CheckingICE : 1;
797
798 /// Whether this statement is an integral constant expression,
799 /// or in C++11, whether the statement is a constant expression. Only
800 /// valid if CheckedICE is true.
801 bool IsICE : 1;
802
803 Stmt *Value;
804 APValue Evaluated;
805
806 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
807 CheckingICE(false), IsICE(false) {}
808
809};
810
811/// Represents a variable declaration or definition.
812class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
813public:
814 /// Initialization styles.
815 enum InitializationStyle {
816 /// C-style initialization with assignment
817 CInit,
818
819 /// Call-style initialization (C++98)
820 CallInit,
821
822 /// Direct list-initialization (C++11)
823 ListInit
824 };
825
826 /// Kinds of thread-local storage.
827 enum TLSKind {
828 /// Not a TLS variable.
829 TLS_None,
830
831 /// TLS with a known-constant initializer.
832 TLS_Static,
833
834 /// TLS with a dynamic initializer.
835 TLS_Dynamic
836 };
837
838 /// Return the string used to specify the storage class \p SC.
839 ///
840 /// It is illegal to call this function with SC == None.
841 static const char *getStorageClassSpecifierString(StorageClass SC);
842
843protected:
844 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
845 // have allocated the auxiliary struct of information there.
846 //
847 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
848 // this as *many* VarDecls are ParmVarDecls that don't have default
849 // arguments. We could save some space by moving this pointer union to be
850 // allocated in trailing space when necessary.
851 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
852
853 /// The initializer for this variable or, for a ParmVarDecl, the
854 /// C++ default argument.
855 mutable InitType Init;
856
857private:
858 friend class ASTDeclReader;
859 friend class ASTNodeImporter;
860 friend class StmtIteratorBase;
861
862 class VarDeclBitfields {
863 friend class ASTDeclReader;
864 friend class VarDecl;
865
866 unsigned SClass : 3;
867 unsigned TSCSpec : 2;
868 unsigned InitStyle : 2;
869 };
870 enum { NumVarDeclBits = 7 };
871
872protected:
873 enum { NumParameterIndexBits = 8 };
874
875 enum DefaultArgKind {
876 DAK_None,
877 DAK_Unparsed,
878 DAK_Uninstantiated,
879 DAK_Normal
880 };
881
882 class ParmVarDeclBitfields {
883 friend class ASTDeclReader;
884 friend class ParmVarDecl;
885
886 unsigned : NumVarDeclBits;
887
888 /// Whether this parameter inherits a default argument from a
889 /// prior declaration.
890 unsigned HasInheritedDefaultArg : 1;
891
892 /// Describes the kind of default argument for this parameter. By default
893 /// this is none. If this is normal, then the default argument is stored in
894 /// the \c VarDecl initializer expression unless we were unable to parse
895 /// (even an invalid) expression for the default argument.
896 unsigned DefaultArgKind : 2;
897
898 /// Whether this parameter undergoes K&R argument promotion.
899 unsigned IsKNRPromoted : 1;
900
901 /// Whether this parameter is an ObjC method parameter or not.
902 unsigned IsObjCMethodParam : 1;
903
904 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
905 /// Otherwise, the number of function parameter scopes enclosing
906 /// the function parameter scope in which this parameter was
907 /// declared.
908 unsigned ScopeDepthOrObjCQuals : 7;
909
910 /// The number of parameters preceding this parameter in the
911 /// function parameter scope in which it was declared.
912 unsigned ParameterIndex : NumParameterIndexBits;
913 };
914
915 class NonParmVarDeclBitfields {
916 friend class ASTDeclReader;
917 friend class ImplicitParamDecl;
918 friend class VarDecl;
919
920 unsigned : NumVarDeclBits;
921
922 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
923 /// Whether this variable is a definition which was demoted due to
924 /// module merge.
925 unsigned IsThisDeclarationADemotedDefinition : 1;
926
927 /// Whether this variable is the exception variable in a C++ catch
928 /// or an Objective-C @catch statement.
929 unsigned ExceptionVar : 1;
930
931 /// Whether this local variable could be allocated in the return
932 /// slot of its function, enabling the named return value optimization
933 /// (NRVO).
934 unsigned NRVOVariable : 1;
935
936 /// Whether this variable is the for-range-declaration in a C++0x
937 /// for-range statement.
938 unsigned CXXForRangeDecl : 1;
939
940 /// Whether this variable is an ARC pseudo-__strong
941 /// variable; see isARCPseudoStrong() for details.
942 unsigned ARCPseudoStrong : 1;
943
944 /// Whether this variable is (C++1z) inline.
945 unsigned IsInline : 1;
946
947 /// Whether this variable has (C++1z) inline explicitly specified.
948 unsigned IsInlineSpecified : 1;
949
950 /// Whether this variable is (C++0x) constexpr.
951 unsigned IsConstexpr : 1;
952
953 /// Whether this variable is the implicit variable for a lambda
954 /// init-capture.
955 unsigned IsInitCapture : 1;
956
957 /// Whether this local extern variable's previous declaration was
958 /// declared in the same block scope. This controls whether we should merge
959 /// the type of this declaration with its previous declaration.
960 unsigned PreviousDeclInSameBlockScope : 1;
961
962 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
963 /// something else.
964 unsigned ImplicitParamKind : 3;
965 };
966
967 union {
968 unsigned AllBits;
969 VarDeclBitfields VarDeclBits;
970 ParmVarDeclBitfields ParmVarDeclBits;
971 NonParmVarDeclBitfields NonParmVarDeclBits;
972 };
973
974 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
975 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
976 TypeSourceInfo *TInfo, StorageClass SC);
977
978 using redeclarable_base = Redeclarable<VarDecl>;
979
980 VarDecl *getNextRedeclarationImpl() override {
981 return getNextRedeclaration();
982 }
983
984 VarDecl *getPreviousDeclImpl() override {
985 return getPreviousDecl();
986 }
987
988 VarDecl *getMostRecentDeclImpl() override {
989 return getMostRecentDecl();
990 }
991
992public:
993 using redecl_range = redeclarable_base::redecl_range;
994 using redecl_iterator = redeclarable_base::redecl_iterator;
995
996 using redeclarable_base::redecls_begin;
997 using redeclarable_base::redecls_end;
998 using redeclarable_base::redecls;
999 using redeclarable_base::getPreviousDecl;
1000 using redeclarable_base::getMostRecentDecl;
1001 using redeclarable_base::isFirstDecl;
1002
1003 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1004 SourceLocation StartLoc, SourceLocation IdLoc,
1005 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1006 StorageClass S);
1007
1008 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1009
1010 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1011
1012 /// Returns the storage class as written in the source. For the
1013 /// computed linkage of symbol, see getLinkage.
1014 StorageClass getStorageClass() const {
1015 return (StorageClass) VarDeclBits.SClass;
1016 }
1017 void setStorageClass(StorageClass SC);
1018
1019 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1020 VarDeclBits.TSCSpec = TSC;
1021 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022 }
1023 ThreadStorageClassSpecifier getTSCSpec() const {
1024 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1025 }
1026 TLSKind getTLSKind() const;
1027
1028 /// Returns true if a variable with function scope is a non-static local
1029 /// variable.
1030 bool hasLocalStorage() const {
1031 if (getStorageClass() == SC_None) {
1032 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1033 // used to describe variables allocated in global memory and which are
1034 // accessed inside a kernel(s) as read-only variables. As such, variables
1035 // in constant address space cannot have local storage.
1036 if (getType().getAddressSpace() == LangAS::opencl_constant)
1037 return false;
1038 // Second check is for C++11 [dcl.stc]p4.
1039 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1040 }
1041
1042 // Global Named Register (GNU extension)
1043 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1044 return false;
1045
1046 // Return true for: Auto, Register.
1047 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1048
1049 return getStorageClass() >= SC_Auto;
1050 }
1051
1052 /// Returns true if a variable with function scope is a static local
1053 /// variable.
1054 bool isStaticLocal() const {
1055 return (getStorageClass() == SC_Static ||
1056 // C++11 [dcl.stc]p4
1057 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1058 && !isFileVarDecl();
1059 }
1060
1061 /// Returns true if a variable has extern or __private_extern__
1062 /// storage.
1063 bool hasExternalStorage() const {
1064 return getStorageClass() == SC_Extern ||
1065 getStorageClass() == SC_PrivateExtern;
1066 }
1067
1068 /// Returns true for all variables that do not have local storage.
1069 ///
1070 /// This includes all global variables as well as static variables declared
1071 /// within a function.
1072 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1073
1074 /// Get the storage duration of this variable, per C++ [basic.stc].
1075 StorageDuration getStorageDuration() const {
1076 return hasLocalStorage() ? SD_Automatic :
1077 getTSCSpec() ? SD_Thread : SD_Static;
1078 }
1079
1080 /// Compute the language linkage.
1081 LanguageLinkage getLanguageLinkage() const;
1082
1083 /// Determines whether this variable is a variable with external, C linkage.
1084 bool isExternC() const;
1085
1086 /// Determines whether this variable's context is, or is nested within,
1087 /// a C++ extern "C" linkage spec.
1088 bool isInExternCContext() const;
1089
1090 /// Determines whether this variable's context is, or is nested within,
1091 /// a C++ extern "C++" linkage spec.
1092 bool isInExternCXXContext() const;
1093
1094 /// Returns true for local variable declarations other than parameters.
1095 /// Note that this includes static variables inside of functions. It also
1096 /// includes variables inside blocks.
1097 ///
1098 /// void foo() { int x; static int y; extern int z; }
1099 bool isLocalVarDecl() const {
1100 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1101 return false;
1102 if (const DeclContext *DC = getLexicalDeclContext())
1103 return DC->getRedeclContext()->isFunctionOrMethod();
1104 return false;
1105 }
1106
1107 /// Similar to isLocalVarDecl but also includes parameters.
1108 bool isLocalVarDeclOrParm() const {
1109 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1110 }
1111
1112 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1113 bool isFunctionOrMethodVarDecl() const {
1114 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1115 return false;
1116 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1117 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1118 }
1119
1120 /// Determines whether this is a static data member.
1121 ///
1122 /// This will only be true in C++, and applies to, e.g., the
1123 /// variable 'x' in:
1124 /// \code
1125 /// struct S {
1126 /// static int x;
1127 /// };
1128 /// \endcode
1129 bool isStaticDataMember() const {
1130 // If it wasn't static, it would be a FieldDecl.
1131 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1132 }
1133
1134 VarDecl *getCanonicalDecl() override;
1135 const VarDecl *getCanonicalDecl() const {
1136 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1137 }
1138
1139 enum DefinitionKind {
1140 /// This declaration is only a declaration.
1141 DeclarationOnly,
1142
1143 /// This declaration is a tentative definition.
1144 TentativeDefinition,
1145
1146 /// This declaration is definitely a definition.
1147 Definition
1148 };
1149
1150 /// Check whether this declaration is a definition. If this could be
1151 /// a tentative definition (in C), don't check whether there's an overriding
1152 /// definition.
1153 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1154 DefinitionKind isThisDeclarationADefinition() const {
1155 return isThisDeclarationADefinition(getASTContext());
1156 }
1157
1158 /// Check whether this variable is defined in this translation unit.
1159 DefinitionKind hasDefinition(ASTContext &) const;
1160 DefinitionKind hasDefinition() const {
1161 return hasDefinition(getASTContext());
1162 }
1163
1164 /// Get the tentative definition that acts as the real definition in a TU.
1165 /// Returns null if there is a proper definition available.
1166 VarDecl *getActingDefinition();
1167 const VarDecl *getActingDefinition() const {
1168 return const_cast<VarDecl*>(this)->getActingDefinition();
1169 }
1170
1171 /// Get the real (not just tentative) definition for this declaration.
1172 VarDecl *getDefinition(ASTContext &);
1173 const VarDecl *getDefinition(ASTContext &C) const {
1174 return const_cast<VarDecl*>(this)->getDefinition(C);
1175 }
1176 VarDecl *getDefinition() {
1177 return getDefinition(getASTContext());
1178 }
1179 const VarDecl *getDefinition() const {
1180 return const_cast<VarDecl*>(this)->getDefinition();
1181 }
1182
1183 /// Determine whether this is or was instantiated from an out-of-line
1184 /// definition of a static data member.
1185 bool isOutOfLine() const override;
1186
1187 /// Returns true for file scoped variable declaration.
1188 bool isFileVarDecl() const {
1189 Kind K = getKind();
1190 if (K == ParmVar || K == ImplicitParam)
1191 return false;
1192
1193 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1194 return true;
1195
1196 if (isStaticDataMember())
1197 return true;
1198
1199 return false;
1200 }
1201
1202 /// Get the initializer for this variable, no matter which
1203 /// declaration it is attached to.
1204 const Expr *getAnyInitializer() const {
1205 const VarDecl *D;
1206 return getAnyInitializer(D);
1207 }
1208
1209 /// Get the initializer for this variable, no matter which
1210 /// declaration it is attached to. Also get that declaration.
1211 const Expr *getAnyInitializer(const VarDecl *&D) const;
1212
1213 bool hasInit() const;
1214 const Expr *getInit() const {
1215 return const_cast<VarDecl *>(this)->getInit();
1216 }
1217 Expr *getInit();
1218
1219 /// Retrieve the address of the initializer expression.
1220 Stmt **getInitAddress();
1221
1222 void setInit(Expr *I);
1223
1224 /// Determine whether this variable's value can be used in a
1225 /// constant expression, according to the relevant language standard.
1226 /// This only checks properties of the declaration, and does not check
1227 /// whether the initializer is in fact a constant expression.
1228 bool isUsableInConstantExpressions(ASTContext &C) const;
1229
1230 EvaluatedStmt *ensureEvaluatedStmt() const;
1231
1232 /// \brief Attempt to evaluate the value of the initializer attached to this
1233 /// declaration, and produce notes explaining why it cannot be evaluated or is
1234 /// not a constant expression. Returns a pointer to the value if evaluation
1235 /// succeeded, 0 otherwise.
1236 APValue *evaluateValue() const;
1237 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1238
1239 /// \brief Return the already-evaluated value of this variable's
1240 /// initializer, or NULL if the value is not yet known. Returns pointer
1241 /// to untyped APValue if the value could not be evaluated.
1242 APValue *getEvaluatedValue() const;
1243
1244 /// \brief Determines whether it is already known whether the
1245 /// initializer is an integral constant expression or not.
1246 bool isInitKnownICE() const;
1247
1248 /// \brief Determines whether the initializer is an integral constant
1249 /// expression, or in C++11, whether the initializer is a constant
1250 /// expression.
1251 ///
1252 /// \pre isInitKnownICE()
1253 bool isInitICE() const;
1254
1255 /// \brief Determine whether the value of the initializer attached to this
1256 /// declaration is an integral constant expression.
1257 bool checkInitIsICE() const;
1258
1259 void setInitStyle(InitializationStyle Style) {
1260 VarDeclBits.InitStyle = Style;
1261 }
1262
1263 /// \brief The style of initialization for this declaration.
1264 ///
1265 /// C-style initialization is "int x = 1;". Call-style initialization is
1266 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1267 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1268 /// expression for class types. List-style initialization is C++11 syntax,
1269 /// e.g. "int x{1};". Clients can distinguish between different forms of
1270 /// initialization by checking this value. In particular, "int x = {1};" is
1271 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1272 /// Init expression in all three cases is an InitListExpr.
1273 InitializationStyle getInitStyle() const {
1274 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1275 }
1276
1277 /// \brief Whether the initializer is a direct-initializer (list or call).
1278 bool isDirectInit() const {
1279 return getInitStyle() != CInit;
1280 }
1281
1282 /// \brief If this definition should pretend to be a declaration.
1283 bool isThisDeclarationADemotedDefinition() const {
1284 return isa<ParmVarDecl>(this) ? false :
1285 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1286 }
1287
1288 /// \brief This is a definition which should be demoted to a declaration.
1289 ///
1290 /// In some cases (mostly module merging) we can end up with two visible
1291 /// definitions one of which needs to be demoted to a declaration to keep
1292 /// the AST invariants.
1293 void demoteThisDefinitionToDeclaration() {
1294 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1295, __extension__ __PRETTY_FUNCTION__))
;
1296 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1297 }
1298
1299 /// \brief Determine whether this variable is the exception variable in a
1300 /// C++ catch statememt or an Objective-C \@catch statement.
1301 bool isExceptionVariable() const {
1302 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1303 }
1304 void setExceptionVariable(bool EV) {
1305 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1305, __extension__ __PRETTY_FUNCTION__))
;
1306 NonParmVarDeclBits.ExceptionVar = EV;
1307 }
1308
1309 /// \brief Determine whether this local variable can be used with the named
1310 /// return value optimization (NRVO).
1311 ///
1312 /// The named return value optimization (NRVO) works by marking certain
1313 /// non-volatile local variables of class type as NRVO objects. These
1314 /// locals can be allocated within the return slot of their containing
1315 /// function, in which case there is no need to copy the object to the
1316 /// return slot when returning from the function. Within the function body,
1317 /// each return that returns the NRVO object will have this variable as its
1318 /// NRVO candidate.
1319 bool isNRVOVariable() const {
1320 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1321 }
1322 void setNRVOVariable(bool NRVO) {
1323 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1323, __extension__ __PRETTY_FUNCTION__))
;
1324 NonParmVarDeclBits.NRVOVariable = NRVO;
1325 }
1326
1327 /// \brief Determine whether this variable is the for-range-declaration in
1328 /// a C++0x for-range statement.
1329 bool isCXXForRangeDecl() const {
1330 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1331 }
1332 void setCXXForRangeDecl(bool FRD) {
1333 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1333, __extension__ __PRETTY_FUNCTION__))
;
1334 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1335 }
1336
1337 /// \brief Determine whether this variable is an ARC pseudo-__strong
1338 /// variable. A pseudo-__strong variable has a __strong-qualified
1339 /// type but does not actually retain the object written into it.
1340 /// Generally such variables are also 'const' for safety.
1341 bool isARCPseudoStrong() const {
1342 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1343 }
1344 void setARCPseudoStrong(bool ps) {
1345 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1345, __extension__ __PRETTY_FUNCTION__))
;
1346 NonParmVarDeclBits.ARCPseudoStrong = ps;
1347 }
1348
1349 /// Whether this variable is (C++1z) inline.
1350 bool isInline() const {
1351 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1352 }
1353 bool isInlineSpecified() const {
1354 return isa<ParmVarDecl>(this) ? false
1355 : NonParmVarDeclBits.IsInlineSpecified;
1356 }
1357 void setInlineSpecified() {
1358 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 NonParmVarDeclBits.IsInline = true;
1360 NonParmVarDeclBits.IsInlineSpecified = true;
1361 }
1362 void setImplicitlyInline() {
1363 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1363, __extension__ __PRETTY_FUNCTION__))
;
1364 NonParmVarDeclBits.IsInline = true;
1365 }
1366
1367 /// Whether this variable is (C++11) constexpr.
1368 bool isConstexpr() const {
1369 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1370 }
1371 void setConstexpr(bool IC) {
1372 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1372, __extension__ __PRETTY_FUNCTION__))
;
1373 NonParmVarDeclBits.IsConstexpr = IC;
1374 }
1375
1376 /// Whether this variable is the implicit variable for a lambda init-capture.
1377 bool isInitCapture() const {
1378 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1379 }
1380 void setInitCapture(bool IC) {
1381 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1381, __extension__ __PRETTY_FUNCTION__))
;
1382 NonParmVarDeclBits.IsInitCapture = IC;
1383 }
1384
1385 /// Whether this local extern variable declaration's previous declaration
1386 /// was declared in the same block scope. Only correct in C++.
1387 bool isPreviousDeclInSameBlockScope() const {
1388 return isa<ParmVarDecl>(this)
1389 ? false
1390 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1391 }
1392 void setPreviousDeclInSameBlockScope(bool Same) {
1393 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1393, __extension__ __PRETTY_FUNCTION__))
;
1394 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1395 }
1396
1397 /// \brief Retrieve the variable declaration from which this variable could
1398 /// be instantiated, if it is an instantiation (rather than a non-template).
1399 VarDecl *getTemplateInstantiationPattern() const;
1400
1401 /// \brief If this variable is an instantiated static data member of a
1402 /// class template specialization, returns the templated static data member
1403 /// from which it was instantiated.
1404 VarDecl *getInstantiatedFromStaticDataMember() const;
1405
1406 /// \brief If this variable is an instantiation of a variable template or a
1407 /// static data member of a class template, determine what kind of
1408 /// template specialization or instantiation this is.
1409 TemplateSpecializationKind getTemplateSpecializationKind() const;
1410
1411 /// \brief If this variable is an instantiation of a variable template or a
1412 /// static data member of a class template, determine its point of
1413 /// instantiation.
1414 SourceLocation getPointOfInstantiation() const;
1415
1416 /// \brief If this variable is an instantiation of a static data member of a
1417 /// class template specialization, retrieves the member specialization
1418 /// information.
1419 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1420
1421 /// \brief For a static data member that was instantiated from a static
1422 /// data member of a class template, set the template specialiation kind.
1423 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1424 SourceLocation PointOfInstantiation = SourceLocation());
1425
1426 /// \brief Specify that this variable is an instantiation of the
1427 /// static data member VD.
1428 void setInstantiationOfStaticDataMember(VarDecl *VD,
1429 TemplateSpecializationKind TSK);
1430
1431 /// \brief Retrieves the variable template that is described by this
1432 /// variable declaration.
1433 ///
1434 /// Every variable template is represented as a VarTemplateDecl and a
1435 /// VarDecl. The former contains template properties (such as
1436 /// the template parameter lists) while the latter contains the
1437 /// actual description of the template's
1438 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1439 /// VarDecl that from a VarTemplateDecl, while
1440 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1441 /// a VarDecl.
1442 VarTemplateDecl *getDescribedVarTemplate() const;
1443
1444 void setDescribedVarTemplate(VarTemplateDecl *Template);
1445
1446 // Implement isa/cast/dyncast/etc.
1447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
13
Calling 'Decl::getKind'
14
Returning from 'Decl::getKind'
15
Calling 'VarDecl::classofKind'
18
Returning from 'VarDecl::classofKind'
1448 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
16
Assuming 'K' is >= firstVar
17
Assuming 'K' is <= lastVar
1449};
1450
1451class ImplicitParamDecl : public VarDecl {
1452 void anchor() override;
1453
1454public:
1455 /// Defines the kind of the implicit parameter: is this an implicit parameter
1456 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1457 /// context or something else.
1458 enum ImplicitParamKind : unsigned {
1459 /// Parameter for Objective-C 'self' argument
1460 ObjCSelf,
1461
1462 /// Parameter for Objective-C '_cmd' argument
1463 ObjCCmd,
1464
1465 /// Parameter for C++ 'this' argument
1466 CXXThis,
1467
1468 /// Parameter for C++ virtual table pointers
1469 CXXVTT,
1470
1471 /// Parameter for captured context
1472 CapturedContext,
1473
1474 /// Other implicit parameter
1475 Other,
1476 };
1477
1478 /// Create implicit parameter.
1479 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1480 SourceLocation IdLoc, IdentifierInfo *Id,
1481 QualType T, ImplicitParamKind ParamKind);
1482 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1483 ImplicitParamKind ParamKind);
1484
1485 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1486
1487 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1488 IdentifierInfo *Id, QualType Type,
1489 ImplicitParamKind ParamKind)
1490 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1491 /*TInfo=*/nullptr, SC_None) {
1492 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1493 setImplicit();
1494 }
1495
1496 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1497 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1498 SourceLocation(), /*Id=*/nullptr, Type,
1499 /*TInfo=*/nullptr, SC_None) {
1500 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1501 setImplicit();
1502 }
1503
1504 /// Returns the implicit parameter kind.
1505 ImplicitParamKind getParameterKind() const {
1506 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1507 }
1508
1509 // Implement isa/cast/dyncast/etc.
1510 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1511 static bool classofKind(Kind K) { return K == ImplicitParam; }
1512};
1513
1514/// Represents a parameter to a function.
1515class ParmVarDecl : public VarDecl {
1516public:
1517 enum { MaxFunctionScopeDepth = 255 };
1518 enum { MaxFunctionScopeIndex = 255 };
1519
1520protected:
1521 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1522 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1523 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1524 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1525 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1525, __extension__ __PRETTY_FUNCTION__))
;
1526 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1526, __extension__ __PRETTY_FUNCTION__))
;
1527 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1527, __extension__ __PRETTY_FUNCTION__))
;
1528 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1528, __extension__ __PRETTY_FUNCTION__))
;
1529 setDefaultArg(DefArg);
1530 }
1531
1532public:
1533 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1534 SourceLocation StartLoc,
1535 SourceLocation IdLoc, IdentifierInfo *Id,
1536 QualType T, TypeSourceInfo *TInfo,
1537 StorageClass S, Expr *DefArg);
1538
1539 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1540
1541 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1542
1543 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1544 ParmVarDeclBits.IsObjCMethodParam = true;
1545 setParameterIndex(parameterIndex);
1546 }
1547
1548 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1549 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1549, __extension__ __PRETTY_FUNCTION__))
;
1550
1551 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1552 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1553, __extension__ __PRETTY_FUNCTION__))
1553 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1553, __extension__ __PRETTY_FUNCTION__))
;
1554
1555 setParameterIndex(parameterIndex);
1556 }
1557
1558 bool isObjCMethodParameter() const {
1559 return ParmVarDeclBits.IsObjCMethodParam;
1560 }
1561
1562 unsigned getFunctionScopeDepth() const {
1563 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1564 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1565 }
1566
1567 /// Returns the index of this parameter in its prototype or method scope.
1568 unsigned getFunctionScopeIndex() const {
1569 return getParameterIndex();
1570 }
1571
1572 ObjCDeclQualifier getObjCDeclQualifier() const {
1573 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1574 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1575 }
1576 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1577 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1577, __extension__ __PRETTY_FUNCTION__))
;
1578 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1579 }
1580
1581 /// True if the value passed to this parameter must undergo
1582 /// K&R-style default argument promotion:
1583 ///
1584 /// C99 6.5.2.2.
1585 /// If the expression that denotes the called function has a type
1586 /// that does not include a prototype, the integer promotions are
1587 /// performed on each argument, and arguments that have type float
1588 /// are promoted to double.
1589 bool isKNRPromoted() const {
1590 return ParmVarDeclBits.IsKNRPromoted;
1591 }
1592 void setKNRPromoted(bool promoted) {
1593 ParmVarDeclBits.IsKNRPromoted = promoted;
1594 }
1595
1596 Expr *getDefaultArg();
1597 const Expr *getDefaultArg() const {
1598 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1599 }
1600
1601 void setDefaultArg(Expr *defarg);
1602
1603 /// \brief Retrieve the source range that covers the entire default
1604 /// argument.
1605 SourceRange getDefaultArgRange() const;
1606 void setUninstantiatedDefaultArg(Expr *arg);
1607 Expr *getUninstantiatedDefaultArg();
1608 const Expr *getUninstantiatedDefaultArg() const {
1609 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1610 }
1611
1612 /// Determines whether this parameter has a default argument,
1613 /// either parsed or not.
1614 bool hasDefaultArg() const;
1615
1616 /// Determines whether this parameter has a default argument that has not
1617 /// yet been parsed. This will occur during the processing of a C++ class
1618 /// whose member functions have default arguments, e.g.,
1619 /// @code
1620 /// class X {
1621 /// public:
1622 /// void f(int x = 17); // x has an unparsed default argument now
1623 /// }; // x has a regular default argument now
1624 /// @endcode
1625 bool hasUnparsedDefaultArg() const {
1626 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1627 }
1628
1629 bool hasUninstantiatedDefaultArg() const {
1630 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1631 }
1632
1633 /// Specify that this parameter has an unparsed default argument.
1634 /// The argument will be replaced with a real default argument via
1635 /// setDefaultArg when the class definition enclosing the function
1636 /// declaration that owns this default argument is completed.
1637 void setUnparsedDefaultArg() {
1638 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1639 }
1640
1641 bool hasInheritedDefaultArg() const {
1642 return ParmVarDeclBits.HasInheritedDefaultArg;
1643 }
1644
1645 void setHasInheritedDefaultArg(bool I = true) {
1646 ParmVarDeclBits.HasInheritedDefaultArg = I;
1647 }
1648
1649 QualType getOriginalType() const;
1650
1651 /// \brief Determine whether this parameter is actually a function
1652 /// parameter pack.
1653 bool isParameterPack() const;
1654
1655 /// Sets the function declaration that owns this
1656 /// ParmVarDecl. Since ParmVarDecls are often created before the
1657 /// FunctionDecls that own them, this routine is required to update
1658 /// the DeclContext appropriately.
1659 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1660
1661 // Implement isa/cast/dyncast/etc.
1662 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1663 static bool classofKind(Kind K) { return K == ParmVar; }
1664
1665private:
1666 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1667
1668 void setParameterIndex(unsigned parameterIndex) {
1669 if (parameterIndex >= ParameterIndexSentinel) {
1670 setParameterIndexLarge(parameterIndex);
1671 return;
1672 }
1673
1674 ParmVarDeclBits.ParameterIndex = parameterIndex;
1675 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 1675, __extension__ __PRETTY_FUNCTION__))
;
1676 }
1677 unsigned getParameterIndex() const {
1678 unsigned d = ParmVarDeclBits.ParameterIndex;
1679 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1680 }
1681
1682 void setParameterIndexLarge(unsigned parameterIndex);
1683 unsigned getParameterIndexLarge() const;
1684};
1685
1686/// Represents a function declaration or definition.
1687///
1688/// Since a given function can be declared several times in a program,
1689/// there may be several FunctionDecls that correspond to that
1690/// function. Only one of those FunctionDecls will be found when
1691/// traversing the list of declarations in the context of the
1692/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1693/// contains all of the information known about the function. Other,
1694/// previous declarations of the function are available via the
1695/// getPreviousDecl() chain.
1696class FunctionDecl : public DeclaratorDecl, public DeclContext,
1697 public Redeclarable<FunctionDecl> {
1698public:
1699 /// \brief The kind of templated function a FunctionDecl can be.
1700 enum TemplatedKind {
1701 TK_NonTemplate,
1702 TK_FunctionTemplate,
1703 TK_MemberSpecialization,
1704 TK_FunctionTemplateSpecialization,
1705 TK_DependentFunctionTemplateSpecialization
1706 };
1707
1708private:
1709 /// A new[]'d array of pointers to VarDecls for the formal
1710 /// parameters of this function. This is null if a prototype or if there are
1711 /// no formals.
1712 ParmVarDecl **ParamInfo = nullptr;
1713
1714 LazyDeclStmtPtr Body;
1715
1716 // FIXME: This can be packed into the bitfields in DeclContext.
1717 // NOTE: VC++ packs bitfields poorly if the types differ.
1718 unsigned SClass : 3;
1719 unsigned IsInline : 1;
1720 unsigned IsInlineSpecified : 1;
1721
1722protected:
1723 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1724 // CXXDeductionGuideDecl.
1725 unsigned IsExplicitSpecified : 1;
1726
1727private:
1728 unsigned IsVirtualAsWritten : 1;
1729 unsigned IsPure : 1;
1730 unsigned HasInheritedPrototype : 1;
1731 unsigned HasWrittenPrototype : 1;
1732 unsigned IsDeleted : 1;
1733 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1734
1735 /// This flag indicates whether this function is trivial for the purpose of
1736 /// calls. This is meaningful only when this function is a copy/move
1737 /// constructor or a destructor.
1738 unsigned IsTrivialForCall : 1;
1739
1740 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1741 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1742 unsigned HasImplicitReturnZero : 1;
1743 unsigned IsLateTemplateParsed : 1;
1744 unsigned IsConstexpr : 1;
1745 unsigned InstantiationIsPending : 1;
1746
1747 /// \brief Indicates if the function uses __try.
1748 unsigned UsesSEHTry : 1;
1749
1750 /// \brief Indicates if the function was a definition but its body was
1751 /// skipped.
1752 unsigned HasSkippedBody : 1;
1753
1754 /// Indicates if the function declaration will have a body, once we're done
1755 /// parsing it.
1756 unsigned WillHaveBody : 1;
1757
1758 /// Indicates that this function is a multiversioned function using attribute
1759 /// 'target'.
1760 unsigned IsMultiVersion : 1;
1761
1762protected:
1763 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1764 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1765 /// int as opposed to adding a single bit to FunctionDecl.
1766 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1767 /// deduction candidate' (is used during overload resolution).
1768 unsigned IsCopyDeductionCandidate : 1;
1769
1770private:
1771
1772 /// Store the ODRHash after first calculation.
1773 unsigned HasODRHash : 1;
1774 unsigned ODRHash;
1775
1776 /// \brief End part of this FunctionDecl's source range.
1777 ///
1778 /// We could compute the full range in getSourceRange(). However, when we're
1779 /// dealing with a function definition deserialized from a PCH/AST file,
1780 /// we can only compute the full range once the function body has been
1781 /// de-serialized, so it's far better to have the (sometimes-redundant)
1782 /// EndRangeLoc.
1783 SourceLocation EndRangeLoc;
1784
1785 /// \brief The template or declaration that this declaration
1786 /// describes or was instantiated from, respectively.
1787 ///
1788 /// For non-templates, this value will be NULL. For function
1789 /// declarations that describe a function template, this will be a
1790 /// pointer to a FunctionTemplateDecl. For member functions
1791 /// of class template specializations, this will be a MemberSpecializationInfo
1792 /// pointer containing information about the specialization.
1793 /// For function template specializations, this will be a
1794 /// FunctionTemplateSpecializationInfo, which contains information about
1795 /// the template being specialized and the template arguments involved in
1796 /// that specialization.
1797 llvm::PointerUnion4<FunctionTemplateDecl *,
1798 MemberSpecializationInfo *,
1799 FunctionTemplateSpecializationInfo *,
1800 DependentFunctionTemplateSpecializationInfo *>
1801 TemplateOrSpecialization;
1802
1803 /// Provides source/type location info for the declaration name embedded in
1804 /// the DeclaratorDecl base class.
1805 DeclarationNameLoc DNLoc;
1806
1807 /// \brief Specify that this function declaration is actually a function
1808 /// template specialization.
1809 ///
1810 /// \param C the ASTContext.
1811 ///
1812 /// \param Template the function template that this function template
1813 /// specialization specializes.
1814 ///
1815 /// \param TemplateArgs the template arguments that produced this
1816 /// function template specialization from the template.
1817 ///
1818 /// \param InsertPos If non-NULL, the position in the function template
1819 /// specialization set where the function template specialization data will
1820 /// be inserted.
1821 ///
1822 /// \param TSK the kind of template specialization this is.
1823 ///
1824 /// \param TemplateArgsAsWritten location info of template arguments.
1825 ///
1826 /// \param PointOfInstantiation point at which the function template
1827 /// specialization was first instantiated.
1828 void setFunctionTemplateSpecialization(ASTContext &C,
1829 FunctionTemplateDecl *Template,
1830 const TemplateArgumentList *TemplateArgs,
1831 void *InsertPos,
1832 TemplateSpecializationKind TSK,
1833 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1834 SourceLocation PointOfInstantiation);
1835
1836 /// \brief Specify that this record is an instantiation of the
1837 /// member function FD.
1838 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1839 TemplateSpecializationKind TSK);
1840
1841 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1842
1843protected:
1844 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1845 const DeclarationNameInfo &NameInfo, QualType T,
1846 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1847 bool isConstexprSpecified)
1848 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1849 StartLoc),
1850 DeclContext(DK), redeclarable_base(C), SClass(S),
1851 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1852 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1853 HasInheritedPrototype(false), HasWrittenPrototype(true),
1854 IsDeleted(false), IsTrivial(false), IsTrivialForCall(false),
1855 IsDefaulted(false),
1856 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1857 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1858 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1859 WillHaveBody(false), IsMultiVersion(false),
1860 IsCopyDeductionCandidate(false), HasODRHash(false), ODRHash(0),
1861 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1862
1863 using redeclarable_base = Redeclarable<FunctionDecl>;
1864
1865 FunctionDecl *getNextRedeclarationImpl() override {
1866 return getNextRedeclaration();
1867 }
1868
1869 FunctionDecl *getPreviousDeclImpl() override {
1870 return getPreviousDecl();
1871 }
1872
1873 FunctionDecl *getMostRecentDeclImpl() override {
1874 return getMostRecentDecl();
1875 }
1876
1877public:
1878 friend class ASTDeclReader;
1879 friend class ASTDeclWriter;
1880
1881 using redecl_range = redeclarable_base::redecl_range;
1882 using redecl_iterator = redeclarable_base::redecl_iterator;
1883
1884 using redeclarable_base::redecls_begin;
1885 using redeclarable_base::redecls_end;
1886 using redeclarable_base::redecls;
1887 using redeclarable_base::getPreviousDecl;
1888 using redeclarable_base::getMostRecentDecl;
1889 using redeclarable_base::isFirstDecl;
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc, SourceLocation NLoc,
1893 DeclarationName N, QualType T,
1894 TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified = false,
1897 bool hasWrittenPrototype = true,
1898 bool isConstexprSpecified = false) {
1899 DeclarationNameInfo NameInfo(N, NLoc);
1900 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1901 SC,
1902 isInlineSpecified, hasWrittenPrototype,
1903 isConstexprSpecified);
1904 }
1905
1906 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1907 SourceLocation StartLoc,
1908 const DeclarationNameInfo &NameInfo,
1909 QualType T, TypeSourceInfo *TInfo,
1910 StorageClass SC,
1911 bool isInlineSpecified,
1912 bool hasWrittenPrototype,
1913 bool isConstexprSpecified = false);
1914
1915 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1916
1917 DeclarationNameInfo getNameInfo() const {
1918 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1919 }
1920
1921 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1922 bool Qualified) const override;
1923
1924 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1925
1926 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1927
1928 /// \brief Returns true if the function has a body (definition). The
1929 /// function body might be in any of the (re-)declarations of this
1930 /// function. The variant that accepts a FunctionDecl pointer will
1931 /// set that function declaration to the actual declaration
1932 /// containing the body (if there is one).
1933 bool hasBody(const FunctionDecl *&Definition) const;
1934
1935 bool hasBody() const override {
1936 const FunctionDecl* Definition;
1937 return hasBody(Definition);
1938 }
1939
1940 /// Returns whether the function has a trivial body that does not require any
1941 /// specific codegen.
1942 bool hasTrivialBody() const;
1943
1944 /// Returns true if the function is defined at all, including a deleted
1945 /// definition. Except for the behavior when the function is deleted, behaves
1946 /// like hasBody.
1947 bool isDefined(const FunctionDecl *&Definition) const;
1948
1949 virtual bool isDefined() const {
1950 const FunctionDecl* Definition;
1951 return isDefined(Definition);
1952 }
1953
1954 /// \brief Get the definition for this declaration.
1955 FunctionDecl *getDefinition() {
1956 const FunctionDecl *Definition;
1957 if (isDefined(Definition))
1958 return const_cast<FunctionDecl *>(Definition);
1959 return nullptr;
1960 }
1961 const FunctionDecl *getDefinition() const {
1962 return const_cast<FunctionDecl *>(this)->getDefinition();
1963 }
1964
1965 /// Retrieve the body (definition) of the function. The function body might be
1966 /// in any of the (re-)declarations of this function. The variant that accepts
1967 /// a FunctionDecl pointer will set that function declaration to the actual
1968 /// declaration containing the body (if there is one).
1969 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1970 /// unnecessary AST de-serialization of the body.
1971 Stmt *getBody(const FunctionDecl *&Definition) const;
1972
1973 Stmt *getBody() const override {
1974 const FunctionDecl* Definition;
1975 return getBody(Definition);
1976 }
1977
1978 /// Returns whether this specific declaration of the function is also a
1979 /// definition that does not contain uninstantiated body.
1980 ///
1981 /// This does not determine whether the function has been defined (e.g., in a
1982 /// previous definition); for that information, use isDefined.
1983 bool isThisDeclarationADefinition() const {
1984 return IsDeleted || IsDefaulted || Body || HasSkippedBody ||
1985 IsLateTemplateParsed || WillHaveBody || hasDefiningAttr();
1986 }
1987
1988 /// Returns whether this specific declaration of the function has a body -
1989 /// that is, if it is a non-deleted definition.
1990 bool doesThisDeclarationHaveABody() const {
1991 return Body || IsLateTemplateParsed;
1992 }
1993
1994 void setBody(Stmt *B);
1995 void setLazyBody(uint64_t Offset) { Body = Offset; }
1996
1997 /// Whether this function is variadic.
1998 bool isVariadic() const;
1999
2000 /// Whether this function is marked as virtual explicitly.
2001 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
2002 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
2003
2004 /// Whether this virtual function is pure, i.e. makes the containing class
2005 /// abstract.
2006 bool isPure() const { return IsPure; }
2007 void setPure(bool P = true);
2008
2009 /// Whether this templated function will be late parsed.
2010 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
2011 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
2012
2013 /// Whether this function is "trivial" in some specialized C++ senses.
2014 /// Can only be true for default constructors, copy constructors,
2015 /// copy assignment operators, and destructors. Not meaningful until
2016 /// the class has been fully built by Sema.
2017 bool isTrivial() const { return IsTrivial; }
2018 void setTrivial(bool IT) { IsTrivial = IT; }
2019
2020 bool isTrivialForCall() const { return IsTrivialForCall; }
2021 void setTrivialForCall(bool IT) { IsTrivialForCall = IT; }
2022
2023 /// Whether this function is defaulted per C++0x. Only valid for
2024 /// special member functions.
2025 bool isDefaulted() const { return IsDefaulted; }
2026 void setDefaulted(bool D = true) { IsDefaulted = D; }
2027
2028 /// Whether this function is explicitly defaulted per C++0x. Only valid
2029 /// for special member functions.
2030 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2031 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2032
2033 /// Whether falling off this function implicitly returns null/zero.
2034 /// If a more specific implicit return value is required, front-ends
2035 /// should synthesize the appropriate return statements.
2036 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2037 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2038
2039 /// \brief Whether this function has a prototype, either because one
2040 /// was explicitly written or because it was "inherited" by merging
2041 /// a declaration without a prototype with a declaration that has a
2042 /// prototype.
2043 bool hasPrototype() const {
2044 return HasWrittenPrototype || HasInheritedPrototype;
2045 }
2046
2047 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2048
2049 /// \brief Whether this function inherited its prototype from a
2050 /// previous declaration.
2051 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2052 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2053
2054 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2055 bool isConstexpr() const { return IsConstexpr; }
2056 void setConstexpr(bool IC) { IsConstexpr = IC; }
2057
2058 /// \brief Whether the instantiation of this function is pending.
2059 /// This bit is set when the decision to instantiate this function is made
2060 /// and unset if and when the function body is created. That leaves out
2061 /// cases where instantiation did not happen because the template definition
2062 /// was not seen in this TU. This bit remains set in those cases, under the
2063 /// assumption that the instantiation will happen in some other TU.
2064 bool instantiationIsPending() const { return InstantiationIsPending; }
2065 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2066
2067 /// \brief Indicates the function uses __try.
2068 bool usesSEHTry() const { return UsesSEHTry; }
2069 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2070
2071 /// \brief Whether this function has been deleted.
2072 ///
2073 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2074 /// acts like a normal function, except that it cannot actually be
2075 /// called or have its address taken. Deleted functions are
2076 /// typically used in C++ overload resolution to attract arguments
2077 /// whose type or lvalue/rvalue-ness would permit the use of a
2078 /// different overload that would behave incorrectly. For example,
2079 /// one might use deleted functions to ban implicit conversion from
2080 /// a floating-point number to an Integer type:
2081 ///
2082 /// @code
2083 /// struct Integer {
2084 /// Integer(long); // construct from a long
2085 /// Integer(double) = delete; // no construction from float or double
2086 /// Integer(long double) = delete; // no construction from long double
2087 /// };
2088 /// @endcode
2089 // If a function is deleted, its first declaration must be.
2090 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2091 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2092 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2093
2094 /// \brief Determines whether this function is "main", which is the
2095 /// entry point into an executable program.
2096 bool isMain() const;
2097
2098 /// \brief Determines whether this function is a MSVCRT user defined entry
2099 /// point.
2100 bool isMSVCRTEntryPoint() const;
2101
2102 /// \brief Determines whether this operator new or delete is one
2103 /// of the reserved global placement operators:
2104 /// void *operator new(size_t, void *);
2105 /// void *operator new[](size_t, void *);
2106 /// void operator delete(void *, void *);
2107 /// void operator delete[](void *, void *);
2108 /// These functions have special behavior under [new.delete.placement]:
2109 /// These functions are reserved, a C++ program may not define
2110 /// functions that displace the versions in the Standard C++ library.
2111 /// The provisions of [basic.stc.dynamic] do not apply to these
2112 /// reserved placement forms of operator new and operator delete.
2113 ///
2114 /// This function must be an allocation or deallocation function.
2115 bool isReservedGlobalPlacementOperator() const;
2116
2117 /// \brief Determines whether this function is one of the replaceable
2118 /// global allocation functions:
2119 /// void *operator new(size_t);
2120 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2121 /// void *operator new[](size_t);
2122 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2123 /// void operator delete(void *) noexcept;
2124 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2125 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2126 /// void operator delete[](void *) noexcept;
2127 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2128 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2129 /// These functions have special behavior under C++1y [expr.new]:
2130 /// An implementation is allowed to omit a call to a replaceable global
2131 /// allocation function. [...]
2132 ///
2133 /// If this function is an aligned allocation/deallocation function, return
2134 /// true through IsAligned.
2135 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2136
2137 /// \brief Determine whether this is a destroying operator delete.
2138 bool isDestroyingOperatorDelete() const;
2139
2140 /// Compute the language linkage.
2141 LanguageLinkage getLanguageLinkage() const;
2142
2143 /// \brief Determines whether this function is a function with
2144 /// external, C linkage.
2145 bool isExternC() const;
2146
2147 /// \brief Determines whether this function's context is, or is nested within,
2148 /// a C++ extern "C" linkage spec.
2149 bool isInExternCContext() const;
2150
2151 /// \brief Determines whether this function's context is, or is nested within,
2152 /// a C++ extern "C++" linkage spec.
2153 bool isInExternCXXContext() const;
2154
2155 /// \brief Determines whether this is a global function.
2156 bool isGlobal() const;
2157
2158 /// \brief Determines whether this function is known to be 'noreturn', through
2159 /// an attribute on its declaration or its type.
2160 bool isNoReturn() const;
2161
2162 /// \brief True if the function was a definition but its body was skipped.
2163 bool hasSkippedBody() const { return HasSkippedBody; }
2164 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2165
2166 /// True if this function will eventually have a body, once it's fully parsed.
2167 bool willHaveBody() const { return WillHaveBody; }
2168 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2169
2170 /// True if this function is considered a multiversioned function.
2171 bool isMultiVersion() const { return getCanonicalDecl()->IsMultiVersion; }
2172
2173 /// Sets the multiversion state for this declaration and all of its
2174 /// redeclarations.
2175 void setIsMultiVersion(bool V = true) {
2176 getCanonicalDecl()->IsMultiVersion = V;
2177 }
2178
2179 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2180
2181 FunctionDecl *getCanonicalDecl() override;
2182 const FunctionDecl *getCanonicalDecl() const {
2183 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2184 }
2185
2186 unsigned getBuiltinID() const;
2187
2188 // ArrayRef interface to parameters.
2189 ArrayRef<ParmVarDecl *> parameters() const {
2190 return {ParamInfo, getNumParams()};
2191 }
2192 MutableArrayRef<ParmVarDecl *> parameters() {
2193 return {ParamInfo, getNumParams()};
2194 }
2195
2196 // Iterator access to formal parameters.
2197 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2198 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2199
2200 bool param_empty() const { return parameters().empty(); }
2201 param_iterator param_begin() { return parameters().begin(); }
2202 param_iterator param_end() { return parameters().end(); }
2203 param_const_iterator param_begin() const { return parameters().begin(); }
2204 param_const_iterator param_end() const { return parameters().end(); }
2205 size_t param_size() const { return parameters().size(); }
2206
2207 /// Return the number of parameters this function must have based on its
2208 /// FunctionType. This is the length of the ParamInfo array after it has been
2209 /// created.
2210 unsigned getNumParams() const;
2211
2212 const ParmVarDecl *getParamDecl(unsigned i) const {
2213 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2213, __extension__ __PRETTY_FUNCTION__))
;
2214 return ParamInfo[i];
2215 }
2216 ParmVarDecl *getParamDecl(unsigned i) {
2217 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2217, __extension__ __PRETTY_FUNCTION__))
;
2218 return ParamInfo[i];
2219 }
2220 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2221 setParams(getASTContext(), NewParamInfo);
2222 }
2223
2224 /// Returns the minimum number of arguments needed to call this function. This
2225 /// may be fewer than the number of function parameters, if some of the
2226 /// parameters have default arguments (in C++).
2227 unsigned getMinRequiredArguments() const;
2228
2229 QualType getReturnType() const {
2230 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2230, __extension__ __PRETTY_FUNCTION__))
;
2231 return getType()->getAs<FunctionType>()->getReturnType();
2232 }
2233
2234 /// \brief Attempt to compute an informative source range covering the
2235 /// function return type. This may omit qualifiers and other information with
2236 /// limited representation in the AST.
2237 SourceRange getReturnTypeSourceRange() const;
2238
2239 /// \brief Attempt to compute an informative source range covering the
2240 /// function exception specification, if any.
2241 SourceRange getExceptionSpecSourceRange() const;
2242
2243 /// \brief Determine the type of an expression that calls this function.
2244 QualType getCallResultType() const {
2245 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2245, __extension__ __PRETTY_FUNCTION__))
;
2246 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2247 }
2248
2249 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2250 /// function, or its return type declaration.
2251 const Attr *getUnusedResultAttr() const;
2252
2253 /// \brief Returns true if this function or its return type has the
2254 /// warn_unused_result attribute.
2255 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2256
2257 /// \brief Returns the storage class as written in the source. For the
2258 /// computed linkage of symbol, see getLinkage.
2259 StorageClass getStorageClass() const { return StorageClass(SClass); }
2260
2261 /// \brief Determine whether the "inline" keyword was specified for this
2262 /// function.
2263 bool isInlineSpecified() const { return IsInlineSpecified; }
2264
2265 /// Set whether the "inline" keyword was specified for this function.
2266 void setInlineSpecified(bool I) {
2267 IsInlineSpecified = I;
2268 IsInline = I;
2269 }
2270
2271 /// Flag that this function is implicitly inline.
2272 void setImplicitlyInline() {
2273 IsInline = true;
2274 }
2275
2276 /// \brief Determine whether this function should be inlined, because it is
2277 /// either marked "inline" or "constexpr" or is a member function of a class
2278 /// that was defined in the class body.
2279 bool isInlined() const { return IsInline; }
2280
2281 bool isInlineDefinitionExternallyVisible() const;
2282
2283 bool isMSExternInline() const;
2284
2285 bool doesDeclarationForceExternallyVisibleDefinition() const;
2286
2287 /// Whether this function declaration represents an C++ overloaded
2288 /// operator, e.g., "operator+".
2289 bool isOverloadedOperator() const {
2290 return getOverloadedOperator() != OO_None;
2291 }
2292
2293 OverloadedOperatorKind getOverloadedOperator() const;
2294
2295 const IdentifierInfo *getLiteralIdentifier() const;
2296
2297 /// \brief If this function is an instantiation of a member function
2298 /// of a class template specialization, retrieves the function from
2299 /// which it was instantiated.
2300 ///
2301 /// This routine will return non-NULL for (non-templated) member
2302 /// functions of class templates and for instantiations of function
2303 /// templates. For example, given:
2304 ///
2305 /// \code
2306 /// template<typename T>
2307 /// struct X {
2308 /// void f(T);
2309 /// };
2310 /// \endcode
2311 ///
2312 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2313 /// whose parent is the class template specialization X<int>. For
2314 /// this declaration, getInstantiatedFromFunction() will return
2315 /// the FunctionDecl X<T>::A. When a complete definition of
2316 /// X<int>::A is required, it will be instantiated from the
2317 /// declaration returned by getInstantiatedFromMemberFunction().
2318 FunctionDecl *getInstantiatedFromMemberFunction() const;
2319
2320 /// \brief What kind of templated function this is.
2321 TemplatedKind getTemplatedKind() const;
2322
2323 /// \brief If this function is an instantiation of a member function of a
2324 /// class template specialization, retrieves the member specialization
2325 /// information.
2326 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2327
2328 /// \brief Specify that this record is an instantiation of the
2329 /// member function FD.
2330 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2331 TemplateSpecializationKind TSK) {
2332 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2333 }
2334
2335 /// \brief Retrieves the function template that is described by this
2336 /// function declaration.
2337 ///
2338 /// Every function template is represented as a FunctionTemplateDecl
2339 /// and a FunctionDecl (or something derived from FunctionDecl). The
2340 /// former contains template properties (such as the template
2341 /// parameter lists) while the latter contains the actual
2342 /// description of the template's
2343 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2344 /// FunctionDecl that describes the function template,
2345 /// getDescribedFunctionTemplate() retrieves the
2346 /// FunctionTemplateDecl from a FunctionDecl.
2347 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2348
2349 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2350
2351 /// \brief Determine whether this function is a function template
2352 /// specialization.
2353 bool isFunctionTemplateSpecialization() const {
2354 return getPrimaryTemplate() != nullptr;
2355 }
2356
2357 /// \brief Retrieve the class scope template pattern that this function
2358 /// template specialization is instantiated from.
2359 FunctionDecl *getClassScopeSpecializationPattern() const;
2360
2361 /// \brief If this function is actually a function template specialization,
2362 /// retrieve information about this function template specialization.
2363 /// Otherwise, returns NULL.
2364 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2365
2366 /// \brief Determines whether this function is a function template
2367 /// specialization or a member of a class template specialization that can
2368 /// be implicitly instantiated.
2369 bool isImplicitlyInstantiable() const;
2370
2371 /// \brief Determines if the given function was instantiated from a
2372 /// function template.
2373 bool isTemplateInstantiation() const;
2374
2375 /// \brief Retrieve the function declaration from which this function could
2376 /// be instantiated, if it is an instantiation (rather than a non-template
2377 /// or a specialization, for example).
2378 FunctionDecl *getTemplateInstantiationPattern() const;
2379
2380 /// \brief Retrieve the primary template that this function template
2381 /// specialization either specializes or was instantiated from.
2382 ///
2383 /// If this function declaration is not a function template specialization,
2384 /// returns NULL.
2385 FunctionTemplateDecl *getPrimaryTemplate() const;
2386
2387 /// \brief Retrieve the template arguments used to produce this function
2388 /// template specialization from the primary template.
2389 ///
2390 /// If this function declaration is not a function template specialization,
2391 /// returns NULL.
2392 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2393
2394 /// \brief Retrieve the template argument list as written in the sources,
2395 /// if any.
2396 ///
2397 /// If this function declaration is not a function template specialization
2398 /// or if it had no explicit template argument list, returns NULL.
2399 /// Note that it an explicit template argument list may be written empty,
2400 /// e.g., template<> void foo<>(char* s);
2401 const ASTTemplateArgumentListInfo*
2402 getTemplateSpecializationArgsAsWritten() const;
2403
2404 /// \brief Specify that this function declaration is actually a function
2405 /// template specialization.
2406 ///
2407 /// \param Template the function template that this function template
2408 /// specialization specializes.
2409 ///
2410 /// \param TemplateArgs the template arguments that produced this
2411 /// function template specialization from the template.
2412 ///
2413 /// \param InsertPos If non-NULL, the position in the function template
2414 /// specialization set where the function template specialization data will
2415 /// be inserted.
2416 ///
2417 /// \param TSK the kind of template specialization this is.
2418 ///
2419 /// \param TemplateArgsAsWritten location info of template arguments.
2420 ///
2421 /// \param PointOfInstantiation point at which the function template
2422 /// specialization was first instantiated.
2423 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2424 const TemplateArgumentList *TemplateArgs,
2425 void *InsertPos,
2426 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2427 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2428 SourceLocation PointOfInstantiation = SourceLocation()) {
2429 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2430 InsertPos, TSK, TemplateArgsAsWritten,
2431 PointOfInstantiation);
2432 }
2433
2434 /// \brief Specifies that this function declaration is actually a
2435 /// dependent function template specialization.
2436 void setDependentTemplateSpecialization(ASTContext &Context,
2437 const UnresolvedSetImpl &Templates,
2438 const TemplateArgumentListInfo &TemplateArgs);
2439
2440 DependentFunctionTemplateSpecializationInfo *
2441 getDependentSpecializationInfo() const;
2442
2443 /// \brief Determine what kind of template instantiation this function
2444 /// represents.
2445 TemplateSpecializationKind getTemplateSpecializationKind() const;
2446
2447 /// \brief Determine what kind of template instantiation this function
2448 /// represents.
2449 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2450 SourceLocation PointOfInstantiation = SourceLocation());
2451
2452 /// \brief Retrieve the (first) point of instantiation of a function template
2453 /// specialization or a member of a class template specialization.
2454 ///
2455 /// \returns the first point of instantiation, if this function was
2456 /// instantiated from a template; otherwise, returns an invalid source
2457 /// location.
2458 SourceLocation getPointOfInstantiation() const;
2459
2460 /// \brief Determine whether this is or was instantiated from an out-of-line
2461 /// definition of a member function.
2462 bool isOutOfLine() const override;
2463
2464 /// \brief Identify a memory copying or setting function.
2465 /// If the given function is a memory copy or setting function, returns
2466 /// the corresponding Builtin ID. If the function is not a memory function,
2467 /// returns 0.
2468 unsigned getMemoryFunctionKind() const;
2469
2470 /// \brief Returns ODRHash of the function. This value is calculated and
2471 /// stored on first call, then the stored value returned on the other calls.
2472 unsigned getODRHash();
2473
2474 // Implement isa/cast/dyncast/etc.
2475 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2476 static bool classofKind(Kind K) {
2477 return K >= firstFunction && K <= lastFunction;
2478 }
2479 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2480 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2481 }
2482 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2483 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2484 }
2485};
2486
2487/// Represents a member of a struct/union/class.
2488class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2489 unsigned BitField : 1;
2490 unsigned Mutable : 1;
2491 mutable unsigned CachedFieldIndex : 30;
2492
2493 /// The kinds of value we can store in InitializerOrBitWidth.
2494 ///
2495 /// Note that this is compatible with InClassInitStyle except for
2496 /// ISK_CapturedVLAType.
2497 enum InitStorageKind {
2498 /// If the pointer is null, there's nothing special. Otherwise,
2499 /// this is a bitfield and the pointer is the Expr* storing the
2500 /// bit-width.
2501 ISK_NoInit = (unsigned) ICIS_NoInit,
2502
2503 /// The pointer is an (optional due to delayed parsing) Expr*
2504 /// holding the copy-initializer.
2505 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2506
2507 /// The pointer is an (optional due to delayed parsing) Expr*
2508 /// holding the list-initializer.
2509 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2510
2511 /// The pointer is a VariableArrayType* that's been captured;
2512 /// the enclosing context is a lambda or captured statement.
2513 ISK_CapturedVLAType,
2514 };
2515
2516 /// If this is a bitfield with a default member initializer, this
2517 /// structure is used to represent the two expressions.
2518 struct InitAndBitWidth {
2519 Expr *Init;
2520 Expr *BitWidth;
2521 };
2522
2523 /// \brief Storage for either the bit-width, the in-class initializer, or
2524 /// both (via InitAndBitWidth), or the captured variable length array bound.
2525 ///
2526 /// If the storage kind is ISK_InClassCopyInit or
2527 /// ISK_InClassListInit, but the initializer is null, then this
2528 /// field has an in-class initializer that has not yet been parsed
2529 /// and attached.
2530 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2531 // overwhelmingly common case that we have none of these things.
2532 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2533
2534protected:
2535 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2536 SourceLocation IdLoc, IdentifierInfo *Id,
2537 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2538 InClassInitStyle InitStyle)
2539 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2540 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2541 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2542 if (BW)
2543 setBitWidth(BW);
2544 }
2545
2546public:
2547 friend class ASTDeclReader;
2548 friend class ASTDeclWriter;
2549
2550 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2551 SourceLocation StartLoc, SourceLocation IdLoc,
2552 IdentifierInfo *Id, QualType T,
2553 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2554 InClassInitStyle InitStyle);
2555
2556 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2557
2558 /// Returns the index of this field within its record,
2559 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2560 unsigned getFieldIndex() const;
2561
2562 /// Determines whether this field is mutable (C++ only).
2563 bool isMutable() const { return Mutable; }
2564
2565 /// Determines whether this field is a bitfield.
2566 bool isBitField() const { return BitField; }
2567
2568 /// Determines whether this is an unnamed bitfield.
2569 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2570
2571 /// Determines whether this field is a
2572 /// representative for an anonymous struct or union. Such fields are
2573 /// unnamed and are implicitly generated by the implementation to
2574 /// store the data for the anonymous union or struct.
2575 bool isAnonymousStructOrUnion() const;
2576
2577 Expr *getBitWidth() const {
2578 if (!BitField)
2579 return nullptr;
2580 void *Ptr = InitStorage.getPointer();
2581 if (getInClassInitStyle())
2582 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2583 return static_cast<Expr*>(Ptr);
2584 }
2585
2586 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2587
2588 /// Set the bit-field width for this member.
2589 // Note: used by some clients (i.e., do not remove it).
2590 void setBitWidth(Expr *Width) {
2591 assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2592, __extension__ __PRETTY_FUNCTION__))
2592 "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2592, __extension__ __PRETTY_FUNCTION__))
;
2593 assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified"
) ? void (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2593, __extension__ __PRETTY_FUNCTION__))
;
2594 InitStorage.setPointer(
2595 InitStorage.getInt()
2596 ? new (getASTContext())
2597 InitAndBitWidth{getInClassInitializer(), Width}
2598 : static_cast<void*>(Width));
2599 BitField = true;
2600 }
2601
2602 /// Remove the bit-field width from this member.
2603 // Note: used by some clients (i.e., do not remove it).
2604 void removeBitWidth() {
2605 assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove"
) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2605, __extension__ __PRETTY_FUNCTION__))
;
2606 InitStorage.setPointer(getInClassInitializer());
2607 BitField = false;
2608 }
2609
2610 /// Get the kind of (C++11) default member initializer that this field has.
2611 InClassInitStyle getInClassInitStyle() const {
2612 InitStorageKind storageKind = InitStorage.getInt();
2613 return (storageKind == ISK_CapturedVLAType
2614 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2615 }
2616
2617 /// Determine whether this member has a C++11 default member initializer.
2618 bool hasInClassInitializer() const {
2619 return getInClassInitStyle() != ICIS_NoInit;
2620 }
2621
2622 /// Get the C++11 default member initializer for this member, or null if one
2623 /// has not been set. If a valid declaration has a default member initializer,
2624 /// but this returns null, then we have not parsed and attached it yet.
2625 Expr *getInClassInitializer() const {
2626 if (!hasInClassInitializer())
2627 return nullptr;
2628 void *Ptr = InitStorage.getPointer();
2629 if (BitField)
2630 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2631 return static_cast<Expr*>(Ptr);
2632 }
2633
2634 /// Set the C++11 in-class initializer for this member.
2635 void setInClassInitializer(Expr *Init) {
2636 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2636, __extension__ __PRETTY_FUNCTION__))
;
2637 if (BitField)
2638 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2639 else
2640 InitStorage.setPointer(Init);
2641 }
2642
2643 /// Remove the C++11 in-class initializer from this member.
2644 void removeInClassInitializer() {
2645 assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() &&
"no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2645, __extension__ __PRETTY_FUNCTION__))
;
2646 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2647 }
2648
2649 /// \brief Determine whether this member captures the variable length array
2650 /// type.
2651 bool hasCapturedVLAType() const {
2652 return InitStorage.getInt() == ISK_CapturedVLAType;
2653 }
2654
2655 /// \brief Get the captured variable length array type.
2656 const VariableArrayType *getCapturedVLAType() const {
2657 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2658 InitStorage.getPointer())
2659 : nullptr;
2660 }
2661
2662 /// \brief Set the captured variable length array type for this field.
2663 void setCapturedVLAType(const VariableArrayType *VLAType);
2664
2665 /// Returns the parent of this field declaration, which
2666 /// is the struct in which this field is defined.
2667 const RecordDecl *getParent() const {
2668 return cast<RecordDecl>(getDeclContext());
2669 }
2670
2671 RecordDecl *getParent() {
2672 return cast<RecordDecl>(getDeclContext());
2673 }
2674
2675 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2676
2677 /// Retrieves the canonical declaration of this field.
2678 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2679 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2680
2681 // Implement isa/cast/dyncast/etc.
2682 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2683 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2684};
2685
2686/// An instance of this object exists for each enum constant
2687/// that is defined. For example, in "enum X {a,b}", each of a/b are
2688/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2689/// TagType for the X EnumDecl.
2690class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2691 Stmt *Init; // an integer constant expression
2692 llvm::APSInt Val; // The value.
2693
2694protected:
2695 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2696 IdentifierInfo *Id, QualType T, Expr *E,
2697 const llvm::APSInt &V)
2698 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2699
2700public:
2701 friend class StmtIteratorBase;
2702
2703 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2704 SourceLocation L, IdentifierInfo *Id,
2705 QualType T, Expr *E,
2706 const llvm::APSInt &V);
2707 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2708
2709 const Expr *getInitExpr() const { return (const Expr*) Init; }
2710 Expr *getInitExpr() { return (Expr*) Init; }
2711 const llvm::APSInt &getInitVal() const { return Val; }
2712
2713 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2714 void setInitVal(const llvm::APSInt &V) { Val = V; }
2715
2716 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2717
2718 /// Retrieves the canonical declaration of this enumerator.
2719 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2720 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2721
2722 // Implement isa/cast/dyncast/etc.
2723 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2724 static bool classofKind(Kind K) { return K == EnumConstant; }
2725};
2726
2727/// Represents a field injected from an anonymous union/struct into the parent
2728/// scope. These are always implicit.
2729class IndirectFieldDecl : public ValueDecl,
2730 public Mergeable<IndirectFieldDecl> {
2731 NamedDecl **Chaining;
2732 unsigned ChainingSize;
2733
2734 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2735 DeclarationName N, QualType T,
2736 MutableArrayRef<NamedDecl *> CH);
2737
2738 void anchor() override;
2739
2740public:
2741 friend class ASTDeclReader;
2742
2743 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2744 SourceLocation L, IdentifierInfo *Id,
2745 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2746
2747 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2748
2749 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2750
2751 ArrayRef<NamedDecl *> chain() const {
2752 return llvm::makeArrayRef(Chaining, ChainingSize);
2753 }
2754 chain_iterator chain_begin() const { return chain().begin(); }
2755 chain_iterator chain_end() const { return chain().end(); }
2756
2757 unsigned getChainingSize() const { return ChainingSize; }
2758
2759 FieldDecl *getAnonField() const {
2760 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2760, __extension__ __PRETTY_FUNCTION__))
;
2761 return cast<FieldDecl>(chain().back());
2762 }
2763
2764 VarDecl *getVarDecl() const {
2765 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 2765, __extension__ __PRETTY_FUNCTION__))
;
2766 return dyn_cast<VarDecl>(chain().front());
2767 }
2768
2769 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2770 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2771
2772 // Implement isa/cast/dyncast/etc.
2773 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2774 static bool classofKind(Kind K) { return K == IndirectField; }
2775};
2776
2777/// Represents a declaration of a type.
2778class TypeDecl : public NamedDecl {
2779 friend class ASTContext;
2780
2781 /// This indicates the Type object that represents
2782 /// this TypeDecl. It is a cache maintained by
2783 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2784 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2785 mutable const Type *TypeForDecl = nullptr;
2786
2787 /// The start of the source range for this declaration.
2788 SourceLocation LocStart;
2789
2790 void anchor() override;
2791
2792protected:
2793 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2794 SourceLocation StartL = SourceLocation())
2795 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2796
2797public:
2798 // Low-level accessor. If you just want the type defined by this node,
2799 // check out ASTContext::getTypeDeclType or one of
2800 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2801 // already know the specific kind of node this is.
2802 const Type *getTypeForDecl() const { return TypeForDecl; }
2803 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2804
2805 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2806 void setLocStart(SourceLocation L) { LocStart = L; }
2807 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2808 if (LocStart.isValid())
2809 return SourceRange(LocStart, getLocation());
2810 else
2811 return SourceRange(getLocation());
2812 }
2813
2814 // Implement isa/cast/dyncast/etc.
2815 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2816 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2817};
2818
2819/// Base class for declarations which introduce a typedef-name.
2820class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2821 struct LLVM_ALIGNAS(8)alignas(8) ModedTInfo {
2822 TypeSourceInfo *first;
2823 QualType second;
2824 };
2825
2826 /// If int part is 0, we have not computed IsTransparentTag.
2827 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2828 mutable llvm::PointerIntPair<
2829 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2830 MaybeModedTInfo;
2831
2832 void anchor() override;
2833
2834protected:
2835 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2836 SourceLocation StartLoc, SourceLocation IdLoc,
2837 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2838 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2839 MaybeModedTInfo(TInfo, 0) {}
2840
2841 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2842
2843 TypedefNameDecl *getNextRedeclarationImpl() override {
2844 return getNextRedeclaration();
2845 }
2846
2847 TypedefNameDecl *getPreviousDeclImpl() override {
2848 return getPreviousDecl();
2849 }
2850
2851 TypedefNameDecl *getMostRecentDeclImpl() override {
2852 return getMostRecentDecl();
2853 }
2854
2855public:
2856 using redecl_range = redeclarable_base::redecl_range;
2857 using redecl_iterator = redeclarable_base::redecl_iterator;
2858
2859 using redeclarable_base::redecls_begin;
2860 using redeclarable_base::redecls_end;
2861 using redeclarable_base::redecls;
2862 using redeclarable_base::getPreviousDecl;
2863 using redeclarable_base::getMostRecentDecl;
2864 using redeclarable_base::isFirstDecl;
2865
2866 bool isModed() const {
2867 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
2868 }
2869
2870 TypeSourceInfo *getTypeSourceInfo() const {
2871 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
2872 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
2873 }
2874
2875 QualType getUnderlyingType() const {
2876 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
2877 : MaybeModedTInfo.getPointer()
2878 .get<TypeSourceInfo *>()
2879 ->getType();
2880 }
2881
2882 void setTypeSourceInfo(TypeSourceInfo *newType) {
2883 MaybeModedTInfo.setPointer(newType);
2884 }
2885
2886 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2887 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
2888 ModedTInfo({unmodedTSI, modedTy}));
2889 }
2890
2891 /// Retrieves the canonical declaration of this typedef-name.
2892 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2893 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2894
2895 /// Retrieves the tag declaration for which this is the typedef name for
2896 /// linkage purposes, if any.
2897 ///
2898 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2899 /// this typedef declaration.
2900 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2901
2902 /// Determines if this typedef shares a name and spelling location with its
2903 /// underlying tag type, as is the case with the NS_ENUM macro.
2904 bool isTransparentTag() const {
2905 if (MaybeModedTInfo.getInt())
2906 return MaybeModedTInfo.getInt() & 0x2;
2907 return isTransparentTagSlow();
2908 }
2909
2910 // Implement isa/cast/dyncast/etc.
2911 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2912 static bool classofKind(Kind K) {
2913 return K >= firstTypedefName && K <= lastTypedefName;
2914 }
2915
2916private:
2917 bool isTransparentTagSlow() const;
2918};
2919
2920/// Represents the declaration of a typedef-name via the 'typedef'
2921/// type specifier.
2922class TypedefDecl : public TypedefNameDecl {
2923 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2924 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2925 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2926
2927public:
2928 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2929 SourceLocation StartLoc, SourceLocation IdLoc,
2930 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2931 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2932
2933 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2934
2935 // Implement isa/cast/dyncast/etc.
2936 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2937 static bool classofKind(Kind K) { return K == Typedef; }
2938};
2939
2940/// Represents the declaration of a typedef-name via a C++11
2941/// alias-declaration.
2942class TypeAliasDecl : public TypedefNameDecl {
2943 /// The template for which this is the pattern, if any.
2944 TypeAliasTemplateDecl *Template;
2945
2946 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2947 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2948 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2949 Template(nullptr) {}
2950
2951public:
2952 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2953 SourceLocation StartLoc, SourceLocation IdLoc,
2954 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2955 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2956
2957 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2958
2959 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2960 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2961
2962 // Implement isa/cast/dyncast/etc.
2963 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2964 static bool classofKind(Kind K) { return K == TypeAlias; }
2965};
2966
2967/// Represents the declaration of a struct/union/class/enum.
2968class TagDecl
2969 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2970public:
2971 // This is really ugly.
2972 using TagKind = TagTypeKind;
2973
2974private:
2975 // FIXME: This can be packed into the bitfields in Decl.
2976 /// The TagKind enum.
2977 unsigned TagDeclKind : 3;
2978
2979 /// True if this is a definition ("struct foo {};"), false if it is a
2980 /// declaration ("struct foo;"). It is not considered a definition
2981 /// until the definition has been fully processed.
2982 unsigned IsCompleteDefinition : 1;
2983
2984protected:
2985 /// True if this is currently being defined.
2986 unsigned IsBeingDefined : 1;
2987
2988private:
2989 /// True if this tag declaration is "embedded" (i.e., defined or declared
2990 /// for the very first time) in the syntax of a declarator.
2991 unsigned IsEmbeddedInDeclarator : 1;
2992
2993 /// True if this tag is free standing, e.g. "struct foo;".
2994 unsigned IsFreeStanding : 1;
2995
2996protected:
2997 // These are used by (and only defined for) EnumDecl.
2998 unsigned NumPositiveBits : 8;
2999 unsigned NumNegativeBits : 8;
3000
3001 /// True if this tag declaration is a scoped enumeration. Only
3002 /// possible in C++11 mode.
3003 unsigned IsScoped : 1;
3004
3005 /// If this tag declaration is a scoped enum,
3006 /// then this is true if the scoped enum was declared using the class
3007 /// tag, false if it was declared with the struct tag. No meaning is
3008 /// associated if this tag declaration is not a scoped enum.
3009 unsigned IsScopedUsingClassTag : 1;
3010
3011 /// True if this is an enumeration with fixed underlying type. Only
3012 /// possible in C++11, Microsoft extensions, or Objective C mode.
3013 unsigned IsFixed : 1;
3014
3015 /// Indicates whether it is possible for declarations of this kind
3016 /// to have an out-of-date definition.
3017 ///
3018 /// This option is only enabled when modules are enabled.
3019 unsigned MayHaveOutOfDateDef : 1;
3020
3021 /// Has the full definition of this type been required by a use somewhere in
3022 /// the TU.
3023 unsigned IsCompleteDefinitionRequired : 1;
3024
3025private:
3026 SourceRange BraceRange;
3027
3028 // A struct representing syntactic qualifier info,
3029 // to be used for the (uncommon) case of out-of-line declarations.
3030 using ExtInfo = QualifierInfo;
3031
3032 /// \brief If the (out-of-line) tag declaration name
3033 /// is qualified, it points to the qualifier info (nns and range);
3034 /// otherwise, if the tag declaration is anonymous and it is part of
3035 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3036 /// otherwise, if the tag declaration is anonymous and it is used as a
3037 /// declaration specifier for variables, it points to the first VarDecl (used
3038 /// for mangling);
3039 /// otherwise, it is a null (TypedefNameDecl) pointer.
3040 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3041
3042 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3043 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3044 const ExtInfo *getExtInfo() const {
3045 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3046 }
3047
3048protected:
3049 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3050 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3051 SourceLocation StartL)
3052 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3053 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3054 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3055 IsCompleteDefinitionRequired(false),
3056 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3057 assert((DK != Enum || TK == TTK_Enum) &&(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3058, __extension__ __PRETTY_FUNCTION__))
3058 "EnumDecl not matched with TTK_Enum")(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3058, __extension__ __PRETTY_FUNCTION__))
;
3059 setPreviousDecl(PrevDecl);
3060 }
3061
3062 using redeclarable_base = Redeclarable<TagDecl>;
3063
3064 TagDecl *getNextRedeclarationImpl() override {
3065 return getNextRedeclaration();
3066 }
3067
3068 TagDecl *getPreviousDeclImpl() override {
3069 return getPreviousDecl();
3070 }
3071
3072 TagDecl *getMostRecentDeclImpl() override {
3073 return getMostRecentDecl();
3074 }
3075
3076 /// @brief Completes the definition of this tag declaration.
3077 ///
3078 /// This is a helper function for derived classes.
3079 void completeDefinition();
3080
3081public:
3082 friend class ASTDeclReader;
3083 friend class ASTDeclWriter;
3084
3085 using redecl_range = redeclarable_base::redecl_range;
3086 using redecl_iterator = redeclarable_base::redecl_iterator;
3087
3088 using redeclarable_base::redecls_begin;
3089 using redeclarable_base::redecls_end;
3090 using redeclarable_base::redecls;
3091 using redeclarable_base::getPreviousDecl;
3092 using redeclarable_base::getMostRecentDecl;
3093 using redeclarable_base::isFirstDecl;
3094
3095 SourceRange getBraceRange() const { return BraceRange; }
3096 void setBraceRange(SourceRange R) { BraceRange = R; }
3097
3098 /// Return SourceLocation representing start of source
3099 /// range ignoring outer template declarations.
3100 SourceLocation getInnerLocStart() const { return getLocStart(); }
3101
3102 /// Return SourceLocation representing start of source
3103 /// range taking into account any outer template declarations.
3104 SourceLocation getOuterLocStart() const;
3105 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3106
3107 TagDecl *getCanonicalDecl() override;
3108 const TagDecl *getCanonicalDecl() const {
3109 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3110 }
3111
3112 /// Return true if this declaration is a completion definition of the type.
3113 /// Provided for consistency.
3114 bool isThisDeclarationADefinition() const {
3115 return isCompleteDefinition();
3116 }
3117
3118 /// Return true if this decl has its body fully specified.
3119 bool isCompleteDefinition() const {
3120 return IsCompleteDefinition;
3121 }
3122
3123 /// \brief Return true if this complete decl is
3124 /// required to be complete for some existing use.
3125 bool isCompleteDefinitionRequired() const {
3126 return IsCompleteDefinitionRequired;
3127 }
3128
3129 /// Return true if this decl is currently being defined.
3130 bool isBeingDefined() const {
3131 return IsBeingDefined;
3132 }
3133
3134 bool isEmbeddedInDeclarator() const {
3135 return IsEmbeddedInDeclarator;
3136 }
3137 void setEmbeddedInDeclarator(bool isInDeclarator) {
3138 IsEmbeddedInDeclarator = isInDeclarator;
3139 }
3140
3141 bool isFreeStanding() const { return IsFreeStanding; }
3142 void setFreeStanding(bool isFreeStanding = true) {
3143 IsFreeStanding = isFreeStanding;
3144 }
3145
3146 /// \brief Whether this declaration declares a type that is
3147 /// dependent, i.e., a type that somehow depends on template
3148 /// parameters.
3149 bool isDependentType() const { return isDependentContext(); }
3150
3151 /// Starts the definition of this tag declaration.
3152 ///
3153 /// This method should be invoked at the beginning of the definition
3154 /// of this tag declaration. It will set the tag type into a state
3155 /// where it is in the process of being defined.
3156 void startDefinition();
3157
3158 /// Returns the TagDecl that actually defines this
3159 /// struct/union/class/enum. When determining whether or not a
3160 /// struct/union/class/enum has a definition, one should use this
3161 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3162 /// whether or not a specific TagDecl is defining declaration, not
3163 /// whether or not the struct/union/class/enum type is defined.
3164 /// This method returns NULL if there is no TagDecl that defines
3165 /// the struct/union/class/enum.
3166 TagDecl *getDefinition() const;
3167
3168 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3169
3170 void setCompleteDefinitionRequired(bool V = true) {
3171 IsCompleteDefinitionRequired = V;
3172 }
3173
3174 StringRef getKindName() const {
3175 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3176 }
3177
3178 TagKind getTagKind() const {
3179 return TagKind(TagDeclKind);
3180 }
3181
3182 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3183
3184 bool isStruct() const { return getTagKind() == TTK_Struct; }
3185 bool isInterface() const { return getTagKind() == TTK_Interface; }
3186 bool isClass() const { return getTagKind() == TTK_Class; }
3187 bool isUnion() const { return getTagKind() == TTK_Union; }
3188 bool isEnum() const { return getTagKind() == TTK_Enum; }
3189
3190 /// Is this tag type named, either directly or via being defined in
3191 /// a typedef of this type?
3192 ///
3193 /// C++11 [basic.link]p8:
3194 /// A type is said to have linkage if and only if:
3195 /// - it is a class or enumeration type that is named (or has a
3196 /// name for linkage purposes) and the name has linkage; ...
3197 /// C++11 [dcl.typedef]p9:
3198 /// If the typedef declaration defines an unnamed class (or enum),
3199 /// the first typedef-name declared by the declaration to be that
3200 /// class type (or enum type) is used to denote the class type (or
3201 /// enum type) for linkage purposes only.
3202 ///
3203 /// C does not have an analogous rule, but the same concept is
3204 /// nonetheless useful in some places.
3205 bool hasNameForLinkage() const {
3206 return (getDeclName() || getTypedefNameForAnonDecl());
3207 }
3208
3209 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3210 return hasExtInfo() ? nullptr
3211 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3212 }
3213
3214 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3215
3216 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3217 /// declaration, if it was present in the source.
3218 NestedNameSpecifier *getQualifier() const {
3219 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3220 : nullptr;
3221 }
3222
3223 /// \brief Retrieve the nested-name-specifier (with source-location
3224 /// information) that qualifies the name of this declaration, if it was
3225 /// present in the source.
3226 NestedNameSpecifierLoc getQualifierLoc() const {
3227 return hasExtInfo() ? getExtInfo()->QualifierLoc
3228 : NestedNameSpecifierLoc();
3229 }
3230
3231 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3232
3233 unsigned getNumTemplateParameterLists() const {
3234 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3235 }
3236
3237 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3238 assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3238, __extension__ __PRETTY_FUNCTION__))
;
3239 return getExtInfo()->TemplParamLists[i];
3240 }
3241
3242 void setTemplateParameterListsInfo(ASTContext &Context,
3243 ArrayRef<TemplateParameterList *> TPLists);
3244
3245 // Implement isa/cast/dyncast/etc.
3246 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3247 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3248
3249 static DeclContext *castToDeclContext(const TagDecl *D) {
3250 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3251 }
3252
3253 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3254 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3255 }
3256};
3257
3258/// Represents an enum. In C++11, enums can be forward-declared
3259/// with a fixed underlying type, and in C we allow them to be forward-declared
3260/// with no underlying type as an extension.
3261class EnumDecl : public TagDecl {
3262 /// This represent the integer type that the enum corresponds
3263 /// to for code generation purposes. Note that the enumerator constants may
3264 /// have a different type than this does.
3265 ///
3266 /// If the underlying integer type was explicitly stated in the source
3267 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3268 /// was automatically deduced somehow, and this is a Type*.
3269 ///
3270 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3271 /// some cases it won't.
3272 ///
3273 /// The underlying type of an enumeration never has any qualifiers, so
3274 /// we can get away with just storing a raw Type*, and thus save an
3275 /// extra pointer when TypeSourceInfo is needed.
3276 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3277
3278 /// The integer type that values of this type should
3279 /// promote to. In C, enumerators are generally of an integer type
3280 /// directly, but gcc-style large enumerators (and all enumerators
3281 /// in C++) are of the enum type instead.
3282 QualType PromotionType;
3283
3284 /// \brief If this enumeration is an instantiation of a member enumeration
3285 /// of a class template specialization, this is the member specialization
3286 /// information.
3287 MemberSpecializationInfo *SpecializationInfo = nullptr;
3288
3289 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3290 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3291 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3292 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3293 assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void
(0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3293, __extension__ __PRETTY_FUNCTION__))
;
3294 IntegerType = (const Type *)nullptr;
3295 NumNegativeBits = 0;
3296 NumPositiveBits = 0;
3297 IsScoped = Scoped;
3298 IsScopedUsingClassTag = ScopedUsingClassTag;
3299 IsFixed = Fixed;
3300 }
3301
3302 void anchor() override;
3303
3304 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3305 TemplateSpecializationKind TSK);
3306public:
3307 friend class ASTDeclReader;
3308
3309 EnumDecl *getCanonicalDecl() override {
3310 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3311 }
3312 const EnumDecl *getCanonicalDecl() const {
3313 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3314 }
3315
3316 EnumDecl *getPreviousDecl() {
3317 return cast_or_null<EnumDecl>(
3318 static_cast<TagDecl *>(this)->getPreviousDecl());
3319 }
3320 const EnumDecl *getPreviousDecl() const {
3321 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3322 }
3323
3324 EnumDecl *getMostRecentDecl() {
3325 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3326 }
3327 const EnumDecl *getMostRecentDecl() const {
3328 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3329 }
3330
3331 EnumDecl *getDefinition() const {
3332 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3333 }
3334
3335 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3336 SourceLocation StartLoc, SourceLocation IdLoc,
3337 IdentifierInfo *Id, EnumDecl *PrevDecl,
3338 bool IsScoped, bool IsScopedUsingClassTag,
3339 bool IsFixed);
3340 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3341
3342 /// When created, the EnumDecl corresponds to a
3343 /// forward-declared enum. This method is used to mark the
3344 /// declaration as being defined; its enumerators have already been
3345 /// added (via DeclContext::addDecl). NewType is the new underlying
3346 /// type of the enumeration type.
3347 void completeDefinition(QualType NewType,
3348 QualType PromotionType,
3349 unsigned NumPositiveBits,
3350 unsigned NumNegativeBits);
3351
3352 // Iterates through the enumerators of this enumeration.
3353 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3354 using enumerator_range =
3355 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3356
3357 enumerator_range enumerators() const {
3358 return enumerator_range(enumerator_begin(), enumerator_end());
3359 }
3360
3361 enumerator_iterator enumerator_begin() const {
3362 const EnumDecl *E = getDefinition();
3363 if (!E)
3364 E = this;
3365 return enumerator_iterator(E->decls_begin());
3366 }
3367
3368 enumerator_iterator enumerator_end() const {
3369 const EnumDecl *E = getDefinition();
3370 if (!E)
3371 E = this;
3372 return enumerator_iterator(E->decls_end());
3373 }
3374
3375 /// Return the integer type that enumerators should promote to.
3376 QualType getPromotionType() const { return PromotionType; }
3377
3378 /// Set the promotion type.
3379 void setPromotionType(QualType T) { PromotionType = T; }
3380
3381 /// Return the integer type this enum decl corresponds to.
3382 /// This returns a null QualType for an enum forward definition with no fixed
3383 /// underlying type.
3384 QualType getIntegerType() const {
3385 if (!IntegerType)
3386 return QualType();
3387 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3388 return QualType(T, 0);
3389 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3390 }
3391
3392 /// \brief Set the underlying integer type.
3393 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3394
3395 /// \brief Set the underlying integer type source info.
3396 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3397
3398 /// \brief Return the type source info for the underlying integer type,
3399 /// if no type source info exists, return 0.
3400 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3401 return IntegerType.dyn_cast<TypeSourceInfo*>();
3402 }
3403
3404 /// \brief Retrieve the source range that covers the underlying type if
3405 /// specified.
3406 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3407
3408 /// \brief Returns the width in bits required to store all the
3409 /// non-negative enumerators of this enum.
3410 unsigned getNumPositiveBits() const {
3411 return NumPositiveBits;
3412 }
3413 void setNumPositiveBits(unsigned Num) {
3414 NumPositiveBits = Num;
3415 assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount"
) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3415, __extension__ __PRETTY_FUNCTION__))
;
3416 }
3417
3418 /// \brief Returns the width in bits required to store all the
3419 /// negative enumerators of this enum. These widths include
3420 /// the rightmost leading 1; that is:
3421 ///
3422 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3423 /// ------------------------ ------- -----------------
3424 /// -1 1111111 1
3425 /// -10 1110110 5
3426 /// -101 1001011 8
3427 unsigned getNumNegativeBits() const {
3428 return NumNegativeBits;
3429 }
3430 void setNumNegativeBits(unsigned Num) {
3431 NumNegativeBits = Num;
3432 }
3433
3434 /// \brief Returns true if this is a C++11 scoped enumeration.
3435 bool isScoped() const {
3436 return IsScoped;
3437 }
3438
3439 /// \brief Returns true if this is a C++11 scoped enumeration.
3440 bool isScopedUsingClassTag() const {
3441 return IsScopedUsingClassTag;
3442 }
3443
3444 /// \brief Returns true if this is an Objective-C, C++11, or
3445 /// Microsoft-style enumeration with a fixed underlying type.
3446 bool isFixed() const {
3447 return IsFixed;
3448 }
3449
3450 /// \brief Returns true if this can be considered a complete type.
3451 bool isComplete() const {
3452 // IntegerType is set for fixed type enums and non-fixed but implicitly
3453 // int-sized Microsoft enums.
3454 return isCompleteDefinition() || IntegerType;
3455 }
3456
3457 /// Returns true if this enum is either annotated with
3458 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3459 bool isClosed() const;
3460
3461 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3462 /// with enum_extensibility(open).
3463 bool isClosedFlag() const;
3464
3465 /// Returns true if this enum is annotated with neither flag_enum nor
3466 /// enum_extensibility(open).
3467 bool isClosedNonFlag() const;
3468
3469 /// \brief Retrieve the enum definition from which this enumeration could
3470 /// be instantiated, if it is an instantiation (rather than a non-template).
3471 EnumDecl *getTemplateInstantiationPattern() const;
3472
3473 /// \brief Returns the enumeration (declared within the template)
3474 /// from which this enumeration type was instantiated, or NULL if
3475 /// this enumeration was not instantiated from any template.
3476 EnumDecl *getInstantiatedFromMemberEnum() const;
3477
3478 /// \brief If this enumeration is a member of a specialization of a
3479 /// templated class, determine what kind of template specialization
3480 /// or instantiation this is.
3481 TemplateSpecializationKind getTemplateSpecializationKind() const;
3482
3483 /// \brief For an enumeration member that was instantiated from a member
3484 /// enumeration of a templated class, set the template specialiation kind.
3485 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3486 SourceLocation PointOfInstantiation = SourceLocation());
3487
3488 /// \brief If this enumeration is an instantiation of a member enumeration of
3489 /// a class template specialization, retrieves the member specialization
3490 /// information.
3491 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3492 return SpecializationInfo;
3493 }
3494
3495 /// \brief Specify that this enumeration is an instantiation of the
3496 /// member enumeration ED.
3497 void setInstantiationOfMemberEnum(EnumDecl *ED,
3498 TemplateSpecializationKind TSK) {
3499 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3500 }
3501
3502 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3503 static bool classofKind(Kind K) { return K == Enum; }
3504};
3505
3506/// Represents a struct/union/class. For example:
3507/// struct X; // Forward declaration, no "body".
3508/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3509/// This decl will be marked invalid if *any* members are invalid.
3510class RecordDecl : public TagDecl {
3511 friend class DeclContext;
3512
3513 // FIXME: This can be packed into the bitfields in Decl.
3514 /// This is true if this struct ends with a flexible
3515 /// array member (e.g. int X[]) or if this union contains a struct that does.
3516 /// If so, this cannot be contained in arrays or other structs as a member.
3517 bool HasFlexibleArrayMember : 1;
3518
3519 /// Whether this is the type of an anonymous struct or union.
3520 bool AnonymousStructOrUnion : 1;
3521
3522 /// This is true if this struct has at least one member
3523 /// containing an Objective-C object pointer type.
3524 bool HasObjectMember : 1;
3525
3526 /// This is true if struct has at least one member of
3527 /// 'volatile' type.
3528 bool HasVolatileMember : 1;
3529
3530 /// Whether the field declarations of this record have been loaded
3531 /// from external storage. To avoid unnecessary deserialization of
3532 /// methods/nested types we allow deserialization of just the fields
3533 /// when needed.
3534 mutable bool LoadedFieldsFromExternalStorage : 1;
3535
3536protected:
3537 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3538 SourceLocation StartLoc, SourceLocation IdLoc,
3539 IdentifierInfo *Id, RecordDecl *PrevDecl);
3540
3541public:
3542 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3543 SourceLocation StartLoc, SourceLocation IdLoc,
3544 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3545 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3546
3547 RecordDecl *getPreviousDecl() {
3548 return cast_or_null<RecordDecl>(
3549 static_cast<TagDecl *>(this)->getPreviousDecl());
3550 }
3551 const RecordDecl *getPreviousDecl() const {
3552 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3553 }
3554
3555 RecordDecl *getMostRecentDecl() {
3556 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3557 }
3558 const RecordDecl *getMostRecentDecl() const {
3559 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3560 }
3561
3562 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3563 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3564
3565 /// Whether this is an anonymous struct or union. To be an anonymous
3566 /// struct or union, it must have been declared without a name and
3567 /// there must be no objects of this type declared, e.g.,
3568 /// @code
3569 /// union { int i; float f; };
3570 /// @endcode
3571 /// is an anonymous union but neither of the following are:
3572 /// @code
3573 /// union X { int i; float f; };
3574 /// union { int i; float f; } obj;
3575 /// @endcode
3576 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3577 void setAnonymousStructOrUnion(bool Anon) {
3578 AnonymousStructOrUnion = Anon;
3579 }
3580
3581 bool hasObjectMember() const { return HasObjectMember; }
3582 void setHasObjectMember (bool val) { HasObjectMember = val; }
3583
3584 bool hasVolatileMember() const { return HasVolatileMember; }
3585 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3586
3587 bool hasLoadedFieldsFromExternalStorage() const {
3588 return LoadedFieldsFromExternalStorage;
3589 }
3590 void setHasLoadedFieldsFromExternalStorage(bool val) {
3591 LoadedFieldsFromExternalStorage = val;
3592 }
3593
3594 /// \brief Determines whether this declaration represents the
3595 /// injected class name.
3596 ///
3597 /// The injected class name in C++ is the name of the class that
3598 /// appears inside the class itself. For example:
3599 ///
3600 /// \code
3601 /// struct C {
3602 /// // C is implicitly declared here as a synonym for the class name.
3603 /// };
3604 ///
3605 /// C::C c; // same as "C c;"
3606 /// \endcode
3607 bool isInjectedClassName() const;
3608
3609 /// \brief Determine whether this record is a class describing a lambda
3610 /// function object.
3611 bool isLambda() const;
3612
3613 /// \brief Determine whether this record is a record for captured variables in
3614 /// CapturedStmt construct.
3615 bool isCapturedRecord() const;
3616
3617 /// \brief Mark the record as a record for captured variables in CapturedStmt
3618 /// construct.
3619 void setCapturedRecord();
3620
3621 /// Returns the RecordDecl that actually defines
3622 /// this struct/union/class. When determining whether or not a
3623 /// struct/union/class is completely defined, one should use this
3624 /// method as opposed to 'isCompleteDefinition'.
3625 /// 'isCompleteDefinition' indicates whether or not a specific
3626 /// RecordDecl is a completed definition, not whether or not the
3627 /// record type is defined. This method returns NULL if there is
3628 /// no RecordDecl that defines the struct/union/tag.
3629 RecordDecl *getDefinition() const {
3630 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3631 }
3632
3633 // Iterator access to field members. The field iterator only visits
3634 // the non-static data members of this class, ignoring any static
3635 // data members, functions, constructors, destructors, etc.
3636 using field_iterator = specific_decl_iterator<FieldDecl>;
3637 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3638
3639 field_range fields() const { return field_range(field_begin(), field_end()); }
3640 field_iterator field_begin() const;
3641
3642 field_iterator field_end() const {
3643 return field_iterator(decl_iterator());
3644 }
3645
3646 // Whether there are any fields (non-static data members) in this record.
3647 bool field_empty() const {
3648 return field_begin() == field_end();
3649 }
3650
3651 /// Note that the definition of this type is now complete.
3652 virtual void completeDefinition();
3653
3654 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3655 static bool classofKind(Kind K) {
3656 return K >= firstRecord && K <= lastRecord;
3657 }
3658
3659 /// \brief Get whether or not this is an ms_struct which can
3660 /// be turned on with an attribute, pragma, or -mms-bitfields
3661 /// commandline option.
3662 bool isMsStruct(const ASTContext &C) const;
3663
3664 /// \brief Whether we are allowed to insert extra padding between fields.
3665 /// These padding are added to help AddressSanitizer detect
3666 /// intra-object-overflow bugs.
3667 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3668
3669 /// Finds the first data member which has a name.
3670 /// nullptr is returned if no named data member exists.
3671 const FieldDecl *findFirstNamedDataMember() const;
3672
3673private:
3674 /// \brief Deserialize just the fields.
3675 void LoadFieldsFromExternalStorage() const;
3676};
3677
3678class FileScopeAsmDecl : public Decl {
3679 StringLiteral *AsmString;
3680 SourceLocation RParenLoc;
3681
3682 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3683 SourceLocation StartL, SourceLocation EndL)
3684 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3685
3686 virtual void anchor();
3687
3688public:
3689 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3690 StringLiteral *Str, SourceLocation AsmLoc,
3691 SourceLocation RParenLoc);
3692
3693 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3694
3695 SourceLocation getAsmLoc() const { return getLocation(); }
3696 SourceLocation getRParenLoc() const { return RParenLoc; }
3697 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3698 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3699 return SourceRange(getAsmLoc(), getRParenLoc());
3700 }
3701
3702 const StringLiteral *getAsmString() const { return AsmString; }
3703 StringLiteral *getAsmString() { return AsmString; }
3704 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3705
3706 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3707 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3708};
3709
3710/// Pepresents a block literal declaration, which is like an
3711/// unnamed FunctionDecl. For example:
3712/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3713class BlockDecl : public Decl, public DeclContext {
3714public:
3715 /// A class which contains all the information about a particular
3716 /// captured value.
3717 class Capture {
3718 enum {
3719 flag_isByRef = 0x1,
3720 flag_isNested = 0x2
3721 };
3722
3723 /// The variable being captured.
3724 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3725
3726 /// The copy expression, expressed in terms of a DeclRef (or
3727 /// BlockDeclRef) to the captured variable. Only required if the
3728 /// variable has a C++ class type.
3729 Expr *CopyExpr;
3730
3731 public:
3732 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3733 : VariableAndFlags(variable,
3734 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3735 CopyExpr(copy) {}
3736
3737 /// The variable being captured.
3738 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3739
3740 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3741 /// variable.
3742 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3743
3744 /// Whether this is a nested capture, i.e. the variable captured
3745 /// is not from outside the immediately enclosing function/block.
3746 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3747
3748 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3749 Expr *getCopyExpr() const { return CopyExpr; }
3750 void setCopyExpr(Expr *e) { CopyExpr = e; }
3751 };
3752
3753private:
3754 // FIXME: This can be packed into the bitfields in Decl.
3755 bool IsVariadic : 1;
3756 bool CapturesCXXThis : 1;
3757 bool BlockMissingReturnType : 1;
3758 bool IsConversionFromLambda : 1;
3759
3760 /// A new[]'d array of pointers to ParmVarDecls for the formal
3761 /// parameters of this function. This is null if a prototype or if there are
3762 /// no formals.
3763 ParmVarDecl **ParamInfo = nullptr;
3764 unsigned NumParams = 0;
3765
3766 Stmt *Body = nullptr;
3767 TypeSourceInfo *SignatureAsWritten = nullptr;
3768
3769 const Capture *Captures = nullptr;
3770 unsigned NumCaptures = 0;
3771
3772 unsigned ManglingNumber = 0;
3773 Decl *ManglingContextDecl = nullptr;
3774
3775protected:
3776 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3777 : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false),
3778 CapturesCXXThis(false), BlockMissingReturnType(true),
3779 IsConversionFromLambda(false) {}
3780
3781public:
3782 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3783 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3784
3785 SourceLocation getCaretLocation() const { return getLocation(); }
3786
3787 bool isVariadic() const { return IsVariadic; }
3788 void setIsVariadic(bool value) { IsVariadic = value; }
3789
3790 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3791 Stmt *getBody() const override { return (Stmt*) Body; }
3792 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3793
3794 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3795 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3796
3797 // ArrayRef access to formal parameters.
3798 ArrayRef<ParmVarDecl *> parameters() const {
3799 return {ParamInfo, getNumParams()};
3800 }
3801 MutableArrayRef<ParmVarDecl *> parameters() {
3802 return {ParamInfo, getNumParams()};
3803 }
3804
3805 // Iterator access to formal parameters.
3806 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3807 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3808
3809 bool param_empty() const { return parameters().empty(); }
3810 param_iterator param_begin() { return parameters().begin(); }
3811 param_iterator param_end() { return parameters().end(); }
3812 param_const_iterator param_begin() const { return parameters().begin(); }
3813 param_const_iterator param_end() const { return parameters().end(); }
3814 size_t param_size() const { return parameters().size(); }
3815
3816 unsigned getNumParams() const { return NumParams; }
3817
3818 const ParmVarDecl *getParamDecl(unsigned i) const {
3819 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3819, __extension__ __PRETTY_FUNCTION__))
;
3820 return ParamInfo[i];
3821 }
3822 ParmVarDecl *getParamDecl(unsigned i) {
3823 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3823, __extension__ __PRETTY_FUNCTION__))
;
3824 return ParamInfo[i];
3825 }
3826
3827 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3828
3829 /// True if this block (or its nested blocks) captures
3830 /// anything of local storage from its enclosing scopes.
3831 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3832
3833 /// Returns the number of captured variables.
3834 /// Does not include an entry for 'this'.
3835 unsigned getNumCaptures() const { return NumCaptures; }
3836
3837 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3838
3839 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3840
3841 capture_const_iterator capture_begin() const { return captures().begin(); }
3842 capture_const_iterator capture_end() const { return captures().end(); }
3843
3844 bool capturesCXXThis() const { return CapturesCXXThis; }
3845 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3846 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3847
3848 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3849 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3850
3851 bool capturesVariable(const VarDecl *var) const;
3852
3853 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3854 bool CapturesCXXThis);
3855
3856 unsigned getBlockManglingNumber() const {
3857 return ManglingNumber;
3858 }
3859
3860 Decl *getBlockManglingContextDecl() const {
3861 return ManglingContextDecl;
3862 }
3863
3864 void setBlockMangling(unsigned Number, Decl *Ctx) {
3865 ManglingNumber = Number;
3866 ManglingContextDecl = Ctx;
3867 }
3868
3869 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3870
3871 // Implement isa/cast/dyncast/etc.
3872 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3873 static bool classofKind(Kind K) { return K == Block; }
3874 static DeclContext *castToDeclContext(const BlockDecl *D) {
3875 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3876 }
3877 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3878 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3879 }
3880};
3881
3882/// Represents the body of a CapturedStmt, and serves as its DeclContext.
3883class CapturedDecl final
3884 : public Decl,
3885 public DeclContext,
3886 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3887protected:
3888 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3889 return NumParams;
3890 }
3891
3892private:
3893 /// \brief The number of parameters to the outlined function.
3894 unsigned NumParams;
3895
3896 /// \brief The position of context parameter in list of parameters.
3897 unsigned ContextParam;
3898
3899 /// \brief The body of the outlined function.
3900 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3901
3902 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3903
3904 ImplicitParamDecl *const *getParams() const {
3905 return getTrailingObjects<ImplicitParamDecl *>();
3906 }
3907
3908 ImplicitParamDecl **getParams() {
3909 return getTrailingObjects<ImplicitParamDecl *>();
3910 }
3911
3912public:
3913 friend class ASTDeclReader;
3914 friend class ASTDeclWriter;
3915 friend TrailingObjects;
3916
3917 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3918 unsigned NumParams);
3919 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3920 unsigned NumParams);
3921
3922 Stmt *getBody() const override;
3923 void setBody(Stmt *B);
3924
3925 bool isNothrow() const;
3926 void setNothrow(bool Nothrow = true);
3927
3928 unsigned getNumParams() const { return NumParams; }
3929
3930 ImplicitParamDecl *getParam(unsigned i) const {
3931 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3931, __extension__ __PRETTY_FUNCTION__))
;
3932 return getParams()[i];
3933 }
3934 void setParam(unsigned i, ImplicitParamDecl *P) {
3935 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3935, __extension__ __PRETTY_FUNCTION__))
;
3936 getParams()[i] = P;
3937 }
3938
3939 // ArrayRef interface to parameters.
3940 ArrayRef<ImplicitParamDecl *> parameters() const {
3941 return {getParams(), getNumParams()};
3942 }
3943 MutableArrayRef<ImplicitParamDecl *> parameters() {
3944 return {getParams(), getNumParams()};
3945 }
3946
3947 /// \brief Retrieve the parameter containing captured variables.
3948 ImplicitParamDecl *getContextParam() const {
3949 assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void
(0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3949, __extension__ __PRETTY_FUNCTION__))
;
3950 return getParam(ContextParam);
3951 }
3952 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3953 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 3953, __extension__ __PRETTY_FUNCTION__))
;
3954 ContextParam = i;
3955 setParam(i, P);
3956 }
3957 unsigned getContextParamPosition() const { return ContextParam; }
3958
3959 using param_iterator = ImplicitParamDecl *const *;
3960 using param_range = llvm::iterator_range<param_iterator>;
3961
3962 /// \brief Retrieve an iterator pointing to the first parameter decl.
3963 param_iterator param_begin() const { return getParams(); }
3964 /// \brief Retrieve an iterator one past the last parameter decl.
3965 param_iterator param_end() const { return getParams() + NumParams; }
3966
3967 // Implement isa/cast/dyncast/etc.
3968 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3969 static bool classofKind(Kind K) { return K == Captured; }
3970 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3971 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3972 }
3973 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3974 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3975 }
3976};
3977
3978/// \brief Describes a module import declaration, which makes the contents
3979/// of the named module visible in the current translation unit.
3980///
3981/// An import declaration imports the named module (or submodule). For example:
3982/// \code
3983/// @import std.vector;
3984/// \endcode
3985///
3986/// Import declarations can also be implicitly generated from
3987/// \#include/\#import directives.
3988class ImportDecl final : public Decl,
3989 llvm::TrailingObjects<ImportDecl, SourceLocation> {
3990 friend class ASTContext;
3991 friend class ASTDeclReader;
3992 friend class ASTReader;
3993 friend TrailingObjects;
3994
3995 /// \brief The imported module, along with a bit that indicates whether
3996 /// we have source-location information for each identifier in the module
3997 /// name.
3998 ///
3999 /// When the bit is false, we only have a single source location for the
4000 /// end of the import declaration.
4001 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4002
4003 /// \brief The next import in the list of imports local to the translation
4004 /// unit being parsed (not loaded from an AST file).
4005 ImportDecl *NextLocalImport = nullptr;
4006
4007 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4008 ArrayRef<SourceLocation> IdentifierLocs);
4009
4010 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4011 SourceLocation EndLoc);
4012
4013 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4014
4015public:
4016 /// \brief Create a new module import declaration.
4017 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4018 SourceLocation StartLoc, Module *Imported,
4019 ArrayRef<SourceLocation> IdentifierLocs);
4020
4021 /// \brief Create a new module import declaration for an implicitly-generated
4022 /// import.
4023 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4024 SourceLocation StartLoc, Module *Imported,
4025 SourceLocation EndLoc);
4026
4027 /// \brief Create a new, deserialized module import declaration.
4028 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4029 unsigned NumLocations);
4030
4031 /// \brief Retrieve the module that was imported by the import declaration.
4032 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4033
4034 /// \brief Retrieves the locations of each of the identifiers that make up
4035 /// the complete module name in the import declaration.
4036 ///
4037 /// This will return an empty array if the locations of the individual
4038 /// identifiers aren't available.
4039 ArrayRef<SourceLocation> getIdentifierLocs() const;
4040
4041 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4042
4043 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4044 static bool classofKind(Kind K) { return K == Import; }
4045};
4046
4047/// \brief Represents a C++ Modules TS module export declaration.
4048///
4049/// For example:
4050/// \code
4051/// export void foo();
4052/// \endcode
4053class ExportDecl final : public Decl, public DeclContext {
4054 virtual void anchor();
4055
4056private:
4057 friend class ASTDeclReader;
4058
4059 /// \brief The source location for the right brace (if valid).
4060 SourceLocation RBraceLoc;
4061
4062 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4063 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4064 RBraceLoc(SourceLocation()) {}
4065
4066public:
4067 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4068 SourceLocation ExportLoc);
4069 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4070
4071 SourceLocation getExportLoc() const { return getLocation(); }
4072 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4073 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4074
4075 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4076 if (RBraceLoc.isValid())
4077 return RBraceLoc;
4078 // No braces: get the end location of the (only) declaration in context
4079 // (if present).
4080 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
4081 }
4082
4083 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4084 return SourceRange(getLocation(), getLocEnd());
4085 }
4086
4087 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4088 static bool classofKind(Kind K) { return K == Export; }
4089 static DeclContext *castToDeclContext(const ExportDecl *D) {
4090 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4091 }
4092 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4093 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4094 }
4095};
4096
4097/// Represents an empty-declaration.
4098class EmptyDecl : public Decl {
4099 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4100
4101 virtual void anchor();
4102
4103public:
4104 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4105 SourceLocation L);
4106 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4107
4108 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4109 static bool classofKind(Kind K) { return K == Empty; }
4110};
4111
4112/// Insertion operator for diagnostics. This allows sending NamedDecl's
4113/// into a diagnostic with <<.
4114inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4115 const NamedDecl* ND) {
4116 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4117 DiagnosticsEngine::ak_nameddecl);
4118 return DB;
4119}
4120inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4121 const NamedDecl* ND) {
4122 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4123 DiagnosticsEngine::ak_nameddecl);
4124 return PD;
4125}
4126
4127template<typename decl_type>
4128void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4129 // Note: This routine is implemented here because we need both NamedDecl
4130 // and Redeclarable to be defined.
4131 assert(RedeclLink.NextIsLatest() &&(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 4132, __extension__ __PRETTY_FUNCTION__))
4132 "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 4132, __extension__ __PRETTY_FUNCTION__))
;
4133
4134 if (PrevDecl) {
4135 // Point to previous. Make sure that this is actually the most recent
4136 // redeclaration, or we can build invalid chains. If the most recent
4137 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4138 First = PrevDecl->getFirstDecl();
4139 assert(First->RedeclLink.NextIsLatest() && "Expected first")(static_cast <bool> (First->RedeclLink.NextIsLatest(
) && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.NextIsLatest() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 4139, __extension__ __PRETTY_FUNCTION__))
;
4140 decl_type *MostRecent = First->getNextRedeclaration();
4141 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4142
4143 // If the declaration was previously visible, a redeclaration of it remains
4144 // visible even if it wouldn't be visible by itself.
4145 static_cast<decl_type*>(this)->IdentifierNamespace |=
4146 MostRecent->getIdentifierNamespace() &
4147 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4148 } else {
4149 // Make this first.
4150 First = static_cast<decl_type*>(this);
4151 }
4152
4153 // First one will point to this one as latest.
4154 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4155
4156 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 4157, __extension__ __PRETTY_FUNCTION__))
4157 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h"
, 4157, __extension__ __PRETTY_FUNCTION__))
;
4158}
4159
4160// Inline function definitions.
4161
4162/// Check if the given decl is complete.
4163///
4164/// We use this function to break a cycle between the inline definitions in
4165/// Type.h and Decl.h.
4166inline bool IsEnumDeclComplete(EnumDecl *ED) {
4167 return ED->isComplete();
4168}
4169
4170/// Check if the given decl is scoped.
4171///
4172/// We use this function to break a cycle between the inline definitions in
4173/// Type.h and Decl.h.
4174inline bool IsEnumDeclScoped(EnumDecl *ED) {
4175 return ED->isScoped();
4176}
4177
4178} // namespace clang
4179
4180#endif // LLVM_CLANG_AST_DECL_H