Bug Summary

File:tools/clang/lib/CodeGen/CGDebugInfo.cpp
Warning:line 633, 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~svn326551/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/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~svn326551/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-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/CodeGen/CGDebugInfo.cpp

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

/build/llvm-toolchain-snapshot-7~svn326551/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 source of the given file ID.
506 Optional<StringRef> getSource(const SourceManager &SM, FileID FID);
507
508 /// Get the file debug info descriptor for the input location.
509 llvm::DIFile *getOrCreateFile(SourceLocation Loc);
510
511 /// Get the file info for main compile unit.
512 llvm::DIFile *getOrCreateMainFile();
513
514 /// Get the type from the cache or create a new type if necessary.
515 llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
516
517 /// Get a reference to a clang module. If \p CreateSkeletonCU is true,
518 /// this also creates a split dwarf skeleton compile unit.
519 llvm::DIModule *
520 getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
521 bool CreateSkeletonCU);
522
523 /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
524 llvm::DIModule *getParentModuleOrNull(const Decl *D);
525
526 /// Get the type from the cache or create a new partial type if
527 /// necessary.
528 llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty,
529 llvm::DIFile *F);
530
531 /// Create type metadata for a source language type.
532 llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
533
534 /// Create new member and increase Offset by FType's size.
535 llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
536 StringRef Name, uint64_t *Offset);
537
538 /// Retrieve the DIDescriptor, if any, for the canonical form of this
539 /// declaration.
540 llvm::DINode *getDeclarationOrDefinition(const Decl *D);
541
542 /// \return debug info descriptor to describe method
543 /// declaration for the given method definition.
544 llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
545
546 /// \return debug info descriptor to describe in-class static data
547 /// member declaration for the given out-of-class definition. If D
548 /// is an out-of-class definition of a static data member of a
549 /// class, find its corresponding in-class declaration.
550 llvm::DIDerivedType *
551 getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
552
553 /// Helper that either creates a forward declaration or a stub.
554 llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
555
556 /// Create a subprogram describing the forward declaration
557 /// represented in the given FunctionDecl wrapped in a GlobalDecl.
558 llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
559
560 /// Create a DISubprogram describing the function
561 /// represented in the given FunctionDecl wrapped in a GlobalDecl.
562 llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
563
564 /// Create a global variable describing the forward declaration
565 /// represented in the given VarDecl.
566 llvm::DIGlobalVariable *
567 getGlobalVariableForwardDeclaration(const VarDecl *VD);
568
569 /// Return a global variable that represents one of the collection of global
570 /// variables created for an anonmyous union.
571 ///
572 /// Recursively collect all of the member fields of a global
573 /// anonymous decl and create static variables for them. The first
574 /// time this is called it needs to be on a union and then from
575 /// there we can have additional unnamed fields.
576 llvm::DIGlobalVariableExpression *
577 CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
578 unsigned LineNo, StringRef LinkageName,
579 llvm::GlobalVariable *Var, llvm::DIScope *DContext);
580
581 /// Get the printing policy for producing names for debug info.
582 PrintingPolicy getPrintingPolicy() const;
583
584 /// Get function name for the given FunctionDecl. If the name is
585 /// constructed on demand (e.g., C++ destructor) then the name is
586 /// stored on the side.
587 StringRef getFunctionName(const FunctionDecl *FD);
588
589 /// Returns the unmangled name of an Objective-C method.
590 /// This is the display name for the debugging info.
591 StringRef getObjCMethodName(const ObjCMethodDecl *FD);
592
593 /// Return selector name. This is used for debugging
594 /// info.
595 StringRef getSelectorName(Selector S);
596
597 /// Get class name including template argument list.
598 StringRef getClassName(const RecordDecl *RD);
599
600 /// Get the vtable name for the given class.
601 StringRef getVTableName(const CXXRecordDecl *Decl);
602
603 /// Get line number for the location. If location is invalid
604 /// then use current location.
605 unsigned getLineNumber(SourceLocation Loc);
606
607 /// Get column number for the location. If location is
608 /// invalid then use current location.
609 /// \param Force Assume DebugColumnInfo option is true.
610 unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
611
612 /// Collect various properties of a FunctionDecl.
613 /// \param GD A GlobalDecl whose getDecl() must return a FunctionDecl.
614 void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
615 StringRef &Name, StringRef &LinkageName,
616 llvm::DIScope *&FDContext,
617 llvm::DINodeArray &TParamsArray,
618 llvm::DINode::DIFlags &Flags);
619
620 /// Collect various properties of a VarDecl.
621 void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
622 unsigned &LineNo, QualType &T, StringRef &Name,
623 StringRef &LinkageName, llvm::DIScope *&VDContext);
624
625 /// Allocate a copy of \p A using the DebugInfoNames allocator
626 /// and return a reference to it. If multiple arguments are given the strings
627 /// are concatenated.
628 StringRef internString(StringRef A, StringRef B = StringRef()) {
629 char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
630 if (!A.empty())
13
Assuming the condition is false
14
Taking false branch
631 std::memcpy(Data, A.data(), A.size());
632 if (!B.empty())
15
Assuming the condition is true
16
Taking true branch
633 std::memcpy(Data + A.size(), B.data(), B.size());
17
Null pointer passed as an argument to a 'nonnull' parameter
634 return StringRef(Data, A.size() + B.size());
635 }
636};
637
638/// A scoped helper to set the current debug location to the specified
639/// location or preferred location of the specified Expr.
640class ApplyDebugLocation {
641private:
642 void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
643 ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
644 SourceLocation TemporaryLocation);
645
646 llvm::DebugLoc OriginalLocation;
647 CodeGenFunction *CGF;
648
649public:
650 /// Set the location to the (valid) TemporaryLocation.
651 ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
652 ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
653 ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
654 ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
655 Other.CGF = nullptr;
656 }
657
658 ~ApplyDebugLocation();
659
660 /// \brief Apply TemporaryLocation if it is valid. Otherwise switch
661 /// to an artificial debug location that has a valid scope, but no
662 /// line information.
663 ///
664 /// Artificial locations are useful when emitting compiler-generated
665 /// helper functions that have no source location associated with
666 /// them. The DWARF specification allows the compiler to use the
667 /// special line number 0 to indicate code that can not be
668 /// attributed to any source location. Note that passing an empty
669 /// SourceLocation to CGDebugInfo::setLocation() will result in the
670 /// last valid location being reused.
671 static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
672 return ApplyDebugLocation(CGF, false, SourceLocation());
673 }
674 /// \brief Apply TemporaryLocation if it is valid. Otherwise switch
675 /// to an artificial debug location that has a valid scope, but no
676 /// line information.
677 static ApplyDebugLocation
678 CreateDefaultArtificial(CodeGenFunction &CGF,
679 SourceLocation TemporaryLocation) {
680 return ApplyDebugLocation(CGF, false, TemporaryLocation);
681 }
682
683 /// Set the IRBuilder to not attach debug locations. Note that
684 /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
685 /// will result in the last valid location being reused. Note that
686 /// all instructions that do not have a location at the beginning of
687 /// a function are counted towards to function prologue.
688 static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
689 return ApplyDebugLocation(CGF, true, SourceLocation());
690 }
691
692};
693
694/// A scoped helper to set the current debug location to an inlined location.
695class ApplyInlineDebugLocation {
696 SourceLocation SavedLocation;
697 CodeGenFunction *CGF;
698
699public:
700 /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
701 /// function \p InlinedFn. The current debug location becomes the inlined call
702 /// site of the inlined function.
703 ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
704 /// Restore everything back to the orginial state.
705 ~ApplyInlineDebugLocation();
706};
707
708} // namespace CodeGen
709} // namespace clang
710
711#endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H