1//===- DWARFDie.cpp -------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/DebugInfo/DWARF/DWARFDie.h"
10#include "llvm/ADT/SmallPtrSet.h"
11#include "llvm/ADT/SmallSet.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/BinaryFormat/Dwarf.h"
14#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
15#include "llvm/DebugInfo/DWARF/DWARFContext.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
17#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
18#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
19#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20#include "llvm/DebugInfo/DWARF/DWARFTypePrinter.h"
21#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
22#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
23#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
24#include "llvm/Object/ObjectFile.h"
25#include "llvm/Support/DataExtractor.h"
26#include "llvm/Support/Format.h"
27#include "llvm/Support/FormatVariadic.h"
28#include "llvm/Support/WithColor.h"
29#include "llvm/Support/raw_ostream.h"
30#include <cassert>
31#include <cinttypes>
32#include <cstdint>
33#include <string>
34
35using namespace llvm;
36using namespace dwarf;
37using namespace object;
38
39static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
40 OS << " (";
41 do {
42 uint64_t Shift = llvm::countr_zero(Val);
43 assert(Shift < 64 && "undefined behavior");
44 uint64_t Bit = 1ULL << Shift;
45 auto PropName = ApplePropertyString(Bit);
46 if (!PropName.empty())
47 OS << PropName;
48 else
49 OS << formatv(Fmt: "DW_APPLE_PROPERTY_{0:x}", Vals&: Bit);
50 if (!(Val ^= Bit))
51 break;
52 OS << ", ";
53 } while (true);
54 OS << ")";
55}
56
57static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
58 const DWARFAddressRangesVector &Ranges,
59 unsigned AddressSize, unsigned Indent,
60 const DIDumpOptions &DumpOpts) {
61 if (!DumpOpts.ShowAddresses)
62 return;
63
64 for (const DWARFAddressRange &R : Ranges) {
65 OS << '\n';
66 OS.indent(NumSpaces: Indent);
67 R.dump(OS, AddressSize, DumpOpts, Obj: &Obj);
68 }
69}
70
71static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
72 DWARFUnit *U, unsigned Indent,
73 DIDumpOptions DumpOpts) {
74 assert(FormValue.isFormClass(DWARFFormValue::FC_SectionOffset) &&
75 "bad FORM for location list");
76 DWARFContext &Ctx = U->getContext();
77 uint64_t Offset = *FormValue.getAsSectionOffset();
78
79 if (FormValue.getForm() == DW_FORM_loclistx) {
80 FormValue.dump(OS, DumpOpts);
81
82 if (auto LoclistOffset = U->getLoclistOffset(Index: Offset))
83 Offset = *LoclistOffset;
84 else
85 return;
86 }
87 U->getLocationTable().dumpLocationList(
88 Offset: &Offset, OS, BaseAddr: U->getBaseAddress(), Obj: Ctx.getDWARFObj(), U, DumpOpts, Indent);
89}
90
91static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue,
92 DWARFUnit *U, unsigned Indent,
93 DIDumpOptions DumpOpts) {
94 assert((FormValue.isFormClass(DWARFFormValue::FC_Block) ||
95 FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) &&
96 "bad FORM for location expression");
97 DWARFContext &Ctx = U->getContext();
98 ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
99 DataExtractor Data(Expr, Ctx.isLittleEndian());
100 DWARFExpression DE(Data, U->getAddressByteSize(), U->getFormParams().Format);
101 printDwarfExpression(E: &DE, OS, DumpOpts, U);
102}
103
104static DWARFDie resolveReferencedType(DWARFDie D, DWARFFormValue F) {
105 return D.getAttributeValueAsReferencedDie(V: F).resolveTypeUnitReference();
106}
107
108static llvm::StringRef
109prettyLanguageVersionString(const DWARFAttribute &AttrValue,
110 const DWARFDie &Die) {
111 if (AttrValue.Attr != DW_AT_language_version)
112 return {};
113
114 auto NameForm = Die.find(Attr: DW_AT_language_name);
115 if (!NameForm)
116 return {};
117
118 auto LName = NameForm->getAsUnsignedConstant();
119 if (!LName)
120 return {};
121
122 auto LVersion = AttrValue.Value.getAsUnsignedConstant();
123 if (!LVersion)
124 return {};
125
126 return llvm::dwarf::LanguageDescription(
127 Name: static_cast<SourceLanguageName>(*LName), Version: *LVersion);
128}
129
130static llvm::Expected<llvm::StringRef>
131getApplePropertyName(const DWARFDie &PropDIE) {
132 if (!PropDIE)
133 return llvm::createStringError(Fmt: "invalid DIE");
134
135 if (PropDIE.getTag() != DW_TAG_APPLE_property)
136 return llvm::createStringError(Fmt: "not referencing a DW_TAG_APPLE_property");
137
138 auto PropNameForm = PropDIE.find(Attr: DW_AT_APPLE_property_name);
139 if (!PropNameForm)
140 return "";
141
142 auto NameOrErr = PropNameForm->getAsCString();
143 if (!NameOrErr)
144 return NameOrErr.takeError();
145
146 return *NameOrErr;
147}
148
149static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
150 const DWARFAttribute &AttrValue, unsigned Indent,
151 DIDumpOptions DumpOpts) {
152 if (!Die.isValid())
153 return;
154 const char BaseIndent[] = " ";
155 OS << BaseIndent;
156 OS.indent(NumSpaces: Indent + 2);
157 dwarf::Attribute Attr = AttrValue.Attr;
158 WithColor(OS, HighlightColor::Attribute) << formatv(Fmt: "{0}", Vals&: Attr);
159
160 dwarf::Form Form = AttrValue.Value.getForm();
161 if (DumpOpts.Verbose || DumpOpts.ShowForm)
162 OS << formatv(Fmt: " [{0}]", Vals&: Form);
163
164 DWARFUnit *U = Die.getDwarfUnit();
165 const DWARFFormValue &FormValue = AttrValue.Value;
166
167 OS << "\t(";
168
169 StringRef Name;
170 std::string File;
171 auto Color = HighlightColor::Enumerator;
172 if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
173 Color = HighlightColor::String;
174 if (const auto *LT = U->getContext().getLineTableForUnit(U)) {
175 if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant()) {
176 if (LT->getFileNameByIndex(
177 FileIndex: *Val, CompDir: U->getCompilationDir(),
178 Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
179 Result&: File)) {
180 File = '"' + File + '"';
181 Name = File;
182 }
183 }
184 }
185 } else if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
186 Name = AttributeValueString(Attr, Val: *Val);
187
188 auto DumpUnsignedConstant = [&OS,
189 &DumpOpts](const DWARFFormValue &FormValue) {
190 if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
191 OS << *Val;
192 else
193 FormValue.dump(OS, DumpOpts);
194 };
195
196 llvm::StringRef PrettyVersionName =
197 prettyLanguageVersionString(AttrValue, Die);
198 bool ShouldDumpRawLanguageVersion =
199 Attr == DW_AT_language_version &&
200 (DumpOpts.Verbose || PrettyVersionName.empty());
201
202 if (!Name.empty())
203 WithColor(OS, Color) << Name;
204 else if (Attr == DW_AT_decl_line || Attr == DW_AT_decl_column ||
205 Attr == DW_AT_call_line || Attr == DW_AT_call_column) {
206 DumpUnsignedConstant(FormValue);
207 } else if (Attr == DW_AT_language_version) {
208 if (ShouldDumpRawLanguageVersion)
209 DumpUnsignedConstant(FormValue);
210 } else if (Attr == DW_AT_low_pc &&
211 (FormValue.getAsAddress() ==
212 dwarf::computeTombstoneAddress(AddressByteSize: U->getAddressByteSize()))) {
213 if (DumpOpts.Verbose) {
214 FormValue.dump(OS, DumpOpts);
215 OS << " (";
216 }
217 OS << "dead code";
218 if (DumpOpts.Verbose)
219 OS << ')';
220 } else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
221 FormValue.getAsUnsignedConstant()) {
222 if (DumpOpts.ShowAddresses) {
223 // Print the actual address rather than the offset.
224 uint64_t LowPC, HighPC, Index;
225 if (Die.getLowAndHighPC(LowPC, HighPC, SectionIndex&: Index))
226 DWARFFormValue::dumpAddress(OS, AddressSize: U->getAddressByteSize(), Address: HighPC);
227 else
228 FormValue.dump(OS, DumpOpts);
229 }
230 } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
231 FormValue.isFormClass(FC: DWARFFormValue::FC_SectionOffset))
232 dumpLocationList(OS, FormValue, U, Indent: sizeof(BaseIndent) + Indent + 4,
233 DumpOpts);
234 else if (FormValue.isFormClass(FC: DWARFFormValue::FC_Exprloc) ||
235 (DWARFAttribute::mayHaveLocationExpr(Attr) &&
236 FormValue.isFormClass(FC: DWARFFormValue::FC_Block)))
237 dumpLocationExpr(OS, FormValue, U, Indent: sizeof(BaseIndent) + Indent + 4,
238 DumpOpts);
239 else
240 FormValue.dump(OS, DumpOpts);
241
242 std::string Space = DumpOpts.ShowAddresses ? " " : "";
243
244 // We have dumped the attribute raw value. For some attributes
245 // having both the raw value and the pretty-printed value is
246 // interesting. These attributes are handled below.
247 if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin ||
248 Attr == DW_AT_call_origin || Attr == DW_AT_import ||
249 Attr == DW_AT_LLVM_virtual_call_origin) {
250 if (const char *Name =
251 Die.getAttributeValueAsReferencedDie(V: FormValue).getName(
252 Kind: DINameKind::LinkageName))
253 OS << Space << "\"" << Name << '\"';
254 } else if (Attr == DW_AT_APPLE_property) {
255 auto PropDIE = Die.getAttributeValueAsReferencedDie(V: FormValue);
256 if (auto PropNameOrErr = getApplePropertyName(PropDIE))
257 OS << Space << "\"" << *PropNameOrErr << '\"';
258 else
259 DumpOpts.RecoverableErrorHandler(createStringError(
260 EC: errc::invalid_argument,
261 S: llvm::formatv(Fmt: "decoding DW_AT_APPLE_property_name: {}",
262 Vals: toString(E: PropNameOrErr.takeError()))));
263 } else if (Attr == DW_AT_type || Attr == DW_AT_containing_type) {
264 DWARFDie D = resolveReferencedType(D: Die, F: FormValue);
265 if (D && !D.isNULL()) {
266 OS << Space << "\"";
267 dumpTypeQualifiedName(DIE: D, OS);
268 OS << '"';
269 }
270 } else if (Attr == DW_AT_APPLE_property_attribute) {
271 if (std::optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
272 dumpApplePropertyAttribute(OS, Val: *OptVal);
273 } else if (Attr == DW_AT_ranges) {
274 const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
275 // For DW_FORM_rnglistx we need to dump the offset separately, since
276 // we have only dumped the index so far.
277 if (FormValue.getForm() == DW_FORM_rnglistx)
278 if (auto RangeListOffset =
279 U->getRnglistOffset(Index: *FormValue.getAsSectionOffset())) {
280 DWARFFormValue FV = DWARFFormValue::createFromUValue(
281 F: dwarf::DW_FORM_sec_offset, V: *RangeListOffset);
282 FV.dump(OS, DumpOpts);
283 }
284 if (auto RangesOrError = Die.getAddressRanges())
285 dumpRanges(Obj, OS, Ranges: RangesOrError.get(), AddressSize: U->getAddressByteSize(),
286 Indent: sizeof(BaseIndent) + Indent + 4, DumpOpts);
287 else
288 DumpOpts.RecoverableErrorHandler(createStringError(
289 EC: errc::invalid_argument, Fmt: "decoding address ranges: %s",
290 Vals: toString(E: RangesOrError.takeError()).c_str()));
291 } else if (Attr == DW_AT_language_version) {
292 if (!PrettyVersionName.empty())
293 WithColor(OS, Color) << (ShouldDumpRawLanguageVersion ? " " : "")
294 << PrettyVersionName;
295 }
296
297 OS << ")\n";
298}
299
300void DWARFDie::getFullName(raw_string_ostream &OS,
301 std::string *OriginalFullName) const {
302 const char *NamePtr = getShortName();
303 if (!NamePtr)
304 return;
305 if (getTag() == DW_TAG_GNU_template_parameter_pack)
306 return;
307 dumpTypeUnqualifiedName(DIE: *this, OS, OriginalFullName);
308}
309
310bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
311
312bool DWARFDie::isSubroutineDIE() const {
313 auto Tag = getTag();
314 return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
315}
316
317std::optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
318 if (!isValid())
319 return std::nullopt;
320 auto AbbrevDecl = getAbbreviationDeclarationPtr();
321 if (AbbrevDecl)
322 return AbbrevDecl->getAttributeValue(DIEOffset: getOffset(), Attr, U: *U);
323 return std::nullopt;
324}
325
326std::optional<DWARFFormValue>
327DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
328 if (!isValid())
329 return std::nullopt;
330 auto AbbrevDecl = getAbbreviationDeclarationPtr();
331 if (AbbrevDecl) {
332 for (auto Attr : Attrs) {
333 if (auto Value = AbbrevDecl->getAttributeValue(DIEOffset: getOffset(), Attr, U: *U))
334 return Value;
335 }
336 }
337 return std::nullopt;
338}
339
340std::optional<DWARFFormValue>
341DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
342 SmallVector<DWARFDie, 3> Worklist;
343 Worklist.push_back(Elt: *this);
344
345 // Keep track if DIEs already seen to prevent infinite recursion.
346 // Empirically we rarely see a depth of more than 3 when dealing with valid
347 // DWARF. This corresponds to following the DW_AT_abstract_origin and
348 // DW_AT_specification just once.
349 SmallSet<DWARFDie, 3> Seen;
350 Seen.insert(V: *this);
351
352 while (!Worklist.empty()) {
353 DWARFDie Die = Worklist.pop_back_val();
354
355 if (!Die.isValid())
356 continue;
357
358 if (auto Value = Die.find(Attrs))
359 return Value;
360
361 for (dwarf::Attribute Attr :
362 {DW_AT_abstract_origin, DW_AT_specification, DW_AT_signature}) {
363 if (auto D = Die.getAttributeValueAsReferencedDie(Attr))
364 if (Seen.insert(V: D).second)
365 Worklist.push_back(Elt: D);
366 }
367 }
368
369 return std::nullopt;
370}
371
372DWARFDie
373DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
374 if (std::optional<DWARFFormValue> F = find(Attr))
375 return getAttributeValueAsReferencedDie(V: *F);
376 return DWARFDie();
377}
378
379DWARFDie
380DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
381 DWARFDie Result;
382 if (std::optional<uint64_t> Offset = V.getAsRelativeReference()) {
383 Result = const_cast<DWARFUnit *>(V.getUnit())
384 ->getDIEForOffset(Offset: V.getUnit()->getOffset() + *Offset);
385 } else if (Offset = V.getAsDebugInfoReference(); Offset) {
386 if (DWARFUnit *SpecUnit = U->getUnitVector().getUnitForOffset(Offset: *Offset))
387 Result = SpecUnit->getDIEForOffset(Offset: *Offset);
388 } else if (std::optional<uint64_t> Sig = V.getAsSignatureReference()) {
389 if (DWARFTypeUnit *TU =
390 U->getContext().getTypeUnitForHash(Hash: *Sig, IsDWO: U->isDWOUnit()))
391 Result = TU->getDIEForOffset(Offset: TU->getTypeOffset() + TU->getOffset());
392 }
393 return Result;
394}
395
396DWARFDie DWARFDie::resolveTypeUnitReference() const {
397 if (auto Attr = find(Attr: DW_AT_signature)) {
398 if (std::optional<uint64_t> Sig = Attr->getAsReferenceUVal()) {
399 if (DWARFTypeUnit *TU =
400 U->getContext().getTypeUnitForHash(Hash: *Sig, IsDWO: U->isDWOUnit()))
401 return TU->getDIEForOffset(Offset: TU->getTypeOffset() + TU->getOffset());
402 }
403 }
404 return *this;
405}
406
407DWARFDie DWARFDie::resolveReferencedType(dwarf::Attribute Attr) const {
408 return getAttributeValueAsReferencedDie(Attr).resolveTypeUnitReference();
409}
410DWARFDie DWARFDie::resolveReferencedType(const DWARFFormValue &V) const {
411 return getAttributeValueAsReferencedDie(V).resolveTypeUnitReference();
412}
413
414std::optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
415 return toSectionOffset(V: find(Attrs: {DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
416}
417
418std::optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
419 return toSectionOffset(V: find(Attr: DW_AT_loclists_base));
420}
421
422std::optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
423 uint64_t Tombstone = dwarf::computeTombstoneAddress(AddressByteSize: U->getAddressByteSize());
424 if (LowPC == Tombstone)
425 return std::nullopt;
426 if (auto FormValue = find(Attr: DW_AT_high_pc)) {
427 if (auto Address = FormValue->getAsAddress()) {
428 // High PC is an address.
429 return Address;
430 }
431 if (auto Offset = FormValue->getAsUnsignedConstant()) {
432 // High PC is an offset from LowPC.
433 return LowPC + *Offset;
434 }
435 }
436 return std::nullopt;
437}
438
439bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
440 uint64_t &SectionIndex) const {
441 auto F = find(Attr: DW_AT_low_pc);
442 auto LowPcAddr = toSectionedAddress(V: F);
443 if (!LowPcAddr)
444 return false;
445 if (auto HighPcAddr = getHighPC(LowPC: LowPcAddr->Address)) {
446 LowPC = LowPcAddr->Address;
447 HighPC = *HighPcAddr;
448 SectionIndex = LowPcAddr->SectionIndex;
449 return true;
450 }
451 return false;
452}
453
454Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
455 if (isNULL())
456 return DWARFAddressRangesVector();
457 // Single range specified by low/high PC.
458 uint64_t LowPC, HighPC, Index;
459 if (getLowAndHighPC(LowPC, HighPC, SectionIndex&: Index))
460 return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
461
462 std::optional<DWARFFormValue> Value = find(Attr: DW_AT_ranges);
463 if (Value) {
464 if (Value->getForm() == DW_FORM_rnglistx)
465 return U->findRnglistFromIndex(Index: *Value->getAsSectionOffset());
466 return U->findRnglistFromOffset(Offset: *Value->getAsSectionOffset());
467 }
468 return DWARFAddressRangesVector();
469}
470
471bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
472 auto RangesOrError = getAddressRanges();
473 if (!RangesOrError) {
474 llvm::consumeError(Err: RangesOrError.takeError());
475 return false;
476 }
477
478 for (const auto &R : RangesOrError.get())
479 if (R.LowPC <= Address && Address < R.HighPC)
480 return true;
481 return false;
482}
483
484// FIXME: should we return a structure akin to DISourceLanguageName here
485// encapsulates an unversioned (dwarf::SourceLanguage) and versioned
486// (dwarf::SourceLanguageName) language, and put the burden on the
487// user to determine which to use?
488std::optional<uint64_t> DWARFDie::getLanguage() const {
489 if (!isValid())
490 return std::nullopt;
491
492 DWARFDie Unit = U->getUnitDIE();
493
494 if (std::optional<DWARFFormValue> LV = Unit.find(Attr: dwarf::DW_AT_language))
495 return LV->getAsUnsignedConstant();
496
497 uint16_t Name =
498 dwarf::toUnsigned(V: Unit.find(Attr: dwarf::DW_AT_language_name), /*Default=*/0);
499 uint32_t Version = dwarf::toUnsigned(V: Unit.find(Attr: dwarf::DW_AT_language_version),
500 /*Default=*/0);
501
502 return llvm::dwarf::toDW_LANG(name: static_cast<SourceLanguageName>(Name), version: Version);
503}
504
505Expected<DWARFLocationExpressionsVector>
506DWARFDie::getLocations(dwarf::Attribute Attr) const {
507 std::optional<DWARFFormValue> Location = find(Attr);
508 if (!Location)
509 return createStringError(EC: inconvertibleErrorCode(), Fmt: "No %s",
510 Vals: dwarf::AttributeString(Attribute: Attr).data());
511
512 if (std::optional<uint64_t> Off = Location->getAsSectionOffset()) {
513 uint64_t Offset = *Off;
514
515 if (Location->getForm() == DW_FORM_loclistx) {
516 if (auto LoclistOffset = U->getLoclistOffset(Index: Offset))
517 Offset = *LoclistOffset;
518 else
519 return createStringError(EC: inconvertibleErrorCode(),
520 S: "Loclist table not found");
521 }
522 return U->findLoclistFromOffset(Offset);
523 }
524
525 if (std::optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
526 return DWARFLocationExpressionsVector{
527 DWARFLocationExpression{.Range: std::nullopt, .Expr: to_vector<4>(Range&: *Expr)}};
528 }
529
530 return createStringError(
531 EC: inconvertibleErrorCode(), Fmt: "Unsupported %s encoding: %s",
532 Vals: dwarf::AttributeString(Attribute: Attr).data(),
533 Vals: dwarf::FormEncodingString(Encoding: Location->getForm()).data());
534}
535
536const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
537 if (!isSubroutineDIE())
538 return nullptr;
539 return getName(Kind);
540}
541
542const char *DWARFDie::getName(DINameKind Kind) const {
543 if (!isValid() || Kind == DINameKind::None)
544 return nullptr;
545 // Try to get mangled name only if it was asked for.
546 if (Kind == DINameKind::LinkageName) {
547 if (auto Name = getLinkageName())
548 return Name;
549 }
550 return getShortName();
551}
552
553const char *DWARFDie::getShortName() const {
554 if (!isValid())
555 return nullptr;
556
557 return dwarf::toString(V: findRecursively(Attrs: dwarf::DW_AT_name), Default: nullptr);
558}
559
560const char *DWARFDie::getLinkageName() const {
561 if (!isValid())
562 return nullptr;
563
564 return dwarf::toString(V: findRecursively(Attrs: {dwarf::DW_AT_MIPS_linkage_name,
565 dwarf::DW_AT_linkage_name}),
566 Default: nullptr);
567}
568
569uint64_t DWARFDie::getDeclLine() const {
570 return toUnsigned(V: findRecursively(Attrs: DW_AT_decl_line), Default: 0);
571}
572
573std::string
574DWARFDie::getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const {
575 if (auto FormValue = findRecursively(Attrs: DW_AT_decl_file))
576 if (auto OptString = FormValue->getAsFile(Kind))
577 return *OptString;
578 return {};
579}
580
581void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
582 uint32_t &CallColumn,
583 uint32_t &CallDiscriminator) const {
584 CallFile = toUnsigned(V: find(Attr: DW_AT_call_file), Default: 0);
585 CallLine = toUnsigned(V: find(Attr: DW_AT_call_line), Default: 0);
586 CallColumn = toUnsigned(V: find(Attr: DW_AT_call_column), Default: 0);
587 CallDiscriminator = toUnsigned(V: find(Attr: DW_AT_GNU_discriminator), Default: 0);
588}
589
590static std::optional<uint64_t>
591getTypeSizeImpl(DWARFDie Die, uint64_t PointerSize,
592 SmallPtrSetImpl<const DWARFDebugInfoEntry *> &Visited) {
593 // Cycle detected?
594 if (!Visited.insert(Ptr: Die.getDebugInfoEntry()).second)
595 return {};
596 if (auto SizeAttr = Die.find(Attr: DW_AT_byte_size))
597 if (std::optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
598 return Size;
599
600 switch (Die.getTag()) {
601 case DW_TAG_pointer_type:
602 case DW_TAG_reference_type:
603 case DW_TAG_rvalue_reference_type:
604 return PointerSize;
605 case DW_TAG_ptr_to_member_type: {
606 if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
607 if (BaseType.getTag() == DW_TAG_subroutine_type)
608 return 2 * PointerSize;
609 return PointerSize;
610 }
611 case DW_TAG_const_type:
612 case DW_TAG_immutable_type:
613 case DW_TAG_volatile_type:
614 case DW_TAG_restrict_type:
615 case DW_TAG_template_alias:
616 case DW_TAG_typedef: {
617 if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
618 return getTypeSizeImpl(Die: BaseType, PointerSize, Visited);
619 break;
620 }
621 case DW_TAG_array_type: {
622 DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type);
623 if (!BaseType)
624 return std::nullopt;
625 std::optional<uint64_t> BaseSize =
626 getTypeSizeImpl(Die: BaseType, PointerSize, Visited);
627 if (!BaseSize)
628 return std::nullopt;
629 uint64_t Size = *BaseSize;
630 for (DWARFDie Child : Die) {
631 if (Child.getTag() != DW_TAG_subrange_type)
632 continue;
633
634 if (auto ElemCountAttr = Child.find(Attr: DW_AT_count))
635 if (std::optional<uint64_t> ElemCount =
636 ElemCountAttr->getAsUnsignedConstant())
637 Size *= *ElemCount;
638 if (auto UpperBoundAttr = Child.find(Attr: DW_AT_upper_bound))
639 if (std::optional<int64_t> UpperBound =
640 UpperBoundAttr->getAsSignedConstant()) {
641 int64_t LowerBound = 0;
642 if (auto LowerBoundAttr = Child.find(Attr: DW_AT_lower_bound))
643 LowerBound = LowerBoundAttr->getAsSignedConstant().value_or(u: 0);
644 Size *= *UpperBound - LowerBound + 1;
645 }
646 }
647 return Size;
648 }
649 default:
650 if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
651 return getTypeSizeImpl(Die: BaseType, PointerSize, Visited);
652 break;
653 }
654 return std::nullopt;
655}
656
657std::optional<uint64_t> DWARFDie::getTypeSize(uint64_t PointerSize) {
658 SmallPtrSet<const DWARFDebugInfoEntry *, 4> Visited;
659 return getTypeSizeImpl(Die: *this, PointerSize, Visited);
660}
661
662/// Helper to dump a DIE with all of its parents, but no siblings.
663static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
664 DIDumpOptions DumpOpts, unsigned Depth = 0) {
665 if (!Die)
666 return Indent;
667 if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
668 return Indent;
669 Indent = dumpParentChain(Die: Die.getParent(), OS, Indent, DumpOpts, Depth: Depth + 1);
670 Die.dump(OS, indent: Indent, DumpOpts);
671 return Indent + 2;
672}
673
674void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
675 DIDumpOptions DumpOpts) const {
676 if (!isValid())
677 return;
678 DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
679 const uint64_t Offset = getOffset();
680 uint64_t offset = Offset;
681 if (DumpOpts.ShowParents) {
682 DIDumpOptions ParentDumpOpts = DumpOpts;
683 ParentDumpOpts.ShowParents = false;
684 ParentDumpOpts.ShowChildren = false;
685 Indent = dumpParentChain(Die: getParent(), OS, Indent, DumpOpts: ParentDumpOpts);
686 }
687
688 if (debug_info_data.isValidOffset(offset)) {
689 uint32_t abbrCode = debug_info_data.getULEB128(offset_ptr: &offset);
690 if (DumpOpts.ShowAddresses)
691 WithColor(OS, HighlightColor::Address).get()
692 << formatv(Fmt: "\n{0:x8}: ", Vals: Offset);
693
694 if (abbrCode) {
695 auto AbbrevDecl = getAbbreviationDeclarationPtr();
696 if (AbbrevDecl) {
697 WithColor(OS, HighlightColor::Tag).get().indent(NumSpaces: Indent)
698 << formatv(Fmt: "{0}", Vals: getTag());
699 if (DumpOpts.Verbose) {
700 OS << formatv(Fmt: " [{0}] {1}", Vals&: abbrCode,
701 Vals: AbbrevDecl->hasChildren() ? '*' : ' ');
702 if (std::optional<uint32_t> ParentIdx = Die->getParentIdx())
703 OS << formatv(Fmt: " ({0:x8})",
704 Vals: U->getDIEAtIndex(Index: *ParentIdx).getOffset());
705 }
706 OS << '\n';
707
708 // Dump all data in the DIE for the attributes.
709 for (const DWARFAttribute &AttrValue : attributes())
710 dumpAttribute(OS, Die: *this, AttrValue, Indent, DumpOpts);
711
712 if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0) {
713 DWARFDie Child = getFirstChild();
714 DumpOpts.ChildRecurseDepth--;
715 DIDumpOptions ChildDumpOpts = DumpOpts;
716 ChildDumpOpts.ShowParents = false;
717 while (Child) {
718 if (DumpOpts.FilterChildTag.empty() ||
719 llvm::is_contained(Range&: DumpOpts.FilterChildTag, Element: Child.getTag()))
720 Child.dump(OS, Indent: Indent + 2, DumpOpts: ChildDumpOpts);
721 Child = Child.getSibling();
722 }
723 }
724 } else {
725 OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
726 << abbrCode << '\n';
727 }
728 } else {
729 OS.indent(NumSpaces: Indent) << "NULL\n";
730 }
731 }
732}
733
734LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(OS&: llvm::errs(), Indent: 0); }
735
736DWARFDie DWARFDie::getParent() const {
737 if (isValid())
738 return U->getParent(Die);
739 return DWARFDie();
740}
741
742DWARFDie DWARFDie::getSibling() const {
743 if (isValid())
744 return U->getSibling(Die);
745 return DWARFDie();
746}
747
748DWARFDie DWARFDie::getPreviousSibling() const {
749 if (isValid())
750 return U->getPreviousSibling(Die);
751 return DWARFDie();
752}
753
754DWARFDie DWARFDie::getFirstChild() const {
755 if (isValid())
756 return U->getFirstChild(Die);
757 return DWARFDie();
758}
759
760DWARFDie DWARFDie::getLastChild() const {
761 if (isValid())
762 return U->getLastChild(Die);
763 return DWARFDie();
764}
765
766iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
767 return make_range(x: attribute_iterator(*this, false),
768 y: attribute_iterator(*this, true));
769}
770
771DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
772 : Die(D), Index(0) {
773 auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
774 assert(AbbrDecl && "Must have abbreviation declaration");
775 if (End) {
776 // This is the end iterator so we set the index to the attribute count.
777 Index = AbbrDecl->getNumAttributes();
778 } else {
779 // This is the begin iterator so we extract the value for this->Index.
780 AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
781 updateForIndex(AbbrDecl: *AbbrDecl, I: 0);
782 }
783}
784
785void DWARFDie::attribute_iterator::updateForIndex(
786 const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
787 Index = I;
788 // AbbrDecl must be valid before calling this function.
789 auto NumAttrs = AbbrDecl.getNumAttributes();
790 if (Index < NumAttrs) {
791 AttrValue.Attr = AbbrDecl.getAttrByIndex(idx: Index);
792 // Add the previous byte size of any previous attribute value.
793 AttrValue.Offset += AttrValue.ByteSize;
794 uint64_t ParseOffset = AttrValue.Offset;
795 if (AbbrDecl.getAttrIsImplicitConstByIndex(idx: Index))
796 AttrValue.Value = DWARFFormValue::createFromSValue(
797 F: AbbrDecl.getFormByIndex(idx: Index),
798 V: AbbrDecl.getAttrImplicitConstValueByIndex(idx: Index));
799 else {
800 auto U = Die.getDwarfUnit();
801 assert(U && "Die must have valid DWARF unit");
802 AttrValue.Value = DWARFFormValue::createFromUnit(
803 F: AbbrDecl.getFormByIndex(idx: Index), Unit: U, OffsetPtr: &ParseOffset);
804 }
805 AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
806 } else {
807 assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
808 AttrValue = {};
809 }
810}
811
812DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
813 if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
814 updateForIndex(AbbrDecl: *AbbrDecl, I: Index + 1);
815 return *this;
816}
817
818bool DWARFAttribute::mayHaveLocationList(dwarf::Attribute Attr) {
819 switch(Attr) {
820 case DW_AT_location:
821 case DW_AT_string_length:
822 case DW_AT_return_addr:
823 case DW_AT_data_member_location:
824 case DW_AT_frame_base:
825 case DW_AT_static_link:
826 case DW_AT_segment:
827 case DW_AT_use_location:
828 case DW_AT_vtable_elem_location:
829 return true;
830 default:
831 return false;
832 }
833}
834
835bool DWARFAttribute::mayHaveLocationExpr(dwarf::Attribute Attr) {
836 switch (Attr) {
837 // From the DWARF v5 specification.
838 case DW_AT_location:
839 case DW_AT_byte_size:
840 case DW_AT_bit_offset:
841 case DW_AT_bit_size:
842 case DW_AT_string_length:
843 case DW_AT_lower_bound:
844 case DW_AT_return_addr:
845 case DW_AT_bit_stride:
846 case DW_AT_upper_bound:
847 case DW_AT_count:
848 case DW_AT_data_member_location:
849 case DW_AT_frame_base:
850 case DW_AT_segment:
851 case DW_AT_static_link:
852 case DW_AT_use_location:
853 case DW_AT_vtable_elem_location:
854 case DW_AT_allocated:
855 case DW_AT_associated:
856 case DW_AT_data_location:
857 case DW_AT_byte_stride:
858 case DW_AT_rank:
859 case DW_AT_call_value:
860 case DW_AT_call_origin:
861 case DW_AT_call_target:
862 case DW_AT_call_target_clobbered:
863 case DW_AT_call_data_location:
864 case DW_AT_call_data_value:
865 // Extensions.
866 case DW_AT_GNU_call_site_value:
867 case DW_AT_GNU_call_site_target:
868 case DW_AT_GNU_call_site_target_clobbered:
869 return true;
870 default:
871 return false;
872 }
873}
874
875namespace llvm {
876
877void dumpTypeQualifiedName(const DWARFDie &DIE, raw_ostream &OS) {
878 DWARFTypePrinter<DWARFDie>(OS).appendQualifiedName(D: DIE);
879}
880
881void dumpTypeUnqualifiedName(const DWARFDie &DIE, raw_ostream &OS,
882 std::string *OriginalFullName) {
883 DWARFTypePrinter<DWARFDie>(OS).appendUnqualifiedName(D: DIE, OriginalFullName);
884}
885
886} // namespace llvm
887