Bug Summary

File:tools/clang/lib/CodeGen/CGDebugInfo.cpp
Warning:line 2989, column 20
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp

1//===--- CGDebugInfo.cpp - Emit Debug Information 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 debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
16#include "CGCXXABI.h"
17#include "CGObjCRuntime.h"
18#include "CGRecordLayout.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "ConstantEmitter.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclFriend.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/RecordLayout.h"
28#include "clang/Basic/FileManager.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/Version.h"
31#include "clang/Frontend/CodeGenOptions.h"
32#include "clang/Frontend/FrontendOptions.h"
33#include "clang/Lex/HeaderSearchOptions.h"
34#include "clang/Lex/ModuleMap.h"
35#include "clang/Lex/PreprocessorOptions.h"
36#include "llvm/ADT/DenseSet.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/Module.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/MD5.h"
47#include "llvm/Support/Path.h"
48using namespace clang;
49using namespace clang::CodeGen;
50
51static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
52 auto TI = Ctx.getTypeInfo(Ty);
53 return TI.AlignIsRequired ? TI.Align : 0;
54}
55
56static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
57 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
58}
59
60static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
61 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
62}
63
64CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
65 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
66 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
67 DBuilder(CGM.getModule()) {
68 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
69 DebugPrefixMap[KV.first] = KV.second;
70 CreateCompileUnit();
71}
72
73CGDebugInfo::~CGDebugInfo() {
74 assert(LexicalBlockStack.empty() &&(static_cast <bool> (LexicalBlockStack.empty() &&
"Region stack mismatch, stack not empty!") ? void (0) : __assert_fail
("LexicalBlockStack.empty() && \"Region stack mismatch, stack not empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 75, __extension__ __PRETTY_FUNCTION__))
75 "Region stack mismatch, stack not empty!")(static_cast <bool> (LexicalBlockStack.empty() &&
"Region stack mismatch, stack not empty!") ? void (0) : __assert_fail
("LexicalBlockStack.empty() && \"Region stack mismatch, stack not empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 75, __extension__ __PRETTY_FUNCTION__))
;
76}
77
78ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
79 SourceLocation TemporaryLocation)
80 : CGF(&CGF) {
81 init(TemporaryLocation);
82}
83
84ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
85 bool DefaultToEmpty,
86 SourceLocation TemporaryLocation)
87 : CGF(&CGF) {
88 init(TemporaryLocation, DefaultToEmpty);
89}
90
91void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
92 bool DefaultToEmpty) {
93 auto *DI = CGF->getDebugInfo();
94 if (!DI) {
95 CGF = nullptr;
96 return;
97 }
98
99 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
100
101 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
102 return;
103
104 if (TemporaryLocation.isValid()) {
105 DI->EmitLocation(CGF->Builder, TemporaryLocation);
106 return;
107 }
108
109 if (DefaultToEmpty) {
110 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
111 return;
112 }
113
114 // Construct a location that has a valid scope, but no line info.
115 assert(!DI->LexicalBlockStack.empty())(static_cast <bool> (!DI->LexicalBlockStack.empty())
? void (0) : __assert_fail ("!DI->LexicalBlockStack.empty()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 115, __extension__ __PRETTY_FUNCTION__))
;
116 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
117 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
118}
119
120ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
121 : CGF(&CGF) {
122 init(E->getExprLoc());
123}
124
125ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
126 : CGF(&CGF) {
127 if (!CGF.getDebugInfo()) {
128 this->CGF = nullptr;
129 return;
130 }
131 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
132 if (Loc)
133 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
134}
135
136ApplyDebugLocation::~ApplyDebugLocation() {
137 // Query CGF so the location isn't overwritten when location updates are
138 // temporarily disabled (for C++ default function arguments)
139 if (CGF)
140 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
141}
142
143ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
144 GlobalDecl InlinedFn)
145 : CGF(&CGF) {
146 if (!CGF.getDebugInfo()) {
147 this->CGF = nullptr;
148 return;
149 }
150 auto &DI = *CGF.getDebugInfo();
151 SavedLocation = DI.getLocation();
152 assert((DI.getInlinedAt() ==(static_cast <bool> ((DI.getInlinedAt() == CGF.Builder.
getCurrentDebugLocation()->getInlinedAt()) && "CGDebugInfo and IRBuilder are out of sync"
) ? void (0) : __assert_fail ("(DI.getInlinedAt() == CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) && \"CGDebugInfo and IRBuilder are out of sync\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 154, __extension__ __PRETTY_FUNCTION__))
153 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&(static_cast <bool> ((DI.getInlinedAt() == CGF.Builder.
getCurrentDebugLocation()->getInlinedAt()) && "CGDebugInfo and IRBuilder are out of sync"
) ? void (0) : __assert_fail ("(DI.getInlinedAt() == CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) && \"CGDebugInfo and IRBuilder are out of sync\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 154, __extension__ __PRETTY_FUNCTION__))
154 "CGDebugInfo and IRBuilder are out of sync")(static_cast <bool> ((DI.getInlinedAt() == CGF.Builder.
getCurrentDebugLocation()->getInlinedAt()) && "CGDebugInfo and IRBuilder are out of sync"
) ? void (0) : __assert_fail ("(DI.getInlinedAt() == CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) && \"CGDebugInfo and IRBuilder are out of sync\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 154, __extension__ __PRETTY_FUNCTION__))
;
155
156 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
157}
158
159ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
160 if (!CGF)
161 return;
162 auto &DI = *CGF->getDebugInfo();
163 DI.EmitInlineFunctionEnd(CGF->Builder);
164 DI.EmitLocation(CGF->Builder, SavedLocation);
165}
166
167void CGDebugInfo::setLocation(SourceLocation Loc) {
168 // If the new location isn't valid return.
169 if (Loc.isInvalid())
170 return;
171
172 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
173
174 // If we've changed files in the middle of a lexical scope go ahead
175 // and create a new lexical scope with file node if it's different
176 // from the one in the scope.
177 if (LexicalBlockStack.empty())
178 return;
179
180 SourceManager &SM = CGM.getContext().getSourceManager();
181 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
182 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
183
184 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
185 return;
186
187 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
188 LexicalBlockStack.pop_back();
189 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
190 LBF->getScope(), getOrCreateFile(CurLoc)));
191 } else if (isa<llvm::DILexicalBlock>(Scope) ||
192 isa<llvm::DISubprogram>(Scope)) {
193 LexicalBlockStack.pop_back();
194 LexicalBlockStack.emplace_back(
195 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
196 }
197}
198
199llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
200 llvm::DIScope *Mod = getParentModuleOrNull(D);
201 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
202 Mod ? Mod : TheCU);
203}
204
205llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
206 llvm::DIScope *Default) {
207 if (!Context)
208 return Default;
209
210 auto I = RegionMap.find(Context);
211 if (I != RegionMap.end()) {
212 llvm::Metadata *V = I->second;
213 return dyn_cast_or_null<llvm::DIScope>(V);
214 }
215
216 // Check namespace.
217 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
218 return getOrCreateNamespace(NSDecl);
219
220 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
221 if (!RDecl->isDependentType())
222 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
223 getOrCreateMainFile());
224 return Default;
225}
226
227PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
228 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
229
230 // If we're emitting codeview, it's important to try to match MSVC's naming so
231 // that visualizers written for MSVC will trigger for our class names. In
232 // particular, we can't have spaces between arguments of standard templates
233 // like basic_string and vector.
234 if (CGM.getCodeGenOpts().EmitCodeView)
235 PP.MSVCFormatting = true;
236
237 return PP;
238}
239
240StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
241 assert(FD && "Invalid FunctionDecl!")(static_cast <bool> (FD && "Invalid FunctionDecl!"
) ? void (0) : __assert_fail ("FD && \"Invalid FunctionDecl!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 IdentifierInfo *FII = FD->getIdentifier();
243 FunctionTemplateSpecializationInfo *Info =
244 FD->getTemplateSpecializationInfo();
245
246 // Emit the unqualified name in normal operation. LLVM and the debugger can
247 // compute the fully qualified name from the scope chain. If we're only
248 // emitting line table info, there won't be any scope chains, so emit the
249 // fully qualified name here so that stack traces are more accurate.
250 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
251 // evaluating the size impact.
252 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
253 CGM.getCodeGenOpts().EmitCodeView;
254
255 if (!Info && FII && !UseQualifiedName)
256 return FII->getName();
257
258 SmallString<128> NS;
259 llvm::raw_svector_ostream OS(NS);
260 if (!UseQualifiedName)
261 FD->printName(OS);
262 else
263 FD->printQualifiedName(OS, getPrintingPolicy());
264
265 // Add any template specialization args.
266 if (Info) {
267 const TemplateArgumentList *TArgs = Info->TemplateArguments;
268 TemplateSpecializationType::PrintTemplateArgumentList(OS, TArgs->asArray(),
269 getPrintingPolicy());
270 }
271
272 // Copy this name on the side and use its reference.
273 return internString(OS.str());
274}
275
276StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
277 SmallString<256> MethodName;
278 llvm::raw_svector_ostream OS(MethodName);
279 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
280 const DeclContext *DC = OMD->getDeclContext();
281 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
282 OS << OID->getName();
283 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
284 OS << OID->getName();
285 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
286 if (OC->IsClassExtension()) {
287 OS << OC->getClassInterface()->getName();
288 } else {
289 OS << OC->getIdentifier()->getNameStart() << '('
290 << OC->getIdentifier()->getNameStart() << ')';
291 }
292 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
293 OS << OCD->getClassInterface()->getName() << '('
294 << OCD->getName() << ')';
295 } else if (isa<ObjCProtocolDecl>(DC)) {
296 // We can extract the type of the class from the self pointer.
297 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
298 QualType ClassTy =
299 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
300 ClassTy.print(OS, PrintingPolicy(LangOptions()));
301 }
302 }
303 OS << ' ' << OMD->getSelector().getAsString() << ']';
304
305 return internString(OS.str());
306}
307
308StringRef CGDebugInfo::getSelectorName(Selector S) {
309 return internString(S.getAsString());
310}
311
312StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
313 if (isa<ClassTemplateSpecializationDecl>(RD)) {
314 SmallString<128> Name;
315 llvm::raw_svector_ostream OS(Name);
316 RD->getNameForDiagnostic(OS, getPrintingPolicy(),
317 /*Qualified*/ false);
318
319 // Copy this name on the side and use its reference.
320 return internString(Name);
321 }
322
323 // quick optimization to avoid having to intern strings that are already
324 // stored reliably elsewhere
325 if (const IdentifierInfo *II = RD->getIdentifier())
326 return II->getName();
327
328 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
329 // used to reconstruct the fully qualified type names.
330 if (CGM.getCodeGenOpts().EmitCodeView) {
331 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
332 assert(RD->getDeclContext() == D->getDeclContext() &&(static_cast <bool> (RD->getDeclContext() == D->getDeclContext
() && "Typedef should not be in another decl context!"
) ? void (0) : __assert_fail ("RD->getDeclContext() == D->getDeclContext() && \"Typedef should not be in another decl context!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 333, __extension__ __PRETTY_FUNCTION__))
333 "Typedef should not be in another decl context!")(static_cast <bool> (RD->getDeclContext() == D->getDeclContext
() && "Typedef should not be in another decl context!"
) ? void (0) : __assert_fail ("RD->getDeclContext() == D->getDeclContext() && \"Typedef should not be in another decl context!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 333, __extension__ __PRETTY_FUNCTION__))
;
334 assert(D->getDeclName().getAsIdentifierInfo() &&(static_cast <bool> (D->getDeclName().getAsIdentifierInfo
() && "Typedef was not named!") ? void (0) : __assert_fail
("D->getDeclName().getAsIdentifierInfo() && \"Typedef was not named!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 335, __extension__ __PRETTY_FUNCTION__))
335 "Typedef was not named!")(static_cast <bool> (D->getDeclName().getAsIdentifierInfo
() && "Typedef was not named!") ? void (0) : __assert_fail
("D->getDeclName().getAsIdentifierInfo() && \"Typedef was not named!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 335, __extension__ __PRETTY_FUNCTION__))
;
336 return D->getDeclName().getAsIdentifierInfo()->getName();
337 }
338
339 if (CGM.getLangOpts().CPlusPlus) {
340 StringRef Name;
341
342 ASTContext &Context = CGM.getContext();
343 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
344 // Anonymous types without a name for linkage purposes have their
345 // declarator mangled in if they have one.
346 Name = DD->getName();
347 else if (const TypedefNameDecl *TND =
348 Context.getTypedefNameForUnnamedTagDecl(RD))
349 // Anonymous types without a name for linkage purposes have their
350 // associate typedef mangled in if they have one.
351 Name = TND->getName();
352
353 if (!Name.empty()) {
354 SmallString<256> UnnamedType("<unnamed-type-");
355 UnnamedType += Name;
356 UnnamedType += '>';
357 return internString(UnnamedType);
358 }
359 }
360 }
361
362 return StringRef();
363}
364
365llvm::DIFile::ChecksumKind
366CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
367 Checksum.clear();
368
369 if (!CGM.getCodeGenOpts().EmitCodeView)
370 return llvm::DIFile::CSK_None;
371
372 SourceManager &SM = CGM.getContext().getSourceManager();
373 bool Invalid;
374 llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
375 if (Invalid)
376 return llvm::DIFile::CSK_None;
377
378 llvm::MD5 Hash;
379 llvm::MD5::MD5Result Result;
380
381 Hash.update(MemBuffer->getBuffer());
382 Hash.final(Result);
383
384 Hash.stringifyResult(Result, Checksum);
385 return llvm::DIFile::CSK_MD5;
386}
387
388llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
389 if (!Loc.isValid())
390 // If Location is not valid then use main input file.
391 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
392 remapDIPath(TheCU->getDirectory()),
393 TheCU->getFile()->getChecksumKind(),
394 TheCU->getFile()->getChecksum());
395
396 SourceManager &SM = CGM.getContext().getSourceManager();
397 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
398
399 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
400 // If the location is not valid then use main input file.
401 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
402 remapDIPath(TheCU->getDirectory()),
403 TheCU->getFile()->getChecksumKind(),
404 TheCU->getFile()->getChecksum());
405
406 // Cache the results.
407 const char *fname = PLoc.getFilename();
408 auto it = DIFileCache.find(fname);
409
410 if (it != DIFileCache.end()) {
411 // Verify that the information still exists.
412 if (llvm::Metadata *V = it->second)
413 return cast<llvm::DIFile>(V);
414 }
415
416 SmallString<32> Checksum;
417 llvm::DIFile::ChecksumKind CSKind =
418 computeChecksum(SM.getFileID(Loc), Checksum);
419
420 llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
421 remapDIPath(getCurrentDirname()),
422 CSKind, Checksum);
423
424 DIFileCache[fname].reset(F);
425 return F;
426}
427
428llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
429 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
430 remapDIPath(TheCU->getDirectory()),
431 TheCU->getFile()->getChecksumKind(),
432 TheCU->getFile()->getChecksum());
433}
434
435std::string CGDebugInfo::remapDIPath(StringRef Path) const {
436 for (const auto &Entry : DebugPrefixMap)
437 if (Path.startswith(Entry.first))
438 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
439 return Path.str();
440}
441
442unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
443 if (Loc.isInvalid() && CurLoc.isInvalid())
444 return 0;
445 SourceManager &SM = CGM.getContext().getSourceManager();
446 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
447 return PLoc.isValid() ? PLoc.getLine() : 0;
448}
449
450unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
451 // We may not want column information at all.
452 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
453 return 0;
454
455 // If the location is invalid then use the current column.
456 if (Loc.isInvalid() && CurLoc.isInvalid())
457 return 0;
458 SourceManager &SM = CGM.getContext().getSourceManager();
459 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
460 return PLoc.isValid() ? PLoc.getColumn() : 0;
461}
462
463StringRef CGDebugInfo::getCurrentDirname() {
464 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
465 return CGM.getCodeGenOpts().DebugCompilationDir;
466
467 if (!CWDName.empty())
468 return CWDName;
469 SmallString<256> CWD;
470 llvm::sys::fs::current_path(CWD);
471 return CWDName = internString(CWD);
472}
473
474void CGDebugInfo::CreateCompileUnit() {
475 SmallString<32> Checksum;
476 llvm::DIFile::ChecksumKind CSKind = llvm::DIFile::CSK_None;
477
478 // Should we be asking the SourceManager for the main file name, instead of
479 // accepting it as an argument? This just causes the main file name to
480 // mismatch with source locations and create extra lexical scopes or
481 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
482 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
483 // because that's what the SourceManager says)
484
485 // Get absolute path name.
486 SourceManager &SM = CGM.getContext().getSourceManager();
487 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
488 if (MainFileName.empty())
489 MainFileName = "<stdin>";
490
491 // The main file name provided via the "-main-file-name" option contains just
492 // the file name itself with no path information. This file name may have had
493 // a relative path, so we look into the actual file entry for the main
494 // file to determine the real absolute path for the file.
495 std::string MainFileDir;
496 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
497 MainFileDir = remapDIPath(MainFile->getDir()->getName());
498 if (MainFileDir != ".") {
499 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
500 llvm::sys::path::append(MainFileDirSS, MainFileName);
501 MainFileName = MainFileDirSS.str();
502 }
503 // If the main file name provided is identical to the input file name, and
504 // if the input file is a preprocessed source, use the module name for
505 // debug info. The module name comes from the name specified in the first
506 // linemarker if the input is a preprocessed source.
507 if (MainFile->getName() == MainFileName &&
508 FrontendOptions::getInputKindForExtension(
509 MainFile->getName().rsplit('.').second)
510 .isPreprocessed())
511 MainFileName = CGM.getModule().getName().str();
512
513 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
514 }
515
516 llvm::dwarf::SourceLanguage LangTag;
517 const LangOptions &LO = CGM.getLangOpts();
518 if (LO.CPlusPlus) {
519 if (LO.ObjC1)
520 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
521 else
522 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
523 } else if (LO.ObjC1) {
524 LangTag = llvm::dwarf::DW_LANG_ObjC;
525 } else if (LO.RenderScript) {
526 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
527 } else if (LO.C99) {
528 LangTag = llvm::dwarf::DW_LANG_C99;
529 } else {
530 LangTag = llvm::dwarf::DW_LANG_C89;
531 }
532
533 std::string Producer = getClangFullVersion();
534
535 // Figure out which version of the ObjC runtime we have.
536 unsigned RuntimeVers = 0;
537 if (LO.ObjC1)
538 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
539
540 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
541 switch (DebugKind) {
542 case codegenoptions::NoDebugInfo:
543 case codegenoptions::LocTrackingOnly:
544 EmissionKind = llvm::DICompileUnit::NoDebug;
545 break;
546 case codegenoptions::DebugLineTablesOnly:
547 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
548 break;
549 case codegenoptions::LimitedDebugInfo:
550 case codegenoptions::FullDebugInfo:
551 EmissionKind = llvm::DICompileUnit::FullDebug;
552 break;
553 }
554
555 // Create new compile unit.
556 // FIXME - Eliminate TheCU.
557 auto &CGOpts = CGM.getCodeGenOpts();
558 TheCU = DBuilder.createCompileUnit(
559 LangTag,
560 DBuilder.createFile(remapDIPath(MainFileName),
561 remapDIPath(getCurrentDirname()), CSKind, Checksum),
562 Producer, LO.Optimize || CGOpts.PrepareForLTO || CGOpts.EmitSummaryIndex,
563 CGOpts.DwarfDebugFlags, RuntimeVers,
564 CGOpts.EnableSplitDwarf ? "" : CGOpts.SplitDwarfFile, EmissionKind,
565 0 /* DWOid */, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
566 CGOpts.GnuPubnames);
567}
568
569llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
570 llvm::dwarf::TypeKind Encoding;
571 StringRef BTName;
572 switch (BT->getKind()) {
573#define BUILTIN_TYPE(Id, SingletonId)
574#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
575#include "clang/AST/BuiltinTypes.def"
576 case BuiltinType::Dependent:
577 llvm_unreachable("Unexpected builtin type")::llvm::llvm_unreachable_internal("Unexpected builtin type", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 577)
;
578 case BuiltinType::NullPtr:
579 return DBuilder.createNullPtrType();
580 case BuiltinType::Void:
581 return nullptr;
582 case BuiltinType::ObjCClass:
583 if (!ClassTy)
584 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
585 "objc_class", TheCU,
586 getOrCreateMainFile(), 0);
587 return ClassTy;
588 case BuiltinType::ObjCId: {
589 // typedef struct objc_class *Class;
590 // typedef struct objc_object {
591 // Class isa;
592 // } *id;
593
594 if (ObjTy)
595 return ObjTy;
596
597 if (!ClassTy)
598 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
599 "objc_class", TheCU,
600 getOrCreateMainFile(), 0);
601
602 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
603
604 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
605
606 ObjTy = DBuilder.createStructType(
607 TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0,
608 llvm::DINode::FlagZero, nullptr, llvm::DINodeArray());
609
610 DBuilder.replaceArrays(
611 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
612 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0,
613 llvm::DINode::FlagZero, ISATy)));
614 return ObjTy;
615 }
616 case BuiltinType::ObjCSel: {
617 if (!SelTy)
618 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
619 "objc_selector", TheCU,
620 getOrCreateMainFile(), 0);
621 return SelTy;
622 }
623
624#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
625 case BuiltinType::Id: \
626 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
627 SingletonId);
628#include "clang/Basic/OpenCLImageTypes.def"
629 case BuiltinType::OCLSampler:
630 return getOrCreateStructPtrType("opencl_sampler_t",
631 OCLSamplerDITy);
632 case BuiltinType::OCLEvent:
633 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
634 case BuiltinType::OCLClkEvent:
635 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
636 case BuiltinType::OCLQueue:
637 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
638 case BuiltinType::OCLReserveID:
639 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
640
641 case BuiltinType::UChar:
642 case BuiltinType::Char_U:
643 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
644 break;
645 case BuiltinType::Char_S:
646 case BuiltinType::SChar:
647 Encoding = llvm::dwarf::DW_ATE_signed_char;
648 break;
649 case BuiltinType::Char16:
650 case BuiltinType::Char32:
651 Encoding = llvm::dwarf::DW_ATE_UTF;
652 break;
653 case BuiltinType::UShort:
654 case BuiltinType::UInt:
655 case BuiltinType::UInt128:
656 case BuiltinType::ULong:
657 case BuiltinType::WChar_U:
658 case BuiltinType::ULongLong:
659 Encoding = llvm::dwarf::DW_ATE_unsigned;
660 break;
661 case BuiltinType::Short:
662 case BuiltinType::Int:
663 case BuiltinType::Int128:
664 case BuiltinType::Long:
665 case BuiltinType::WChar_S:
666 case BuiltinType::LongLong:
667 Encoding = llvm::dwarf::DW_ATE_signed;
668 break;
669 case BuiltinType::Bool:
670 Encoding = llvm::dwarf::DW_ATE_boolean;
671 break;
672 case BuiltinType::Half:
673 case BuiltinType::Float:
674 case BuiltinType::LongDouble:
675 case BuiltinType::Float16:
676 case BuiltinType::Float128:
677 case BuiltinType::Double:
678 // FIXME: For targets where long double and __float128 have the same size,
679 // they are currently indistinguishable in the debugger without some
680 // special treatment. However, there is currently no consensus on encoding
681 // and this should be updated once a DWARF encoding exists for distinct
682 // floating point types of the same size.
683 Encoding = llvm::dwarf::DW_ATE_float;
684 break;
685 }
686
687 switch (BT->getKind()) {
688 case BuiltinType::Long:
689 BTName = "long int";
690 break;
691 case BuiltinType::LongLong:
692 BTName = "long long int";
693 break;
694 case BuiltinType::ULong:
695 BTName = "long unsigned int";
696 break;
697 case BuiltinType::ULongLong:
698 BTName = "long long unsigned int";
699 break;
700 default:
701 BTName = BT->getName(CGM.getLangOpts());
702 break;
703 }
704 // Bit size and offset of the type.
705 uint64_t Size = CGM.getContext().getTypeSize(BT);
706 return DBuilder.createBasicType(BTName, Size, Encoding);
707}
708
709llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
710 // Bit size and offset of the type.
711 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
712 if (Ty->isComplexIntegerType())
713 Encoding = llvm::dwarf::DW_ATE_lo_user;
714
715 uint64_t Size = CGM.getContext().getTypeSize(Ty);
716 return DBuilder.createBasicType("complex", Size, Encoding);
717}
718
719llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
720 llvm::DIFile *Unit) {
721 QualifierCollector Qc;
722 const Type *T = Qc.strip(Ty);
723
724 // Ignore these qualifiers for now.
725 Qc.removeObjCGCAttr();
726 Qc.removeAddressSpace();
727 Qc.removeObjCLifetime();
728
729 // We will create one Derived type for one qualifier and recurse to handle any
730 // additional ones.
731 llvm::dwarf::Tag Tag;
732 if (Qc.hasConst()) {
733 Tag = llvm::dwarf::DW_TAG_const_type;
734 Qc.removeConst();
735 } else if (Qc.hasVolatile()) {
736 Tag = llvm::dwarf::DW_TAG_volatile_type;
737 Qc.removeVolatile();
738 } else if (Qc.hasRestrict()) {
739 Tag = llvm::dwarf::DW_TAG_restrict_type;
740 Qc.removeRestrict();
741 } else {
742 assert(Qc.empty() && "Unknown type qualifier for debug info")(static_cast <bool> (Qc.empty() && "Unknown type qualifier for debug info"
) ? void (0) : __assert_fail ("Qc.empty() && \"Unknown type qualifier for debug info\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 742, __extension__ __PRETTY_FUNCTION__))
;
743 return getOrCreateType(QualType(T, 0), Unit);
744 }
745
746 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
747
748 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
749 // CVR derived types.
750 return DBuilder.createQualifiedType(Tag, FromTy);
751}
752
753llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
754 llvm::DIFile *Unit) {
755
756 // The frontend treats 'id' as a typedef to an ObjCObjectType,
757 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
758 // debug info, we want to emit 'id' in both cases.
759 if (Ty->isObjCQualifiedIdType())
760 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
761
762 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
763 Ty->getPointeeType(), Unit);
764}
765
766llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
767 llvm::DIFile *Unit) {
768 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
769 Ty->getPointeeType(), Unit);
770}
771
772/// \return whether a C++ mangling exists for the type defined by TD.
773static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
774 switch (TheCU->getSourceLanguage()) {
775 case llvm::dwarf::DW_LANG_C_plus_plus:
776 return true;
777 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
778 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
779 default:
780 return false;
781 }
782}
783
784/// In C++ mode, types have linkage, so we can rely on the ODR and
785/// on their mangled names, if they're external.
786static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
787 CodeGenModule &CGM,
788 llvm::DICompileUnit *TheCU) {
789 SmallString<256> FullName;
790 const TagDecl *TD = Ty->getDecl();
791
792 if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
793 return FullName;
794
795 // TODO: This is using the RTTI name. Is there a better way to get
796 // a unique string for a type?
797 llvm::raw_svector_ostream Out(FullName);
798 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
799 return FullName;
800}
801
802/// \return the approproate DWARF tag for a composite type.
803static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
804 llvm::dwarf::Tag Tag;
805 if (RD->isStruct() || RD->isInterface())
806 Tag = llvm::dwarf::DW_TAG_structure_type;
807 else if (RD->isUnion())
808 Tag = llvm::dwarf::DW_TAG_union_type;
809 else {
810 // FIXME: This could be a struct type giving a default visibility different
811 // than C++ class type, but needs llvm metadata changes first.
812 assert(RD->isClass())(static_cast <bool> (RD->isClass()) ? void (0) : __assert_fail
("RD->isClass()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 812, __extension__ __PRETTY_FUNCTION__))
;
813 Tag = llvm::dwarf::DW_TAG_class_type;
814 }
815 return Tag;
816}
817
818llvm::DICompositeType *
819CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
820 llvm::DIScope *Ctx) {
821 const RecordDecl *RD = Ty->getDecl();
822 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
823 return cast<llvm::DICompositeType>(T);
824 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
825 unsigned Line = getLineNumber(RD->getLocation());
826 StringRef RDName = getClassName(RD);
827
828 uint64_t Size = 0;
829 uint32_t Align = 0;
830
831 // Create the type.
832 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
833 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
834 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
835 llvm::DINode::FlagFwdDecl, FullName);
836 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
837 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
838 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
839 CollectCXXTemplateParams(TSpecial, DefUnit));
840 ReplaceMap.emplace_back(
841 std::piecewise_construct, std::make_tuple(Ty),
842 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
843 return RetTy;
844}
845
846llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
847 const Type *Ty,
848 QualType PointeeTy,
849 llvm::DIFile *Unit) {
850 // Bit size, align and offset of the type.
851 // Size is always the size of a pointer. We can't use getTypeSize here
852 // because that does not return the correct value for references.
853 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
854 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
855 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
856 Optional<unsigned> DWARFAddressSpace =
857 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
858
859 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
860 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
861 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
862 Size, Align, DWARFAddressSpace);
863 else
864 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
865 Align, DWARFAddressSpace);
866}
867
868llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
869 llvm::DIType *&Cache) {
870 if (Cache)
871 return Cache;
872 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
873 TheCU, getOrCreateMainFile(), 0);
874 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
875 Cache = DBuilder.createPointerType(Cache, Size);
876 return Cache;
877}
878
879llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
880 llvm::DIFile *Unit) {
881 SmallVector<llvm::Metadata *, 8> EltTys;
882 QualType FType;
883 uint64_t FieldSize, FieldOffset;
884 uint32_t FieldAlign;
885 llvm::DINodeArray Elements;
886
887 FieldOffset = 0;
888 FType = CGM.getContext().UnsignedLongTy;
889 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
890 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
891
892 Elements = DBuilder.getOrCreateArray(EltTys);
893 EltTys.clear();
894
895 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
896 unsigned LineNo = 0;
897
898 auto *EltTy =
899 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
900 FieldOffset, 0, Flags, nullptr, Elements);
901
902 // Bit size, align and offset of the type.
903 uint64_t Size = CGM.getContext().getTypeSize(Ty);
904
905 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
906
907 FieldOffset = 0;
908 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
909 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
910 FType = CGM.getContext().IntTy;
911 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
912 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
913 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
914 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
915
916 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
917 FieldSize = CGM.getContext().getTypeSize(Ty);
918 FieldAlign = CGM.getContext().getTypeAlign(Ty);
919 EltTys.push_back(DBuilder.createMemberType(
920 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset,
921 llvm::DINode::FlagZero, DescTy));
922
923 FieldOffset += FieldSize;
924 Elements = DBuilder.getOrCreateArray(EltTys);
925
926 // The __block_literal_generic structs are marked with a special
927 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
928 // the debugger needs to know about. To allow type uniquing, emit
929 // them without a name or a location.
930 EltTy =
931 DBuilder.createStructType(Unit, "", nullptr, LineNo,
932 FieldOffset, 0, Flags, nullptr, Elements);
933
934 return DBuilder.createPointerType(EltTy, Size);
935}
936
937llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
938 llvm::DIFile *Unit) {
939 assert(Ty->isTypeAlias())(static_cast <bool> (Ty->isTypeAlias()) ? void (0) :
__assert_fail ("Ty->isTypeAlias()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 939, __extension__ __PRETTY_FUNCTION__))
;
940 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
941
942 SmallString<128> NS;
943 llvm::raw_svector_ostream OS(NS);
944 Ty->getTemplateName().print(OS, getPrintingPolicy(),
945 /*qualified*/ false);
946
947 TemplateSpecializationType::PrintTemplateArgumentList(
948 OS, Ty->template_arguments(), getPrintingPolicy());
949
950 auto *AliasDecl = cast<TypeAliasTemplateDecl>(
951 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
952
953 SourceLocation Loc = AliasDecl->getLocation();
954 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
955 getLineNumber(Loc),
956 getDeclContextDescriptor(AliasDecl));
957}
958
959llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
960 llvm::DIFile *Unit) {
961 // We don't set size information, but do specify where the typedef was
962 // declared.
963 SourceLocation Loc = Ty->getDecl()->getLocation();
964
965 // Typedefs are derived from some other type.
966 return DBuilder.createTypedef(
967 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
968 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
969 getDeclContextDescriptor(Ty->getDecl()));
970}
971
972static unsigned getDwarfCC(CallingConv CC) {
973 switch (CC) {
974 case CC_C:
975 // Avoid emitting DW_AT_calling_convention if the C convention was used.
976 return 0;
977
978 case CC_X86StdCall:
979 return llvm::dwarf::DW_CC_BORLAND_stdcall;
980 case CC_X86FastCall:
981 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
982 case CC_X86ThisCall:
983 return llvm::dwarf::DW_CC_BORLAND_thiscall;
984 case CC_X86VectorCall:
985 return llvm::dwarf::DW_CC_LLVM_vectorcall;
986 case CC_X86Pascal:
987 return llvm::dwarf::DW_CC_BORLAND_pascal;
988
989 // FIXME: Create new DW_CC_ codes for these calling conventions.
990 case CC_Win64:
991 case CC_X86_64SysV:
992 case CC_AAPCS:
993 case CC_AAPCS_VFP:
994 case CC_IntelOclBicc:
995 case CC_SpirFunction:
996 case CC_OpenCLKernel:
997 case CC_Swift:
998 case CC_PreserveMost:
999 case CC_PreserveAll:
1000 case CC_X86RegCall:
1001 return 0;
1002 }
1003 return 0;
1004}
1005
1006llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1007 llvm::DIFile *Unit) {
1008 SmallVector<llvm::Metadata *, 16> EltTys;
1009
1010 // Add the result type at least.
1011 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1012
1013 // Set up remainder of arguments if there is a prototype.
1014 // otherwise emit it as a variadic function.
1015 if (isa<FunctionNoProtoType>(Ty))
1016 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1017 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1018 for (const QualType &ParamType : FPT->param_types())
1019 EltTys.push_back(getOrCreateType(ParamType, Unit));
1020 if (FPT->isVariadic())
1021 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1022 }
1023
1024 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1025 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1026 getDwarfCC(Ty->getCallConv()));
1027}
1028
1029/// Convert an AccessSpecifier into the corresponding DINode flag.
1030/// As an optimization, return 0 if the access specifier equals the
1031/// default for the containing type.
1032static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1033 const RecordDecl *RD) {
1034 AccessSpecifier Default = clang::AS_none;
1035 if (RD && RD->isClass())
1036 Default = clang::AS_private;
1037 else if (RD && (RD->isStruct() || RD->isUnion()))
1038 Default = clang::AS_public;
1039
1040 if (Access == Default)
1041 return llvm::DINode::FlagZero;
1042
1043 switch (Access) {
1044 case clang::AS_private:
1045 return llvm::DINode::FlagPrivate;
1046 case clang::AS_protected:
1047 return llvm::DINode::FlagProtected;
1048 case clang::AS_public:
1049 return llvm::DINode::FlagPublic;
1050 case clang::AS_none:
1051 return llvm::DINode::FlagZero;
1052 }
1053 llvm_unreachable("unexpected access enumerator")::llvm::llvm_unreachable_internal("unexpected access enumerator"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1053)
;
1054}
1055
1056llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1057 llvm::DIScope *RecordTy,
1058 const RecordDecl *RD) {
1059 StringRef Name = BitFieldDecl->getName();
1060 QualType Ty = BitFieldDecl->getType();
1061 SourceLocation Loc = BitFieldDecl->getLocation();
1062 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1063 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1064
1065 // Get the location for the field.
1066 llvm::DIFile *File = getOrCreateFile(Loc);
1067 unsigned Line = getLineNumber(Loc);
1068
1069 const CGBitFieldInfo &BitFieldInfo =
1070 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1071 uint64_t SizeInBits = BitFieldInfo.Size;
1072 assert(SizeInBits > 0 && "found named 0-width bitfield")(static_cast <bool> (SizeInBits > 0 && "found named 0-width bitfield"
) ? void (0) : __assert_fail ("SizeInBits > 0 && \"found named 0-width bitfield\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1072, __extension__ __PRETTY_FUNCTION__))
;
1073 uint64_t StorageOffsetInBits =
1074 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1075 uint64_t Offset = BitFieldInfo.Offset;
1076 // The bit offsets for big endian machines are reversed for big
1077 // endian target, compensate for that as the DIDerivedType requires
1078 // un-reversed offsets.
1079 if (CGM.getDataLayout().isBigEndian())
1080 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1081 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1082 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1083 return DBuilder.createBitFieldMemberType(
1084 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1085 Flags, DebugType);
1086}
1087
1088llvm::DIType *
1089CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1090 AccessSpecifier AS, uint64_t offsetInBits,
1091 uint32_t AlignInBits, llvm::DIFile *tunit,
1092 llvm::DIScope *scope, const RecordDecl *RD) {
1093 llvm::DIType *debugType = getOrCreateType(type, tunit);
1094
1095 // Get the location for the field.
1096 llvm::DIFile *file = getOrCreateFile(loc);
1097 unsigned line = getLineNumber(loc);
1098
1099 uint64_t SizeInBits = 0;
1100 auto Align = AlignInBits;
1101 if (!type->isIncompleteArrayType()) {
1102 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1103 SizeInBits = TI.Width;
1104 if (!Align)
1105 Align = getTypeAlignIfRequired(type, CGM.getContext());
1106 }
1107
1108 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1109 return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
1110 Align, offsetInBits, flags, debugType);
1111}
1112
1113void CGDebugInfo::CollectRecordLambdaFields(
1114 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1115 llvm::DIType *RecordTy) {
1116 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1117 // has the name and the location of the variable so we should iterate over
1118 // both concurrently.
1119 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1120 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1121 unsigned fieldno = 0;
1122 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1123 E = CXXDecl->captures_end();
1124 I != E; ++I, ++Field, ++fieldno) {
1125 const LambdaCapture &C = *I;
1126 if (C.capturesVariable()) {
1127 SourceLocation Loc = C.getLocation();
1128 assert(!Field->isBitField() && "lambdas don't have bitfield members!")(static_cast <bool> (!Field->isBitField() &&
"lambdas don't have bitfield members!") ? void (0) : __assert_fail
("!Field->isBitField() && \"lambdas don't have bitfield members!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1128, __extension__ __PRETTY_FUNCTION__))
;
1129 VarDecl *V = C.getCapturedVar();
1130 StringRef VName = V->getName();
1131 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1132 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1133 llvm::DIType *FieldType = createFieldType(
1134 VName, Field->getType(), Loc, Field->getAccess(),
1135 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1136 elements.push_back(FieldType);
1137 } else if (C.capturesThis()) {
1138 // TODO: Need to handle 'this' in some way by probably renaming the
1139 // this of the lambda class and having a field member of 'this' or
1140 // by using AT_object_pointer for the function and having that be
1141 // used as 'this' for semantic references.
1142 FieldDecl *f = *Field;
1143 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1144 QualType type = f->getType();
1145 llvm::DIType *fieldType = createFieldType(
1146 "this", type, f->getLocation(), f->getAccess(),
1147 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1148
1149 elements.push_back(fieldType);
1150 }
1151 }
1152}
1153
1154llvm::DIDerivedType *
1155CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1156 const RecordDecl *RD) {
1157 // Create the descriptor for the static variable, with or without
1158 // constant initializers.
1159 Var = Var->getCanonicalDecl();
1160 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1161 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1162
1163 unsigned LineNumber = getLineNumber(Var->getLocation());
1164 StringRef VName = Var->getName();
1165 llvm::Constant *C = nullptr;
1166 if (Var->getInit()) {
1167 const APValue *Value = Var->evaluateValue();
1168 if (Value) {
1169 if (Value->isInt())
1170 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1171 if (Value->isFloat())
1172 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1173 }
1174 }
1175
1176 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1177 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1178 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1179 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1180 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1181 return GV;
1182}
1183
1184void CGDebugInfo::CollectRecordNormalField(
1185 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1186 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1187 const RecordDecl *RD) {
1188 StringRef name = field->getName();
1189 QualType type = field->getType();
1190
1191 // Ignore unnamed fields unless they're anonymous structs/unions.
1192 if (name.empty() && !type->isRecordType())
1193 return;
1194
1195 llvm::DIType *FieldType;
1196 if (field->isBitField()) {
1197 FieldType = createBitFieldType(field, RecordTy, RD);
1198 } else {
1199 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1200 FieldType =
1201 createFieldType(name, type, field->getLocation(), field->getAccess(),
1202 OffsetInBits, Align, tunit, RecordTy, RD);
1203 }
1204
1205 elements.push_back(FieldType);
1206}
1207
1208void CGDebugInfo::CollectRecordNestedType(
1209 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1210 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1211 // Injected class names are not considered nested records.
1212 if (isa<InjectedClassNameType>(Ty))
1213 return;
1214 SourceLocation Loc = TD->getLocation();
1215 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1216 elements.push_back(nestedType);
1217}
1218
1219void CGDebugInfo::CollectRecordFields(
1220 const RecordDecl *record, llvm::DIFile *tunit,
1221 SmallVectorImpl<llvm::Metadata *> &elements,
1222 llvm::DICompositeType *RecordTy) {
1223 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1224
1225 if (CXXDecl && CXXDecl->isLambda())
1226 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1227 else {
1228 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1229
1230 // Debug info for nested types is included in the member list only for
1231 // CodeView.
1232 bool IncludeNestedTypes = CGM.getCodeGenOpts().EmitCodeView;
1233
1234 // Field number for non-static fields.
1235 unsigned fieldNo = 0;
1236
1237 // Static and non-static members should appear in the same order as
1238 // the corresponding declarations in the source program.
1239 for (const auto *I : record->decls())
1240 if (const auto *V = dyn_cast<VarDecl>(I)) {
1241 if (V->hasAttr<NoDebugAttr>())
1242 continue;
1243 // Reuse the existing static member declaration if one exists
1244 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1245 if (MI != StaticDataMemberCache.end()) {
1246 assert(MI->second &&(static_cast <bool> (MI->second && "Static data member declaration should still exist"
) ? void (0) : __assert_fail ("MI->second && \"Static data member declaration should still exist\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1247, __extension__ __PRETTY_FUNCTION__))
1247 "Static data member declaration should still exist")(static_cast <bool> (MI->second && "Static data member declaration should still exist"
) ? void (0) : __assert_fail ("MI->second && \"Static data member declaration should still exist\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1247, __extension__ __PRETTY_FUNCTION__))
;
1248 elements.push_back(MI->second);
1249 } else {
1250 auto Field = CreateRecordStaticField(V, RecordTy, record);
1251 elements.push_back(Field);
1252 }
1253 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1254 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1255 elements, RecordTy, record);
1256
1257 // Bump field number for next field.
1258 ++fieldNo;
1259 } else if (IncludeNestedTypes) {
1260 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1261 if (!nestedType->isImplicit() &&
1262 nestedType->getDeclContext() == record)
1263 CollectRecordNestedType(nestedType, elements);
1264 }
1265 }
1266}
1267
1268llvm::DISubroutineType *
1269CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1270 llvm::DIFile *Unit) {
1271 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1272 if (Method->isStatic())
1273 return cast_or_null<llvm::DISubroutineType>(
1274 getOrCreateType(QualType(Func, 0), Unit));
1275 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1276 Func, Unit);
1277}
1278
1279llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1280 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1281 // Add "this" pointer.
1282 llvm::DITypeRefArray Args(
1283 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1284 ->getTypeArray());
1285 assert(Args.size() && "Invalid number of arguments!")(static_cast <bool> (Args.size() && "Invalid number of arguments!"
) ? void (0) : __assert_fail ("Args.size() && \"Invalid number of arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1285, __extension__ __PRETTY_FUNCTION__))
;
1286
1287 SmallVector<llvm::Metadata *, 16> Elts;
1288
1289 // First element is always return type. For 'void' functions it is NULL.
1290 Elts.push_back(Args[0]);
1291
1292 // "this" pointer is always first argument.
1293 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1294 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1295 // Create pointer type directly in this case.
1296 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1297 QualType PointeeTy = ThisPtrTy->getPointeeType();
1298 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1299 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1300 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1301 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1302 llvm::DIType *ThisPtrType =
1303 DBuilder.createPointerType(PointeeType, Size, Align);
1304 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1305 // TODO: This and the artificial type below are misleading, the
1306 // types aren't artificial the argument is, but the current
1307 // metadata doesn't represent that.
1308 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1309 Elts.push_back(ThisPtrType);
1310 } else {
1311 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1312 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1313 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1314 Elts.push_back(ThisPtrType);
1315 }
1316
1317 // Copy rest of the arguments.
1318 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1319 Elts.push_back(Args[i]);
1320
1321 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1322
1323 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1324 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1325 Flags |= llvm::DINode::FlagLValueReference;
1326 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1327 Flags |= llvm::DINode::FlagRValueReference;
1328
1329 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1330 getDwarfCC(Func->getCallConv()));
1331}
1332
1333/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1334/// inside a function.
1335static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1336 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1337 return isFunctionLocalClass(NRD);
1338 if (isa<FunctionDecl>(RD->getDeclContext()))
1339 return true;
1340 return false;
1341}
1342
1343llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1344 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1345 bool IsCtorOrDtor =
1346 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1347
1348 StringRef MethodName = getFunctionName(Method);
1349 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1350
1351 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1352 // make sense to give a single ctor/dtor a linkage name.
1353 StringRef MethodLinkageName;
1354 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1355 // property to use here. It may've been intended to model "is non-external
1356 // type" but misses cases of non-function-local but non-external classes such
1357 // as those in anonymous namespaces as well as the reverse - external types
1358 // that are function local, such as those in (non-local) inline functions.
1359 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1360 MethodLinkageName = CGM.getMangledName(Method);
1361
1362 // Get the location for the method.
1363 llvm::DIFile *MethodDefUnit = nullptr;
1364 unsigned MethodLine = 0;
1365 if (!Method->isImplicit()) {
1366 MethodDefUnit = getOrCreateFile(Method->getLocation());
1367 MethodLine = getLineNumber(Method->getLocation());
1368 }
1369
1370 // Collect virtual method info.
1371 llvm::DIType *ContainingType = nullptr;
1372 unsigned Virtuality = 0;
1373 unsigned VIndex = 0;
1374 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1375 int ThisAdjustment = 0;
1376
1377 if (Method->isVirtual()) {
1378 if (Method->isPure())
1379 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1380 else
1381 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1382
1383 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1384 // It doesn't make sense to give a virtual destructor a vtable index,
1385 // since a single destructor has two entries in the vtable.
1386 if (!isa<CXXDestructorDecl>(Method))
1387 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1388 } else {
1389 // Emit MS ABI vftable information. There is only one entry for the
1390 // deleting dtor.
1391 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1392 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1393 MicrosoftVTableContext::MethodVFTableLocation ML =
1394 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1395 VIndex = ML.Index;
1396
1397 // CodeView only records the vftable offset in the class that introduces
1398 // the virtual method. This is possible because, unlike Itanium, the MS
1399 // C++ ABI does not include all virtual methods from non-primary bases in
1400 // the vtable for the most derived class. For example, if C inherits from
1401 // A and B, C's primary vftable will not include B's virtual methods.
1402 if (Method->begin_overridden_methods() == Method->end_overridden_methods())
1403 Flags |= llvm::DINode::FlagIntroducedVirtual;
1404
1405 // The 'this' adjustment accounts for both the virtual and non-virtual
1406 // portions of the adjustment. Presumably the debugger only uses it when
1407 // it knows the dynamic type of an object.
1408 ThisAdjustment = CGM.getCXXABI()
1409 .getVirtualFunctionPrologueThisAdjustment(GD)
1410 .getQuantity();
1411 }
1412 ContainingType = RecordTy;
1413 }
1414
1415 if (Method->isStatic())
1416 Flags |= llvm::DINode::FlagStaticMember;
1417 if (Method->isImplicit())
1418 Flags |= llvm::DINode::FlagArtificial;
1419 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1420 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1421 if (CXXC->isExplicit())
1422 Flags |= llvm::DINode::FlagExplicit;
1423 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1424 if (CXXC->isExplicit())
1425 Flags |= llvm::DINode::FlagExplicit;
1426 }
1427 if (Method->hasPrototype())
1428 Flags |= llvm::DINode::FlagPrototyped;
1429 if (Method->getRefQualifier() == RQ_LValue)
1430 Flags |= llvm::DINode::FlagLValueReference;
1431 if (Method->getRefQualifier() == RQ_RValue)
1432 Flags |= llvm::DINode::FlagRValueReference;
1433
1434 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1435 llvm::DISubprogram *SP = DBuilder.createMethod(
1436 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1437 MethodTy, /*isLocalToUnit=*/false, /*isDefinition=*/false, Virtuality,
1438 VIndex, ThisAdjustment, ContainingType, Flags, CGM.getLangOpts().Optimize,
1439 TParamsArray.get());
1440
1441 SPCache[Method->getCanonicalDecl()].reset(SP);
1442
1443 return SP;
1444}
1445
1446void CGDebugInfo::CollectCXXMemberFunctions(
1447 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1448 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1449
1450 // Since we want more than just the individual member decls if we
1451 // have templated functions iterate over every declaration to gather
1452 // the functions.
1453 for (const auto *I : RD->decls()) {
1454 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1455 // If the member is implicit, don't add it to the member list. This avoids
1456 // the member being added to type units by LLVM, while still allowing it
1457 // to be emitted into the type declaration/reference inside the compile
1458 // unit.
1459 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1460 // FIXME: Handle Using(Shadow?)Decls here to create
1461 // DW_TAG_imported_declarations inside the class for base decls brought into
1462 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1463 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1464 // referenced)
1465 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1466 continue;
1467
1468 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1469 continue;
1470
1471 // Reuse the existing member function declaration if it exists.
1472 // It may be associated with the declaration of the type & should be
1473 // reused as we're building the definition.
1474 //
1475 // This situation can arise in the vtable-based debug info reduction where
1476 // implicit members are emitted in a non-vtable TU.
1477 auto MI = SPCache.find(Method->getCanonicalDecl());
1478 EltTys.push_back(MI == SPCache.end()
1479 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1480 : static_cast<llvm::Metadata *>(MI->second));
1481 }
1482}
1483
1484void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1485 SmallVectorImpl<llvm::Metadata *> &EltTys,
1486 llvm::DIType *RecordTy) {
1487 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1488 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1489 llvm::DINode::FlagZero);
1490
1491 // If we are generating CodeView debug info, we also need to emit records for
1492 // indirect virtual base classes.
1493 if (CGM.getCodeGenOpts().EmitCodeView) {
1494 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1495 llvm::DINode::FlagIndirectVirtualBase);
1496 }
1497}
1498
1499void CGDebugInfo::CollectCXXBasesAux(
1500 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1501 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1502 const CXXRecordDecl::base_class_const_range &Bases,
1503 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1504 llvm::DINode::DIFlags StartingFlags) {
1505 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1506 for (const auto &BI : Bases) {
1507 const auto *Base =
1508 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1509 if (!SeenTypes.insert(Base).second)
1510 continue;
1511 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1512 llvm::DINode::DIFlags BFlags = StartingFlags;
1513 uint64_t BaseOffset;
1514
1515 if (BI.isVirtual()) {
1516 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1517 // virtual base offset offset is -ve. The code generator emits dwarf
1518 // expression where it expects +ve number.
1519 BaseOffset = 0 - CGM.getItaniumVTableContext()
1520 .getVirtualBaseOffsetOffset(RD, Base)
1521 .getQuantity();
1522 } else {
1523 // In the MS ABI, store the vbtable offset, which is analogous to the
1524 // vbase offset offset in Itanium.
1525 BaseOffset =
1526 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1527 }
1528 BFlags |= llvm::DINode::FlagVirtual;
1529 } else
1530 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1531 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1532 // BI->isVirtual() and bits when not.
1533
1534 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1535 llvm::DIType *DTy =
1536 DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset, BFlags);
1537 EltTys.push_back(DTy);
1538 }
1539}
1540
1541llvm::DINodeArray
1542CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1543 ArrayRef<TemplateArgument> TAList,
1544 llvm::DIFile *Unit) {
1545 SmallVector<llvm::Metadata *, 16> TemplateParams;
1546 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1547 const TemplateArgument &TA = TAList[i];
1548 StringRef Name;
1549 if (TPList)
1550 Name = TPList->getParam(i)->getName();
1551 switch (TA.getKind()) {
1552 case TemplateArgument::Type: {
1553 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1554 TemplateParams.push_back(
1555 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1556 } break;
1557 case TemplateArgument::Integral: {
1558 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1559 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1560 TheCU, Name, TTy,
1561 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1562 } break;
1563 case TemplateArgument::Declaration: {
1564 const ValueDecl *D = TA.getAsDecl();
1565 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1566 llvm::DIType *TTy = getOrCreateType(T, Unit);
1567 llvm::Constant *V = nullptr;
1568 const CXXMethodDecl *MD;
1569 // Variable pointer template parameters have a value that is the address
1570 // of the variable.
1571 if (const auto *VD = dyn_cast<VarDecl>(D))
1572 V = CGM.GetAddrOfGlobalVar(VD);
1573 // Member function pointers have special support for building them, though
1574 // this is currently unsupported in LLVM CodeGen.
1575 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1576 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1577 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1578 V = CGM.GetAddrOfFunction(FD);
1579 // Member data pointers have special handling too to compute the fixed
1580 // offset within the object.
1581 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1582 // These five lines (& possibly the above member function pointer
1583 // handling) might be able to be refactored to use similar code in
1584 // CodeGenModule::getMemberPointerConstant
1585 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1586 CharUnits chars =
1587 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1588 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1589 }
1590 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1591 TheCU, Name, TTy,
1592 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1593 } break;
1594 case TemplateArgument::NullPtr: {
1595 QualType T = TA.getNullPtrType();
1596 llvm::DIType *TTy = getOrCreateType(T, Unit);
1597 llvm::Constant *V = nullptr;
1598 // Special case member data pointer null values since they're actually -1
1599 // instead of zero.
1600 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1601 // But treat member function pointers as simple zero integers because
1602 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1603 // CodeGen grows handling for values of non-null member function
1604 // pointers then perhaps we could remove this special case and rely on
1605 // EmitNullMemberPointer for member function pointers.
1606 if (MPT->isMemberDataPointer())
1607 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1608 if (!V)
1609 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1610 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1611 TheCU, Name, TTy, V));
1612 } break;
1613 case TemplateArgument::Template:
1614 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1615 TheCU, Name, nullptr,
1616 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1617 break;
1618 case TemplateArgument::Pack:
1619 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1620 TheCU, Name, nullptr,
1621 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1622 break;
1623 case TemplateArgument::Expression: {
1624 const Expr *E = TA.getAsExpr();
1625 QualType T = E->getType();
1626 if (E->isGLValue())
1627 T = CGM.getContext().getLValueReferenceType(T);
1628 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1629 assert(V && "Expression in template argument isn't constant")(static_cast <bool> (V && "Expression in template argument isn't constant"
) ? void (0) : __assert_fail ("V && \"Expression in template argument isn't constant\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1629, __extension__ __PRETTY_FUNCTION__))
;
1630 llvm::DIType *TTy = getOrCreateType(T, Unit);
1631 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1632 TheCU, Name, TTy, V->stripPointerCasts()));
1633 } break;
1634 // And the following should never occur:
1635 case TemplateArgument::TemplateExpansion:
1636 case TemplateArgument::Null:
1637 llvm_unreachable(::llvm::llvm_unreachable_internal("These argument types shouldn't exist in concrete types"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1638)
1638 "These argument types shouldn't exist in concrete types")::llvm::llvm_unreachable_internal("These argument types shouldn't exist in concrete types"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1638)
;
1639 }
1640 }
1641 return DBuilder.getOrCreateArray(TemplateParams);
1642}
1643
1644llvm::DINodeArray
1645CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1646 llvm::DIFile *Unit) {
1647 if (FD->getTemplatedKind() ==
1648 FunctionDecl::TK_FunctionTemplateSpecialization) {
1649 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1650 ->getTemplate()
1651 ->getTemplateParameters();
1652 return CollectTemplateParams(
1653 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1654 }
1655 return llvm::DINodeArray();
1656}
1657
1658llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1659 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1660 // Always get the full list of parameters, not just the ones from
1661 // the specialization.
1662 TemplateParameterList *TPList =
1663 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1664 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1665 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1666}
1667
1668llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1669 if (VTablePtrType)
1670 return VTablePtrType;
1671
1672 ASTContext &Context = CGM.getContext();
1673
1674 /* Function type */
1675 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1676 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1677 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1678 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1679 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1680 Optional<unsigned> DWARFAddressSpace =
1681 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1682
1683 llvm::DIType *vtbl_ptr_type =
1684 DBuilder.createPointerType(SubTy, Size, 0, DWARFAddressSpace,
1685 "__vtbl_ptr_type");
1686 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1687 return VTablePtrType;
1688}
1689
1690StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1691 // Copy the gdb compatible name on the side and use its reference.
1692 return internString("_vptr$", RD->getNameAsString());
1693}
1694
1695void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1696 SmallVectorImpl<llvm::Metadata *> &EltTys,
1697 llvm::DICompositeType *RecordTy) {
1698 // If this class is not dynamic then there is not any vtable info to collect.
1699 if (!RD->isDynamicClass())
1700 return;
1701
1702 // Don't emit any vtable shape or vptr info if this class doesn't have an
1703 // extendable vfptr. This can happen if the class doesn't have virtual
1704 // methods, or in the MS ABI if those virtual methods only come from virtually
1705 // inherited bases.
1706 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1707 if (!RL.hasExtendableVFPtr())
1708 return;
1709
1710 // CodeView needs to know how large the vtable of every dynamic class is, so
1711 // emit a special named pointer type into the element list. The vptr type
1712 // points to this type as well.
1713 llvm::DIType *VPtrTy = nullptr;
1714 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
1715 CGM.getTarget().getCXXABI().isMicrosoft();
1716 if (NeedVTableShape) {
1717 uint64_t PtrWidth =
1718 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1719 const VTableLayout &VFTLayout =
1720 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
1721 unsigned VSlotCount =
1722 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
1723 unsigned VTableWidth = PtrWidth * VSlotCount;
1724 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1725 Optional<unsigned> DWARFAddressSpace =
1726 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1727
1728 // Create a very wide void* type and insert it directly in the element list.
1729 llvm::DIType *VTableType =
1730 DBuilder.createPointerType(nullptr, VTableWidth, 0, DWARFAddressSpace,
1731 "__vtbl_ptr_type");
1732 EltTys.push_back(VTableType);
1733
1734 // The vptr is a pointer to this special vtable type.
1735 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
1736 }
1737
1738 // If there is a primary base then the artificial vptr member lives there.
1739 if (RL.getPrimaryBase())
1740 return;
1741
1742 if (!VPtrTy)
1743 VPtrTy = getOrCreateVTablePtrType(Unit);
1744
1745 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1746 llvm::DIType *VPtrMember = DBuilder.createMemberType(
1747 Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1748 llvm::DINode::FlagArtificial, VPtrTy);
1749 EltTys.push_back(VPtrMember);
1750}
1751
1752llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1753 SourceLocation Loc) {
1754 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1754, __extension__ __PRETTY_FUNCTION__))
;
1755 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1756 return T;
1757}
1758
1759llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1760 SourceLocation Loc) {
1761 return getOrCreateStandaloneType(D, Loc);
1762}
1763
1764llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1765 SourceLocation Loc) {
1766 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1766, __extension__ __PRETTY_FUNCTION__))
;
1767 assert(!D.isNull() && "null type")(static_cast <bool> (!D.isNull() && "null type"
) ? void (0) : __assert_fail ("!D.isNull() && \"null type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1767, __extension__ __PRETTY_FUNCTION__))
;
1768 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1769 assert(T && "could not create debug info for type")(static_cast <bool> (T && "could not create debug info for type"
) ? void (0) : __assert_fail ("T && \"could not create debug info for type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1769, __extension__ __PRETTY_FUNCTION__))
;
1770
1771 RetainedTypes.push_back(D.getAsOpaquePtr());
1772 return T;
1773}
1774
1775void CGDebugInfo::completeType(const EnumDecl *ED) {
1776 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1777 return;
1778 QualType Ty = CGM.getContext().getEnumType(ED);
1779 void *TyPtr = Ty.getAsOpaquePtr();
1780 auto I = TypeCache.find(TyPtr);
1781 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1782 return;
1783 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1784 assert(!Res->isForwardDecl())(static_cast <bool> (!Res->isForwardDecl()) ? void (
0) : __assert_fail ("!Res->isForwardDecl()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1784, __extension__ __PRETTY_FUNCTION__))
;
1785 TypeCache[TyPtr].reset(Res);
1786}
1787
1788void CGDebugInfo::completeType(const RecordDecl *RD) {
1789 if (DebugKind > codegenoptions::LimitedDebugInfo ||
1790 !CGM.getLangOpts().CPlusPlus)
1791 completeRequiredType(RD);
1792}
1793
1794/// Return true if the class or any of its methods are marked dllimport.
1795static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
1796 if (RD->hasAttr<DLLImportAttr>())
1797 return true;
1798 for (const CXXMethodDecl *MD : RD->methods())
1799 if (MD->hasAttr<DLLImportAttr>())
1800 return true;
1801 return false;
1802}
1803
1804/// Does a type definition exist in an imported clang module?
1805static bool isDefinedInClangModule(const RecordDecl *RD) {
1806 // Only definitions that where imported from an AST file come from a module.
1807 if (!RD || !RD->isFromASTFile())
1808 return false;
1809 // Anonymous entities cannot be addressed. Treat them as not from module.
1810 if (!RD->isExternallyVisible() && RD->getName().empty())
1811 return false;
1812 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
1813 if (!CXXDecl->isCompleteDefinition())
1814 return false;
1815 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
1816 if (TemplateKind != TSK_Undeclared) {
1817 // This is a template, check the origin of the first member.
1818 if (CXXDecl->field_begin() == CXXDecl->field_end())
1819 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
1820 if (!CXXDecl->field_begin()->isFromASTFile())
1821 return false;
1822 }
1823 }
1824 return true;
1825}
1826
1827void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1828 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1829 if (CXXRD->isDynamicClass() &&
1830 CGM.getVTableLinkage(CXXRD) ==
1831 llvm::GlobalValue::AvailableExternallyLinkage &&
1832 !isClassOrMethodDLLImport(CXXRD))
1833 return;
1834
1835 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
1836 return;
1837
1838 completeClass(RD);
1839}
1840
1841void CGDebugInfo::completeClass(const RecordDecl *RD) {
1842 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1843 return;
1844 QualType Ty = CGM.getContext().getRecordType(RD);
1845 void *TyPtr = Ty.getAsOpaquePtr();
1846 auto I = TypeCache.find(TyPtr);
1847 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1848 return;
1849 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1850 assert(!Res->isForwardDecl())(static_cast <bool> (!Res->isForwardDecl()) ? void (
0) : __assert_fail ("!Res->isForwardDecl()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 1850, __extension__ __PRETTY_FUNCTION__))
;
1851 TypeCache[TyPtr].reset(Res);
1852}
1853
1854static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1855 CXXRecordDecl::method_iterator End) {
1856 for (CXXMethodDecl *MD : llvm::make_range(I, End))
1857 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
1858 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1859 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
1860 return true;
1861 return false;
1862}
1863
1864static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
1865 bool DebugTypeExtRefs, const RecordDecl *RD,
1866 const LangOptions &LangOpts) {
1867 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
1868 return true;
1869
1870 if (auto *ES = RD->getASTContext().getExternalSource())
1871 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
1872 return true;
1873
1874 if (DebugKind > codegenoptions::LimitedDebugInfo)
1875 return false;
1876
1877 if (!LangOpts.CPlusPlus)
1878 return false;
1879
1880 if (!RD->isCompleteDefinitionRequired())
1881 return true;
1882
1883 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1884
1885 if (!CXXDecl)
1886 return false;
1887
1888 // Only emit complete debug info for a dynamic class when its vtable is
1889 // emitted. However, Microsoft debuggers don't resolve type information
1890 // across DLL boundaries, so skip this optimization if the class or any of its
1891 // methods are marked dllimport. This isn't a complete solution, since objects
1892 // without any dllimport methods can be used in one DLL and constructed in
1893 // another, but it is the current behavior of LimitedDebugInfo.
1894 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
1895 !isClassOrMethodDLLImport(CXXDecl))
1896 return true;
1897
1898 TemplateSpecializationKind Spec = TSK_Undeclared;
1899 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1900 Spec = SD->getSpecializationKind();
1901
1902 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1903 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1904 CXXDecl->method_end()))
1905 return true;
1906
1907 return false;
1908}
1909
1910void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1911 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
1912 return;
1913
1914 QualType Ty = CGM.getContext().getRecordType(RD);
1915 llvm::DIType *T = getTypeOrNull(Ty);
1916 if (T && T->isForwardDecl())
1917 completeClassData(RD);
1918}
1919
1920llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1921 RecordDecl *RD = Ty->getDecl();
1922 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1923 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
1924 CGM.getLangOpts())) {
1925 if (!T)
1926 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
1927 return T;
1928 }
1929
1930 return CreateTypeDefinition(Ty);
1931}
1932
1933llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1934 RecordDecl *RD = Ty->getDecl();
1935
1936 // Get overall information about the record type for the debug info.
1937 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1938
1939 // Records and classes and unions can all be recursive. To handle them, we
1940 // first generate a debug descriptor for the struct as a forward declaration.
1941 // Then (if it is a definition) we go through and get debug info for all of
1942 // its members. Finally, we create a descriptor for the complete type (which
1943 // may refer to the forward decl if the struct is recursive) and replace all
1944 // uses of the forward declaration with the final definition.
1945 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
1946
1947 const RecordDecl *D = RD->getDefinition();
1948 if (!D || !D->isCompleteDefinition())
1949 return FwdDecl;
1950
1951 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1952 CollectContainingType(CXXDecl, FwdDecl);
1953
1954 // Push the struct on region stack.
1955 LexicalBlockStack.emplace_back(&*FwdDecl);
1956 RegionMap[Ty->getDecl()].reset(FwdDecl);
1957
1958 // Convert all the elements.
1959 SmallVector<llvm::Metadata *, 16> EltTys;
1960 // what about nested types?
1961
1962 // Note: The split of CXXDecl information here is intentional, the
1963 // gdb tests will depend on a certain ordering at printout. The debug
1964 // information offsets are still correct if we merge them all together
1965 // though.
1966 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1967 if (CXXDecl) {
1968 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1969 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
1970 }
1971
1972 // Collect data fields (including static variables and any initializers).
1973 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1974 if (CXXDecl)
1975 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1976
1977 LexicalBlockStack.pop_back();
1978 RegionMap.erase(Ty->getDecl());
1979
1980 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1981 DBuilder.replaceArrays(FwdDecl, Elements);
1982
1983 if (FwdDecl->isTemporary())
1984 FwdDecl =
1985 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1986
1987 RegionMap[Ty->getDecl()].reset(FwdDecl);
1988 return FwdDecl;
1989}
1990
1991llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1992 llvm::DIFile *Unit) {
1993 // Ignore protocols.
1994 return getOrCreateType(Ty->getBaseType(), Unit);
1995}
1996
1997llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
1998 llvm::DIFile *Unit) {
1999 // Ignore protocols.
2000 SourceLocation Loc = Ty->getDecl()->getLocation();
2001
2002 // Use Typedefs to represent ObjCTypeParamType.
2003 return DBuilder.createTypedef(
2004 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2005 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2006 getDeclContextDescriptor(Ty->getDecl()));
2007}
2008
2009/// \return true if Getter has the default name for the property PD.
2010static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2011 const ObjCMethodDecl *Getter) {
2012 assert(PD)(static_cast <bool> (PD) ? void (0) : __assert_fail ("PD"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2012, __extension__ __PRETTY_FUNCTION__))
;
2013 if (!Getter)
2014 return true;
2015
2016 assert(Getter->getDeclName().isObjCZeroArgSelector())(static_cast <bool> (Getter->getDeclName().isObjCZeroArgSelector
()) ? void (0) : __assert_fail ("Getter->getDeclName().isObjCZeroArgSelector()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2016, __extension__ __PRETTY_FUNCTION__))
;
2017 return PD->getName() ==
2018 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2019}
2020
2021/// \return true if Setter has the default name for the property PD.
2022static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2023 const ObjCMethodDecl *Setter) {
2024 assert(PD)(static_cast <bool> (PD) ? void (0) : __assert_fail ("PD"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2024, __extension__ __PRETTY_FUNCTION__))
;
2025 if (!Setter)
2026 return true;
2027
2028 assert(Setter->getDeclName().isObjCOneArgSelector())(static_cast <bool> (Setter->getDeclName().isObjCOneArgSelector
()) ? void (0) : __assert_fail ("Setter->getDeclName().isObjCOneArgSelector()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2028, __extension__ __PRETTY_FUNCTION__))
;
2029 return SelectorTable::constructSetterName(PD->getName()) ==
2030 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2031}
2032
2033llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2034 llvm::DIFile *Unit) {
2035 ObjCInterfaceDecl *ID = Ty->getDecl();
2036 if (!ID)
2037 return nullptr;
2038
2039 // Return a forward declaration if this type was imported from a clang module,
2040 // and this is not the compile unit with the implementation of the type (which
2041 // may contain hidden ivars).
2042 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2043 !ID->getImplementation())
2044 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2045 ID->getName(),
2046 getDeclContextDescriptor(ID), Unit, 0);
2047
2048 // Get overall information about the record type for the debug info.
2049 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2050 unsigned Line = getLineNumber(ID->getLocation());
2051 auto RuntimeLang =
2052 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2053
2054 // If this is just a forward declaration return a special forward-declaration
2055 // debug type since we won't be able to lay out the entire type.
2056 ObjCInterfaceDecl *Def = ID->getDefinition();
2057 if (!Def || !Def->getImplementation()) {
2058 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2059 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2060 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2061 DefUnit, Line, RuntimeLang);
2062 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2063 return FwdDecl;
2064 }
2065
2066 return CreateTypeDefinition(Ty, Unit);
2067}
2068
2069llvm::DIModule *
2070CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2071 bool CreateSkeletonCU) {
2072 // Use the Module pointer as the key into the cache. This is a
2073 // nullptr if the "Module" is a PCH, which is safe because we don't
2074 // support chained PCH debug info, so there can only be a single PCH.
2075 const Module *M = Mod.getModuleOrNull();
2076 auto ModRef = ModuleCache.find(M);
2077 if (ModRef != ModuleCache.end())
2078 return cast<llvm::DIModule>(ModRef->second);
2079
2080 // Macro definitions that were defined with "-D" on the command line.
2081 SmallString<128> ConfigMacros;
2082 {
2083 llvm::raw_svector_ostream OS(ConfigMacros);
2084 const auto &PPOpts = CGM.getPreprocessorOpts();
2085 unsigned I = 0;
2086 // Translate the macro definitions back into a commmand line.
2087 for (auto &M : PPOpts.Macros) {
2088 if (++I > 1)
2089 OS << " ";
2090 const std::string &Macro = M.first;
2091 bool Undef = M.second;
2092 OS << "\"-" << (Undef ? 'U' : 'D');
2093 for (char c : Macro)
2094 switch (c) {
2095 case '\\' : OS << "\\\\"; break;
2096 case '"' : OS << "\\\""; break;
2097 default: OS << c;
2098 }
2099 OS << '\"';
2100 }
2101 }
2102
2103 bool IsRootModule = M ? !M->Parent : true;
2104 if (CreateSkeletonCU && IsRootModule) {
2105 // PCH files don't have a signature field in the control block,
2106 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2107 // We use the lower 64 bits for debug info.
2108 uint64_t Signature =
2109 Mod.getSignature()
2110 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2111 : ~1ULL;
2112 llvm::DIBuilder DIB(CGM.getModule());
2113 DIB.createCompileUnit(TheCU->getSourceLanguage(),
2114 DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2115 TheCU->getProducer(), true, StringRef(), 0,
2116 Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2117 Signature);
2118 DIB.finalize();
2119 }
2120 llvm::DIModule *Parent =
2121 IsRootModule ? nullptr
2122 : getOrCreateModuleRef(
2123 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2124 CreateSkeletonCU);
2125 llvm::DIModule *DIMod =
2126 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2127 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2128 ModuleCache[M].reset(DIMod);
2129 return DIMod;
2130}
2131
2132llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2133 llvm::DIFile *Unit) {
2134 ObjCInterfaceDecl *ID = Ty->getDecl();
2135 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2136 unsigned Line = getLineNumber(ID->getLocation());
2137 unsigned RuntimeLang = TheCU->getSourceLanguage();
2138
2139 // Bit size, align and offset of the type.
2140 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2141 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2142
2143 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2144 if (ID->getImplementation())
2145 Flags |= llvm::DINode::FlagObjcClassComplete;
2146
2147 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2148 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2149 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2150 nullptr, llvm::DINodeArray(), RuntimeLang);
2151
2152 QualType QTy(Ty, 0);
2153 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2154
2155 // Push the struct on region stack.
2156 LexicalBlockStack.emplace_back(RealDecl);
2157 RegionMap[Ty->getDecl()].reset(RealDecl);
2158
2159 // Convert all the elements.
2160 SmallVector<llvm::Metadata *, 16> EltTys;
2161
2162 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2163 if (SClass) {
2164 llvm::DIType *SClassTy =
2165 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2166 if (!SClassTy)
2167 return nullptr;
2168
2169 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0,
2170 llvm::DINode::FlagZero);
2171 EltTys.push_back(InhTag);
2172 }
2173
2174 // Create entries for all of the properties.
2175 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2176 SourceLocation Loc = PD->getLocation();
2177 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2178 unsigned PLine = getLineNumber(Loc);
2179 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2180 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2181 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2182 PD->getName(), PUnit, PLine,
2183 hasDefaultGetterName(PD, Getter) ? ""
2184 : getSelectorName(PD->getGetterName()),
2185 hasDefaultSetterName(PD, Setter) ? ""
2186 : getSelectorName(PD->getSetterName()),
2187 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2188 EltTys.push_back(PropertyNode);
2189 };
2190 {
2191 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
2192 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2193 for (auto *PD : ClassExt->properties()) {
2194 PropertySet.insert(PD->getIdentifier());
2195 AddProperty(PD);
2196 }
2197 for (const auto *PD : ID->properties()) {
2198 // Don't emit duplicate metadata for properties that were already in a
2199 // class extension.
2200 if (!PropertySet.insert(PD->getIdentifier()).second)
2201 continue;
2202 AddProperty(PD);
2203 }
2204 }
2205
2206 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2207 unsigned FieldNo = 0;
2208 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2209 Field = Field->getNextIvar(), ++FieldNo) {
2210 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2211 if (!FieldTy)
2212 return nullptr;
2213
2214 StringRef FieldName = Field->getName();
2215
2216 // Ignore unnamed fields.
2217 if (FieldName.empty())
2218 continue;
2219
2220 // Get the location for the field.
2221 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2222 unsigned FieldLine = getLineNumber(Field->getLocation());
2223 QualType FType = Field->getType();
2224 uint64_t FieldSize = 0;
2225 uint32_t FieldAlign = 0;
2226
2227 if (!FType->isIncompleteArrayType()) {
2228
2229 // Bit size, align and offset of the type.
2230 FieldSize = Field->isBitField()
2231 ? Field->getBitWidthValue(CGM.getContext())
2232 : CGM.getContext().getTypeSize(FType);
2233 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2234 }
2235
2236 uint64_t FieldOffset;
2237 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2238 // We don't know the runtime offset of an ivar if we're using the
2239 // non-fragile ABI. For bitfields, use the bit offset into the first
2240 // byte of storage of the bitfield. For other fields, use zero.
2241 if (Field->isBitField()) {
2242 FieldOffset =
2243 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2244 FieldOffset %= CGM.getContext().getCharWidth();
2245 } else {
2246 FieldOffset = 0;
2247 }
2248 } else {
2249 FieldOffset = RL.getFieldOffset(FieldNo);
2250 }
2251
2252 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2253 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2254 Flags = llvm::DINode::FlagProtected;
2255 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2256 Flags = llvm::DINode::FlagPrivate;
2257 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2258 Flags = llvm::DINode::FlagPublic;
2259
2260 llvm::MDNode *PropertyNode = nullptr;
2261 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2262 if (ObjCPropertyImplDecl *PImpD =
2263 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2264 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2265 SourceLocation Loc = PD->getLocation();
2266 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2267 unsigned PLine = getLineNumber(Loc);
2268 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2269 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2270 PropertyNode = DBuilder.createObjCProperty(
2271 PD->getName(), PUnit, PLine,
2272 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
2273 PD->getGetterName()),
2274 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
2275 PD->getSetterName()),
2276 PD->getPropertyAttributes(),
2277 getOrCreateType(PD->getType(), PUnit));
2278 }
2279 }
2280 }
2281 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2282 FieldSize, FieldAlign, FieldOffset, Flags,
2283 FieldTy, PropertyNode);
2284 EltTys.push_back(FieldTy);
2285 }
2286
2287 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2288 DBuilder.replaceArrays(RealDecl, Elements);
2289
2290 LexicalBlockStack.pop_back();
2291 return RealDecl;
2292}
2293
2294llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2295 llvm::DIFile *Unit) {
2296 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2297 int64_t Count = Ty->getNumElements();
2298 if (Count == 0)
2299 // If number of elements are not known then this is an unbounded array.
2300 // Use Count == -1 to express such arrays.
2301 Count = -1;
2302
2303 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
2304 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2305
2306 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2307 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2308
2309 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2310}
2311
2312llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2313 uint64_t Size;
2314 uint32_t Align;
2315
2316 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2317 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2318 Size = 0;
2319 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2320 CGM.getContext());
2321 } else if (Ty->isIncompleteArrayType()) {
2322 Size = 0;
2323 if (Ty->getElementType()->isIncompleteType())
2324 Align = 0;
2325 else
2326 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2327 } else if (Ty->isIncompleteType()) {
2328 Size = 0;
2329 Align = 0;
2330 } else {
2331 // Size and align of the whole array, not the element type.
2332 Size = CGM.getContext().getTypeSize(Ty);
2333 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2334 }
2335
2336 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2337 // interior arrays, do we care? Why aren't nested arrays represented the
2338 // obvious/recursive way?
2339 SmallVector<llvm::Metadata *, 8> Subscripts;
2340 QualType EltTy(Ty, 0);
2341 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2342 // If the number of elements is known, then count is that number. Otherwise,
2343 // it's -1. This allows us to represent a subrange with an array of 0
2344 // elements, like this:
2345 //
2346 // struct foo {
2347 // int x[0];
2348 // };
2349 int64_t Count = -1; // Count == -1 is an unbounded array.
2350 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2351 Count = CAT->getSize().getZExtValue();
2352 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2353 if (Expr *Size = VAT->getSizeExpr()) {
2354 llvm::APSInt V;
2355 if (Size->EvaluateAsInt(V, CGM.getContext()))
2356 Count = V.getExtValue();
2357 }
2358 }
2359
2360 // FIXME: Verify this is right for VLAs.
2361 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2362 EltTy = Ty->getElementType();
2363 }
2364
2365 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2366
2367 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2368 SubscriptArray);
2369}
2370
2371llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2372 llvm::DIFile *Unit) {
2373 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2374 Ty->getPointeeType(), Unit);
2375}
2376
2377llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2378 llvm::DIFile *Unit) {
2379 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2380 Ty->getPointeeType(), Unit);
2381}
2382
2383llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2384 llvm::DIFile *U) {
2385 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2386 uint64_t Size = 0;
2387
2388 if (!Ty->isIncompleteType()) {
2389 Size = CGM.getContext().getTypeSize(Ty);
2390
2391 // Set the MS inheritance model. There is no flag for the unspecified model.
2392 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2393 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2394 case MSInheritanceAttr::Keyword_single_inheritance:
2395 Flags |= llvm::DINode::FlagSingleInheritance;
2396 break;
2397 case MSInheritanceAttr::Keyword_multiple_inheritance:
2398 Flags |= llvm::DINode::FlagMultipleInheritance;
2399 break;
2400 case MSInheritanceAttr::Keyword_virtual_inheritance:
2401 Flags |= llvm::DINode::FlagVirtualInheritance;
2402 break;
2403 case MSInheritanceAttr::Keyword_unspecified_inheritance:
2404 break;
2405 }
2406 }
2407 }
2408
2409 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2410 if (Ty->isMemberDataPointerType())
2411 return DBuilder.createMemberPointerType(
2412 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2413 Flags);
2414
2415 const FunctionProtoType *FPT =
2416 Ty->getPointeeType()->getAs<FunctionProtoType>();
2417 return DBuilder.createMemberPointerType(
2418 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2419 Ty->getClass(), FPT->getTypeQuals())),
2420 FPT, U),
2421 ClassType, Size, /*Align=*/0, Flags);
2422}
2423
2424llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2425 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2426 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2427}
2428
2429llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
2430 llvm::DIFile *U) {
2431 return getOrCreateType(Ty->getElementType(), U);
2432}
2433
2434llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2435 const EnumDecl *ED = Ty->getDecl();
2436
2437 uint64_t Size = 0;
2438 uint32_t Align = 0;
2439 if (!ED->getTypeForDecl()->isIncompleteType()) {
2440 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2441 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2442 }
2443
2444 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2445
2446 bool isImportedFromModule =
2447 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2448
2449 // If this is just a forward declaration, construct an appropriately
2450 // marked node and just return it.
2451 if (isImportedFromModule || !ED->getDefinition()) {
2452 // Note that it is possible for enums to be created as part of
2453 // their own declcontext. In this case a FwdDecl will be created
2454 // twice. This doesn't cause a problem because both FwdDecls are
2455 // entered into the ReplaceMap: finalize() will replace the first
2456 // FwdDecl with the second and then replace the second with
2457 // complete type.
2458 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2459 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2460 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2461 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2462
2463 unsigned Line = getLineNumber(ED->getLocation());
2464 StringRef EDName = ED->getName();
2465 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2466 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2467 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
2468
2469 ReplaceMap.emplace_back(
2470 std::piecewise_construct, std::make_tuple(Ty),
2471 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2472 return RetTy;
2473 }
2474
2475 return CreateTypeDefinition(Ty);
2476}
2477
2478llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2479 const EnumDecl *ED = Ty->getDecl();
2480 uint64_t Size = 0;
2481 uint32_t Align = 0;
2482 if (!ED->getTypeForDecl()->isIncompleteType()) {
2483 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2484 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2485 }
2486
2487 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2488
2489 // Create elements for each enumerator.
2490 SmallVector<llvm::Metadata *, 16> Enumerators;
2491 ED = ED->getDefinition();
2492 for (const auto *Enum : ED->enumerators()) {
2493 Enumerators.push_back(DBuilder.createEnumerator(
2494 Enum->getName(), Enum->getInitVal().getSExtValue()));
2495 }
2496
2497 // Return a CompositeType for the enum itself.
2498 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2499
2500 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2501 unsigned Line = getLineNumber(ED->getLocation());
2502 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2503 llvm::DIType *ClassTy =
2504 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
2505 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2506 Line, Size, Align, EltArray, ClassTy,
2507 FullName);
2508}
2509
2510llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2511 unsigned MType, SourceLocation LineLoc,
2512 StringRef Name, StringRef Value) {
2513 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2514 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2515}
2516
2517llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2518 SourceLocation LineLoc,
2519 SourceLocation FileLoc) {
2520 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2521 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2522 return DBuilder.createTempMacroFile(Parent, Line, FName);
2523}
2524
2525static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2526 Qualifiers Quals;
2527 do {
2528 Qualifiers InnerQuals = T.getLocalQualifiers();
2529 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2530 // that is already there.
2531 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2532 Quals += InnerQuals;
2533 QualType LastT = T;
2534 switch (T->getTypeClass()) {
2535 default:
2536 return C.getQualifiedType(T.getTypePtr(), Quals);
2537 case Type::TemplateSpecialization: {
2538 const auto *Spec = cast<TemplateSpecializationType>(T);
2539 if (Spec->isTypeAlias())
2540 return C.getQualifiedType(T.getTypePtr(), Quals);
2541 T = Spec->desugar();
2542 break;
2543 }
2544 case Type::TypeOfExpr:
2545 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2546 break;
2547 case Type::TypeOf:
2548 T = cast<TypeOfType>(T)->getUnderlyingType();
2549 break;
2550 case Type::Decltype:
2551 T = cast<DecltypeType>(T)->getUnderlyingType();
2552 break;
2553 case Type::UnaryTransform:
2554 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2555 break;
2556 case Type::Attributed:
2557 T = cast<AttributedType>(T)->getEquivalentType();
2558 break;
2559 case Type::Elaborated:
2560 T = cast<ElaboratedType>(T)->getNamedType();
2561 break;
2562 case Type::Paren:
2563 T = cast<ParenType>(T)->getInnerType();
2564 break;
2565 case Type::SubstTemplateTypeParm:
2566 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2567 break;
2568 case Type::Auto:
2569 case Type::DeducedTemplateSpecialization: {
2570 QualType DT = cast<DeducedType>(T)->getDeducedType();
2571 assert(!DT.isNull() && "Undeduced types shouldn't reach here.")(static_cast <bool> (!DT.isNull() && "Undeduced types shouldn't reach here."
) ? void (0) : __assert_fail ("!DT.isNull() && \"Undeduced types shouldn't reach here.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2571, __extension__ __PRETTY_FUNCTION__))
;
2572 T = DT;
2573 break;
2574 }
2575 case Type::Adjusted:
2576 case Type::Decayed:
2577 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2578 T = cast<AdjustedType>(T)->getAdjustedType();
2579 break;
2580 }
2581
2582 assert(T != LastT && "Type unwrapping failed to unwrap!")(static_cast <bool> (T != LastT && "Type unwrapping failed to unwrap!"
) ? void (0) : __assert_fail ("T != LastT && \"Type unwrapping failed to unwrap!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2582, __extension__ __PRETTY_FUNCTION__))
;
2583 (void)LastT;
2584 } while (true);
2585}
2586
2587llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2588
2589 // Unwrap the type as needed for debug information.
2590 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2591
2592 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2593 if (it != TypeCache.end()) {
2594 // Verify that the debug info still exists.
2595 if (llvm::Metadata *V = it->second)
2596 return cast<llvm::DIType>(V);
2597 }
2598
2599 return nullptr;
2600}
2601
2602void CGDebugInfo::completeTemplateDefinition(
2603 const ClassTemplateSpecializationDecl &SD) {
2604 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2605 return;
2606 completeUnusedClass(SD);
2607}
2608
2609void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2610 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2611 return;
2612
2613 completeClassData(&D);
2614 // In case this type has no member function definitions being emitted, ensure
2615 // it is retained
2616 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
2617}
2618
2619llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2620 if (Ty.isNull())
2621 return nullptr;
2622
2623 // Unwrap the type as needed for debug information.
2624 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2625
2626 if (auto *T = getTypeOrNull(Ty))
2627 return T;
2628
2629 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2630 void* TyPtr = Ty.getAsOpaquePtr();
2631
2632 // And update the type cache.
2633 TypeCache[TyPtr].reset(Res);
2634
2635 return Res;
2636}
2637
2638llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2639 // A forward declaration inside a module header does not belong to the module.
2640 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2641 return nullptr;
2642 if (DebugTypeExtRefs && D->isFromASTFile()) {
2643 // Record a reference to an imported clang module or precompiled header.
2644 auto *Reader = CGM.getContext().getExternalSource();
2645 auto Idx = D->getOwningModuleID();
2646 auto Info = Reader->getSourceDescriptor(Idx);
2647 if (Info)
2648 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2649 } else if (ClangModuleMap) {
2650 // We are building a clang module or a precompiled header.
2651 //
2652 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2653 // and it wouldn't be necessary to specify the parent scope
2654 // because the type is already unique by definition (it would look
2655 // like the output of -fno-standalone-debug). On the other hand,
2656 // the parent scope helps a consumer to quickly locate the object
2657 // file where the type's definition is located, so it might be
2658 // best to make this behavior a command line or debugger tuning
2659 // option.
2660 FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
2661 if (Module *M = D->getOwningModule()) {
2662 // This is a (sub-)module.
2663 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2664 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2665 } else {
2666 // This the precompiled header being built.
2667 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
2668 }
2669 }
2670
2671 return nullptr;
2672}
2673
2674llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2675 // Handle qualifiers, which recursively handles what they refer to.
2676 if (Ty.hasLocalQualifiers())
2677 return CreateQualifiedType(Ty, Unit);
2678
2679 // Work out details of type.
2680 switch (Ty->getTypeClass()) {
2681#define TYPE(Class, Base)
2682#define ABSTRACT_TYPE(Class, Base)
2683#define NON_CANONICAL_TYPE(Class, Base)
2684#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2685#include "clang/AST/TypeNodes.def"
2686 llvm_unreachable("Dependent types cannot show up in debug information")::llvm::llvm_unreachable_internal("Dependent types cannot show up in debug information"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2686)
;
2687
2688 case Type::ExtVector:
2689 case Type::Vector:
2690 return CreateType(cast<VectorType>(Ty), Unit);
2691 case Type::ObjCObjectPointer:
2692 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2693 case Type::ObjCObject:
2694 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2695 case Type::ObjCTypeParam:
2696 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
2697 case Type::ObjCInterface:
2698 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2699 case Type::Builtin:
2700 return CreateType(cast<BuiltinType>(Ty));
2701 case Type::Complex:
2702 return CreateType(cast<ComplexType>(Ty));
2703 case Type::Pointer:
2704 return CreateType(cast<PointerType>(Ty), Unit);
2705 case Type::BlockPointer:
2706 return CreateType(cast<BlockPointerType>(Ty), Unit);
2707 case Type::Typedef:
2708 return CreateType(cast<TypedefType>(Ty), Unit);
2709 case Type::Record:
2710 return CreateType(cast<RecordType>(Ty));
2711 case Type::Enum:
2712 return CreateEnumType(cast<EnumType>(Ty));
2713 case Type::FunctionProto:
2714 case Type::FunctionNoProto:
2715 return CreateType(cast<FunctionType>(Ty), Unit);
2716 case Type::ConstantArray:
2717 case Type::VariableArray:
2718 case Type::IncompleteArray:
2719 return CreateType(cast<ArrayType>(Ty), Unit);
2720
2721 case Type::LValueReference:
2722 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2723 case Type::RValueReference:
2724 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2725
2726 case Type::MemberPointer:
2727 return CreateType(cast<MemberPointerType>(Ty), Unit);
2728
2729 case Type::Atomic:
2730 return CreateType(cast<AtomicType>(Ty), Unit);
2731
2732 case Type::Pipe:
2733 return CreateType(cast<PipeType>(Ty), Unit);
2734
2735 case Type::TemplateSpecialization:
2736 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2737
2738 case Type::Auto:
2739 case Type::Attributed:
2740 case Type::Adjusted:
2741 case Type::Decayed:
2742 case Type::DeducedTemplateSpecialization:
2743 case Type::Elaborated:
2744 case Type::Paren:
2745 case Type::SubstTemplateTypeParm:
2746 case Type::TypeOfExpr:
2747 case Type::TypeOf:
2748 case Type::Decltype:
2749 case Type::UnaryTransform:
2750 case Type::PackExpansion:
2751 break;
2752 }
2753
2754 llvm_unreachable("type should have been unwrapped!")::llvm::llvm_unreachable_internal("type should have been unwrapped!"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2754)
;
2755}
2756
2757llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2758 llvm::DIFile *Unit) {
2759 QualType QTy(Ty, 0);
2760
2761 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2762
2763 // We may have cached a forward decl when we could have created
2764 // a non-forward decl. Go ahead and create a non-forward decl
2765 // now.
2766 if (T && !T->isForwardDecl())
2767 return T;
2768
2769 // Otherwise create the type.
2770 llvm::DICompositeType *Res = CreateLimitedType(Ty);
2771
2772 // Propagate members from the declaration to the definition
2773 // CreateType(const RecordType*) will overwrite this with the members in the
2774 // correct order if the full type is needed.
2775 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2776
2777 // And update the type cache.
2778 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2779 return Res;
2780}
2781
2782// TODO: Currently used for context chains when limiting debug info.
2783llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2784 RecordDecl *RD = Ty->getDecl();
2785
2786 // Get overall information about the record type for the debug info.
2787 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2788 unsigned Line = getLineNumber(RD->getLocation());
2789 StringRef RDName = getClassName(RD);
2790
2791 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2792
2793 // If we ended up creating the type during the context chain construction,
2794 // just return that.
2795 auto *T = cast_or_null<llvm::DICompositeType>(
2796 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2797 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2798 return T;
2799
2800 // If this is just a forward or incomplete declaration, construct an
2801 // appropriately marked node and just return it.
2802 const RecordDecl *D = RD->getDefinition();
2803 if (!D || !D->isCompleteDefinition())
2804 return getOrCreateRecordFwdDecl(Ty, RDContext);
2805
2806 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2807 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
2808
2809 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2810
2811 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2812 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
2813 llvm::DINode::FlagZero, FullName);
2814
2815 // Elements of composite types usually have back to the type, creating
2816 // uniquing cycles. Distinct nodes are more efficient.
2817 switch (RealDecl->getTag()) {
2818 default:
2819 llvm_unreachable("invalid composite type tag")::llvm::llvm_unreachable_internal("invalid composite type tag"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 2819)
;
2820
2821 case llvm::dwarf::DW_TAG_array_type:
2822 case llvm::dwarf::DW_TAG_enumeration_type:
2823 // Array elements and most enumeration elements don't have back references,
2824 // so they don't tend to be involved in uniquing cycles and there is some
2825 // chance of merging them when linking together two modules. Only make
2826 // them distinct if they are ODR-uniqued.
2827 if (FullName.empty())
2828 break;
2829 LLVM_FALLTHROUGH[[clang::fallthrough]];
2830
2831 case llvm::dwarf::DW_TAG_structure_type:
2832 case llvm::dwarf::DW_TAG_union_type:
2833 case llvm::dwarf::DW_TAG_class_type:
2834 // Immediatley resolve to a distinct node.
2835 RealDecl =
2836 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
2837 break;
2838 }
2839
2840 RegionMap[Ty->getDecl()].reset(RealDecl);
2841 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2842
2843 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2844 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2845 CollectCXXTemplateParams(TSpecial, DefUnit));
2846 return RealDecl;
2847}
2848
2849void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2850 llvm::DICompositeType *RealDecl) {
2851 // A class's primary base or the class itself contains the vtable.
2852 llvm::DICompositeType *ContainingType = nullptr;
2853 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2854 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2855 // Seek non-virtual primary base root.
2856 while (1) {
2857 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2858 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2859 if (PBT && !BRL.isPrimaryBaseVirtual())
2860 PBase = PBT;
2861 else
2862 break;
2863 }
2864 ContainingType = cast<llvm::DICompositeType>(
2865 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2866 getOrCreateFile(RD->getLocation())));
2867 } else if (RD->isDynamicClass())
2868 ContainingType = RealDecl;
2869
2870 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2871}
2872
2873llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2874 StringRef Name, uint64_t *Offset) {
2875 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2876 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2877 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2878 llvm::DIType *Ty =
2879 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
2880 *Offset, llvm::DINode::FlagZero, FieldTy);
2881 *Offset += FieldSize;
2882 return Ty;
2883}
2884
2885void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2886 StringRef &Name,
2887 StringRef &LinkageName,
2888 llvm::DIScope *&FDContext,
2889 llvm::DINodeArray &TParamsArray,
2890 llvm::DINode::DIFlags &Flags) {
2891 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2892 Name = getFunctionName(FD);
2893 // Use mangled name as linkage name for C/C++ functions.
2894 if (FD->hasPrototype()) {
2895 LinkageName = CGM.getMangledName(GD);
2896 Flags |= llvm::DINode::FlagPrototyped;
2897 }
2898 // No need to replicate the linkage name if it isn't different from the
2899 // subprogram name, no need to have it at all unless coverage is enabled or
2900 // debug is set to more than just line tables or extra debug info is needed.
2901 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
2902 !CGM.getCodeGenOpts().EmitGcovNotes &&
2903 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
2904 DebugKind <= codegenoptions::DebugLineTablesOnly))
2905 LinkageName = StringRef();
2906
2907 if (DebugKind >= codegenoptions::LimitedDebugInfo) {
2908 if (const NamespaceDecl *NSDecl =
2909 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2910 FDContext = getOrCreateNamespace(NSDecl);
2911 else if (const RecordDecl *RDecl =
2912 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
2913 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
2914 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
2915 }
2916 // Check if it is a noreturn-marked function
2917 if (FD->isNoReturn())
2918 Flags |= llvm::DINode::FlagNoReturn;
2919 // Collect template parameters.
2920 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2921 }
2922}
2923
2924void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2925 unsigned &LineNo, QualType &T,
2926 StringRef &Name, StringRef &LinkageName,
2927 llvm::DIScope *&VDContext) {
2928 Unit = getOrCreateFile(VD->getLocation());
2929 LineNo = getLineNumber(VD->getLocation());
2930
2931 setLocation(VD->getLocation());
2932
2933 T = VD->getType();
2934 if (T->isIncompleteArrayType()) {
2935 // CodeGen turns int[] into int[1] so we'll do the same here.
2936 llvm::APInt ConstVal(32, 1);
2937 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2938
2939 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2940 ArrayType::Normal, 0);
2941 }
2942
2943 Name = VD->getName();
2944 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2945 !isa<ObjCMethodDecl>(VD->getDeclContext()))
2946 LinkageName = CGM.getMangledName(VD);
2947 if (LinkageName == Name)
2948 LinkageName = StringRef();
2949
2950 // Since we emit declarations (DW_AT_members) for static members, place the
2951 // definition of those static members in the namespace they were declared in
2952 // in the source code (the lexical decl context).
2953 // FIXME: Generalize this for even non-member global variables where the
2954 // declaration and definition may have different lexical decl contexts, once
2955 // we have support for emitting declarations of (non-member) global variables.
2956 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2957 : VD->getDeclContext();
2958 // When a record type contains an in-line initialization of a static data
2959 // member, and the record type is marked as __declspec(dllexport), an implicit
2960 // definition of the member will be created in the record context. DWARF
2961 // doesn't seem to have a nice way to describe this in a form that consumers
2962 // are likely to understand, so fake the "normal" situation of a definition
2963 // outside the class by putting it in the global scope.
2964 if (DC->isRecord())
2965 DC = CGM.getContext().getTranslationUnitDecl();
2966
2967 llvm::DIScope *Mod = getParentModuleOrNull(VD);
2968 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
2969}
2970
2971llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
2972 bool Stub) {
2973 llvm::DINodeArray TParamsArray;
2974 StringRef Name, LinkageName;
2975 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2976 SourceLocation Loc = GD.getDecl()->getLocation();
2977 llvm::DIFile *Unit = getOrCreateFile(Loc);
2978 llvm::DIScope *DContext = Unit;
2979 unsigned Line = getLineNumber(Loc);
2980 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext,
2981 TParamsArray, Flags);
2982 auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
2
Calling 'dyn_cast'
51
Returning from 'dyn_cast'
52
'FD' initialized here
2983
2984 // Build function type.
2985 SmallVector<QualType, 16> ArgTypes;
2986 if (FD)
53
Assuming 'FD' is null
54
Assuming pointer value is null
55
Taking false branch
2987 for (const ParmVarDecl *Parm : FD->parameters())
2988 ArgTypes.push_back(Parm->getType());
2989 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
56
Called C++ object pointer is null
2990 QualType FnType = CGM.getContext().getFunctionType(
2991 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
2992 if (Stub) {
2993 return DBuilder.createFunction(
2994 DContext, Name, LinkageName, Unit, Line,
2995 getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
2996 !FD->isExternallyVisible(),
2997 /* isDefinition = */ true, 0, Flags, CGM.getLangOpts().Optimize,
2998 TParamsArray.get(), getFunctionDeclaration(FD));
2999 }
3000
3001 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3002 DContext, Name, LinkageName, Unit, Line,
3003 getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
3004 !FD->isExternallyVisible(),
3005 /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
3006 TParamsArray.get(), getFunctionDeclaration(FD));
3007 const auto *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
3008 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3009 std::make_tuple(CanonDecl),
3010 std::make_tuple(SP));
3011 return SP;
3012}
3013
3014llvm::DISubprogram *
3015CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3016 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
1
Calling 'CGDebugInfo::getFunctionFwdDeclOrStub'
3017}
3018
3019llvm::DISubprogram *
3020CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3021 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3022}
3023
3024llvm::DIGlobalVariable *
3025CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3026 QualType T;
3027 StringRef Name, LinkageName;
3028 SourceLocation Loc = VD->getLocation();
3029 llvm::DIFile *Unit = getOrCreateFile(Loc);
3030 llvm::DIScope *DContext = Unit;
3031 unsigned Line = getLineNumber(Loc);
3032
3033 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
3034 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3035 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3036 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3037 !VD->isExternallyVisible(), nullptr, Align);
3038 FwdDeclReplaceMap.emplace_back(
3039 std::piecewise_construct,
3040 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3041 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3042 return GV;
3043}
3044
3045llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3046 // We only need a declaration (not a definition) of the type - so use whatever
3047 // we would otherwise do to get a type for a pointee. (forward declarations in
3048 // limited debug info, full definitions (if the type definition is available)
3049 // in unlimited debug info)
3050 if (const auto *TD = dyn_cast<TypeDecl>(D))
3051 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3052 getOrCreateFile(TD->getLocation()));
3053 auto I = DeclCache.find(D->getCanonicalDecl());
3054
3055 if (I != DeclCache.end()) {
3056 auto N = I->second;
3057 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3058 return GVE->getVariable();
3059 return dyn_cast_or_null<llvm::DINode>(N);
3060 }
3061
3062 // No definition for now. Emit a forward definition that might be
3063 // merged with a potential upcoming definition.
3064 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3065 return getFunctionForwardDeclaration(FD);
3066 else if (const auto *VD = dyn_cast<VarDecl>(D))
3067 return getGlobalVariableForwardDeclaration(VD);
3068
3069 return nullptr;
3070}
3071
3072llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3073 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3074 return nullptr;
3075
3076 const auto *FD = dyn_cast<FunctionDecl>(D);
3077 if (!FD)
3078 return nullptr;
3079
3080 // Setup context.
3081 auto *S = getDeclContextDescriptor(D);
3082
3083 auto MI = SPCache.find(FD->getCanonicalDecl());
3084 if (MI == SPCache.end()) {
3085 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3086 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3087 cast<llvm::DICompositeType>(S));
3088 }
3089 }
3090 if (MI != SPCache.end()) {
3091 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3092 if (SP && !SP->isDefinition())
3093 return SP;
3094 }
3095
3096 for (auto NextFD : FD->redecls()) {
3097 auto MI = SPCache.find(NextFD->getCanonicalDecl());
3098 if (MI != SPCache.end()) {
3099 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3100 if (SP && !SP->isDefinition())
3101 return SP;
3102 }
3103 }
3104 return nullptr;
3105}
3106
3107// getOrCreateFunctionType - Construct type. If it is a c++ method, include
3108// implicit parameter "this".
3109llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3110 QualType FnType,
3111 llvm::DIFile *F) {
3112 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3113 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3114 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3115 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3116
3117 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3118 return getOrCreateMethodType(Method, F);
3119
3120 const auto *FTy = FnType->getAs<FunctionType>();
3121 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3122
3123 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3124 // Add "self" and "_cmd"
3125 SmallVector<llvm::Metadata *, 16> Elts;
3126
3127 // First element is always return type. For 'void' functions it is NULL.
3128 QualType ResultTy = OMethod->getReturnType();
3129
3130 // Replace the instancetype keyword with the actual type.
3131 if (ResultTy == CGM.getContext().getObjCInstanceType())
3132 ResultTy = CGM.getContext().getPointerType(
3133 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3134
3135 Elts.push_back(getOrCreateType(ResultTy, F));
3136 // "self" pointer is always first argument.
3137 QualType SelfDeclTy;
3138 if (auto *SelfDecl = OMethod->getSelfDecl())
3139 SelfDeclTy = SelfDecl->getType();
3140 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3141 if (FPT->getNumParams() > 1)
3142 SelfDeclTy = FPT->getParamType(0);
3143 if (!SelfDeclTy.isNull())
3144 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3145 // "_cmd" pointer is always second argument.
3146 Elts.push_back(DBuilder.createArtificialType(
3147 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3148 // Get rest of the arguments.
3149 for (const auto *PI : OMethod->parameters())
3150 Elts.push_back(getOrCreateType(PI->getType(), F));
3151 // Variadic methods need a special marker at the end of the type list.
3152 if (OMethod->isVariadic())
3153 Elts.push_back(DBuilder.createUnspecifiedParameter());
3154
3155 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3156 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3157 getDwarfCC(CC));
3158 }
3159
3160 // Handle variadic function types; they need an additional
3161 // unspecified parameter.
3162 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3163 if (FD->isVariadic()) {
3164 SmallVector<llvm::Metadata *, 16> EltTys;
3165 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3166 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3167 for (QualType ParamType : FPT->param_types())
3168 EltTys.push_back(getOrCreateType(ParamType, F));
3169 EltTys.push_back(DBuilder.createUnspecifiedParameter());
3170 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3171 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3172 getDwarfCC(CC));
3173 }
3174
3175 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3176}
3177
3178void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3179 SourceLocation ScopeLoc, QualType FnType,
3180 llvm::Function *Fn, CGBuilderTy &Builder) {
3181
3182 StringRef Name;
3183 StringRef LinkageName;
3184
3185 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3186
3187 const Decl *D = GD.getDecl();
3188 bool HasDecl = (D != nullptr);
3189
3190 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3191 llvm::DIFile *Unit = getOrCreateFile(Loc);
3192 llvm::DIScope *FDContext = Unit;
3193 llvm::DINodeArray TParamsArray;
3194 if (!HasDecl) {
3195 // Use llvm function name.
3196 LinkageName = Fn->getName();
3197 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3198 // If there is a subprogram for this function available then use it.
3199 auto FI = SPCache.find(FD->getCanonicalDecl());
3200 if (FI != SPCache.end()) {
3201 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3202 if (SP && SP->isDefinition()) {
3203 LexicalBlockStack.emplace_back(SP);
3204 RegionMap[D].reset(SP);
3205 return;
3206 }
3207 }
3208 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3209 TParamsArray, Flags);
3210 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3211 Name = getObjCMethodName(OMD);
3212 Flags |= llvm::DINode::FlagPrototyped;
3213 } else {
3214 // Use llvm function name.
3215 Name = Fn->getName();
3216 Flags |= llvm::DINode::FlagPrototyped;
3217 }
3218 if (Name.startswith("\01"))
3219 Name = Name.substr(1);
3220
3221 if (!HasDecl || D->isImplicit()) {
3222 Flags |= llvm::DINode::FlagArtificial;
3223 // Artificial functions should not silently reuse CurLoc.
3224 CurLoc = SourceLocation();
3225 }
3226 unsigned LineNo = getLineNumber(Loc);
3227 unsigned ScopeLine = getLineNumber(ScopeLoc);
3228
3229 // FIXME: The function declaration we're constructing here is mostly reusing
3230 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3231 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3232 // all subprograms instead of the actual context since subprogram definitions
3233 // are emitted as CU level entities by the backend.
3234 llvm::DISubprogram *SP = DBuilder.createFunction(
3235 FDContext, Name, LinkageName, Unit, LineNo,
3236 getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
3237 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3238 TParamsArray.get(), getFunctionDeclaration(D));
3239 Fn->setSubprogram(SP);
3240 // We might get here with a VarDecl in the case we're generating
3241 // code for the initialization of globals. Do not record these decls
3242 // as they will overwrite the actual VarDecl Decl in the cache.
3243 if (HasDecl && isa<FunctionDecl>(D))
3244 DeclCache[D->getCanonicalDecl()].reset(SP);
3245
3246 // Push the function onto the lexical block stack.
3247 LexicalBlockStack.emplace_back(SP);
3248
3249 if (HasDecl)
3250 RegionMap[D].reset(SP);
3251}
3252
3253void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3254 QualType FnType) {
3255 StringRef Name;
3256 StringRef LinkageName;
3257
3258 const Decl *D = GD.getDecl();
3259 if (!D)
3260 return;
3261
3262 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3263 llvm::DIFile *Unit = getOrCreateFile(Loc);
3264 llvm::DIScope *FDContext = getDeclContextDescriptor(D);
3265 llvm::DINodeArray TParamsArray;
3266 if (isa<FunctionDecl>(D)) {
3267 // If there is a DISubprogram for this function available then use it.
3268 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3269 TParamsArray, Flags);
3270 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3271 Name = getObjCMethodName(OMD);
3272 Flags |= llvm::DINode::FlagPrototyped;
3273 } else {
3274 llvm_unreachable("not a function or ObjC method")::llvm::llvm_unreachable_internal("not a function or ObjC method"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3274)
;
3275 }
3276 if (!Name.empty() && Name[0] == '\01')
3277 Name = Name.substr(1);
3278
3279 if (D->isImplicit()) {
3280 Flags |= llvm::DINode::FlagArtificial;
3281 // Artificial functions without a location should not silently reuse CurLoc.
3282 if (Loc.isInvalid())
3283 CurLoc = SourceLocation();
3284 }
3285 unsigned LineNo = getLineNumber(Loc);
3286 unsigned ScopeLine = 0;
3287
3288 DBuilder.retainType(DBuilder.createFunction(
3289 FDContext, Name, LinkageName, Unit, LineNo,
3290 getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/,
3291 false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3292 TParamsArray.get(), getFunctionDeclaration(D)));
3293}
3294
3295void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3296 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3297 // If there is a subprogram for this function available then use it.
3298 auto FI = SPCache.find(FD->getCanonicalDecl());
3299 llvm::DISubprogram *SP = nullptr;
3300 if (FI != SPCache.end())
3301 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3302 if (!SP || !SP->isDefinition())
3303 SP = getFunctionStub(GD);
3304 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3305 LexicalBlockStack.emplace_back(SP);
3306 setInlinedAt(Builder.getCurrentDebugLocation());
3307 EmitLocation(Builder, FD->getLocation());
3308}
3309
3310void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3311 assert(CurInlinedAt && "unbalanced inline scope stack")(static_cast <bool> (CurInlinedAt && "unbalanced inline scope stack"
) ? void (0) : __assert_fail ("CurInlinedAt && \"unbalanced inline scope stack\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3311, __extension__ __PRETTY_FUNCTION__))
;
3312 EmitFunctionEnd(Builder, nullptr);
3313 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3314}
3315
3316void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3317 // Update our current location
3318 setLocation(Loc);
3319
3320 if (CurLoc.isInvalid() || CurLoc.isMacroID())
3321 return;
3322
3323 llvm::MDNode *Scope = LexicalBlockStack.back();
3324 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3325 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3326}
3327
3328void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3329 llvm::MDNode *Back = nullptr;
3330 if (!LexicalBlockStack.empty())
3331 Back = LexicalBlockStack.back().get();
3332 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3333 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3334 getColumnNumber(CurLoc)));
3335}
3336
3337void CGDebugInfo::AppendAddressSpaceXDeref(
3338 unsigned AddressSpace,
3339 SmallVectorImpl<int64_t> &Expr) const {
3340 Optional<unsigned> DWARFAddressSpace =
3341 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3342 if (!DWARFAddressSpace)
3343 return;
3344
3345 Expr.push_back(llvm::dwarf::DW_OP_constu);
3346 Expr.push_back(DWARFAddressSpace.getValue());
3347 Expr.push_back(llvm::dwarf::DW_OP_swap);
3348 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3349}
3350
3351void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3352 SourceLocation Loc) {
3353 // Set our current location.
3354 setLocation(Loc);
3355
3356 // Emit a line table change for the current location inside the new scope.
3357 Builder.SetCurrentDebugLocation(
3358 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3359 LexicalBlockStack.back(), CurInlinedAt));
3360
3361 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3362 return;
3363
3364 // Create a new lexical block and push it on the stack.
3365 CreateLexicalBlock(Loc);
3366}
3367
3368void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3369 SourceLocation Loc) {
3370 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!")(static_cast <bool> (!LexicalBlockStack.empty() &&
"Region stack mismatch, stack empty!") ? void (0) : __assert_fail
("!LexicalBlockStack.empty() && \"Region stack mismatch, stack empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3370, __extension__ __PRETTY_FUNCTION__))
;
3371
3372 // Provide an entry in the line table for the end of the block.
3373 EmitLocation(Builder, Loc);
3374
3375 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3376 return;
3377
3378 LexicalBlockStack.pop_back();
3379}
3380
3381void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3382 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!")(static_cast <bool> (!LexicalBlockStack.empty() &&
"Region stack mismatch, stack empty!") ? void (0) : __assert_fail
("!LexicalBlockStack.empty() && \"Region stack mismatch, stack empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3382, __extension__ __PRETTY_FUNCTION__))
;
3383 unsigned RCount = FnBeginRegionCount.back();
3384 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch")(static_cast <bool> (RCount <= LexicalBlockStack.size
() && "Region stack mismatch") ? void (0) : __assert_fail
("RCount <= LexicalBlockStack.size() && \"Region stack mismatch\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3384, __extension__ __PRETTY_FUNCTION__))
;
3385
3386 // Pop all regions for this function.
3387 while (LexicalBlockStack.size() != RCount) {
3388 // Provide an entry in the line table for the end of the block.
3389 EmitLocation(Builder, CurLoc);
3390 LexicalBlockStack.pop_back();
3391 }
3392 FnBeginRegionCount.pop_back();
3393
3394 if (Fn && Fn->getSubprogram())
3395 DBuilder.finalizeSubprogram(Fn->getSubprogram());
3396}
3397
3398llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3399 uint64_t *XOffset) {
3400
3401 SmallVector<llvm::Metadata *, 5> EltTys;
3402 QualType FType;
3403 uint64_t FieldSize, FieldOffset;
3404 uint32_t FieldAlign;
3405
3406 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3407 QualType Type = VD->getType();
3408
3409 FieldOffset = 0;
3410 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3411 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3412 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3413 FType = CGM.getContext().IntTy;
3414 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3415 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3416
3417 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3418 if (HasCopyAndDispose) {
3419 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3420 EltTys.push_back(
3421 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3422 EltTys.push_back(
3423 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3424 }
3425 bool HasByrefExtendedLayout;
3426 Qualifiers::ObjCLifetime Lifetime;
3427 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3428 HasByrefExtendedLayout) &&
3429 HasByrefExtendedLayout) {
3430 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3431 EltTys.push_back(
3432 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3433 }
3434
3435 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3436 if (Align > CGM.getContext().toCharUnitsFromBits(
3437 CGM.getTarget().getPointerAlign(0))) {
3438 CharUnits FieldOffsetInBytes =
3439 CGM.getContext().toCharUnitsFromBits(FieldOffset);
3440 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3441 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3442
3443 if (NumPaddingBytes.isPositive()) {
3444 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3445 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3446 pad, ArrayType::Normal, 0);
3447 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3448 }
3449 }
3450
3451 FType = Type;
3452 llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
3453 FieldSize = CGM.getContext().getTypeSize(FType);
3454 FieldAlign = CGM.getContext().toBits(Align);
3455
3456 *XOffset = FieldOffset;
3457 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
3458 FieldAlign, FieldOffset,
3459 llvm::DINode::FlagZero, FieldTy);
3460 EltTys.push_back(FieldTy);
3461 FieldOffset += FieldSize;
3462
3463 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3464
3465 llvm::DINode::DIFlags Flags = llvm::DINode::FlagBlockByrefStruct;
3466
3467 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
3468 nullptr, Elements);
3469}
3470
3471void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
3472 llvm::Optional<unsigned> ArgNo,
3473 CGBuilderTy &Builder) {
3474 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3474, __extension__ __PRETTY_FUNCTION__))
;
3475 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!")(static_cast <bool> (!LexicalBlockStack.empty() &&
"Region stack mismatch, stack empty!") ? void (0) : __assert_fail
("!LexicalBlockStack.empty() && \"Region stack mismatch, stack empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3475, __extension__ __PRETTY_FUNCTION__))
;
3476 if (VD->hasAttr<NoDebugAttr>())
3477 return;
3478
3479 bool Unwritten =
3480 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3481 cast<Decl>(VD->getDeclContext())->isImplicit());
3482 llvm::DIFile *Unit = nullptr;
3483 if (!Unwritten)
3484 Unit = getOrCreateFile(VD->getLocation());
3485 llvm::DIType *Ty;
3486 uint64_t XOffset = 0;
3487 if (VD->hasAttr<BlocksAttr>())
3488 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3489 else
3490 Ty = getOrCreateType(VD->getType(), Unit);
3491
3492 // If there is no debug info for this type then do not emit debug info
3493 // for this variable.
3494 if (!Ty)
3495 return;
3496
3497 // Get location information.
3498 unsigned Line = 0;
3499 unsigned Column = 0;
3500 if (!Unwritten) {
3501 Line = getLineNumber(VD->getLocation());
3502 Column = getColumnNumber(VD->getLocation());
3503 }
3504 SmallVector<int64_t, 13> Expr;
3505 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3506 if (VD->isImplicit())
3507 Flags |= llvm::DINode::FlagArtificial;
3508
3509 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3510
3511 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
3512 AppendAddressSpaceXDeref(AddressSpace, Expr);
3513
3514 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
3515 // object pointer flag.
3516 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
3517 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
3518 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3519 Flags |= llvm::DINode::FlagObjectPointer;
3520 }
3521
3522 // Note: Older versions of clang used to emit byval references with an extra
3523 // DW_OP_deref, because they referenced the IR arg directly instead of
3524 // referencing an alloca. Newer versions of LLVM don't treat allocas
3525 // differently from other function arguments when used in a dbg.declare.
3526 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
3527 StringRef Name = VD->getName();
3528 if (!Name.empty()) {
3529 if (VD->hasAttr<BlocksAttr>()) {
3530 // Here, we need an offset *into* the alloca.
3531 CharUnits offset = CharUnits::fromQuantity(32);
3532 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3533 // offset of __forwarding field
3534 offset = CGM.getContext().toCharUnitsFromBits(
3535 CGM.getTarget().getPointerWidth(0));
3536 Expr.push_back(offset.getQuantity());
3537 Expr.push_back(llvm::dwarf::DW_OP_deref);
3538 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3539 // offset of x field
3540 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3541 Expr.push_back(offset.getQuantity());
3542 }
3543 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
3544 // If VD is an anonymous union then Storage represents value for
3545 // all union fields.
3546 const auto *RD = cast<RecordDecl>(RT->getDecl());
3547 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
3548 // GDB has trouble finding local variables in anonymous unions, so we emit
3549 // artifical local variables for each of the members.
3550 //
3551 // FIXME: Remove this code as soon as GDB supports this.
3552 // The debug info verifier in LLVM operates based on the assumption that a
3553 // variable has the same size as its storage and we had to disable the check
3554 // for artificial variables.
3555 for (const auto *Field : RD->fields()) {
3556 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3557 StringRef FieldName = Field->getName();
3558
3559 // Ignore unnamed fields. Do not ignore unnamed records.
3560 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3561 continue;
3562
3563 // Use VarDecl's Tag, Scope and Line number.
3564 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
3565 auto *D = DBuilder.createAutoVariable(
3566 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3567 Flags | llvm::DINode::FlagArtificial, FieldAlign);
3568
3569 // Insert an llvm.dbg.declare into the current block.
3570 DBuilder.insertDeclare(
3571 Storage, D, DBuilder.createExpression(Expr),
3572 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3573 Builder.GetInsertBlock());
3574 }
3575 }
3576 }
3577
3578 // Create the descriptor for the variable.
3579 auto *D = ArgNo
3580 ? DBuilder.createParameterVariable(
3581 Scope, Name, *ArgNo, Unit, Line, Ty,
3582 CGM.getLangOpts().Optimize, Flags)
3583 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3584 CGM.getLangOpts().Optimize, Flags,
3585 Align);
3586
3587 // Insert an llvm.dbg.declare into the current block.
3588 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3589 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3590 Builder.GetInsertBlock());
3591}
3592
3593void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
3594 llvm::Value *Storage,
3595 CGBuilderTy &Builder) {
3596 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3596, __extension__ __PRETTY_FUNCTION__))
;
3597 EmitDeclare(VD, Storage, llvm::None, Builder);
3598}
3599
3600llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3601 llvm::DIType *Ty) {
3602 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3603 if (CachedTy)
3604 Ty = CachedTy;
3605 return DBuilder.createObjectPointerType(Ty);
3606}
3607
3608void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3609 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3610 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3611 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3611, __extension__ __PRETTY_FUNCTION__))
;
3612 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!")(static_cast <bool> (!LexicalBlockStack.empty() &&
"Region stack mismatch, stack empty!") ? void (0) : __assert_fail
("!LexicalBlockStack.empty() && \"Region stack mismatch, stack empty!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3612, __extension__ __PRETTY_FUNCTION__))
;
3613
3614 if (Builder.GetInsertBlock() == nullptr)
3615 return;
3616 if (VD->hasAttr<NoDebugAttr>())
3617 return;
3618
3619 bool isByRef = VD->hasAttr<BlocksAttr>();
3620
3621 uint64_t XOffset = 0;
3622 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3623 llvm::DIType *Ty;
3624 if (isByRef)
3625 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3626 else
3627 Ty = getOrCreateType(VD->getType(), Unit);
3628
3629 // Self is passed along as an implicit non-arg variable in a
3630 // block. Mark it as the object pointer.
3631 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
3632 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3633 Ty = CreateSelfType(VD->getType(), Ty);
3634
3635 // Get location information.
3636 unsigned Line = getLineNumber(VD->getLocation());
3637 unsigned Column = getColumnNumber(VD->getLocation());
3638
3639 const llvm::DataLayout &target = CGM.getDataLayout();
3640
3641 CharUnits offset = CharUnits::fromQuantity(
3642 target.getStructLayout(blockInfo.StructureType)
3643 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3644
3645 SmallVector<int64_t, 9> addr;
3646 addr.push_back(llvm::dwarf::DW_OP_deref);
3647 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3648 addr.push_back(offset.getQuantity());
3649 if (isByRef) {
3650 addr.push_back(llvm::dwarf::DW_OP_deref);
3651 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3652 // offset of __forwarding field
3653 offset =
3654 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3655 addr.push_back(offset.getQuantity());
3656 addr.push_back(llvm::dwarf::DW_OP_deref);
3657 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3658 // offset of x field
3659 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3660 addr.push_back(offset.getQuantity());
3661 }
3662
3663 // Create the descriptor for the variable.
3664 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3665 auto *D = DBuilder.createAutoVariable(
3666 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3667 Line, Ty, false, llvm::DINode::FlagZero, Align);
3668
3669 // Insert an llvm.dbg.declare into the current block.
3670 auto DL =
3671 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
3672 auto *Expr = DBuilder.createExpression(addr);
3673 if (InsertPoint)
3674 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
3675 else
3676 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
3677}
3678
3679void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3680 unsigned ArgNo,
3681 CGBuilderTy &Builder) {
3682 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3682, __extension__ __PRETTY_FUNCTION__))
;
3683 EmitDeclare(VD, AI, ArgNo, Builder);
3684}
3685
3686namespace {
3687struct BlockLayoutChunk {
3688 uint64_t OffsetInBits;
3689 const BlockDecl::Capture *Capture;
3690};
3691bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3692 return l.OffsetInBits < r.OffsetInBits;
3693}
3694}
3695
3696void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3697 StringRef Name,
3698 unsigned ArgNo,
3699 llvm::AllocaInst *Alloca,
3700 CGBuilderTy &Builder) {
3701 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3701, __extension__ __PRETTY_FUNCTION__))
;
3702 ASTContext &C = CGM.getContext();
3703 const BlockDecl *blockDecl = block.getBlockDecl();
3704
3705 // Collect some general information about the block's location.
3706 SourceLocation loc = blockDecl->getCaretLocation();
3707 llvm::DIFile *tunit = getOrCreateFile(loc);
3708 unsigned line = getLineNumber(loc);
3709 unsigned column = getColumnNumber(loc);
3710
3711 // Build the debug-info type for the block literal.
3712 getDeclContextDescriptor(blockDecl);
3713
3714 const llvm::StructLayout *blockLayout =
3715 CGM.getDataLayout().getStructLayout(block.StructureType);
3716
3717 SmallVector<llvm::Metadata *, 16> fields;
3718 fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public,
3719 blockLayout->getElementOffsetInBits(0),
3720 tunit, tunit));
3721 fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public,
3722 blockLayout->getElementOffsetInBits(1),
3723 tunit, tunit));
3724 fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public,
3725 blockLayout->getElementOffsetInBits(2),
3726 tunit, tunit));
3727 auto *FnTy = block.getBlockExpr()->getFunctionType();
3728 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3729 fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public,
3730 blockLayout->getElementOffsetInBits(3),
3731 tunit, tunit));
3732 fields.push_back(createFieldType(
3733 "__descriptor", C.getPointerType(block.NeedsCopyDispose
3734 ? C.getBlockDescriptorExtendedType()
3735 : C.getBlockDescriptorType()),
3736 loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3737
3738 // We want to sort the captures by offset, not because DWARF
3739 // requires this, but because we're paranoid about debuggers.
3740 SmallVector<BlockLayoutChunk, 8> chunks;
3741
3742 // 'this' capture.
3743 if (blockDecl->capturesCXXThis()) {
3744 BlockLayoutChunk chunk;
3745 chunk.OffsetInBits =
3746 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3747 chunk.Capture = nullptr;
3748 chunks.push_back(chunk);
3749 }
3750
3751 // Variable captures.
3752 for (const auto &capture : blockDecl->captures()) {
3753 const VarDecl *variable = capture.getVariable();
3754 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3755
3756 // Ignore constant captures.
3757 if (captureInfo.isConstant())
3758 continue;
3759
3760 BlockLayoutChunk chunk;
3761 chunk.OffsetInBits =
3762 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3763 chunk.Capture = &capture;
3764 chunks.push_back(chunk);
3765 }
3766
3767 // Sort by offset.
3768 llvm::array_pod_sort(chunks.begin(), chunks.end());
3769
3770 for (const BlockLayoutChunk &Chunk : chunks) {
3771 uint64_t offsetInBits = Chunk.OffsetInBits;
3772 const BlockDecl::Capture *capture = Chunk.Capture;
3773
3774 // If we have a null capture, this must be the C++ 'this' capture.
3775 if (!capture) {
3776 QualType type;
3777 if (auto *Method =
3778 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
3779 type = Method->getThisType(C);
3780 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
3781 type = QualType(RDecl->getTypeForDecl(), 0);
3782 else
3783 llvm_unreachable("unexpected block declcontext")::llvm::llvm_unreachable_internal("unexpected block declcontext"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3783)
;
3784
3785 fields.push_back(createFieldType("this", type, loc, AS_public,
3786 offsetInBits, tunit, tunit));
3787 continue;
3788 }
3789
3790 const VarDecl *variable = capture->getVariable();
3791 StringRef name = variable->getName();
3792
3793 llvm::DIType *fieldType;
3794 if (capture->isByRef()) {
3795 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3796 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
3797
3798 // FIXME: this creates a second copy of this type!
3799 uint64_t xoffset;
3800 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3801 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3802 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3803 PtrInfo.Width, Align, offsetInBits,
3804 llvm::DINode::FlagZero, fieldType);
3805 } else {
3806 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
3807 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
3808 offsetInBits, Align, tunit, tunit);
3809 }
3810 fields.push_back(fieldType);
3811 }
3812
3813 SmallString<36> typeName;
3814 llvm::raw_svector_ostream(typeName) << "__block_literal_"
3815 << CGM.getUniqueBlockCount();
3816
3817 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3818
3819 llvm::DIType *type =
3820 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3821 CGM.getContext().toBits(block.BlockSize), 0,
3822 llvm::DINode::FlagZero, nullptr, fieldsArray);
3823 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3824
3825 // Get overall information about the block.
3826 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
3827 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3828
3829 // Create the descriptor for the parameter.
3830 auto *debugVar = DBuilder.createParameterVariable(
3831 scope, Name, ArgNo, tunit, line, type,
3832 CGM.getLangOpts().Optimize, flags);
3833
3834 // Insert an llvm.dbg.declare into the current block.
3835 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
3836 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
3837 Builder.GetInsertBlock());
3838}
3839
3840llvm::DIDerivedType *
3841CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3842 if (!D->isStaticDataMember())
3843 return nullptr;
3844
3845 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3846 if (MI != StaticDataMemberCache.end()) {
3847 assert(MI->second && "Static data member declaration should still exist")(static_cast <bool> (MI->second && "Static data member declaration should still exist"
) ? void (0) : __assert_fail ("MI->second && \"Static data member declaration should still exist\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3847, __extension__ __PRETTY_FUNCTION__))
;
3848 return MI->second;
3849 }
3850
3851 // If the member wasn't found in the cache, lazily construct and add it to the
3852 // type (used when a limited form of the type is emitted).
3853 auto DC = D->getDeclContext();
3854 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
3855 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3856}
3857
3858llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
3859 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3860 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3861 llvm::DIGlobalVariableExpression *GVE = nullptr;
3862
3863 for (const auto *Field : RD->fields()) {
3864 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3865 StringRef FieldName = Field->getName();
3866
3867 // Ignore unnamed fields, but recurse into anonymous records.
3868 if (FieldName.empty()) {
3869 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
3870 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3871 Var, DContext);
3872 continue;
3873 }
3874 // Use VarDecl's Tag, Scope and Line number.
3875 GVE = DBuilder.createGlobalVariableExpression(
3876 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
3877 Var->hasLocalLinkage());
3878 Var->addDebugInfo(GVE);
3879 }
3880 return GVE;
3881}
3882
3883void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3884 const VarDecl *D) {
3885 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3885, __extension__ __PRETTY_FUNCTION__))
;
3886 if (D->hasAttr<NoDebugAttr>())
3887 return;
3888
3889 // If we already created a DIGlobalVariable for this declaration, just attach
3890 // it to the llvm::GlobalVariable.
3891 auto Cached = DeclCache.find(D->getCanonicalDecl());
3892 if (Cached != DeclCache.end())
3893 return Var->addDebugInfo(
3894 cast<llvm::DIGlobalVariableExpression>(Cached->second));
3895
3896 // Create global variable debug descriptor.
3897 llvm::DIFile *Unit = nullptr;
3898 llvm::DIScope *DContext = nullptr;
3899 unsigned LineNo;
3900 StringRef DeclName, LinkageName;
3901 QualType T;
3902 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3903
3904 // Attempt to store one global variable for the declaration - even if we
3905 // emit a lot of fields.
3906 llvm::DIGlobalVariableExpression *GVE = nullptr;
3907
3908 // If this is an anonymous union then we'll want to emit a global
3909 // variable for each member of the anonymous union so that it's possible
3910 // to find the name of any field in the union.
3911 if (T->isUnionType() && DeclName.empty()) {
3912 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3913 assert(RD->isAnonymousStructOrUnion() &&(static_cast <bool> (RD->isAnonymousStructOrUnion() &&
"unnamed non-anonymous struct or union?") ? void (0) : __assert_fail
("RD->isAnonymousStructOrUnion() && \"unnamed non-anonymous struct or union?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3914, __extension__ __PRETTY_FUNCTION__))
3914 "unnamed non-anonymous struct or union?")(static_cast <bool> (RD->isAnonymousStructOrUnion() &&
"unnamed non-anonymous struct or union?") ? void (0) : __assert_fail
("RD->isAnonymousStructOrUnion() && \"unnamed non-anonymous struct or union?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3914, __extension__ __PRETTY_FUNCTION__))
;
3915 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3916 } else {
3917 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3918
3919 SmallVector<int64_t, 4> Expr;
3920 unsigned AddressSpace =
3921 CGM.getContext().getTargetAddressSpace(D->getType());
3922 AppendAddressSpaceXDeref(AddressSpace, Expr);
3923
3924 GVE = DBuilder.createGlobalVariableExpression(
3925 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3926 Var->hasLocalLinkage(),
3927 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
3928 getOrCreateStaticDataMemberDeclarationOrNull(D), Align);
3929 Var->addDebugInfo(GVE);
3930 }
3931 DeclCache[D->getCanonicalDecl()].reset(GVE);
3932}
3933
3934void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
3935 assert(DebugKind >= codegenoptions::LimitedDebugInfo)(static_cast <bool> (DebugKind >= codegenoptions::LimitedDebugInfo
) ? void (0) : __assert_fail ("DebugKind >= codegenoptions::LimitedDebugInfo"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3935, __extension__ __PRETTY_FUNCTION__))
;
3936 if (VD->hasAttr<NoDebugAttr>())
3937 return;
3938 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3939 // Create the descriptor for the variable.
3940 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3941 StringRef Name = VD->getName();
3942 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3943 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3944 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
3945 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?")(static_cast <bool> (isa<EnumType>(ED->getTypeForDecl
()) && "Enum without EnumType?") ? void (0) : __assert_fail
("isa<EnumType>(ED->getTypeForDecl()) && \"Enum without EnumType?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 3945, __extension__ __PRETTY_FUNCTION__))
;
3946 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3947 }
3948 // Do not use global variables for enums.
3949 //
3950 // FIXME: why not?
3951 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3952 return;
3953 // Do not emit separate definitions for function local const/statics.
3954 if (isa<FunctionDecl>(VD->getDeclContext()))
3955 return;
3956 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3957 auto *VarD = cast<VarDecl>(VD);
3958 if (VarD->isStaticDataMember()) {
3959 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3960 getDeclContextDescriptor(VarD);
3961 // Ensure that the type is retained even though it's otherwise unreferenced.
3962 //
3963 // FIXME: This is probably unnecessary, since Ty should reference RD
3964 // through its scope.
3965 RetainedTypes.push_back(
3966 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3967 return;
3968 }
3969
3970 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
3971
3972 auto &GV = DeclCache[VD];
3973 if (GV)
3974 return;
3975 llvm::DIExpression *InitExpr = nullptr;
3976 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
3977 // FIXME: Add a representation for integer constants wider than 64 bits.
3978 if (Init.isInt())
3979 InitExpr =
3980 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
3981 else if (Init.isFloat())
3982 InitExpr = DBuilder.createConstantValueExpression(
3983 Init.getFloat().bitcastToAPInt().getZExtValue());
3984 }
3985 GV.reset(DBuilder.createGlobalVariableExpression(
3986 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3987 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
3988 Align));
3989}
3990
3991llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3992 if (!LexicalBlockStack.empty())
3993 return LexicalBlockStack.back();
3994 llvm::DIScope *Mod = getParentModuleOrNull(D);
3995 return getContextDescriptor(D, Mod ? Mod : TheCU);
3996}
3997
3998void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3999 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4000 return;
4001 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4002 if (!NSDecl->isAnonymousNamespace() ||
4003 CGM.getCodeGenOpts().DebugExplicitImport) {
4004 auto Loc = UD.getLocation();
4005 DBuilder.createImportedModule(
4006 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4007 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4008 }
4009}
4010
4011void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4012 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4013 return;
4014 assert(UD.shadow_size() &&(static_cast <bool> (UD.shadow_size() && "We shouldn't be codegening an invalid UsingDecl containing no decls"
) ? void (0) : __assert_fail ("UD.shadow_size() && \"We shouldn't be codegening an invalid UsingDecl containing no decls\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4015, __extension__ __PRETTY_FUNCTION__))
4015 "We shouldn't be codegening an invalid UsingDecl containing no decls")(static_cast <bool> (UD.shadow_size() && "We shouldn't be codegening an invalid UsingDecl containing no decls"
) ? void (0) : __assert_fail ("UD.shadow_size() && \"We shouldn't be codegening an invalid UsingDecl containing no decls\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4015, __extension__ __PRETTY_FUNCTION__))
;
4016 // Emitting one decl is sufficient - debuggers can detect that this is an
4017 // overloaded name & provide lookup for all the overloads.
4018 const UsingShadowDecl &USD = **UD.shadow_begin();
4019
4020 // FIXME: Skip functions with undeduced auto return type for now since we
4021 // don't currently have the plumbing for separate declarations & definitions
4022 // of free functions and mismatched types (auto in the declaration, concrete
4023 // return type in the definition)
4024 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4025 if (const auto *AT =
4026 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
4027 if (AT->getDeducedType().isNull())
4028 return;
4029 if (llvm::DINode *Target =
4030 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4031 auto Loc = USD.getLocation();
4032 DBuilder.createImportedDeclaration(
4033 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4034 getOrCreateFile(Loc), getLineNumber(Loc));
4035 }
4036}
4037
4038void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4039 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4040 return;
4041 if (Module *M = ID.getImportedModule()) {
4042 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
4043 auto Loc = ID.getLocation();
4044 DBuilder.createImportedDeclaration(
4045 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4046 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4047 getLineNumber(Loc));
4048 }
4049}
4050
4051llvm::DIImportedEntity *
4052CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4053 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4054 return nullptr;
4055 auto &VH = NamespaceAliasCache[&NA];
4056 if (VH)
4057 return cast<llvm::DIImportedEntity>(VH);
4058 llvm::DIImportedEntity *R;
4059 auto Loc = NA.getLocation();
4060 if (const auto *Underlying =
4061 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4062 // This could cache & dedup here rather than relying on metadata deduping.
4063 R = DBuilder.createImportedDeclaration(
4064 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4065 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4066 getLineNumber(Loc), NA.getName());
4067 else
4068 R = DBuilder.createImportedDeclaration(
4069 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4070 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4071 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4072 VH.reset(R);
4073 return R;
4074}
4075
4076llvm::DINamespace *
4077CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4078 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4079 // if necessary, and this way multiple declarations of the same namespace in
4080 // different parent modules stay distinct.
4081 auto I = NamespaceCache.find(NSDecl);
4082 if (I != NamespaceCache.end())
4083 return cast<llvm::DINamespace>(I->second);
4084
4085 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4086 // Don't trust the context if it is a DIModule (see comment above).
4087 llvm::DINamespace *NS =
4088 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4089 NamespaceCache[NSDecl].reset(NS);
4090 return NS;
4091}
4092
4093void CGDebugInfo::setDwoId(uint64_t Signature) {
4094 assert(TheCU && "no main compile unit")(static_cast <bool> (TheCU && "no main compile unit"
) ? void (0) : __assert_fail ("TheCU && \"no main compile unit\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4094, __extension__ __PRETTY_FUNCTION__))
;
4095 TheCU->setDWOId(Signature);
4096}
4097
4098
4099void CGDebugInfo::finalize() {
4100 // Creating types might create further types - invalidating the current
4101 // element and the size(), so don't cache/reference them.
4102 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4103 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4104 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4105 ? CreateTypeDefinition(E.Type, E.Unit)
4106 : E.Decl;
4107 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4108 }
4109
4110 for (auto p : ReplaceMap) {
4111 assert(p.second)(static_cast <bool> (p.second) ? void (0) : __assert_fail
("p.second", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4111, __extension__ __PRETTY_FUNCTION__))
;
4112 auto *Ty = cast<llvm::DIType>(p.second);
4113 assert(Ty->isForwardDecl())(static_cast <bool> (Ty->isForwardDecl()) ? void (0)
: __assert_fail ("Ty->isForwardDecl()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4113, __extension__ __PRETTY_FUNCTION__))
;
4114
4115 auto it = TypeCache.find(p.first);
4116 assert(it != TypeCache.end())(static_cast <bool> (it != TypeCache.end()) ? void (0) :
__assert_fail ("it != TypeCache.end()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4116, __extension__ __PRETTY_FUNCTION__))
;
4117 assert(it->second)(static_cast <bool> (it->second) ? void (0) : __assert_fail
("it->second", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4117, __extension__ __PRETTY_FUNCTION__))
;
4118
4119 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4120 cast<llvm::DIType>(it->second));
4121 }
4122
4123 for (const auto &p : FwdDeclReplaceMap) {
4124 assert(p.second)(static_cast <bool> (p.second) ? void (0) : __assert_fail
("p.second", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/CodeGen/CGDebugInfo.cpp"
, 4124, __extension__ __PRETTY_FUNCTION__))
;
4125 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
4126 llvm::Metadata *Repl;
4127
4128 auto it = DeclCache.find(p.first);
4129 // If there has been no definition for the declaration, call RAUW
4130 // with ourselves, that will destroy the temporary MDNode and
4131 // replace it with a standard one, avoiding leaking memory.
4132 if (it == DeclCache.end())
4133 Repl = p.second;
4134 else
4135 Repl = it->second;
4136
4137 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4138 Repl = GVE->getVariable();
4139 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4140 }
4141
4142 // We keep our own list of retained types, because we need to look
4143 // up the final type in the type cache.
4144 for (auto &RT : RetainedTypes)
4145 if (auto MD = TypeCache[RT])
4146 DBuilder.retainType(cast<llvm::DIType>(MD));
4147
4148 DBuilder.finalize();
4149}
4150
4151void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4152 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4153 return;
4154
4155 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
4156 // Don't ignore in case of explicit cast where it is referenced indirectly.
4157 DBuilder.retainType(DieTy);
4158}
4159
4160llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4161 if (LexicalBlockStack.empty())
4162 return llvm::DebugLoc();
4163
4164 llvm::MDNode *Scope = LexicalBlockStack.back();
4165 return llvm::DebugLoc::get(
4166 getLineNumber(Loc), getColumnNumber(Loc), Scope);
4167}

/build/llvm-toolchain-snapshot-6.0~svn318882/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));
6
Calling 'simplify_type::getSimplifiedValue'
7
Returning from 'simplify_type::getSimplifiedValue'
31
Calling 'simplify_type::getSimplifiedValue'
32
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);
13
Calling 'FunctionDecl::classof'
20
Returning from 'FunctionDecl::classof'
38
Calling 'FunctionDecl::classof'
43
Returning from 'FunctionDecl::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-6.0~svn318882/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-6.0~svn318882/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-6.0~svn318882/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-6.0~svn318882/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
11
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
36
Within the expansion of the macro 'assert':
107 return isa_impl<To, From>::doit(*Val);
12
Calling 'isa_impl::doit'
21
Returning from 'isa_impl::doit'
37
Calling 'isa_impl::doit'
44
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-6.0~svn318882/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,
9
Calling 'isa_impl_wrap::doit'
23
Returning from 'isa_impl_wrap::doit'
34
Calling 'isa_impl_wrap::doit'
46
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
5
Calling 'simplify_type::getSimplifiedValue'
8
Returning from 'simplify_type::getSimplifiedValue'
30
Calling 'simplify_type::getSimplifiedValue'
33
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);
10
Calling 'isa_impl_cl::doit'
22
Returning from 'isa_impl_cl::doit'
35
Calling 'isa_impl_cl::doit'
45
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,
4
Calling 'isa_impl_wrap::doit'
24
Returning from 'isa_impl_wrap::doit'
29
Calling 'isa_impl_wrap::doit'
47
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-6.0~svn318882/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-6.0~svn318882/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-6.0~svn318882/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
28
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
256 return cast_convert_val<X, Y*,
48
Calling 'cast_convert_val::doit'
49
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-6.0~svn318882/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-6.0~svn318882/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-6.0~svn318882/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-6.0~svn318882/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;
3
Calling 'isa'
25
Returning from 'isa'
26
'?' condition is true
27
Calling 'cast'
50
Returning from 'cast'
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-6.0~svn318882/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/// \brief 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 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 /// \brief Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// \brief Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// TranslationUnitDecl - 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/// \brief 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/// \brief 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/// \brief 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/// NamedDecl - This represents a decl with a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245class NamedDecl : public Decl {
246 /// Name - The name of this declaration, which is typically a normal
247 /// identifier but may also be a special kind of name (C++
248 /// constructor, Objective-C selector, etc.)
249 DeclarationName Name;
250
251 virtual void anchor();
252
253private:
254 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
255
256protected:
257 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
258 : Decl(DK, DC, L), Name(N) {}
259
260public:
261 /// getIdentifier - Get the identifier that names this declaration,
262 /// if there is one. This will return NULL if this declaration has
263 /// no name (e.g., for an unnamed class) or if the name is a special
264 /// name (C++ constructor, Objective-C selector, etc.).
265 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
266
267 /// getName - Get the name of identifier for this declaration as a StringRef.
268 /// This requires that the declaration have a name and that it be a simple
269 /// identifier.
270 StringRef getName() const {
271 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 271, __extension__ __PRETTY_FUNCTION__))
;
272 return getIdentifier() ? getIdentifier()->getName() : "";
273 }
274
275 /// getNameAsString - Get a human-readable name for the declaration, even if
276 /// it is one of the special kinds of names (C++ constructor, Objective-C
277 /// selector, etc). Creating this name requires expensive string
278 /// manipulation, so it should be called only when performance doesn't matter.
279 /// For simple declarations, getNameAsCString() should suffice.
280 //
281 // FIXME: This function should be renamed to indicate that it is not just an
282 // alternate form of getName(), and clients should move as appropriate.
283 //
284 // FIXME: Deprecated, move clients to getName().
285 std::string getNameAsString() const { return Name.getAsString(); }
286
287 virtual void printName(raw_ostream &os) const;
288
289 /// getDeclName - Get the actual, stored name of the declaration,
290 /// which may be a special name.
291 DeclarationName getDeclName() const { return Name; }
292
293 /// \brief Set the name of this declaration.
294 void setDeclName(DeclarationName N) { Name = N; }
295
296 /// printQualifiedName - Returns human-readable qualified name for
297 /// declaration, like A::B::i, for i being member of namespace A::B.
298 /// If declaration is not member of context which can be named (record,
299 /// namespace), it will return same result as printName().
300 /// Creating this name is expensive, so it should be called only when
301 /// performance doesn't matter.
302 void printQualifiedName(raw_ostream &OS) const;
303 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
304
305 // FIXME: Remove string version.
306 std::string getQualifiedNameAsString() const;
307
308 /// getNameForDiagnostic - Appends a human-readable name for this
309 /// declaration into the given stream.
310 ///
311 /// This is the method invoked by Sema when displaying a NamedDecl
312 /// in a diagnostic. It does not necessarily produce the same
313 /// result as printName(); for example, class template
314 /// specializations are printed with their template arguments.
315 virtual void getNameForDiagnostic(raw_ostream &OS,
316 const PrintingPolicy &Policy,
317 bool Qualified) const;
318
319 /// \brief Determine whether this declaration, if
320 /// known to be well-formed within its context, will replace the
321 /// declaration OldD if introduced into scope. A declaration will
322 /// replace another declaration if, for example, it is a
323 /// redeclaration of the same variable or function, but not if it is
324 /// a declaration of a different kind (function vs. class) or an
325 /// overloaded function.
326 ///
327 /// \param IsKnownNewer \c true if this declaration is known to be newer
328 /// than \p OldD (for instance, if this declaration is newly-created).
329 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
330
331 /// \brief Determine whether this declaration has linkage.
332 bool hasLinkage() const;
333
334 using Decl::isModulePrivate;
335 using Decl::setModulePrivate;
336
337 /// \brief Determine whether this declaration is a C++ class member.
338 bool isCXXClassMember() const {
339 const DeclContext *DC = getDeclContext();
340
341 // C++0x [class.mem]p1:
342 // The enumerators of an unscoped enumeration defined in
343 // the class are members of the class.
344 if (isa<EnumDecl>(DC))
345 DC = DC->getRedeclContext();
346
347 return DC->isRecord();
348 }
349
350 /// \brief Determine whether the given declaration is an instance member of
351 /// a C++ class.
352 bool isCXXInstanceMember() const;
353
354 /// \brief Determine what kind of linkage this entity has.
355 /// This is not the linkage as defined by the standard or the codegen notion
356 /// of linkage. It is just an implementation detail that is used to compute
357 /// those.
358 Linkage getLinkageInternal() const;
359
360 /// \brief Get the linkage from a semantic point of view. Entities in
361 /// anonymous namespaces are external (in c++98).
362 Linkage getFormalLinkage() const {
363 return clang::getFormalLinkage(getLinkageInternal());
364 }
365
366 /// \brief True if this decl has external linkage.
367 bool hasExternalFormalLinkage() const {
368 return isExternalFormalLinkage(getLinkageInternal());
369 }
370
371 bool isExternallyVisible() const {
372 return clang::isExternallyVisible(getLinkageInternal());
373 }
374
375 /// Determine whether this declaration can be redeclared in a
376 /// different translation unit.
377 bool isExternallyDeclarable() const {
378 return isExternallyVisible() && !getOwningModuleForLinkage();
379 }
380
381 /// \brief Determines the visibility of this entity.
382 Visibility getVisibility() const {
383 return getLinkageAndVisibility().getVisibility();
384 }
385
386 /// \brief Determines the linkage and visibility of this entity.
387 LinkageInfo getLinkageAndVisibility() const;
388
389 /// Kinds of explicit visibility.
390 enum ExplicitVisibilityKind {
391 /// Do an LV computation for, ultimately, a type.
392 /// Visibility may be restricted by type visibility settings and
393 /// the visibility of template arguments.
394 VisibilityForType,
395
396 /// Do an LV computation for, ultimately, a non-type declaration.
397 /// Visibility may be restricted by value visibility settings and
398 /// the visibility of template arguments.
399 VisibilityForValue
400 };
401
402 /// \brief If visibility was explicitly specified for this
403 /// declaration, return that visibility.
404 Optional<Visibility>
405 getExplicitVisibility(ExplicitVisibilityKind kind) const;
406
407 /// \brief True if the computed linkage is valid. Used for consistency
408 /// checking. Should always return true.
409 bool isLinkageValid() const;
410
411 /// \brief True if something has required us to compute the linkage
412 /// of this declaration.
413 ///
414 /// Language features which can retroactively change linkage (like a
415 /// typedef name for linkage purposes) may need to consider this,
416 /// but hopefully only in transitory ways during parsing.
417 bool hasLinkageBeenComputed() const {
418 return hasCachedLinkage();
419 }
420
421 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
422 /// the underlying named decl.
423 NamedDecl *getUnderlyingDecl() {
424 // Fast-path the common case.
425 if (this->getKind() != UsingShadow &&
426 this->getKind() != ConstructorUsingShadow &&
427 this->getKind() != ObjCCompatibleAlias &&
428 this->getKind() != NamespaceAlias)
429 return this;
430
431 return getUnderlyingDeclImpl();
432 }
433 const NamedDecl *getUnderlyingDecl() const {
434 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
435 }
436
437 NamedDecl *getMostRecentDecl() {
438 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
439 }
440 const NamedDecl *getMostRecentDecl() const {
441 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
442 }
443
444 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
445
446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
447 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
448};
449
450inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
451 ND.printName(OS);
452 return OS;
453}
454
455/// LabelDecl - Represents the declaration of a label. Labels also have a
456/// corresponding LabelStmt, which indicates the position that the label was
457/// defined at. For normal labels, the location of the decl is the same as the
458/// location of the statement. For GNU local labels (__label__), the decl
459/// location is where the __label__ is.
460class LabelDecl : public NamedDecl {
461 LabelStmt *TheStmt;
462 StringRef MSAsmName;
463 bool MSAsmNameResolved = false;
464
465 /// LocStart - For normal labels, this is the same as the main declaration
466 /// label, i.e., the location of the identifier; for GNU local labels,
467 /// this is the location of the __label__ keyword.
468 SourceLocation LocStart;
469
470 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
471 LabelStmt *S, SourceLocation StartL)
472 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
473
474 void anchor() override;
475
476public:
477 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
478 SourceLocation IdentL, IdentifierInfo *II);
479 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
480 SourceLocation IdentL, IdentifierInfo *II,
481 SourceLocation GnuLabelL);
482 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
483
484 LabelStmt *getStmt() const { return TheStmt; }
485 void setStmt(LabelStmt *T) { TheStmt = T; }
486
487 bool isGnuLocal() const { return LocStart != getLocation(); }
488 void setLocStart(SourceLocation L) { LocStart = L; }
489
490 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
491 return SourceRange(LocStart, getLocation());
492 }
493
494 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
495 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
496 void setMSAsmLabel(StringRef Name);
497 StringRef getMSAsmLabel() const { return MSAsmName; }
498 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
499
500 // Implement isa/cast/dyncast/etc.
501 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
502 static bool classofKind(Kind K) { return K == Label; }
503};
504
505/// NamespaceDecl - Represent a C++ namespace.
506class NamespaceDecl : public NamedDecl, public DeclContext,
507 public Redeclarable<NamespaceDecl>
508{
509 /// LocStart - The starting location of the source range, pointing
510 /// to either the namespace or the inline keyword.
511 SourceLocation LocStart;
512
513 /// RBraceLoc - The ending location of the source range.
514 SourceLocation RBraceLoc;
515
516 /// \brief A pointer to either the anonymous namespace that lives just inside
517 /// this namespace or to the first namespace in the chain (the latter case
518 /// only when this is not the first in the chain), along with a
519 /// boolean value indicating whether this is an inline namespace.
520 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
521
522 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
523 SourceLocation StartLoc, SourceLocation IdLoc,
524 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
525
526 using redeclarable_base = Redeclarable<NamespaceDecl>;
527
528 NamespaceDecl *getNextRedeclarationImpl() override;
529 NamespaceDecl *getPreviousDeclImpl() override;
530 NamespaceDecl *getMostRecentDeclImpl() override;
531
532public:
533 friend class ASTDeclReader;
534 friend class ASTDeclWriter;
535
536 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
537 bool Inline, SourceLocation StartLoc,
538 SourceLocation IdLoc, IdentifierInfo *Id,
539 NamespaceDecl *PrevDecl);
540
541 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
542
543 using redecl_range = redeclarable_base::redecl_range;
544 using redecl_iterator = redeclarable_base::redecl_iterator;
545
546 using redeclarable_base::redecls_begin;
547 using redeclarable_base::redecls_end;
548 using redeclarable_base::redecls;
549 using redeclarable_base::getPreviousDecl;
550 using redeclarable_base::getMostRecentDecl;
551 using redeclarable_base::isFirstDecl;
552
553 /// \brief Returns true if this is an anonymous namespace declaration.
554 ///
555 /// For example:
556 /// \code
557 /// namespace {
558 /// ...
559 /// };
560 /// \endcode
561 /// q.v. C++ [namespace.unnamed]
562 bool isAnonymousNamespace() const {
563 return !getIdentifier();
564 }
565
566 /// \brief Returns true if this is an inline namespace declaration.
567 bool isInline() const {
568 return AnonOrFirstNamespaceAndInline.getInt();
569 }
570
571 /// \brief Set whether this is an inline namespace declaration.
572 void setInline(bool Inline) {
573 AnonOrFirstNamespaceAndInline.setInt(Inline);
574 }
575
576 /// \brief Get the original (first) namespace declaration.
577 NamespaceDecl *getOriginalNamespace();
578
579 /// \brief Get the original (first) namespace declaration.
580 const NamespaceDecl *getOriginalNamespace() const;
581
582 /// \brief Return true if this declaration is an original (first) declaration
583 /// of the namespace. This is false for non-original (subsequent) namespace
584 /// declarations and anonymous namespaces.
585 bool isOriginalNamespace() const;
586
587 /// \brief Retrieve the anonymous namespace nested inside this namespace,
588 /// if any.
589 NamespaceDecl *getAnonymousNamespace() const {
590 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
591 }
592
593 void setAnonymousNamespace(NamespaceDecl *D) {
594 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
595 }
596
597 /// Retrieves the canonical declaration of this namespace.
598 NamespaceDecl *getCanonicalDecl() override {
599 return getOriginalNamespace();
600 }
601 const NamespaceDecl *getCanonicalDecl() const {
602 return getOriginalNamespace();
603 }
604
605 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
606 return SourceRange(LocStart, RBraceLoc);
607 }
608
609 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
610 SourceLocation getRBraceLoc() const { return RBraceLoc; }
611 void setLocStart(SourceLocation L) { LocStart = L; }
612 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
613
614 // Implement isa/cast/dyncast/etc.
615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
616 static bool classofKind(Kind K) { return K == Namespace; }
617 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
618 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
619 }
620 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
621 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
622 }
623};
624
625/// ValueDecl - Represent the declaration of a variable (in which case it is
626/// an lvalue) a function (in which case it is a function designator) or
627/// an enum constant.
628class ValueDecl : public NamedDecl {
629 QualType DeclType;
630
631 void anchor() override;
632
633protected:
634 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
635 DeclarationName N, QualType T)
636 : NamedDecl(DK, DC, L, N), DeclType(T) {}
637
638public:
639 QualType getType() const { return DeclType; }
640 void setType(QualType newType) { DeclType = newType; }
641
642 /// \brief Determine whether this symbol is weakly-imported,
643 /// or declared with the weak or weak-ref attr.
644 bool isWeak() const;
645
646 // Implement isa/cast/dyncast/etc.
647 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
648 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
649};
650
651/// QualifierInfo - A struct with extended info about a syntactic
652/// name qualifier, to be used for the case of out-of-line declarations.
653struct QualifierInfo {
654 NestedNameSpecifierLoc QualifierLoc;
655
656 /// NumTemplParamLists - The number of "outer" template parameter lists.
657 /// The count includes all of the template parameter lists that were matched
658 /// against the template-ids occurring into the NNS and possibly (in the
659 /// case of an explicit specialization) a final "template <>".
660 unsigned NumTemplParamLists = 0;
661
662 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
663 /// containing pointers to the "outer" template parameter lists.
664 /// It includes all of the template parameter lists that were matched
665 /// against the template-ids occurring into the NNS and possibly (in the
666 /// case of an explicit specialization) a final "template <>".
667 TemplateParameterList** TemplParamLists = nullptr;
668
669 QualifierInfo() = default;
670 QualifierInfo(const QualifierInfo &) = delete;
671 QualifierInfo& operator=(const QualifierInfo &) = delete;
672
673 /// setTemplateParameterListsInfo - Sets info about "outer" template
674 /// parameter lists.
675 void setTemplateParameterListsInfo(ASTContext &Context,
676 ArrayRef<TemplateParameterList *> TPLists);
677};
678
679/// \brief Represents a ValueDecl that came out of a declarator.
680/// Contains type source information through TypeSourceInfo.
681class DeclaratorDecl : public ValueDecl {
682 // A struct representing both a TInfo and a syntactic qualifier,
683 // to be used for the (uncommon) case of out-of-line declarations.
684 struct ExtInfo : public QualifierInfo {
685 TypeSourceInfo *TInfo;
686 };
687
688 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
689
690 /// InnerLocStart - The start of the source range for this declaration,
691 /// ignoring outer template declarations.
692 SourceLocation InnerLocStart;
693
694 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
695 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
696 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
697
698protected:
699 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
700 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
701 SourceLocation StartL)
702 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
703
704public:
705 friend class ASTDeclReader;
706 friend class ASTDeclWriter;
707
708 TypeSourceInfo *getTypeSourceInfo() const {
709 return hasExtInfo()
710 ? getExtInfo()->TInfo
711 : DeclInfo.get<TypeSourceInfo*>();
712 }
713
714 void setTypeSourceInfo(TypeSourceInfo *TI) {
715 if (hasExtInfo())
716 getExtInfo()->TInfo = TI;
717 else
718 DeclInfo = TI;
719 }
720
721 /// getInnerLocStart - Return SourceLocation representing start of source
722 /// range ignoring outer template declarations.
723 SourceLocation getInnerLocStart() const { return InnerLocStart; }
724 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
725
726 /// getOuterLocStart - Return SourceLocation representing start of source
727 /// range taking into account any outer template declarations.
728 SourceLocation getOuterLocStart() const;
729
730 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
731
732 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
733 return getOuterLocStart();
734 }
735
736 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
737 /// declaration, if it was present in the source.
738 NestedNameSpecifier *getQualifier() const {
739 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
740 : nullptr;
741 }
742
743 /// \brief Retrieve the nested-name-specifier (with source-location
744 /// information) that qualifies the name of this declaration, if it was
745 /// present in the source.
746 NestedNameSpecifierLoc getQualifierLoc() const {
747 return hasExtInfo() ? getExtInfo()->QualifierLoc
748 : NestedNameSpecifierLoc();
749 }
750
751 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
752
753 unsigned getNumTemplateParameterLists() const {
754 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
755 }
756
757 TemplateParameterList *getTemplateParameterList(unsigned index) const {
758 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759 return getExtInfo()->TemplParamLists[index];
760 }
761
762 void setTemplateParameterListsInfo(ASTContext &Context,
763 ArrayRef<TemplateParameterList *> TPLists);
764
765 SourceLocation getTypeSpecStartLoc() const;
766
767 // Implement isa/cast/dyncast/etc.
768 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
769 static bool classofKind(Kind K) {
770 return K >= firstDeclarator && K <= lastDeclarator;
771 }
772};
773
774/// \brief Structure used to store a statement, the constant value to
775/// which it was evaluated (if any), and whether or not the statement
776/// is an integral constant expression (if known).
777struct EvaluatedStmt {
778 /// \brief Whether this statement was already evaluated.
779 bool WasEvaluated : 1;
780
781 /// \brief Whether this statement is being evaluated.
782 bool IsEvaluating : 1;
783
784 /// \brief Whether we already checked whether this statement was an
785 /// integral constant expression.
786 bool CheckedICE : 1;
787
788 /// \brief Whether we are checking whether this statement is an
789 /// integral constant expression.
790 bool CheckingICE : 1;
791
792 /// \brief Whether this statement is an integral constant expression,
793 /// or in C++11, whether the statement is a constant expression. Only
794 /// valid if CheckedICE is true.
795 bool IsICE : 1;
796
797 Stmt *Value;
798 APValue Evaluated;
799
800 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
801 CheckingICE(false), IsICE(false) {}
802
803};
804
805/// VarDecl - An instance of this class is created to represent a variable
806/// declaration or definition.
807class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
808public:
809 /// \brief Initialization styles.
810 enum InitializationStyle {
811 /// C-style initialization with assignment
812 CInit,
813
814 /// Call-style initialization (C++98)
815 CallInit,
816
817 /// Direct list-initialization (C++11)
818 ListInit
819 };
820
821 /// \brief Kinds of thread-local storage.
822 enum TLSKind {
823 /// Not a TLS variable.
824 TLS_None,
825
826 /// TLS with a known-constant initializer.
827 TLS_Static,
828
829 /// TLS with a dynamic initializer.
830 TLS_Dynamic
831 };
832
833 /// getStorageClassSpecifierString - Return the string used to
834 /// specify the storage class \p SC.
835 ///
836 /// It is illegal to call this function with SC == None.
837 static const char *getStorageClassSpecifierString(StorageClass SC);
838
839protected:
840 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
841 // have allocated the auxiliary struct of information there.
842 //
843 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
844 // this as *many* VarDecls are ParmVarDecls that don't have default
845 // arguments. We could save some space by moving this pointer union to be
846 // allocated in trailing space when necessary.
847 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
848
849 /// \brief The initializer for this variable or, for a ParmVarDecl, the
850 /// C++ default argument.
851 mutable InitType Init;
852
853private:
854 friend class ASTDeclReader;
855 friend class ASTNodeImporter;
856 friend class StmtIteratorBase;
857
858 class VarDeclBitfields {
859 friend class ASTDeclReader;
860 friend class VarDecl;
861
862 unsigned SClass : 3;
863 unsigned TSCSpec : 2;
864 unsigned InitStyle : 2;
865 };
866 enum { NumVarDeclBits = 7 };
867
868protected:
869 enum { NumParameterIndexBits = 8 };
870
871 enum DefaultArgKind {
872 DAK_None,
873 DAK_Unparsed,
874 DAK_Uninstantiated,
875 DAK_Normal
876 };
877
878 class ParmVarDeclBitfields {
879 friend class ASTDeclReader;
880 friend class ParmVarDecl;
881
882 unsigned : NumVarDeclBits;
883
884 /// Whether this parameter inherits a default argument from a
885 /// prior declaration.
886 unsigned HasInheritedDefaultArg : 1;
887
888 /// Describes the kind of default argument for this parameter. By default
889 /// this is none. If this is normal, then the default argument is stored in
890 /// the \c VarDecl initializer expression unless we were unable to parse
891 /// (even an invalid) expression for the default argument.
892 unsigned DefaultArgKind : 2;
893
894 /// Whether this parameter undergoes K&R argument promotion.
895 unsigned IsKNRPromoted : 1;
896
897 /// Whether this parameter is an ObjC method parameter or not.
898 unsigned IsObjCMethodParam : 1;
899
900 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
901 /// Otherwise, the number of function parameter scopes enclosing
902 /// the function parameter scope in which this parameter was
903 /// declared.
904 unsigned ScopeDepthOrObjCQuals : 7;
905
906 /// The number of parameters preceding this parameter in the
907 /// function parameter scope in which it was declared.
908 unsigned ParameterIndex : NumParameterIndexBits;
909 };
910
911 class NonParmVarDeclBitfields {
912 friend class ASTDeclReader;
913 friend class ImplicitParamDecl;
914 friend class VarDecl;
915
916 unsigned : NumVarDeclBits;
917
918 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
919 /// \brief Whether this variable is a definition which was demoted due to
920 /// module merge.
921 unsigned IsThisDeclarationADemotedDefinition : 1;
922
923 /// \brief Whether this variable is the exception variable in a C++ catch
924 /// or an Objective-C @catch statement.
925 unsigned ExceptionVar : 1;
926
927 /// \brief Whether this local variable could be allocated in the return
928 /// slot of its function, enabling the named return value optimization
929 /// (NRVO).
930 unsigned NRVOVariable : 1;
931
932 /// \brief Whether this variable is the for-range-declaration in a C++0x
933 /// for-range statement.
934 unsigned CXXForRangeDecl : 1;
935
936 /// \brief Whether this variable is an ARC pseudo-__strong
937 /// variable; see isARCPseudoStrong() for details.
938 unsigned ARCPseudoStrong : 1;
939
940 /// \brief Whether this variable is (C++1z) inline.
941 unsigned IsInline : 1;
942
943 /// \brief Whether this variable has (C++1z) inline explicitly specified.
944 unsigned IsInlineSpecified : 1;
945
946 /// \brief Whether this variable is (C++0x) constexpr.
947 unsigned IsConstexpr : 1;
948
949 /// \brief Whether this variable is the implicit variable for a lambda
950 /// init-capture.
951 unsigned IsInitCapture : 1;
952
953 /// \brief Whether this local extern variable's previous declaration was
954 /// declared in the same block scope. This controls whether we should merge
955 /// the type of this declaration with its previous declaration.
956 unsigned PreviousDeclInSameBlockScope : 1;
957
958 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
959 /// something else.
960 unsigned ImplicitParamKind : 3;
961 };
962
963 union {
964 unsigned AllBits;
965 VarDeclBitfields VarDeclBits;
966 ParmVarDeclBitfields ParmVarDeclBits;
967 NonParmVarDeclBitfields NonParmVarDeclBits;
968 };
969
970 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
971 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
972 TypeSourceInfo *TInfo, StorageClass SC);
973
974 using redeclarable_base = Redeclarable<VarDecl>;
975
976 VarDecl *getNextRedeclarationImpl() override {
977 return getNextRedeclaration();
978 }
979
980 VarDecl *getPreviousDeclImpl() override {
981 return getPreviousDecl();
982 }
983
984 VarDecl *getMostRecentDeclImpl() override {
985 return getMostRecentDecl();
986 }
987
988public:
989 using redecl_range = redeclarable_base::redecl_range;
990 using redecl_iterator = redeclarable_base::redecl_iterator;
991
992 using redeclarable_base::redecls_begin;
993 using redeclarable_base::redecls_end;
994 using redeclarable_base::redecls;
995 using redeclarable_base::getPreviousDecl;
996 using redeclarable_base::getMostRecentDecl;
997 using redeclarable_base::isFirstDecl;
998
999 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1000 SourceLocation StartLoc, SourceLocation IdLoc,
1001 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1002 StorageClass S);
1003
1004 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1005
1006 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1007
1008 /// \brief Returns the storage class as written in the source. For the
1009 /// computed linkage of symbol, see getLinkage.
1010 StorageClass getStorageClass() const {
1011 return (StorageClass) VarDeclBits.SClass;
1012 }
1013 void setStorageClass(StorageClass SC);
1014
1015 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1016 VarDeclBits.TSCSpec = TSC;
1017 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018 }
1019 ThreadStorageClassSpecifier getTSCSpec() const {
1020 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1021 }
1022 TLSKind getTLSKind() const;
1023
1024 /// hasLocalStorage - Returns true if a variable with function scope
1025 /// is a non-static local variable.
1026 bool hasLocalStorage() const {
1027 if (getStorageClass() == SC_None) {
1028 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1029 // used to describe variables allocated in global memory and which are
1030 // accessed inside a kernel(s) as read-only variables. As such, variables
1031 // in constant address space cannot have local storage.
1032 if (getType().getAddressSpace() == LangAS::opencl_constant)
1033 return false;
1034 // Second check is for C++11 [dcl.stc]p4.
1035 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1036 }
1037
1038 // Global Named Register (GNU extension)
1039 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1040 return false;
1041
1042 // Return true for: Auto, Register.
1043 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1044
1045 return getStorageClass() >= SC_Auto;
1046 }
1047
1048 /// isStaticLocal - Returns true if a variable with function scope is a
1049 /// static local variable.
1050 bool isStaticLocal() const {
1051 return (getStorageClass() == SC_Static ||
1052 // C++11 [dcl.stc]p4
1053 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1054 && !isFileVarDecl();
1055 }
1056
1057 /// \brief Returns true if a variable has extern or __private_extern__
1058 /// storage.
1059 bool hasExternalStorage() const {
1060 return getStorageClass() == SC_Extern ||
1061 getStorageClass() == SC_PrivateExtern;
1062 }
1063
1064 /// \brief Returns true for all variables that do not have local storage.
1065 ///
1066 /// This includes all global variables as well as static variables declared
1067 /// within a function.
1068 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1069
1070 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1071 StorageDuration getStorageDuration() const {
1072 return hasLocalStorage() ? SD_Automatic :
1073 getTSCSpec() ? SD_Thread : SD_Static;
1074 }
1075
1076 /// \brief Compute the language linkage.
1077 LanguageLinkage getLanguageLinkage() const;
1078
1079 /// \brief Determines whether this variable is a variable with
1080 /// external, C linkage.
1081 bool isExternC() const;
1082
1083 /// \brief Determines whether this variable's context is, or is nested within,
1084 /// a C++ extern "C" linkage spec.
1085 bool isInExternCContext() const;
1086
1087 /// \brief Determines whether this variable's context is, or is nested within,
1088 /// a C++ extern "C++" linkage spec.
1089 bool isInExternCXXContext() const;
1090
1091 /// isLocalVarDecl - Returns true for local variable declarations
1092 /// other than parameters. Note that this includes static variables
1093 /// inside of functions. It also includes variables inside blocks.
1094 ///
1095 /// void foo() { int x; static int y; extern int z; }
1096 bool isLocalVarDecl() const {
1097 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1098 return false;
1099 if (const DeclContext *DC = getLexicalDeclContext())
1100 return DC->getRedeclContext()->isFunctionOrMethod();
1101 return false;
1102 }
1103
1104 /// \brief Similar to isLocalVarDecl but also includes parameters.
1105 bool isLocalVarDeclOrParm() const {
1106 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1107 }
1108
1109 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1110 /// excludes variables declared in blocks.
1111 bool isFunctionOrMethodVarDecl() const {
1112 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1113 return false;
1114 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1115 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1116 }
1117
1118 /// \brief Determines whether this is a static data member.
1119 ///
1120 /// This will only be true in C++, and applies to, e.g., the
1121 /// variable 'x' in:
1122 /// \code
1123 /// struct S {
1124 /// static int x;
1125 /// };
1126 /// \endcode
1127 bool isStaticDataMember() const {
1128 // If it wasn't static, it would be a FieldDecl.
1129 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1130 }
1131
1132 VarDecl *getCanonicalDecl() override;
1133 const VarDecl *getCanonicalDecl() const {
1134 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1135 }
1136
1137 enum DefinitionKind {
1138 /// This declaration is only a declaration.
1139 DeclarationOnly,
1140
1141 /// This declaration is a tentative definition.
1142 TentativeDefinition,
1143
1144 /// This declaration is definitely a definition.
1145 Definition
1146 };
1147
1148 /// \brief Check whether this declaration is a definition. If this could be
1149 /// a tentative definition (in C), don't check whether there's an overriding
1150 /// definition.
1151 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1152 DefinitionKind isThisDeclarationADefinition() const {
1153 return isThisDeclarationADefinition(getASTContext());
1154 }
1155
1156 /// \brief Check whether this variable is defined in this
1157 /// translation unit.
1158 DefinitionKind hasDefinition(ASTContext &) const;
1159 DefinitionKind hasDefinition() const {
1160 return hasDefinition(getASTContext());
1161 }
1162
1163 /// \brief Get the tentative definition that acts as the real definition in
1164 /// a TU. Returns null if there is a proper definition available.
1165 VarDecl *getActingDefinition();
1166 const VarDecl *getActingDefinition() const {
1167 return const_cast<VarDecl*>(this)->getActingDefinition();
1168 }
1169
1170 /// \brief Get the real (not just tentative) definition for this declaration.
1171 VarDecl *getDefinition(ASTContext &);
1172 const VarDecl *getDefinition(ASTContext &C) const {
1173 return const_cast<VarDecl*>(this)->getDefinition(C);
1174 }
1175 VarDecl *getDefinition() {
1176 return getDefinition(getASTContext());
1177 }
1178 const VarDecl *getDefinition() const {
1179 return const_cast<VarDecl*>(this)->getDefinition();
1180 }
1181
1182 /// \brief Determine whether this is or was instantiated from an out-of-line
1183 /// definition of a static data member.
1184 bool isOutOfLine() const override;
1185
1186 /// isFileVarDecl - Returns true for file scoped variable declaration.
1187 bool isFileVarDecl() const {
1188 Kind K = getKind();
1189 if (K == ParmVar || K == ImplicitParam)
1190 return false;
1191
1192 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1193 return true;
1194
1195 if (isStaticDataMember())
1196 return true;
1197
1198 return false;
1199 }
1200
1201 /// getAnyInitializer - Get the initializer for this variable, no matter which
1202 /// declaration it is attached to.
1203 const Expr *getAnyInitializer() const {
1204 const VarDecl *D;
1205 return getAnyInitializer(D);
1206 }
1207
1208 /// getAnyInitializer - Get the initializer for this variable, no matter which
1209 /// declaration it is attached to. Also get that declaration.
1210 const Expr *getAnyInitializer(const VarDecl *&D) const;
1211
1212 bool hasInit() const;
1213 const Expr *getInit() const {
1214 return const_cast<VarDecl *>(this)->getInit();
1215 }
1216 Expr *getInit();
1217
1218 /// \brief Retrieve the address of the initializer expression.
1219 Stmt **getInitAddress();
1220
1221 void setInit(Expr *I);
1222
1223 /// \brief Determine whether this variable's value can be used in a
1224 /// constant expression, according to the relevant language standard.
1225 /// This only checks properties of the declaration, and does not check
1226 /// whether the initializer is in fact a constant expression.
1227 bool isUsableInConstantExpressions(ASTContext &C) const;
1228
1229 EvaluatedStmt *ensureEvaluatedStmt() const;
1230
1231 /// \brief Attempt to evaluate the value of the initializer attached to this
1232 /// declaration, and produce notes explaining why it cannot be evaluated or is
1233 /// not a constant expression. Returns a pointer to the value if evaluation
1234 /// succeeded, 0 otherwise.
1235 APValue *evaluateValue() const;
1236 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1237
1238 /// \brief Return the already-evaluated value of this variable's
1239 /// initializer, or NULL if the value is not yet known. Returns pointer
1240 /// to untyped APValue if the value could not be evaluated.
1241 APValue *getEvaluatedValue() const;
1242
1243 /// \brief Determines whether it is already known whether the
1244 /// initializer is an integral constant expression or not.
1245 bool isInitKnownICE() const;
1246
1247 /// \brief Determines whether the initializer is an integral constant
1248 /// expression, or in C++11, whether the initializer is a constant
1249 /// expression.
1250 ///
1251 /// \pre isInitKnownICE()
1252 bool isInitICE() const;
1253
1254 /// \brief Determine whether the value of the initializer attached to this
1255 /// declaration is an integral constant expression.
1256 bool checkInitIsICE() const;
1257
1258 void setInitStyle(InitializationStyle Style) {
1259 VarDeclBits.InitStyle = Style;
1260 }
1261
1262 /// \brief The style of initialization for this declaration.
1263 ///
1264 /// C-style initialization is "int x = 1;". Call-style initialization is
1265 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1266 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1267 /// expression for class types. List-style initialization is C++11 syntax,
1268 /// e.g. "int x{1};". Clients can distinguish between different forms of
1269 /// initialization by checking this value. In particular, "int x = {1};" is
1270 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1271 /// Init expression in all three cases is an InitListExpr.
1272 InitializationStyle getInitStyle() const {
1273 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1274 }
1275
1276 /// \brief Whether the initializer is a direct-initializer (list or call).
1277 bool isDirectInit() const {
1278 return getInitStyle() != CInit;
1279 }
1280
1281 /// \brief If this definition should pretend to be a declaration.
1282 bool isThisDeclarationADemotedDefinition() const {
1283 return isa<ParmVarDecl>(this) ? false :
1284 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1285 }
1286
1287 /// \brief This is a definition which should be demoted to a declaration.
1288 ///
1289 /// In some cases (mostly module merging) we can end up with two visible
1290 /// definitions one of which needs to be demoted to a declaration to keep
1291 /// the AST invariants.
1292 void demoteThisDefinitionToDeclaration() {
1293 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1293, __extension__ __PRETTY_FUNCTION__))
;
1294 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1296 }
1297
1298 /// \brief Determine whether this variable is the exception variable in a
1299 /// C++ catch statememt or an Objective-C \@catch statement.
1300 bool isExceptionVariable() const {
1301 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1302 }
1303 void setExceptionVariable(bool EV) {
1304 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1304, __extension__ __PRETTY_FUNCTION__))
;
1305 NonParmVarDeclBits.ExceptionVar = EV;
1306 }
1307
1308 /// \brief Determine whether this local variable can be used with the named
1309 /// return value optimization (NRVO).
1310 ///
1311 /// The named return value optimization (NRVO) works by marking certain
1312 /// non-volatile local variables of class type as NRVO objects. These
1313 /// locals can be allocated within the return slot of their containing
1314 /// function, in which case there is no need to copy the object to the
1315 /// return slot when returning from the function. Within the function body,
1316 /// each return that returns the NRVO object will have this variable as its
1317 /// NRVO candidate.
1318 bool isNRVOVariable() const {
1319 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1320 }
1321 void setNRVOVariable(bool NRVO) {
1322 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1322, __extension__ __PRETTY_FUNCTION__))
;
1323 NonParmVarDeclBits.NRVOVariable = NRVO;
1324 }
1325
1326 /// \brief Determine whether this variable is the for-range-declaration in
1327 /// a C++0x for-range statement.
1328 bool isCXXForRangeDecl() const {
1329 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1330 }
1331 void setCXXForRangeDecl(bool FRD) {
1332 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1332, __extension__ __PRETTY_FUNCTION__))
;
1333 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1334 }
1335
1336 /// \brief Determine whether this variable is an ARC pseudo-__strong
1337 /// variable. A pseudo-__strong variable has a __strong-qualified
1338 /// type but does not actually retain the object written into it.
1339 /// Generally such variables are also 'const' for safety.
1340 bool isARCPseudoStrong() const {
1341 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1342 }
1343 void setARCPseudoStrong(bool ps) {
1344 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1344, __extension__ __PRETTY_FUNCTION__))
;
1345 NonParmVarDeclBits.ARCPseudoStrong = ps;
1346 }
1347
1348 /// Whether this variable is (C++1z) inline.
1349 bool isInline() const {
1350 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1351 }
1352 bool isInlineSpecified() const {
1353 return isa<ParmVarDecl>(this) ? false
1354 : NonParmVarDeclBits.IsInlineSpecified;
1355 }
1356 void setInlineSpecified() {
1357 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1357, __extension__ __PRETTY_FUNCTION__))
;
1358 NonParmVarDeclBits.IsInline = true;
1359 NonParmVarDeclBits.IsInlineSpecified = true;
1360 }
1361 void setImplicitlyInline() {
1362 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1362, __extension__ __PRETTY_FUNCTION__))
;
1363 NonParmVarDeclBits.IsInline = true;
1364 }
1365
1366 /// Whether this variable is (C++11) constexpr.
1367 bool isConstexpr() const {
1368 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1369 }
1370 void setConstexpr(bool IC) {
1371 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1371, __extension__ __PRETTY_FUNCTION__))
;
1372 NonParmVarDeclBits.IsConstexpr = IC;
1373 }
1374
1375 /// Whether this variable is the implicit variable for a lambda init-capture.
1376 bool isInitCapture() const {
1377 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1378 }
1379 void setInitCapture(bool IC) {
1380 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1380, __extension__ __PRETTY_FUNCTION__))
;
1381 NonParmVarDeclBits.IsInitCapture = IC;
1382 }
1383
1384 /// Whether this local extern variable declaration's previous declaration
1385 /// was declared in the same block scope. Only correct in C++.
1386 bool isPreviousDeclInSameBlockScope() const {
1387 return isa<ParmVarDecl>(this)
1388 ? false
1389 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1390 }
1391 void setPreviousDeclInSameBlockScope(bool Same) {
1392 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1392, __extension__ __PRETTY_FUNCTION__))
;
1393 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1394 }
1395
1396 /// \brief Retrieve the variable declaration from which this variable could
1397 /// be instantiated, if it is an instantiation (rather than a non-template).
1398 VarDecl *getTemplateInstantiationPattern() const;
1399
1400 /// \brief If this variable is an instantiated static data member of a
1401 /// class template specialization, returns the templated static data member
1402 /// from which it was instantiated.
1403 VarDecl *getInstantiatedFromStaticDataMember() const;
1404
1405 /// \brief If this variable is an instantiation of a variable template or a
1406 /// static data member of a class template, determine what kind of
1407 /// template specialization or instantiation this is.
1408 TemplateSpecializationKind getTemplateSpecializationKind() const;
1409
1410 /// \brief If this variable is an instantiation of a variable template or a
1411 /// static data member of a class template, determine its point of
1412 /// instantiation.
1413 SourceLocation getPointOfInstantiation() const;
1414
1415 /// \brief If this variable is an instantiation of a static data member of a
1416 /// class template specialization, retrieves the member specialization
1417 /// information.
1418 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1419
1420 /// \brief For a static data member that was instantiated from a static
1421 /// data member of a class template, set the template specialiation kind.
1422 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1423 SourceLocation PointOfInstantiation = SourceLocation());
1424
1425 /// \brief Specify that this variable is an instantiation of the
1426 /// static data member VD.
1427 void setInstantiationOfStaticDataMember(VarDecl *VD,
1428 TemplateSpecializationKind TSK);
1429
1430 /// \brief Retrieves the variable template that is described by this
1431 /// variable declaration.
1432 ///
1433 /// Every variable template is represented as a VarTemplateDecl and a
1434 /// VarDecl. The former contains template properties (such as
1435 /// the template parameter lists) while the latter contains the
1436 /// actual description of the template's
1437 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1438 /// VarDecl that from a VarTemplateDecl, while
1439 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1440 /// a VarDecl.
1441 VarTemplateDecl *getDescribedVarTemplate() const;
1442
1443 void setDescribedVarTemplate(VarTemplateDecl *Template);
1444
1445 // Implement isa/cast/dyncast/etc.
1446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1447 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1448};
1449
1450class ImplicitParamDecl : public VarDecl {
1451 void anchor() override;
1452
1453public:
1454 /// Defines the kind of the implicit parameter: is this an implicit parameter
1455 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1456 /// context or something else.
1457 enum ImplicitParamKind : unsigned {
1458 /// Parameter for Objective-C 'self' argument
1459 ObjCSelf,
1460
1461 /// Parameter for Objective-C '_cmd' argument
1462 ObjCCmd,
1463
1464 /// Parameter for C++ 'this' argument
1465 CXXThis,
1466
1467 /// Parameter for C++ virtual table pointers
1468 CXXVTT,
1469
1470 /// Parameter for captured context
1471 CapturedContext,
1472
1473 /// Other implicit parameter
1474 Other,
1475 };
1476
1477 /// Create implicit parameter.
1478 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1479 SourceLocation IdLoc, IdentifierInfo *Id,
1480 QualType T, ImplicitParamKind ParamKind);
1481 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1482 ImplicitParamKind ParamKind);
1483
1484 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1485
1486 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1487 IdentifierInfo *Id, QualType Type,
1488 ImplicitParamKind ParamKind)
1489 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1490 /*TInfo=*/nullptr, SC_None) {
1491 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1492 setImplicit();
1493 }
1494
1495 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1496 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1497 SourceLocation(), /*Id=*/nullptr, Type,
1498 /*TInfo=*/nullptr, SC_None) {
1499 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1500 setImplicit();
1501 }
1502
1503 /// Returns the implicit parameter kind.
1504 ImplicitParamKind getParameterKind() const {
1505 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1506 }
1507
1508 // Implement isa/cast/dyncast/etc.
1509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1510 static bool classofKind(Kind K) { return K == ImplicitParam; }
1511};
1512
1513/// ParmVarDecl - Represents a parameter to a function.
1514class ParmVarDecl : public VarDecl {
1515public:
1516 enum { MaxFunctionScopeDepth = 255 };
1517 enum { MaxFunctionScopeIndex = 255 };
1518
1519protected:
1520 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1521 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1522 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1523 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1524 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1524, __extension__ __PRETTY_FUNCTION__))
;
1525 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1525, __extension__ __PRETTY_FUNCTION__))
;
1526 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1526, __extension__ __PRETTY_FUNCTION__))
;
1527 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1527, __extension__ __PRETTY_FUNCTION__))
;
1528 setDefaultArg(DefArg);
1529 }
1530
1531public:
1532 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1533 SourceLocation StartLoc,
1534 SourceLocation IdLoc, IdentifierInfo *Id,
1535 QualType T, TypeSourceInfo *TInfo,
1536 StorageClass S, Expr *DefArg);
1537
1538 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1539
1540 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1541
1542 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1543 ParmVarDeclBits.IsObjCMethodParam = true;
1544 setParameterIndex(parameterIndex);
1545 }
1546
1547 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1548 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1548, __extension__ __PRETTY_FUNCTION__))
;
1549
1550 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1551 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
1552 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
;
1553
1554 setParameterIndex(parameterIndex);
1555 }
1556
1557 bool isObjCMethodParameter() const {
1558 return ParmVarDeclBits.IsObjCMethodParam;
1559 }
1560
1561 unsigned getFunctionScopeDepth() const {
1562 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1563 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1564 }
1565
1566 /// Returns the index of this parameter in its prototype or method scope.
1567 unsigned getFunctionScopeIndex() const {
1568 return getParameterIndex();
1569 }
1570
1571 ObjCDeclQualifier getObjCDeclQualifier() const {
1572 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1573 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1574 }
1575 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1576 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1576, __extension__ __PRETTY_FUNCTION__))
;
1577 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1578 }
1579
1580 /// True if the value passed to this parameter must undergo
1581 /// K&R-style default argument promotion:
1582 ///
1583 /// C99 6.5.2.2.
1584 /// If the expression that denotes the called function has a type
1585 /// that does not include a prototype, the integer promotions are
1586 /// performed on each argument, and arguments that have type float
1587 /// are promoted to double.
1588 bool isKNRPromoted() const {
1589 return ParmVarDeclBits.IsKNRPromoted;
1590 }
1591 void setKNRPromoted(bool promoted) {
1592 ParmVarDeclBits.IsKNRPromoted = promoted;
1593 }
1594
1595 Expr *getDefaultArg();
1596 const Expr *getDefaultArg() const {
1597 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1598 }
1599
1600 void setDefaultArg(Expr *defarg);
1601
1602 /// \brief Retrieve the source range that covers the entire default
1603 /// argument.
1604 SourceRange getDefaultArgRange() const;
1605 void setUninstantiatedDefaultArg(Expr *arg);
1606 Expr *getUninstantiatedDefaultArg();
1607 const Expr *getUninstantiatedDefaultArg() const {
1608 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1609 }
1610
1611 /// hasDefaultArg - Determines whether this parameter has a default argument,
1612 /// either parsed or not.
1613 bool hasDefaultArg() const;
1614
1615 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1616 /// default argument that has not yet been parsed. This will occur
1617 /// during the processing of a C++ class whose member functions have
1618 /// 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 /// setUnparsedDefaultArg - Specify that this parameter has an
1634 /// unparsed default argument. The argument will be replaced with a
1635 /// real default argument via setDefaultArg when the class
1636 /// definition enclosing the function declaration that owns this
1637 /// default argument is completed.
1638 void setUnparsedDefaultArg() {
1639 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1640 }
1641
1642 bool hasInheritedDefaultArg() const {
1643 return ParmVarDeclBits.HasInheritedDefaultArg;
1644 }
1645
1646 void setHasInheritedDefaultArg(bool I = true) {
1647 ParmVarDeclBits.HasInheritedDefaultArg = I;
1648 }
1649
1650 QualType getOriginalType() const;
1651
1652 /// \brief Determine whether this parameter is actually a function
1653 /// parameter pack.
1654 bool isParameterPack() const;
1655
1656 /// setOwningFunction - Sets the function declaration that owns this
1657 /// ParmVarDecl. Since ParmVarDecls are often created before the
1658 /// FunctionDecls that own them, this routine is required to update
1659 /// the DeclContext appropriately.
1660 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1661
1662 // Implement isa/cast/dyncast/etc.
1663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1664 static bool classofKind(Kind K) { return K == ParmVar; }
1665
1666private:
1667 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1668
1669 void setParameterIndex(unsigned parameterIndex) {
1670 if (parameterIndex >= ParameterIndexSentinel) {
1671 setParameterIndexLarge(parameterIndex);
1672 return;
1673 }
1674
1675 ParmVarDeclBits.ParameterIndex = parameterIndex;
1676 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
;
1677 }
1678 unsigned getParameterIndex() const {
1679 unsigned d = ParmVarDeclBits.ParameterIndex;
1680 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1681 }
1682
1683 void setParameterIndexLarge(unsigned parameterIndex);
1684 unsigned getParameterIndexLarge() const;
1685};
1686
1687/// FunctionDecl - An instance of this class is created to represent a
1688/// function declaration or definition.
1689///
1690/// Since a given function can be declared several times in a program,
1691/// there may be several FunctionDecls that correspond to that
1692/// function. Only one of those FunctionDecls will be found when
1693/// traversing the list of declarations in the context of the
1694/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1695/// contains all of the information known about the function. Other,
1696/// previous declarations of the function are available via the
1697/// getPreviousDecl() chain.
1698class FunctionDecl : public DeclaratorDecl, public DeclContext,
1699 public Redeclarable<FunctionDecl> {
1700public:
1701 /// \brief The kind of templated function a FunctionDecl can be.
1702 enum TemplatedKind {
1703 TK_NonTemplate,
1704 TK_FunctionTemplate,
1705 TK_MemberSpecialization,
1706 TK_FunctionTemplateSpecialization,
1707 TK_DependentFunctionTemplateSpecialization
1708 };
1709
1710private:
1711 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1712 /// parameters of this function. This is null if a prototype or if there are
1713 /// no formals.
1714 ParmVarDecl **ParamInfo = nullptr;
1715
1716 LazyDeclStmtPtr Body;
1717
1718 // FIXME: This can be packed into the bitfields in DeclContext.
1719 // NOTE: VC++ packs bitfields poorly if the types differ.
1720 unsigned SClass : 3;
1721 unsigned IsInline : 1;
1722 unsigned IsInlineSpecified : 1;
1723
1724protected:
1725 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1726 // CXXDeductionGuideDecl.
1727 unsigned IsExplicitSpecified : 1;
1728
1729private:
1730 unsigned IsVirtualAsWritten : 1;
1731 unsigned IsPure : 1;
1732 unsigned HasInheritedPrototype : 1;
1733 unsigned HasWrittenPrototype : 1;
1734 unsigned IsDeleted : 1;
1735 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1736 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1737 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1738 unsigned HasImplicitReturnZero : 1;
1739 unsigned IsLateTemplateParsed : 1;
1740 unsigned IsConstexpr : 1;
1741 unsigned InstantiationIsPending : 1;
1742
1743 /// \brief Indicates if the function uses __try.
1744 unsigned UsesSEHTry : 1;
1745
1746 /// \brief Indicates if the function was a definition but its body was
1747 /// skipped.
1748 unsigned HasSkippedBody : 1;
1749
1750 /// Indicates if the function declaration will have a body, once we're done
1751 /// parsing it.
1752 unsigned WillHaveBody : 1;
1753
1754protected:
1755 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1756 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1757 /// int as opposed to adding a single bit to FunctionDecl.
1758 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1759 /// deduction candidate' (is used during overload resolution).
1760 unsigned IsCopyDeductionCandidate : 1;
1761
1762private:
1763 /// \brief End part of this FunctionDecl's source range.
1764 ///
1765 /// We could compute the full range in getSourceRange(). However, when we're
1766 /// dealing with a function definition deserialized from a PCH/AST file,
1767 /// we can only compute the full range once the function body has been
1768 /// de-serialized, so it's far better to have the (sometimes-redundant)
1769 /// EndRangeLoc.
1770 SourceLocation EndRangeLoc;
1771
1772 /// \brief The template or declaration that this declaration
1773 /// describes or was instantiated from, respectively.
1774 ///
1775 /// For non-templates, this value will be NULL. For function
1776 /// declarations that describe a function template, this will be a
1777 /// pointer to a FunctionTemplateDecl. For member functions
1778 /// of class template specializations, this will be a MemberSpecializationInfo
1779 /// pointer containing information about the specialization.
1780 /// For function template specializations, this will be a
1781 /// FunctionTemplateSpecializationInfo, which contains information about
1782 /// the template being specialized and the template arguments involved in
1783 /// that specialization.
1784 llvm::PointerUnion4<FunctionTemplateDecl *,
1785 MemberSpecializationInfo *,
1786 FunctionTemplateSpecializationInfo *,
1787 DependentFunctionTemplateSpecializationInfo *>
1788 TemplateOrSpecialization;
1789
1790 /// DNLoc - Provides source/type location info for the
1791 /// declaration name embedded in the DeclaratorDecl base class.
1792 DeclarationNameLoc DNLoc;
1793
1794 /// \brief Specify that this function declaration is actually a function
1795 /// template specialization.
1796 ///
1797 /// \param C the ASTContext.
1798 ///
1799 /// \param Template the function template that this function template
1800 /// specialization specializes.
1801 ///
1802 /// \param TemplateArgs the template arguments that produced this
1803 /// function template specialization from the template.
1804 ///
1805 /// \param InsertPos If non-NULL, the position in the function template
1806 /// specialization set where the function template specialization data will
1807 /// be inserted.
1808 ///
1809 /// \param TSK the kind of template specialization this is.
1810 ///
1811 /// \param TemplateArgsAsWritten location info of template arguments.
1812 ///
1813 /// \param PointOfInstantiation point at which the function template
1814 /// specialization was first instantiated.
1815 void setFunctionTemplateSpecialization(ASTContext &C,
1816 FunctionTemplateDecl *Template,
1817 const TemplateArgumentList *TemplateArgs,
1818 void *InsertPos,
1819 TemplateSpecializationKind TSK,
1820 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1821 SourceLocation PointOfInstantiation);
1822
1823 /// \brief Specify that this record is an instantiation of the
1824 /// member function FD.
1825 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1826 TemplateSpecializationKind TSK);
1827
1828 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1829
1830protected:
1831 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1832 const DeclarationNameInfo &NameInfo, QualType T,
1833 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1834 bool isConstexprSpecified)
1835 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1836 StartLoc),
1837 DeclContext(DK), redeclarable_base(C), SClass(S),
1838 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1839 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1840 HasInheritedPrototype(false), HasWrittenPrototype(true),
1841 IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1842 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1843 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1844 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1845 WillHaveBody(false), IsCopyDeductionCandidate(false),
1846 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1847
1848 using redeclarable_base = Redeclarable<FunctionDecl>;
1849
1850 FunctionDecl *getNextRedeclarationImpl() override {
1851 return getNextRedeclaration();
1852 }
1853
1854 FunctionDecl *getPreviousDeclImpl() override {
1855 return getPreviousDecl();
1856 }
1857
1858 FunctionDecl *getMostRecentDeclImpl() override {
1859 return getMostRecentDecl();
1860 }
1861
1862public:
1863 friend class ASTDeclReader;
1864 friend class ASTDeclWriter;
1865
1866 using redecl_range = redeclarable_base::redecl_range;
1867 using redecl_iterator = redeclarable_base::redecl_iterator;
1868
1869 using redeclarable_base::redecls_begin;
1870 using redeclarable_base::redecls_end;
1871 using redeclarable_base::redecls;
1872 using redeclarable_base::getPreviousDecl;
1873 using redeclarable_base::getMostRecentDecl;
1874 using redeclarable_base::isFirstDecl;
1875
1876 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1877 SourceLocation StartLoc, SourceLocation NLoc,
1878 DeclarationName N, QualType T,
1879 TypeSourceInfo *TInfo,
1880 StorageClass SC,
1881 bool isInlineSpecified = false,
1882 bool hasWrittenPrototype = true,
1883 bool isConstexprSpecified = false) {
1884 DeclarationNameInfo NameInfo(N, NLoc);
1885 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1886 SC,
1887 isInlineSpecified, hasWrittenPrototype,
1888 isConstexprSpecified);
1889 }
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc,
1893 const DeclarationNameInfo &NameInfo,
1894 QualType T, TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified,
1897 bool hasWrittenPrototype,
1898 bool isConstexprSpecified = false);
1899
1900 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1901
1902 DeclarationNameInfo getNameInfo() const {
1903 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1904 }
1905
1906 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1907 bool Qualified) const override;
1908
1909 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1910
1911 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1912
1913 /// \brief Returns true if the function has a body (definition). The
1914 /// function body might be in any of the (re-)declarations of this
1915 /// function. The variant that accepts a FunctionDecl pointer will
1916 /// set that function declaration to the actual declaration
1917 /// containing the body (if there is one).
1918 bool hasBody(const FunctionDecl *&Definition) const;
1919
1920 bool hasBody() const override {
1921 const FunctionDecl* Definition;
1922 return hasBody(Definition);
1923 }
1924
1925 /// hasTrivialBody - Returns whether the function has a trivial body that does
1926 /// not require any specific codegen.
1927 bool hasTrivialBody() const;
1928
1929 /// isDefined - Returns true if the function is defined at all, including
1930 /// a deleted definition. Except for the behavior when the function is
1931 /// deleted, behaves like hasBody.
1932 bool isDefined(const FunctionDecl *&Definition) const;
1933
1934 virtual bool isDefined() const {
1935 const FunctionDecl* Definition;
1936 return isDefined(Definition);
1937 }
1938
1939 /// \brief Get the definition for this declaration.
1940 FunctionDecl *getDefinition() {
1941 const FunctionDecl *Definition;
1942 if (isDefined(Definition))
1943 return const_cast<FunctionDecl *>(Definition);
1944 return nullptr;
1945 }
1946 const FunctionDecl *getDefinition() const {
1947 return const_cast<FunctionDecl *>(this)->getDefinition();
1948 }
1949
1950 /// getBody - Retrieve the body (definition) of the function. The
1951 /// function body might be in any of the (re-)declarations of this
1952 /// function. The variant that accepts a FunctionDecl pointer will
1953 /// set that function declaration to the actual declaration
1954 /// containing the body (if there is one).
1955 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1956 /// unnecessary AST de-serialization of the body.
1957 Stmt *getBody(const FunctionDecl *&Definition) const;
1958
1959 Stmt *getBody() const override {
1960 const FunctionDecl* Definition;
1961 return getBody(Definition);
1962 }
1963
1964 /// Returns whether this specific declaration of the function is also a
1965 /// definition that does not contain uninstantiated body.
1966 ///
1967 /// This does not determine whether the function has been defined (e.g., in a
1968 /// previous definition); for that information, use isDefined.
1969 bool isThisDeclarationADefinition() const {
1970 return IsDeleted || IsDefaulted || Body || IsLateTemplateParsed ||
1971 WillHaveBody || hasDefiningAttr();
1972 }
1973
1974 /// doesThisDeclarationHaveABody - Returns whether this specific
1975 /// declaration of the function has a body - that is, if it is a non-
1976 /// deleted definition.
1977 bool doesThisDeclarationHaveABody() const {
1978 return Body || IsLateTemplateParsed;
1979 }
1980
1981 void setBody(Stmt *B);
1982 void setLazyBody(uint64_t Offset) { Body = Offset; }
1983
1984 /// Whether this function is variadic.
1985 bool isVariadic() const;
1986
1987 /// Whether this function is marked as virtual explicitly.
1988 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1989 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1990
1991 /// Whether this virtual function is pure, i.e. makes the containing class
1992 /// abstract.
1993 bool isPure() const { return IsPure; }
1994 void setPure(bool P = true);
1995
1996 /// Whether this templated function will be late parsed.
1997 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1998 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1999
2000 /// Whether this function is "trivial" in some specialized C++ senses.
2001 /// Can only be true for default constructors, copy constructors,
2002 /// copy assignment operators, and destructors. Not meaningful until
2003 /// the class has been fully built by Sema.
2004 bool isTrivial() const { return IsTrivial; }
2005 void setTrivial(bool IT) { IsTrivial = IT; }
2006
2007 /// Whether this function is defaulted per C++0x. Only valid for
2008 /// special member functions.
2009 bool isDefaulted() const { return IsDefaulted; }
2010 void setDefaulted(bool D = true) { IsDefaulted = D; }
2011
2012 /// Whether this function is explicitly defaulted per C++0x. Only valid
2013 /// for special member functions.
2014 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2015 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2016
2017 /// Whether falling off this function implicitly returns null/zero.
2018 /// If a more specific implicit return value is required, front-ends
2019 /// should synthesize the appropriate return statements.
2020 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2021 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2022
2023 /// \brief Whether this function has a prototype, either because one
2024 /// was explicitly written or because it was "inherited" by merging
2025 /// a declaration without a prototype with a declaration that has a
2026 /// prototype.
2027 bool hasPrototype() const {
2028 return HasWrittenPrototype || HasInheritedPrototype;
2029 }
2030
2031 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2032
2033 /// \brief Whether this function inherited its prototype from a
2034 /// previous declaration.
2035 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2036 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2037
2038 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2039 bool isConstexpr() const { return IsConstexpr; }
2040 void setConstexpr(bool IC) { IsConstexpr = IC; }
2041
2042 /// \brief Whether the instantiation of this function is pending.
2043 /// This bit is set when the decision to instantiate this function is made
2044 /// and unset if and when the function body is created. That leaves out
2045 /// cases where instantiation did not happen because the template definition
2046 /// was not seen in this TU. This bit remains set in those cases, under the
2047 /// assumption that the instantiation will happen in some other TU.
2048 bool instantiationIsPending() const { return InstantiationIsPending; }
2049 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2050
2051 /// \brief Indicates the function uses __try.
2052 bool usesSEHTry() const { return UsesSEHTry; }
2053 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2054
2055 /// \brief Whether this function has been deleted.
2056 ///
2057 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2058 /// acts like a normal function, except that it cannot actually be
2059 /// called or have its address taken. Deleted functions are
2060 /// typically used in C++ overload resolution to attract arguments
2061 /// whose type or lvalue/rvalue-ness would permit the use of a
2062 /// different overload that would behave incorrectly. For example,
2063 /// one might use deleted functions to ban implicit conversion from
2064 /// a floating-point number to an Integer type:
2065 ///
2066 /// @code
2067 /// struct Integer {
2068 /// Integer(long); // construct from a long
2069 /// Integer(double) = delete; // no construction from float or double
2070 /// Integer(long double) = delete; // no construction from long double
2071 /// };
2072 /// @endcode
2073 // If a function is deleted, its first declaration must be.
2074 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2075 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2076 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2077
2078 /// \brief Determines whether this function is "main", which is the
2079 /// entry point into an executable program.
2080 bool isMain() const;
2081
2082 /// \brief Determines whether this function is a MSVCRT user defined entry
2083 /// point.
2084 bool isMSVCRTEntryPoint() const;
2085
2086 /// \brief Determines whether this operator new or delete is one
2087 /// of the reserved global placement operators:
2088 /// void *operator new(size_t, void *);
2089 /// void *operator new[](size_t, void *);
2090 /// void operator delete(void *, void *);
2091 /// void operator delete[](void *, void *);
2092 /// These functions have special behavior under [new.delete.placement]:
2093 /// These functions are reserved, a C++ program may not define
2094 /// functions that displace the versions in the Standard C++ library.
2095 /// The provisions of [basic.stc.dynamic] do not apply to these
2096 /// reserved placement forms of operator new and operator delete.
2097 ///
2098 /// This function must be an allocation or deallocation function.
2099 bool isReservedGlobalPlacementOperator() const;
2100
2101 /// \brief Determines whether this function is one of the replaceable
2102 /// global allocation functions:
2103 /// void *operator new(size_t);
2104 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2105 /// void *operator new[](size_t);
2106 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2107 /// void operator delete(void *) noexcept;
2108 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2109 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2110 /// void operator delete[](void *) noexcept;
2111 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2112 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2113 /// These functions have special behavior under C++1y [expr.new]:
2114 /// An implementation is allowed to omit a call to a replaceable global
2115 /// allocation function. [...]
2116 ///
2117 /// If this function is an aligned allocation/deallocation function, return
2118 /// true through IsAligned.
2119 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2120
2121 /// \brief Determine whether this is a destroying operator delete.
2122 bool isDestroyingOperatorDelete() const;
2123
2124 /// Compute the language linkage.
2125 LanguageLinkage getLanguageLinkage() const;
2126
2127 /// \brief Determines whether this function is a function with
2128 /// external, C linkage.
2129 bool isExternC() const;
2130
2131 /// \brief Determines whether this function's context is, or is nested within,
2132 /// a C++ extern "C" linkage spec.
2133 bool isInExternCContext() const;
2134
2135 /// \brief Determines whether this function's context is, or is nested within,
2136 /// a C++ extern "C++" linkage spec.
2137 bool isInExternCXXContext() const;
2138
2139 /// \brief Determines whether this is a global function.
2140 bool isGlobal() const;
2141
2142 /// \brief Determines whether this function is known to be 'noreturn', through
2143 /// an attribute on its declaration or its type.
2144 bool isNoReturn() const;
2145
2146 /// \brief True if the function was a definition but its body was skipped.
2147 bool hasSkippedBody() const { return HasSkippedBody; }
2148 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2149
2150 /// True if this function will eventually have a body, once it's fully parsed.
2151 bool willHaveBody() const { return WillHaveBody; }
2152 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2153
2154 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2155
2156 FunctionDecl *getCanonicalDecl() override;
2157 const FunctionDecl *getCanonicalDecl() const {
2158 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2159 }
2160
2161 unsigned getBuiltinID() const;
2162
2163 // ArrayRef interface to parameters.
2164 ArrayRef<ParmVarDecl *> parameters() const {
2165 return {ParamInfo, getNumParams()};
2166 }
2167 MutableArrayRef<ParmVarDecl *> parameters() {
2168 return {ParamInfo, getNumParams()};
2169 }
2170
2171 // Iterator access to formal parameters.
2172 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2173 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2174
2175 bool param_empty() const { return parameters().empty(); }
2176 param_iterator param_begin() { return parameters().begin(); }
2177 param_iterator param_end() { return parameters().end(); }
2178 param_const_iterator param_begin() const { return parameters().begin(); }
2179 param_const_iterator param_end() const { return parameters().end(); }
2180 size_t param_size() const { return parameters().size(); }
2181
2182 /// getNumParams - Return the number of parameters this function must have
2183 /// based on its FunctionType. This is the length of the ParamInfo array
2184 /// after it has been created.
2185 unsigned getNumParams() const;
2186
2187 const ParmVarDecl *getParamDecl(unsigned i) const {
2188 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2188, __extension__ __PRETTY_FUNCTION__))
;
2189 return ParamInfo[i];
2190 }
2191 ParmVarDecl *getParamDecl(unsigned i) {
2192 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2192, __extension__ __PRETTY_FUNCTION__))
;
2193 return ParamInfo[i];
2194 }
2195 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2196 setParams(getASTContext(), NewParamInfo);
2197 }
2198
2199 /// getMinRequiredArguments - Returns the minimum number of arguments
2200 /// needed to call this function. This may be fewer than the number of
2201 /// function parameters, if some of the parameters have default
2202 /// arguments (in C++).
2203 unsigned getMinRequiredArguments() const;
2204
2205 QualType getReturnType() const {
2206 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2206, __extension__ __PRETTY_FUNCTION__))
;
2207 return getType()->getAs<FunctionType>()->getReturnType();
2208 }
2209
2210 /// \brief Attempt to compute an informative source range covering the
2211 /// function return type. This may omit qualifiers and other information with
2212 /// limited representation in the AST.
2213 SourceRange getReturnTypeSourceRange() const;
2214
2215 /// \brief Attempt to compute an informative source range covering the
2216 /// function exception specification, if any.
2217 SourceRange getExceptionSpecSourceRange() const;
2218
2219 /// \brief Determine the type of an expression that calls this function.
2220 QualType getCallResultType() const {
2221 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2221, __extension__ __PRETTY_FUNCTION__))
;
2222 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2223 }
2224
2225 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2226 /// function, or its return type declaration.
2227 const Attr *getUnusedResultAttr() const;
2228
2229 /// \brief Returns true if this function or its return type has the
2230 /// warn_unused_result attribute.
2231 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2232
2233 /// \brief Returns the storage class as written in the source. For the
2234 /// computed linkage of symbol, see getLinkage.
2235 StorageClass getStorageClass() const { return StorageClass(SClass); }
2236
2237 /// \brief Determine whether the "inline" keyword was specified for this
2238 /// function.
2239 bool isInlineSpecified() const { return IsInlineSpecified; }
2240
2241 /// Set whether the "inline" keyword was specified for this function.
2242 void setInlineSpecified(bool I) {
2243 IsInlineSpecified = I;
2244 IsInline = I;
2245 }
2246
2247 /// Flag that this function is implicitly inline.
2248 void setImplicitlyInline() {
2249 IsInline = true;
2250 }
2251
2252 /// \brief Determine whether this function should be inlined, because it is
2253 /// either marked "inline" or "constexpr" or is a member function of a class
2254 /// that was defined in the class body.
2255 bool isInlined() const { return IsInline; }
2256
2257 bool isInlineDefinitionExternallyVisible() const;
2258
2259 bool isMSExternInline() const;
2260
2261 bool doesDeclarationForceExternallyVisibleDefinition() const;
2262
2263 /// isOverloadedOperator - Whether this function declaration
2264 /// represents an C++ overloaded operator, e.g., "operator+".
2265 bool isOverloadedOperator() const {
2266 return getOverloadedOperator() != OO_None;
2267 }
2268
2269 OverloadedOperatorKind getOverloadedOperator() const;
2270
2271 const IdentifierInfo *getLiteralIdentifier() const;
2272
2273 /// \brief If this function is an instantiation of a member function
2274 /// of a class template specialization, retrieves the function from
2275 /// which it was instantiated.
2276 ///
2277 /// This routine will return non-NULL for (non-templated) member
2278 /// functions of class templates and for instantiations of function
2279 /// templates. For example, given:
2280 ///
2281 /// \code
2282 /// template<typename T>
2283 /// struct X {
2284 /// void f(T);
2285 /// };
2286 /// \endcode
2287 ///
2288 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2289 /// whose parent is the class template specialization X<int>. For
2290 /// this declaration, getInstantiatedFromFunction() will return
2291 /// the FunctionDecl X<T>::A. When a complete definition of
2292 /// X<int>::A is required, it will be instantiated from the
2293 /// declaration returned by getInstantiatedFromMemberFunction().
2294 FunctionDecl *getInstantiatedFromMemberFunction() const;
2295
2296 /// \brief What kind of templated function this is.
2297 TemplatedKind getTemplatedKind() const;
2298
2299 /// \brief If this function is an instantiation of a member function of a
2300 /// class template specialization, retrieves the member specialization
2301 /// information.
2302 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2303
2304 /// \brief Specify that this record is an instantiation of the
2305 /// member function FD.
2306 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2307 TemplateSpecializationKind TSK) {
2308 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2309 }
2310
2311 /// \brief Retrieves the function template that is described by this
2312 /// function declaration.
2313 ///
2314 /// Every function template is represented as a FunctionTemplateDecl
2315 /// and a FunctionDecl (or something derived from FunctionDecl). The
2316 /// former contains template properties (such as the template
2317 /// parameter lists) while the latter contains the actual
2318 /// description of the template's
2319 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2320 /// FunctionDecl that describes the function template,
2321 /// getDescribedFunctionTemplate() retrieves the
2322 /// FunctionTemplateDecl from a FunctionDecl.
2323 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2324
2325 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2326
2327 /// \brief Determine whether this function is a function template
2328 /// specialization.
2329 bool isFunctionTemplateSpecialization() const {
2330 return getPrimaryTemplate() != nullptr;
2331 }
2332
2333 /// \brief Retrieve the class scope template pattern that this function
2334 /// template specialization is instantiated from.
2335 FunctionDecl *getClassScopeSpecializationPattern() const;
2336
2337 /// \brief If this function is actually a function template specialization,
2338 /// retrieve information about this function template specialization.
2339 /// Otherwise, returns NULL.
2340 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2341
2342 /// \brief Determines whether this function is a function template
2343 /// specialization or a member of a class template specialization that can
2344 /// be implicitly instantiated.
2345 bool isImplicitlyInstantiable() const;
2346
2347 /// \brief Determines if the given function was instantiated from a
2348 /// function template.
2349 bool isTemplateInstantiation() const;
2350
2351 /// \brief Retrieve the function declaration from which this function could
2352 /// be instantiated, if it is an instantiation (rather than a non-template
2353 /// or a specialization, for example).
2354 FunctionDecl *getTemplateInstantiationPattern() const;
2355
2356 /// \brief Retrieve the primary template that this function template
2357 /// specialization either specializes or was instantiated from.
2358 ///
2359 /// If this function declaration is not a function template specialization,
2360 /// returns NULL.
2361 FunctionTemplateDecl *getPrimaryTemplate() const;
2362
2363 /// \brief Retrieve the template arguments used to produce this function
2364 /// template specialization from the primary template.
2365 ///
2366 /// If this function declaration is not a function template specialization,
2367 /// returns NULL.
2368 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2369
2370 /// \brief Retrieve the template argument list as written in the sources,
2371 /// if any.
2372 ///
2373 /// If this function declaration is not a function template specialization
2374 /// or if it had no explicit template argument list, returns NULL.
2375 /// Note that it an explicit template argument list may be written empty,
2376 /// e.g., template<> void foo<>(char* s);
2377 const ASTTemplateArgumentListInfo*
2378 getTemplateSpecializationArgsAsWritten() const;
2379
2380 /// \brief Specify that this function declaration is actually a function
2381 /// template specialization.
2382 ///
2383 /// \param Template the function template that this function template
2384 /// specialization specializes.
2385 ///
2386 /// \param TemplateArgs the template arguments that produced this
2387 /// function template specialization from the template.
2388 ///
2389 /// \param InsertPos If non-NULL, the position in the function template
2390 /// specialization set where the function template specialization data will
2391 /// be inserted.
2392 ///
2393 /// \param TSK the kind of template specialization this is.
2394 ///
2395 /// \param TemplateArgsAsWritten location info of template arguments.
2396 ///
2397 /// \param PointOfInstantiation point at which the function template
2398 /// specialization was first instantiated.
2399 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2400 const TemplateArgumentList *TemplateArgs,
2401 void *InsertPos,
2402 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2403 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2404 SourceLocation PointOfInstantiation = SourceLocation()) {
2405 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2406 InsertPos, TSK, TemplateArgsAsWritten,
2407 PointOfInstantiation);
2408 }
2409
2410 /// \brief Specifies that this function declaration is actually a
2411 /// dependent function template specialization.
2412 void setDependentTemplateSpecialization(ASTContext &Context,
2413 const UnresolvedSetImpl &Templates,
2414 const TemplateArgumentListInfo &TemplateArgs);
2415
2416 DependentFunctionTemplateSpecializationInfo *
2417 getDependentSpecializationInfo() const;
2418
2419 /// \brief Determine what kind of template instantiation this function
2420 /// represents.
2421 TemplateSpecializationKind getTemplateSpecializationKind() const;
2422
2423 /// \brief Determine what kind of template instantiation this function
2424 /// represents.
2425 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2426 SourceLocation PointOfInstantiation = SourceLocation());
2427
2428 /// \brief Retrieve the (first) point of instantiation of a function template
2429 /// specialization or a member of a class template specialization.
2430 ///
2431 /// \returns the first point of instantiation, if this function was
2432 /// instantiated from a template; otherwise, returns an invalid source
2433 /// location.
2434 SourceLocation getPointOfInstantiation() const;
2435
2436 /// \brief Determine whether this is or was instantiated from an out-of-line
2437 /// definition of a member function.
2438 bool isOutOfLine() const override;
2439
2440 /// \brief Identify a memory copying or setting function.
2441 /// If the given function is a memory copy or setting function, returns
2442 /// the corresponding Builtin ID. If the function is not a memory function,
2443 /// returns 0.
2444 unsigned getMemoryFunctionKind() const;
2445
2446 // Implement isa/cast/dyncast/etc.
2447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
14
Calling 'Decl::getKind'
15
Returning from 'Decl::getKind'
16
Calling 'FunctionDecl::classofKind'
19
Returning from 'FunctionDecl::classofKind'
39
Calling 'Decl::getKind'
40
Returning from 'Decl::getKind'
41
Calling 'FunctionDecl::classofKind'
42
Returning from 'FunctionDecl::classofKind'
2448 static bool classofKind(Kind K) {
2449 return K >= firstFunction && K <= lastFunction;
17
Assuming 'K' is >= firstFunction
18
Assuming 'K' is <= lastFunction
2450 }
2451 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2452 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2453 }
2454 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2455 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2456 }
2457};
2458
2459/// FieldDecl - An instance of this class is created by Sema::ActOnField to
2460/// represent a member of a struct/union/class.
2461class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2462 unsigned BitField : 1;
2463 unsigned Mutable : 1;
2464 mutable unsigned CachedFieldIndex : 30;
2465
2466 /// The kinds of value we can store in InitializerOrBitWidth.
2467 ///
2468 /// Note that this is compatible with InClassInitStyle except for
2469 /// ISK_CapturedVLAType.
2470 enum InitStorageKind {
2471 /// If the pointer is null, there's nothing special. Otherwise,
2472 /// this is a bitfield and the pointer is the Expr* storing the
2473 /// bit-width.
2474 ISK_NoInit = (unsigned) ICIS_NoInit,
2475
2476 /// The pointer is an (optional due to delayed parsing) Expr*
2477 /// holding the copy-initializer.
2478 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2479
2480 /// The pointer is an (optional due to delayed parsing) Expr*
2481 /// holding the list-initializer.
2482 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2483
2484 /// The pointer is a VariableArrayType* that's been captured;
2485 /// the enclosing context is a lambda or captured statement.
2486 ISK_CapturedVLAType,
2487 };
2488
2489 /// If this is a bitfield with a default member initializer, this
2490 /// structure is used to represent the two expressions.
2491 struct InitAndBitWidth {
2492 Expr *Init;
2493 Expr *BitWidth;
2494 };
2495
2496 /// \brief Storage for either the bit-width, the in-class initializer, or
2497 /// both (via InitAndBitWidth), or the captured variable length array bound.
2498 ///
2499 /// If the storage kind is ISK_InClassCopyInit or
2500 /// ISK_InClassListInit, but the initializer is null, then this
2501 /// field has an in-class initializer that has not yet been parsed
2502 /// and attached.
2503 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2504 // overwhelmingly common case that we have none of these things.
2505 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2506
2507protected:
2508 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2509 SourceLocation IdLoc, IdentifierInfo *Id,
2510 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2511 InClassInitStyle InitStyle)
2512 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2513 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2514 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2515 if (BW)
2516 setBitWidth(BW);
2517 }
2518
2519public:
2520 friend class ASTDeclReader;
2521 friend class ASTDeclWriter;
2522
2523 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2524 SourceLocation StartLoc, SourceLocation IdLoc,
2525 IdentifierInfo *Id, QualType T,
2526 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2527 InClassInitStyle InitStyle);
2528
2529 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2530
2531 /// getFieldIndex - Returns the index of this field within its record,
2532 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2533 unsigned getFieldIndex() const;
2534
2535 /// isMutable - Determines whether this field is mutable (C++ only).
2536 bool isMutable() const { return Mutable; }
2537
2538 /// \brief Determines whether this field is a bitfield.
2539 bool isBitField() const { return BitField; }
2540
2541 /// @brief Determines whether this is an unnamed bitfield.
2542 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2543
2544 /// isAnonymousStructOrUnion - Determines whether this field is a
2545 /// representative for an anonymous struct or union. Such fields are
2546 /// unnamed and are implicitly generated by the implementation to
2547 /// store the data for the anonymous union or struct.
2548 bool isAnonymousStructOrUnion() const;
2549
2550 Expr *getBitWidth() const {
2551 if (!BitField)
2552 return nullptr;
2553 void *Ptr = InitStorage.getPointer();
2554 if (getInClassInitStyle())
2555 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2556 return static_cast<Expr*>(Ptr);
2557 }
2558
2559 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2560
2561 /// setBitWidth - Set the bit-field width for this member.
2562 // Note: used by some clients (i.e., do not remove it).
2563 void setBitWidth(Expr *Width) {
2564 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2565, __extension__ __PRETTY_FUNCTION__))
2565 "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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2565, __extension__ __PRETTY_FUNCTION__))
;
2566 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2566, __extension__ __PRETTY_FUNCTION__))
;
2567 InitStorage.setPointer(
2568 InitStorage.getInt()
2569 ? new (getASTContext())
2570 InitAndBitWidth{getInClassInitializer(), Width}
2571 : static_cast<void*>(Width));
2572 BitField = true;
2573 }
2574
2575 /// removeBitWidth - Remove the bit-field width from this member.
2576 // Note: used by some clients (i.e., do not remove it).
2577 void removeBitWidth() {
2578 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2578, __extension__ __PRETTY_FUNCTION__))
;
2579 InitStorage.setPointer(getInClassInitializer());
2580 BitField = false;
2581 }
2582
2583 /// Get the kind of (C++11) default member initializer that this field has.
2584 InClassInitStyle getInClassInitStyle() const {
2585 InitStorageKind storageKind = InitStorage.getInt();
2586 return (storageKind == ISK_CapturedVLAType
2587 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2588 }
2589
2590 /// Determine whether this member has a C++11 default member initializer.
2591 bool hasInClassInitializer() const {
2592 return getInClassInitStyle() != ICIS_NoInit;
2593 }
2594
2595 /// Get the C++11 default member initializer for this member, or null if one
2596 /// has not been set. If a valid declaration has a default member initializer,
2597 /// but this returns null, then we have not parsed and attached it yet.
2598 Expr *getInClassInitializer() const {
2599 if (!hasInClassInitializer())
2600 return nullptr;
2601 void *Ptr = InitStorage.getPointer();
2602 if (BitField)
2603 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2604 return static_cast<Expr*>(Ptr);
2605 }
2606
2607 /// setInClassInitializer - Set the C++11 in-class initializer for this
2608 /// member.
2609 void setInClassInitializer(Expr *Init) {
2610 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2610, __extension__ __PRETTY_FUNCTION__))
;
2611 if (BitField)
2612 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2613 else
2614 InitStorage.setPointer(Init);
2615 }
2616
2617 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2618 /// member.
2619 void removeInClassInitializer() {
2620 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2620, __extension__ __PRETTY_FUNCTION__))
;
2621 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2622 }
2623
2624 /// \brief Determine whether this member captures the variable length array
2625 /// type.
2626 bool hasCapturedVLAType() const {
2627 return InitStorage.getInt() == ISK_CapturedVLAType;
2628 }
2629
2630 /// \brief Get the captured variable length array type.
2631 const VariableArrayType *getCapturedVLAType() const {
2632 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2633 InitStorage.getPointer())
2634 : nullptr;
2635 }
2636
2637 /// \brief Set the captured variable length array type for this field.
2638 void setCapturedVLAType(const VariableArrayType *VLAType);
2639
2640 /// getParent - Returns the parent of this field declaration, which
2641 /// is the struct in which this field is defined.
2642 const RecordDecl *getParent() const {
2643 return cast<RecordDecl>(getDeclContext());
2644 }
2645
2646 RecordDecl *getParent() {
2647 return cast<RecordDecl>(getDeclContext());
2648 }
2649
2650 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2651
2652 /// Retrieves the canonical declaration of this field.
2653 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2654 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2655
2656 // Implement isa/cast/dyncast/etc.
2657 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2658 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2659};
2660
2661/// EnumConstantDecl - An instance of this object exists for each enum constant
2662/// that is defined. For example, in "enum X {a,b}", each of a/b are
2663/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2664/// TagType for the X EnumDecl.
2665class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2666 Stmt *Init; // an integer constant expression
2667 llvm::APSInt Val; // The value.
2668
2669protected:
2670 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2671 IdentifierInfo *Id, QualType T, Expr *E,
2672 const llvm::APSInt &V)
2673 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2674
2675public:
2676 friend class StmtIteratorBase;
2677
2678 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2679 SourceLocation L, IdentifierInfo *Id,
2680 QualType T, Expr *E,
2681 const llvm::APSInt &V);
2682 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2683
2684 const Expr *getInitExpr() const { return (const Expr*) Init; }
2685 Expr *getInitExpr() { return (Expr*) Init; }
2686 const llvm::APSInt &getInitVal() const { return Val; }
2687
2688 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2689 void setInitVal(const llvm::APSInt &V) { Val = V; }
2690
2691 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2692
2693 /// Retrieves the canonical declaration of this enumerator.
2694 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2695 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2696
2697 // Implement isa/cast/dyncast/etc.
2698 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2699 static bool classofKind(Kind K) { return K == EnumConstant; }
2700};
2701
2702/// IndirectFieldDecl - An instance of this class is created to represent a
2703/// field injected from an anonymous union/struct into the parent scope.
2704/// IndirectFieldDecl are always implicit.
2705class IndirectFieldDecl : public ValueDecl,
2706 public Mergeable<IndirectFieldDecl> {
2707 NamedDecl **Chaining;
2708 unsigned ChainingSize;
2709
2710 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2711 DeclarationName N, QualType T,
2712 MutableArrayRef<NamedDecl *> CH);
2713
2714 void anchor() override;
2715
2716public:
2717 friend class ASTDeclReader;
2718
2719 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2720 SourceLocation L, IdentifierInfo *Id,
2721 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2722
2723 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2724
2725 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2726
2727 ArrayRef<NamedDecl *> chain() const {
2728 return llvm::makeArrayRef(Chaining, ChainingSize);
2729 }
2730 chain_iterator chain_begin() const { return chain().begin(); }
2731 chain_iterator chain_end() const { return chain().end(); }
2732
2733 unsigned getChainingSize() const { return ChainingSize; }
2734
2735 FieldDecl *getAnonField() const {
2736 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2736, __extension__ __PRETTY_FUNCTION__))
;
2737 return cast<FieldDecl>(chain().back());
2738 }
2739
2740 VarDecl *getVarDecl() const {
2741 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 2741, __extension__ __PRETTY_FUNCTION__))
;
2742 return dyn_cast<VarDecl>(chain().front());
2743 }
2744
2745 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2746 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2747
2748 // Implement isa/cast/dyncast/etc.
2749 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2750 static bool classofKind(Kind K) { return K == IndirectField; }
2751};
2752
2753/// TypeDecl - Represents a declaration of a type.
2754class TypeDecl : public NamedDecl {
2755 friend class ASTContext;
2756
2757 /// TypeForDecl - This indicates the Type object that represents
2758 /// this TypeDecl. It is a cache maintained by
2759 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2760 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2761 mutable const Type *TypeForDecl = nullptr;
2762
2763 /// LocStart - The start of the source range for this declaration.
2764 SourceLocation LocStart;
2765
2766 void anchor() override;
2767
2768protected:
2769 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2770 SourceLocation StartL = SourceLocation())
2771 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2772
2773public:
2774 // Low-level accessor. If you just want the type defined by this node,
2775 // check out ASTContext::getTypeDeclType or one of
2776 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2777 // already know the specific kind of node this is.
2778 const Type *getTypeForDecl() const { return TypeForDecl; }
2779 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2780
2781 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2782 void setLocStart(SourceLocation L) { LocStart = L; }
2783 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2784 if (LocStart.isValid())
2785 return SourceRange(LocStart, getLocation());
2786 else
2787 return SourceRange(getLocation());
2788 }
2789
2790 // Implement isa/cast/dyncast/etc.
2791 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2792 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2793};
2794
2795/// Base class for declarations which introduce a typedef-name.
2796class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2797 using ModedTInfo = std::pair<TypeSourceInfo *, QualType>;
2798 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *> MaybeModedTInfo;
2799
2800 // FIXME: This can be packed into the bitfields in Decl.
2801 /// If 0, we have not computed IsTransparentTag.
2802 /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2803 mutable unsigned CacheIsTransparentTag : 2;
2804
2805 void anchor() override;
2806
2807protected:
2808 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2809 SourceLocation StartLoc, SourceLocation IdLoc,
2810 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2811 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2812 MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2813
2814 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2815
2816 TypedefNameDecl *getNextRedeclarationImpl() override {
2817 return getNextRedeclaration();
2818 }
2819
2820 TypedefNameDecl *getPreviousDeclImpl() override {
2821 return getPreviousDecl();
2822 }
2823
2824 TypedefNameDecl *getMostRecentDeclImpl() override {
2825 return getMostRecentDecl();
2826 }
2827
2828public:
2829 using redecl_range = redeclarable_base::redecl_range;
2830 using redecl_iterator = redeclarable_base::redecl_iterator;
2831
2832 using redeclarable_base::redecls_begin;
2833 using redeclarable_base::redecls_end;
2834 using redeclarable_base::redecls;
2835 using redeclarable_base::getPreviousDecl;
2836 using redeclarable_base::getMostRecentDecl;
2837 using redeclarable_base::isFirstDecl;
2838
2839 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2840
2841 TypeSourceInfo *getTypeSourceInfo() const {
2842 return isModed()
2843 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2844 : MaybeModedTInfo.get<TypeSourceInfo*>();
2845 }
2846
2847 QualType getUnderlyingType() const {
2848 return isModed()
2849 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2850 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2851 }
2852
2853 void setTypeSourceInfo(TypeSourceInfo *newType) {
2854 MaybeModedTInfo = newType;
2855 }
2856
2857 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2858 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2859 }
2860
2861 /// Retrieves the canonical declaration of this typedef-name.
2862 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2863 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2864
2865 /// Retrieves the tag declaration for which this is the typedef name for
2866 /// linkage purposes, if any.
2867 ///
2868 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2869 /// this typedef declaration.
2870 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2871
2872 /// Determines if this typedef shares a name and spelling location with its
2873 /// underlying tag type, as is the case with the NS_ENUM macro.
2874 bool isTransparentTag() const {
2875 if (CacheIsTransparentTag)
2876 return CacheIsTransparentTag & 0x2;
2877 return isTransparentTagSlow();
2878 }
2879
2880 // Implement isa/cast/dyncast/etc.
2881 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2882 static bool classofKind(Kind K) {
2883 return K >= firstTypedefName && K <= lastTypedefName;
2884 }
2885
2886private:
2887 bool isTransparentTagSlow() const;
2888};
2889
2890/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2891/// type specifier.
2892class TypedefDecl : public TypedefNameDecl {
2893 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2894 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2895 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2896
2897public:
2898 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2899 SourceLocation StartLoc, SourceLocation IdLoc,
2900 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2901 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2902
2903 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2904
2905 // Implement isa/cast/dyncast/etc.
2906 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2907 static bool classofKind(Kind K) { return K == Typedef; }
2908};
2909
2910/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2911/// alias-declaration.
2912class TypeAliasDecl : public TypedefNameDecl {
2913 /// The template for which this is the pattern, if any.
2914 TypeAliasTemplateDecl *Template;
2915
2916 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2917 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2918 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2919 Template(nullptr) {}
2920
2921public:
2922 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2923 SourceLocation StartLoc, SourceLocation IdLoc,
2924 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2925 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2926
2927 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2928
2929 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2930 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2931
2932 // Implement isa/cast/dyncast/etc.
2933 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2934 static bool classofKind(Kind K) { return K == TypeAlias; }
2935};
2936
2937/// TagDecl - Represents the declaration of a struct/union/class/enum.
2938class TagDecl
2939 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2940public:
2941 // This is really ugly.
2942 using TagKind = TagTypeKind;
2943
2944private:
2945 // FIXME: This can be packed into the bitfields in Decl.
2946 /// TagDeclKind - The TagKind enum.
2947 unsigned TagDeclKind : 3;
2948
2949 /// IsCompleteDefinition - True if this is a definition ("struct foo
2950 /// {};"), false if it is a declaration ("struct foo;"). It is not
2951 /// a definition until the definition has been fully processed.
2952 unsigned IsCompleteDefinition : 1;
2953
2954protected:
2955 /// IsBeingDefined - True if this is currently being defined.
2956 unsigned IsBeingDefined : 1;
2957
2958private:
2959 /// IsEmbeddedInDeclarator - True if this tag declaration is
2960 /// "embedded" (i.e., defined or declared for the very first time)
2961 /// in the syntax of a declarator.
2962 unsigned IsEmbeddedInDeclarator : 1;
2963
2964 /// \brief True if this tag is free standing, e.g. "struct foo;".
2965 unsigned IsFreeStanding : 1;
2966
2967protected:
2968 // These are used by (and only defined for) EnumDecl.
2969 unsigned NumPositiveBits : 8;
2970 unsigned NumNegativeBits : 8;
2971
2972 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2973 /// possible in C++11 mode.
2974 unsigned IsScoped : 1;
2975
2976 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2977 /// then this is true if the scoped enum was declared using the class
2978 /// tag, false if it was declared with the struct tag. No meaning is
2979 /// associated if this tag declaration is not a scoped enum.
2980 unsigned IsScopedUsingClassTag : 1;
2981
2982 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2983 /// possible in C++11, Microsoft extensions, or Objective C mode.
2984 unsigned IsFixed : 1;
2985
2986 /// \brief Indicates whether it is possible for declarations of this kind
2987 /// to have an out-of-date definition.
2988 ///
2989 /// This option is only enabled when modules are enabled.
2990 unsigned MayHaveOutOfDateDef : 1;
2991
2992 /// Has the full definition of this type been required by a use somewhere in
2993 /// the TU.
2994 unsigned IsCompleteDefinitionRequired : 1;
2995
2996private:
2997 SourceRange BraceRange;
2998
2999 // A struct representing syntactic qualifier info,
3000 // to be used for the (uncommon) case of out-of-line declarations.
3001 using ExtInfo = QualifierInfo;
3002
3003 /// \brief If the (out-of-line) tag declaration name
3004 /// is qualified, it points to the qualifier info (nns and range);
3005 /// otherwise, if the tag declaration is anonymous and it is part of
3006 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3007 /// otherwise, if the tag declaration is anonymous and it is used as a
3008 /// declaration specifier for variables, it points to the first VarDecl (used
3009 /// for mangling);
3010 /// otherwise, it is a null (TypedefNameDecl) pointer.
3011 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3012
3013 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3014 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3015 const ExtInfo *getExtInfo() const {
3016 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3017 }
3018
3019protected:
3020 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3021 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3022 SourceLocation StartL)
3023 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3024 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3025 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3026 IsCompleteDefinitionRequired(false),
3027 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3028 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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 3029, __extension__ __PRETTY_FUNCTION__))
3029 "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-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 3029, __extension__ __PRETTY_FUNCTION__))
;
3030 setPreviousDecl(PrevDecl);
3031 }
3032
3033