Bug Summary

File:tools/clang/lib/CodeGen/CGDebugInfo.cpp
Warning:line 630, column 7
Null pointer passed as an argument to a 'nonnull' parameter

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~svn324994/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn324994/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn324994/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn324994/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn324994/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn324994/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~svn324994/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-13-110831-2594-1 -x c++ /build/llvm-toolchain-snapshot-7~svn324994/tools/clang/lib/CodeGen/CGDebugInfo.cpp

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

/build/llvm-toolchain-snapshot-7~svn324994/tools/clang/lib/CodeGen/CGDebugInfo.h

1//===--- CGDebugInfo.h - DebugInfo for LLVM CodeGen -------------*- 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 is the source-level debug info generator for llvm translation.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
15#define LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
16
17#include "CGBuilder.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/Type.h"
22#include "clang/AST/TypeOrdering.h"
23#include "clang/Basic/SourceLocation.h"
24#include "clang/Frontend/CodeGenOptions.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/Optional.h"
28#include "llvm/IR/DIBuilder.h"
29#include "llvm/IR/DebugInfo.h"
30#include "llvm/IR/ValueHandle.h"
31#include "llvm/Support/Allocator.h"
32
33namespace llvm {
34class MDNode;
35}
36
37namespace clang {
38class ClassTemplateSpecializationDecl;
39class GlobalDecl;
40class ModuleMap;
41class ObjCInterfaceDecl;
42class ObjCIvarDecl;
43class UsingDecl;
44class VarDecl;
45
46namespace CodeGen {
47class CodeGenModule;
48class CodeGenFunction;
49class CGBlockInfo;
50
51/// This class gathers all debug information during compilation and is
52/// responsible for emitting to llvm globals or pass directly to the
53/// backend.
54class CGDebugInfo {
55 friend class ApplyDebugLocation;
56 friend class SaveAndRestoreLocation;
57 CodeGenModule &CGM;
58 const codegenoptions::DebugInfoKind DebugKind;
59 bool DebugTypeExtRefs;
60 llvm::DIBuilder DBuilder;
61 llvm::DICompileUnit *TheCU = nullptr;
62 ModuleMap *ClangModuleMap = nullptr;
63 ExternalASTSource::ASTSourceDescriptor PCHDescriptor;
64 SourceLocation CurLoc;
65 llvm::MDNode *CurInlinedAt = nullptr;
66 llvm::DIType *VTablePtrType = nullptr;
67 llvm::DIType *ClassTy = nullptr;
68 llvm::DICompositeType *ObjTy = nullptr;
69 llvm::DIType *SelTy = nullptr;
70#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
71 llvm::DIType *SingletonId = nullptr;
72#include "clang/Basic/OpenCLImageTypes.def"
73 llvm::DIType *OCLSamplerDITy = nullptr;
74 llvm::DIType *OCLEventDITy = nullptr;
75 llvm::DIType *OCLClkEventDITy = nullptr;
76 llvm::DIType *OCLQueueDITy = nullptr;
77 llvm::DIType *OCLNDRangeDITy = nullptr;
78 llvm::DIType *OCLReserveIDDITy = nullptr;
79
80 /// Cache of previously constructed Types.
81 llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
82
83 llvm::SmallDenseMap<llvm::StringRef, llvm::StringRef> DebugPrefixMap;
84
85 /// Cache that maps VLA types to size expressions for that type,
86 /// represented by instantiated Metadata nodes.
87 llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;
88
89 struct ObjCInterfaceCacheEntry {
90 const ObjCInterfaceType *Type;
91 llvm::DIType *Decl;
92 llvm::DIFile *Unit;
93 ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType *Decl,
94 llvm::DIFile *Unit)
95 : Type(Type), Decl(Decl), Unit(Unit) {}
96 };
97
98 /// Cache of previously constructed interfaces which may change.
99 llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
100
101 /// Cache of references to clang modules and precompiled headers.
102 llvm::DenseMap<const Module *, llvm::TrackingMDRef> ModuleCache;
103
104 /// List of interfaces we want to keep even if orphaned.
105 std::vector<void *> RetainedTypes;
106
107 /// Cache of forward declared types to RAUW at the end of compilation.
108 std::vector<std::pair<const TagType *, llvm::TrackingMDRef>> ReplaceMap;
109
110 /// Cache of replaceable forward declarations (functions and
111 /// variables) to RAUW at the end of compilation.
112 std::vector<std::pair<const DeclaratorDecl *, llvm::TrackingMDRef>>
113 FwdDeclReplaceMap;
114
115 /// Keep track of our current nested lexical block.
116 std::vector<llvm::TypedTrackingMDRef<llvm::DIScope>> LexicalBlockStack;
117 llvm::DenseMap<const Decl *, llvm::TrackingMDRef> RegionMap;
118 /// Keep track of LexicalBlockStack counter at the beginning of a
119 /// function. This is used to pop unbalanced regions at the end of a
120 /// function.
121 std::vector<unsigned> FnBeginRegionCount;
122
123 /// This is a storage for names that are constructed on demand. For
124 /// example, C++ destructors, C++ operators etc..
125 llvm::BumpPtrAllocator DebugInfoNames;
126 StringRef CWDName;
127
128 llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;
129 llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;
130 /// Cache declarations relevant to DW_TAG_imported_declarations (C++
131 /// using declarations) that aren't covered by other more specific caches.
132 llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;
133 llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache;
134 llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>
135 NamespaceAliasCache;
136 llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>>
137 StaticDataMemberCache;
138
139 /// Helper functions for getOrCreateType.
140 /// @{
141 /// Currently the checksum of an interface includes the number of
142 /// ivars and property accessors.
143 llvm::DIType *CreateType(const BuiltinType *Ty);
144 llvm::DIType *CreateType(const ComplexType *Ty);
145 llvm::DIType *CreateQualifiedType(QualType Ty, llvm::DIFile *Fg);
146 llvm::DIType *CreateType(const TypedefType *Ty, llvm::DIFile *Fg);
147 llvm::DIType *CreateType(const TemplateSpecializationType *Ty,
148 llvm::DIFile *Fg);
149 llvm::DIType *CreateType(const ObjCObjectPointerType *Ty, llvm::DIFile *F);
150 llvm::DIType *CreateType(const PointerType *Ty, llvm::DIFile *F);
151 llvm::DIType *CreateType(const BlockPointerType *Ty, llvm::DIFile *F);
152 llvm::DIType *CreateType(const FunctionType *Ty, llvm::DIFile *F);
153 /// Get structure or union type.
154 llvm::DIType *CreateType(const RecordType *Tyg);
155 llvm::DIType *CreateTypeDefinition(const RecordType *Ty);
156 llvm::DICompositeType *CreateLimitedType(const RecordType *Ty);
157 void CollectContainingType(const CXXRecordDecl *RD,
158 llvm::DICompositeType *CT);
159 /// Get Objective-C interface type.
160 llvm::DIType *CreateType(const ObjCInterfaceType *Ty, llvm::DIFile *F);
161 llvm::DIType *CreateTypeDefinition(const ObjCInterfaceType *Ty,
162 llvm::DIFile *F);
163 /// Get Objective-C object type.
164 llvm::DIType *CreateType(const ObjCObjectType *Ty, llvm::DIFile *F);
165 llvm::DIType *CreateType(const ObjCTypeParamType *Ty, llvm::DIFile *Unit);
166
167 llvm::DIType *CreateType(const VectorType *Ty, llvm::DIFile *F);
168 llvm::DIType *CreateType(const ArrayType *Ty, llvm::DIFile *F);
169 llvm::DIType *CreateType(const LValueReferenceType *Ty, llvm::DIFile *F);
170 llvm::DIType *CreateType(const RValueReferenceType *Ty, llvm::DIFile *Unit);
171 llvm::DIType *CreateType(const MemberPointerType *Ty, llvm::DIFile *F);
172 llvm::DIType *CreateType(const AtomicType *Ty, llvm::DIFile *F);
173 llvm::DIType *CreateType(const PipeType *Ty, llvm::DIFile *F);
174 /// Get enumeration type.
175 llvm::DIType *CreateEnumType(const EnumType *Ty);
176 llvm::DIType *CreateTypeDefinition(const EnumType *Ty);
177 /// Look up the completed type for a self pointer in the TypeCache and
178 /// create a copy of it with the ObjectPointer and Artificial flags
179 /// set. If the type is not cached, a new one is created. This should
180 /// never happen though, since creating a type for the implicit self
181 /// argument implies that we already parsed the interface definition
182 /// and the ivar declarations in the implementation.
183 llvm::DIType *CreateSelfType(const QualType &QualTy, llvm::DIType *Ty);
184 /// @}
185
186 /// Get the type from the cache or return null type if it doesn't
187 /// exist.
188 llvm::DIType *getTypeOrNull(const QualType);
189 /// Return the debug type for a C++ method.
190 /// \arg CXXMethodDecl is of FunctionType. This function type is
191 /// not updated to include implicit \c this pointer. Use this routine
192 /// to get a method type which includes \c this pointer.
193 llvm::DISubroutineType *getOrCreateMethodType(const CXXMethodDecl *Method,
194 llvm::DIFile *F);
195 llvm::DISubroutineType *
196 getOrCreateInstanceMethodType(QualType ThisPtr, const FunctionProtoType *Func,
197 llvm::DIFile *Unit);
198 llvm::DISubroutineType *
199 getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F);
200 /// \return debug info descriptor for vtable.
201 llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F);
202
203 /// \return namespace descriptor for the given namespace decl.
204 llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N);
205 llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty,
206 QualType PointeeTy, llvm::DIFile *F);
207 llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache);
208
209 /// A helper function to create a subprogram for a single member
210 /// function GlobalDecl.
211 llvm::DISubprogram *CreateCXXMemberFunction(const CXXMethodDecl *Method,
212 llvm::DIFile *F,
213 llvm::DIType *RecordTy);
214
215 /// A helper function to collect debug info for C++ member
216 /// functions. This is used while creating debug info entry for a
217 /// Record.
218 void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile *F,
219 SmallVectorImpl<llvm::Metadata *> &E,
220 llvm::DIType *T);
221
222 /// A helper function to collect debug info for C++ base
223 /// classes. This is used while creating debug info entry for a
224 /// Record.
225 void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile *F,
226 SmallVectorImpl<llvm::Metadata *> &EltTys,
227 llvm::DIType *RecordTy);
228
229 /// Helper function for CollectCXXBases.
230 /// Adds debug info entries for types in Bases that are not in SeenTypes.
231 void CollectCXXBasesAux(const CXXRecordDecl *RD, llvm::DIFile *Unit,
232 SmallVectorImpl<llvm::Metadata *> &EltTys,
233 llvm::DIType *RecordTy,
234 const CXXRecordDecl::base_class_const_range &Bases,
235 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
236 llvm::DINode::DIFlags StartingFlags);
237
238 /// A helper function to collect template parameters.
239 llvm::DINodeArray CollectTemplateParams(const TemplateParameterList *TPList,
240 ArrayRef<TemplateArgument> TAList,
241 llvm::DIFile *Unit);
242 /// A helper function to collect debug info for function template
243 /// parameters.
244 llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,
245 llvm::DIFile *Unit);
246
247 /// A helper function to collect debug info for template
248 /// parameters.
249 llvm::DINodeArray
250 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TS,
251 llvm::DIFile *F);
252
253 llvm::DIType *createFieldType(StringRef name, QualType type,
254 SourceLocation loc, AccessSpecifier AS,
255 uint64_t offsetInBits,
256 uint32_t AlignInBits,
257 llvm::DIFile *tunit, llvm::DIScope *scope,
258 const RecordDecl *RD = nullptr);
259
260 llvm::DIType *createFieldType(StringRef name, QualType type,
261 SourceLocation loc, AccessSpecifier AS,
262 uint64_t offsetInBits, llvm::DIFile *tunit,
263 llvm::DIScope *scope,
264 const RecordDecl *RD = nullptr) {
265 return createFieldType(name, type, loc, AS, offsetInBits, 0, tunit, scope,
266 RD);
267 }
268
269 /// Create new bit field member.
270 llvm::DIType *createBitFieldType(const FieldDecl *BitFieldDecl,
271 llvm::DIScope *RecordTy,
272 const RecordDecl *RD);
273
274 /// Helpers for collecting fields of a record.
275 /// @{
276 void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
277 SmallVectorImpl<llvm::Metadata *> &E,
278 llvm::DIType *RecordTy);
279 llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,
280 llvm::DIType *RecordTy,
281 const RecordDecl *RD);
282 void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
283 llvm::DIFile *F,
284 SmallVectorImpl<llvm::Metadata *> &E,
285 llvm::DIType *RecordTy, const RecordDecl *RD);
286 void CollectRecordNestedType(const TypeDecl *RD,
287 SmallVectorImpl<llvm::Metadata *> &E);
288 void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,
289 SmallVectorImpl<llvm::Metadata *> &E,
290 llvm::DICompositeType *RecordTy);
291
292 /// If the C++ class has vtable info then insert appropriate debug
293 /// info entry in EltTys vector.
294 void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,
295 SmallVectorImpl<llvm::Metadata *> &EltTys,
296 llvm::DICompositeType *RecordTy);
297 /// @}
298
299 /// Create a new lexical block node and push it on the stack.
300 void CreateLexicalBlock(SourceLocation Loc);
301
302 /// If target-specific LLVM \p AddressSpace directly maps to target-specific
303 /// DWARF address space, appends extended dereferencing mechanism to complex
304 /// expression \p Expr. Otherwise, does nothing.
305 ///
306 /// Extended dereferencing mechanism is has the following format:
307 /// DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
308 void AppendAddressSpaceXDeref(unsigned AddressSpace,
309 SmallVectorImpl<int64_t> &Expr) const;
310
311public:
312 CGDebugInfo(CodeGenModule &CGM);
313 ~CGDebugInfo();
314
315 void finalize();
316
317 /// Register VLA size expression debug node with the qualified type.
318 void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {
319 SizeExprCache[Ty] = SizeExpr;
320 }
321
322 /// Module debugging: Support for building PCMs.
323 /// @{
324 /// Set the main CU's DwoId field to \p Signature.
325 void setDwoId(uint64_t Signature);
326
327 /// When generating debug information for a clang module or
328 /// precompiled header, this module map will be used to determine
329 /// the module of origin of each Decl.
330 void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }
331
332 /// When generating debug information for a clang module or
333 /// precompiled header, this module map will be used to determine
334 /// the module of origin of each Decl.
335 void setPCHDescriptor(ExternalASTSource::ASTSourceDescriptor PCH) {
336 PCHDescriptor = PCH;
337 }
338 /// @}
339
340 /// Update the current source location. If \arg loc is invalid it is
341 /// ignored.
342 void setLocation(SourceLocation Loc);
343
344 /// Return the current source location. This does not necessarily correspond
345 /// to the IRBuilder's current DebugLoc.
346 SourceLocation getLocation() const { return CurLoc; }
347
348 /// Update the current inline scope. All subsequent calls to \p EmitLocation
349 /// will create a location with this inlinedAt field.
350 void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }
351
352 /// \return the current inline scope.
353 llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }
354
355 // Converts a SourceLocation to a DebugLoc
356 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);
357
358 /// Emit metadata to indicate a change in line/column information in
359 /// the source file. If the location is invalid, the previous
360 /// location will be reused.
361 void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
362
363 /// Emit a call to llvm.dbg.function.start to indicate
364 /// start of a new function.
365 /// \param Loc The location of the function header.
366 /// \param ScopeLoc The location of the function body.
367 void EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
368 SourceLocation ScopeLoc, QualType FnType,
369 llvm::Function *Fn, CGBuilderTy &Builder);
370
371 /// Start a new scope for an inlined function.
372 void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);
373 /// End an inlined function scope.
374 void EmitInlineFunctionEnd(CGBuilderTy &Builder);
375
376 /// Emit debug info for a function declaration.
377 void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType);
378
379 /// Constructs the debug code for exiting a function.
380 void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);
381
382 /// Emit metadata to indicate the beginning of a new lexical block
383 /// and push the block onto the stack.
384 void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
385
386 /// Emit metadata to indicate the end of a new lexical block and pop
387 /// the current block.
388 void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
389
390 /// Emit call to \c llvm.dbg.declare for an automatic variable
391 /// declaration.
392 /// Returns a pointer to the DILocalVariable associated with the
393 /// llvm.dbg.declare, or nullptr otherwise.
394 llvm::DILocalVariable *EmitDeclareOfAutoVariable(const VarDecl *Decl,
395 llvm::Value *AI,
396 CGBuilderTy &Builder);
397
398 /// Emit call to \c llvm.dbg.declare for an imported variable
399 /// declaration in a block.
400 void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable,
401 llvm::Value *storage,
402 CGBuilderTy &Builder,
403 const CGBlockInfo &blockInfo,
404 llvm::Instruction *InsertPoint = nullptr);
405
406 /// Emit call to \c llvm.dbg.declare for an argument variable
407 /// declaration.
408 void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
409 unsigned ArgNo, CGBuilderTy &Builder);
410
411 /// Emit call to \c llvm.dbg.declare for the block-literal argument
412 /// to a block invocation function.
413 void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
414 StringRef Name, unsigned ArgNo,
415 llvm::AllocaInst *LocalAddr,
416 CGBuilderTy &Builder);
417
418 /// Emit information about a global variable.
419 void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
420
421 /// Emit a constant global variable's debug info.
422 void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
423
424 /// Emit C++ using directive.
425 void EmitUsingDirective(const UsingDirectiveDecl &UD);
426
427 /// Emit the type explicitly casted to.
428 void EmitExplicitCastType(QualType Ty);
429
430 /// Emit C++ using declaration.
431 void EmitUsingDecl(const UsingDecl &UD);
432
433 /// Emit an @import declaration.
434 void EmitImportDecl(const ImportDecl &ID);
435
436 /// Emit C++ namespace alias.
437 llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
438
439 /// Emit record type's standalone debug info.
440 llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
441
442 /// Emit an Objective-C interface type standalone debug info.
443 llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
444
445 /// Emit standalone debug info for a type.
446 llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
447
448 void completeType(const EnumDecl *ED);
449 void completeType(const RecordDecl *RD);
450 void completeRequiredType(const RecordDecl *RD);
451 void completeClassData(const RecordDecl *RD);
452 void completeClass(const RecordDecl *RD);
453
454 void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
455 void completeUnusedClass(const CXXRecordDecl &D);
456
457 /// Create debug info for a macro defined by a #define directive or a macro
458 /// undefined by a #undef directive.
459 llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,
460 SourceLocation LineLoc, StringRef Name,
461 StringRef Value);
462
463 /// Create debug info for a file referenced by an #include directive.
464 llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,
465 SourceLocation LineLoc,
466 SourceLocation FileLoc);
467
468private:
469 /// Emit call to llvm.dbg.declare for a variable declaration.
470 /// Returns a pointer to the DILocalVariable associated with the
471 /// llvm.dbg.declare, or nullptr otherwise.
472 llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,
473 llvm::Optional<unsigned> ArgNo,
474 CGBuilderTy &Builder);
475
476 /// Build up structure info for the byref. See \a BuildByRefType.
477 llvm::DIType *EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
478 uint64_t *OffSet);
479
480 /// Get context info for the DeclContext of \p Decl.
481 llvm::DIScope *getDeclContextDescriptor(const Decl *D);
482 /// Get context info for a given DeclContext \p Decl.
483 llvm::DIScope *getContextDescriptor(const Decl *Context,
484 llvm::DIScope *Default);
485
486 llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
487
488 /// Create a forward decl for a RecordType in a given context.
489 llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
490 llvm::DIScope *);
491
492 /// Return current directory name.
493 StringRef getCurrentDirname();
494
495 /// Create new compile unit.
496 void CreateCompileUnit();
497
498 /// Remap a given path with the current debug prefix map
499 std::string remapDIPath(StringRef) const;
500
501 /// Compute the file checksum debug info for input file ID.
502 Optional<llvm::DIFile::ChecksumKind>
503 computeChecksum(FileID FID, SmallString<32> &Checksum) const;
504
505 /// Get the file debug info descriptor for the input location.
506 llvm::DIFile *getOrCreateFile(SourceLocation Loc);
507
508 /// Get the file info for main compile unit.
509 llvm::DIFile *getOrCreateMainFile();
510
511 /// Get the type from the cache or create a new type if necessary.
512 llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
513
514 /// Get a reference to a clang module. If \p CreateSkeletonCU is true,
515 /// this also creates a split dwarf skeleton compile unit.
516 llvm::DIModule *
517 getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
518 bool CreateSkeletonCU);
519
520 /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
521 llvm::DIModule *getParentModuleOrNull(const Decl *D);
522
523 /// Get the type from the cache or create a new partial type if
524 /// necessary.
525 llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty,
526 llvm::DIFile *F);
527
528 /// Create type metadata for a source language type.
529 llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
530
531 /// Create new member and increase Offset by FType's size.
532 llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
533 StringRef Name, uint64_t *Offset);
534
535 /// Retrieve the DIDescriptor, if any, for the canonical form of this
536 /// declaration.
537 llvm::DINode *getDeclarationOrDefinition(const Decl *D);
538
539 /// \return debug info descriptor to describe method
540 /// declaration for the given method definition.
541 llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
542
543 /// \return debug info descriptor to describe in-class static data
544 /// member declaration for the given out-of-class definition. If D
545 /// is an out-of-class definition of a static data member of a
546 /// class, find its corresponding in-class declaration.
547 llvm::DIDerivedType *
548 getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
549
550 /// Helper that either creates a forward declaration or a stub.
551 llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
552
553 /// Create a subprogram describing the forward declaration
554 /// represented in the given FunctionDecl wrapped in a GlobalDecl.
555 llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
556
557 /// Create a DISubprogram describing the function
558 /// represented in the given FunctionDecl wrapped in a GlobalDecl.
559 llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
560
561 /// Create a global variable describing the forward declaration
562 /// represented in the given VarDecl.
563 llvm::DIGlobalVariable *
564 getGlobalVariableForwardDeclaration(const VarDecl *VD);
565
566 /// Return a global variable that represents one of the collection of global
567 /// variables created for an anonmyous union.
568 ///
569 /// Recursively collect all of the member fields of a global
570 /// anonymous decl and create static variables for them. The first
571 /// time this is called it needs to be on a union and then from
572 /// there we can have additional unnamed fields.
573 llvm::DIGlobalVariableExpression *
574 CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
575 unsigned LineNo, StringRef LinkageName,
576 llvm::GlobalVariable *Var, llvm::DIScope *DContext);
577
578 /// Get the printing policy for producing names for debug info.
579 PrintingPolicy getPrintingPolicy() const;
580
581 /// Get function name for the given FunctionDecl. If the name is
582 /// constructed on demand (e.g., C++ destructor) then the name is
583 /// stored on the side.
584 StringRef getFunctionName(const FunctionDecl *FD);
585
586 /// Returns the unmangled name of an Objective-C method.
587 /// This is the display name for the debugging info.
588 StringRef getObjCMethodName(const ObjCMethodDecl *FD);
589
590 /// Return selector name. This is used for debugging
591 /// info.
592 StringRef getSelectorName(Selector S);
593
594 /// Get class name including template argument list.
595 StringRef getClassName(const RecordDecl *RD);
596
597 /// Get the vtable name for the given class.
598 StringRef getVTableName(const CXXRecordDecl *Decl);
599
600 /// Get line number for the location. If location is invalid
601 /// then use current location.
602 unsigned getLineNumber(SourceLocation Loc);
603
604 /// Get column number for the location. If location is
605 /// invalid then use current location.
606 /// \param Force Assume DebugColumnInfo option is true.
607 unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
608
609 /// Collect various properties of a FunctionDecl.
610 /// \param GD A GlobalDecl whose getDecl() must return a FunctionDecl.
611 void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
612 StringRef &Name, StringRef &LinkageName,
613 llvm::DIScope *&FDContext,
614 llvm::DINodeArray &TParamsArray,
615 llvm::DINode::DIFlags &Flags);
616
617 /// Collect various properties of a VarDecl.
618 void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
619 unsigned &LineNo, QualType &T, StringRef &Name,
620 StringRef &LinkageName, llvm::DIScope *&VDContext);
621
622 /// Allocate a copy of \p A using the DebugInfoNames allocator
623 /// and return a reference to it. If multiple arguments are given the strings
624 /// are concatenated.
625 StringRef internString(StringRef A, StringRef B = StringRef()) {
626 char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
627 if (!A.empty())
15
Assuming the condition is false
16
Taking false branch
628 std::memcpy(Data, A.data(), A.size());
629 if (!B.empty())
17
Assuming the condition is true
18
Taking true branch
630 std::memcpy(Data + A.size(), B.data(), B.size());
19
Null pointer passed as an argument to a 'nonnull' parameter
631 return StringRef(Data, A.size() + B.size());
632 }
633};
634
635/// A scoped helper to set the current debug location to the specified
636/// location or preferred location of the specified Expr.
637class ApplyDebugLocation {
638private:
639 void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
640 ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
641 SourceLocation TemporaryLocation);
642
643 llvm::DebugLoc OriginalLocation;
644 CodeGenFunction *CGF;
645
646public:
647 /// Set the location to the (valid) TemporaryLocation.
648 ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
649 ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
650 ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
651 ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
652 Other.CGF = nullptr;
653 }
654
655 ~ApplyDebugLocation();
656
657 /// \brief Apply TemporaryLocation if it is valid. Otherwise switch
658 /// to an artificial debug location that has a valid scope, but no
659 /// line information.
660 ///
661 /// Artificial locations are useful when emitting compiler-generated
662 /// helper functions that have no source location associated with
663 /// them. The DWARF specification allows the compiler to use the
664 /// special line number 0 to indicate code that can not be
665 /// attributed to any source location. Note that passing an empty
666 /// SourceLocation to CGDebugInfo::setLocation() will result in the
667 /// last valid location being reused.
668 static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
669 return ApplyDebugLocation(CGF, false, SourceLocation());
670 }
671 /// \brief Apply TemporaryLocation if it is valid. Otherwise switch
672 /// to an artificial debug location that has a valid scope, but no
673 /// line information.
674 static ApplyDebugLocation
675 CreateDefaultArtificial(CodeGenFunction &CGF,
676 SourceLocation TemporaryLocation) {
677 return ApplyDebugLocation(CGF, false, TemporaryLocation);
678 }
679
680 /// Set the IRBuilder to not attach debug locations. Note that
681 /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
682 /// will result in the last valid location being reused. Note that
683 /// all instructions that do not have a location at the beginning of
684 /// a function are counted towards to function prologue.
685 static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
686 return ApplyDebugLocation(CGF, true, SourceLocation());
687 }
688
689};
690
691/// A scoped helper to set the current debug location to an inlined location.
692class ApplyInlineDebugLocation {
693 SourceLocation SavedLocation;
694 CodeGenFunction *CGF;
695
696public:
697 /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
698 /// function \p InlinedFn. The current debug location becomes the inlined call
699 /// site of the inlined function.
700 ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
701 /// Restore everything back to the orginial state.
702 ~ApplyInlineDebugLocation();
703};
704
705} // namespace CodeGen
706} // namespace clang
707
708#endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H