Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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