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