Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGDebugInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGDebugInfo.cpp

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

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

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
107 return isa_impl<To, From>::doit(*Val);
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
256 return cast_convert_val<X, Y*,
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/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;
13
Assuming the condition is true
14
'?' condition is true
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