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/None.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/SmallSet.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/BinaryFormat/Dwarf.h"
15 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
18 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/DataExtractor.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/FormatAdapters.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/WithColor.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cinttypes>
32 #include <cstdint>
33 #include <string>
34 #include <utility>
35 
36 using namespace llvm;
37 using namespace dwarf;
38 using namespace object;
39 
40 static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
41   OS << " (";
42   do {
43     uint64_t Shift = countTrailingZeros(Val);
44     assert(Shift < 64 && "undefined behavior");
45     uint64_t Bit = 1ULL << Shift;
46     auto PropName = ApplePropertyString(Bit);
47     if (!PropName.empty())
48       OS << PropName;
49     else
50       OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
51     if (!(Val ^= Bit))
52       break;
53     OS << ", ";
54   } while (true);
55   OS << ")";
56 }
57 
58 static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
59                        const DWARFAddressRangesVector &Ranges,
60                        unsigned AddressSize, unsigned Indent,
61                        const DIDumpOptions &DumpOpts) {
62   if (!DumpOpts.ShowAddresses)
63     return;
64 
65   for (const DWARFAddressRange &R : Ranges) {
66     OS << '\n';
67     OS.indent(Indent);
68     R.dump(OS, AddressSize, DumpOpts, &Obj);
69   }
70 }
71 
72 static void dumpLocation(raw_ostream &OS, DWARFFormValue &FormValue,
73                          DWARFUnit *U, unsigned Indent,
74                          DIDumpOptions DumpOpts) {
75   DWARFContext &Ctx = U->getContext();
76   const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
77   if (FormValue.isFormClass(DWARFFormValue::FC_Block) ||
78       FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) {
79     ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
80     DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
81                        Ctx.isLittleEndian(), 0);
82     DWARFExpression(Data, U->getAddressByteSize()).print(OS, MRI, U);
83     return;
84   }
85 
86   if (FormValue.isFormClass(DWARFFormValue::FC_SectionOffset)) {
87     uint64_t Offset = *FormValue.getAsSectionOffset();
88 
89     if (FormValue.getForm() == DW_FORM_loclistx) {
90       FormValue.dump(OS, DumpOpts);
91 
92       if (auto LoclistOffset = U->getLoclistOffset(Offset))
93         Offset = *LoclistOffset;
94       else
95         return;
96     }
97     U->getLocationTable().dumpLocationList(&Offset, OS, U->getBaseAddress(),
98                                            MRI, Ctx.getDWARFObj(), U, DumpOpts,
99                                            Indent);
100     return;
101   }
102 
103   FormValue.dump(OS, DumpOpts);
104 }
105 
106 /// Dump the name encoded in the type tag.
107 static void dumpTypeTagName(raw_ostream &OS, dwarf::Tag T) {
108   StringRef TagStr = TagString(T);
109   if (!TagStr.startswith("DW_TAG_") || !TagStr.endswith("_type"))
110     return;
111   OS << TagStr.substr(7, TagStr.size() - 12) << " ";
112 }
113 
114 static void dumpArrayType(raw_ostream &OS, const DWARFDie &D) {
115   Optional<uint64_t> Bound;
116   for (const DWARFDie &C : D.children())
117     if (C.getTag() == DW_TAG_subrange_type) {
118       Optional<uint64_t> LB;
119       Optional<uint64_t> Count;
120       Optional<uint64_t> UB;
121       Optional<unsigned> DefaultLB;
122       if (Optional<DWARFFormValue> L = C.find(DW_AT_lower_bound))
123         LB = L->getAsUnsignedConstant();
124       if (Optional<DWARFFormValue> CountV = C.find(DW_AT_count))
125         Count = CountV->getAsUnsignedConstant();
126       if (Optional<DWARFFormValue> UpperV = C.find(DW_AT_upper_bound))
127         UB = UpperV->getAsUnsignedConstant();
128       if (Optional<DWARFFormValue> LV =
129               D.getDwarfUnit()->getUnitDIE().find(DW_AT_language))
130         if (Optional<uint64_t> LC = LV->getAsUnsignedConstant())
131           if ((DefaultLB =
132                    LanguageLowerBound(static_cast<dwarf::SourceLanguage>(*LC))))
133             if (LB && *LB == *DefaultLB)
134               LB = None;
135       if (!LB && !Count && !UB)
136         OS << "[]";
137       else if (!LB && (Count || UB) && DefaultLB)
138         OS << '[' << (Count ? *Count : *UB - *DefaultLB + 1) << ']';
139       else {
140         OS << "[[";
141         if (LB)
142           OS << *LB;
143         else
144           OS << '?';
145         OS << ", ";
146         if (Count)
147           if (LB)
148             OS << *LB + *Count;
149           else
150             OS << "? + " << *Count;
151         else if (UB)
152           OS << *UB + 1;
153         else
154           OS << '?';
155         OS << ")]";
156       }
157     }
158 }
159 
160 /// Recursively dump the DIE type name when applicable.
161 static void dumpTypeName(raw_ostream &OS, const DWARFDie &D) {
162   if (!D.isValid())
163     return;
164 
165   if (const char *Name = D.getName(DINameKind::LinkageName)) {
166     OS << Name;
167     return;
168   }
169 
170   // FIXME: We should have pretty printers per language. Currently we print
171   // everything as if it was C++ and fall back to the TAG type name.
172   const dwarf::Tag T = D.getTag();
173   switch (T) {
174   case DW_TAG_array_type:
175   case DW_TAG_pointer_type:
176   case DW_TAG_ptr_to_member_type:
177   case DW_TAG_reference_type:
178   case DW_TAG_rvalue_reference_type:
179   case DW_TAG_subroutine_type:
180     break;
181   default:
182     dumpTypeTagName(OS, T);
183   }
184 
185   // Follow the DW_AT_type if possible.
186   DWARFDie TypeDie = D.getAttributeValueAsReferencedDie(DW_AT_type);
187   dumpTypeName(OS, TypeDie);
188 
189   switch (T) {
190   case DW_TAG_subroutine_type: {
191     if (!TypeDie)
192       OS << "void";
193     OS << '(';
194     bool First = true;
195     for (const DWARFDie &C : D.children()) {
196       if (C.getTag() == DW_TAG_formal_parameter) {
197         if (!First)
198           OS << ", ";
199         First = false;
200         dumpTypeName(OS, C.getAttributeValueAsReferencedDie(DW_AT_type));
201       }
202     }
203     OS << ')';
204     break;
205   }
206   case DW_TAG_array_type: {
207     dumpArrayType(OS, D);
208     break;
209   }
210   case DW_TAG_pointer_type:
211     OS << '*';
212     break;
213   case DW_TAG_ptr_to_member_type:
214     if (DWARFDie Cont =
215             D.getAttributeValueAsReferencedDie(DW_AT_containing_type)) {
216       dumpTypeName(OS << ' ', Cont);
217       OS << "::";
218     }
219     OS << '*';
220     break;
221   case DW_TAG_reference_type:
222     OS << '&';
223     break;
224   case DW_TAG_rvalue_reference_type:
225     OS << "&&";
226     break;
227   default:
228     break;
229   }
230 }
231 
232 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
233                           uint64_t *OffsetPtr, dwarf::Attribute Attr,
234                           dwarf::Form Form, unsigned Indent,
235                           DIDumpOptions DumpOpts) {
236   if (!Die.isValid())
237     return;
238   const char BaseIndent[] = "            ";
239   OS << BaseIndent;
240   OS.indent(Indent + 2);
241   WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
242 
243   if (DumpOpts.Verbose || DumpOpts.ShowForm)
244     OS << formatv(" [{0}]", Form);
245 
246   DWARFUnit *U = Die.getDwarfUnit();
247   DWARFFormValue FormValue = DWARFFormValue::createFromUnit(Form, U, OffsetPtr);
248 
249   OS << "\t(";
250 
251   StringRef Name;
252   std::string File;
253   auto Color = HighlightColor::Enumerator;
254   if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
255     Color = HighlightColor::String;
256     if (const auto *LT = U->getContext().getLineTableForUnit(U))
257       if (LT->getFileNameByIndex(
258               FormValue.getAsUnsignedConstant().getValue(),
259               U->getCompilationDir(),
260               DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
261         File = '"' + File + '"';
262         Name = File;
263       }
264   } else if (Optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
265     Name = AttributeValueString(Attr, *Val);
266 
267   if (!Name.empty())
268     WithColor(OS, Color) << Name;
269   else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
270     OS << *FormValue.getAsUnsignedConstant();
271   else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
272            FormValue.getAsUnsignedConstant()) {
273     if (DumpOpts.ShowAddresses) {
274       // Print the actual address rather than the offset.
275       uint64_t LowPC, HighPC, Index;
276       if (Die.getLowAndHighPC(LowPC, HighPC, Index))
277         OS << format("0x%016" PRIx64, HighPC);
278       else
279         FormValue.dump(OS, DumpOpts);
280     }
281   } else if (Form == dwarf::Form::DW_FORM_exprloc ||
282              DWARFAttribute::mayHaveLocationDescription(Attr))
283     dumpLocation(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4, DumpOpts);
284   else
285     FormValue.dump(OS, DumpOpts);
286 
287   std::string Space = DumpOpts.ShowAddresses ? " " : "";
288 
289   // We have dumped the attribute raw value. For some attributes
290   // having both the raw value and the pretty-printed value is
291   // interesting. These attributes are handled below.
292   if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
293     if (const char *Name =
294             Die.getAttributeValueAsReferencedDie(FormValue).getName(
295                 DINameKind::LinkageName))
296       OS << Space << "\"" << Name << '\"';
297   } else if (Attr == DW_AT_type) {
298     OS << Space << "\"";
299     dumpTypeName(OS, Die.getAttributeValueAsReferencedDie(FormValue));
300     OS << '"';
301   } else if (Attr == DW_AT_APPLE_property_attribute) {
302     if (Optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
303       dumpApplePropertyAttribute(OS, *OptVal);
304   } else if (Attr == DW_AT_ranges) {
305     const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
306     // For DW_FORM_rnglistx we need to dump the offset separately, since
307     // we have only dumped the index so far.
308     if (FormValue.getForm() == DW_FORM_rnglistx)
309       if (auto RangeListOffset =
310               U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
311         DWARFFormValue FV = DWARFFormValue::createFromUValue(
312             dwarf::DW_FORM_sec_offset, *RangeListOffset);
313         FV.dump(OS, DumpOpts);
314       }
315     if (auto RangesOrError = Die.getAddressRanges())
316       dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
317                  sizeof(BaseIndent) + Indent + 4, DumpOpts);
318     else
319       WithColor::error() << "decoding address ranges: "
320                          << toString(RangesOrError.takeError()) << '\n';
321   }
322 
323   OS << ")\n";
324 }
325 
326 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
327 
328 bool DWARFDie::isSubroutineDIE() const {
329   auto Tag = getTag();
330   return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
331 }
332 
333 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
334   if (!isValid())
335     return None;
336   auto AbbrevDecl = getAbbreviationDeclarationPtr();
337   if (AbbrevDecl)
338     return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
339   return None;
340 }
341 
342 Optional<DWARFFormValue>
343 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
344   if (!isValid())
345     return None;
346   auto AbbrevDecl = getAbbreviationDeclarationPtr();
347   if (AbbrevDecl) {
348     for (auto Attr : Attrs) {
349       if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
350         return Value;
351     }
352   }
353   return None;
354 }
355 
356 Optional<DWARFFormValue>
357 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
358   std::vector<DWARFDie> Worklist;
359   Worklist.push_back(*this);
360 
361   // Keep track if DIEs already seen to prevent infinite recursion.
362   // Empirically we rarely see a depth of more than 3 when dealing with valid
363   // DWARF. This corresponds to following the DW_AT_abstract_origin and
364   // DW_AT_specification just once.
365   SmallSet<DWARFDie, 3> Seen;
366   Seen.insert(*this);
367 
368   while (!Worklist.empty()) {
369     DWARFDie Die = Worklist.back();
370     Worklist.pop_back();
371 
372     if (!Die.isValid())
373       continue;
374 
375     if (auto Value = Die.find(Attrs))
376       return Value;
377 
378     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
379       if (Seen.insert(D).second)
380         Worklist.push_back(D);
381 
382     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
383       if (Seen.insert(D).second)
384         Worklist.push_back(D);
385   }
386 
387   return None;
388 }
389 
390 DWARFDie
391 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
392   if (Optional<DWARFFormValue> F = find(Attr))
393     return getAttributeValueAsReferencedDie(*F);
394   return DWARFDie();
395 }
396 
397 DWARFDie
398 DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
399   if (auto SpecRef = V.getAsRelativeReference()) {
400     if (SpecRef->Unit)
401       return SpecRef->Unit->getDIEForOffset(SpecRef->Unit->getOffset() + SpecRef->Offset);
402     if (auto SpecUnit = U->getUnitVector().getUnitForOffset(SpecRef->Offset))
403       return SpecUnit->getDIEForOffset(SpecRef->Offset);
404   }
405   return DWARFDie();
406 }
407 
408 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
409   return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
410 }
411 
412 Optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
413   return toSectionOffset(find(DW_AT_loclists_base));
414 }
415 
416 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
417   if (auto FormValue = find(DW_AT_high_pc)) {
418     if (auto Address = FormValue->getAsAddress()) {
419       // High PC is an address.
420       return Address;
421     }
422     if (auto Offset = FormValue->getAsUnsignedConstant()) {
423       // High PC is an offset from LowPC.
424       return LowPC + *Offset;
425     }
426   }
427   return None;
428 }
429 
430 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
431                                uint64_t &SectionIndex) const {
432   auto F = find(DW_AT_low_pc);
433   auto LowPcAddr = toSectionedAddress(F);
434   if (!LowPcAddr)
435     return false;
436   if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
437     LowPC = LowPcAddr->Address;
438     HighPC = *HighPcAddr;
439     SectionIndex = LowPcAddr->SectionIndex;
440     return true;
441   }
442   return false;
443 }
444 
445 Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
446   if (isNULL())
447     return DWARFAddressRangesVector();
448   // Single range specified by low/high PC.
449   uint64_t LowPC, HighPC, Index;
450   if (getLowAndHighPC(LowPC, HighPC, Index))
451     return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
452 
453   Optional<DWARFFormValue> Value = find(DW_AT_ranges);
454   if (Value) {
455     if (Value->getForm() == DW_FORM_rnglistx)
456       return U->findRnglistFromIndex(*Value->getAsSectionOffset());
457     return U->findRnglistFromOffset(*Value->getAsSectionOffset());
458   }
459   return DWARFAddressRangesVector();
460 }
461 
462 void DWARFDie::collectChildrenAddressRanges(
463     DWARFAddressRangesVector &Ranges) const {
464   if (isNULL())
465     return;
466   if (isSubprogramDIE()) {
467     if (auto DIERangesOrError = getAddressRanges())
468       Ranges.insert(Ranges.end(), DIERangesOrError.get().begin(),
469                     DIERangesOrError.get().end());
470     else
471       llvm::consumeError(DIERangesOrError.takeError());
472   }
473 
474   for (auto Child : children())
475     Child.collectChildrenAddressRanges(Ranges);
476 }
477 
478 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
479   auto RangesOrError = getAddressRanges();
480   if (!RangesOrError) {
481     llvm::consumeError(RangesOrError.takeError());
482     return false;
483   }
484 
485   for (const auto &R : RangesOrError.get())
486     if (R.LowPC <= Address && Address < R.HighPC)
487       return true;
488   return false;
489 }
490 
491 Expected<DWARFLocationExpressionsVector>
492 DWARFDie::getLocations(dwarf::Attribute Attr) const {
493   Optional<DWARFFormValue> Location = find(Attr);
494   if (!Location)
495     return createStringError(inconvertibleErrorCode(), "No %s",
496                              dwarf::AttributeString(Attr).data());
497 
498   if (Optional<uint64_t> Off = Location->getAsSectionOffset()) {
499     uint64_t Offset = *Off;
500 
501     if (Location->getForm() == DW_FORM_loclistx) {
502       if (auto LoclistOffset = U->getLoclistOffset(Offset))
503         Offset = *LoclistOffset;
504       else
505         return createStringError(inconvertibleErrorCode(),
506                                  "Loclist table not found");
507     }
508     return U->findLoclistFromOffset(Offset);
509   }
510 
511   if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
512     return DWARFLocationExpressionsVector{
513         DWARFLocationExpression{None, to_vector<4>(*Expr)}};
514   }
515 
516   return createStringError(
517       inconvertibleErrorCode(), "Unsupported %s encoding: %s",
518       dwarf::AttributeString(Attr).data(),
519       dwarf::FormEncodingString(Location->getForm()).data());
520 }
521 
522 const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
523   if (!isSubroutineDIE())
524     return nullptr;
525   return getName(Kind);
526 }
527 
528 const char *DWARFDie::getName(DINameKind Kind) const {
529   if (!isValid() || Kind == DINameKind::None)
530     return nullptr;
531   // Try to get mangled name only if it was asked for.
532   if (Kind == DINameKind::LinkageName) {
533     if (auto Name = dwarf::toString(
534             findRecursively({DW_AT_MIPS_linkage_name, DW_AT_linkage_name}),
535             nullptr))
536       return Name;
537   }
538   if (auto Name = dwarf::toString(findRecursively(DW_AT_name), nullptr))
539     return Name;
540   return nullptr;
541 }
542 
543 uint64_t DWARFDie::getDeclLine() const {
544   return toUnsigned(findRecursively(DW_AT_decl_line), 0);
545 }
546 
547 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
548                               uint32_t &CallColumn,
549                               uint32_t &CallDiscriminator) const {
550   CallFile = toUnsigned(find(DW_AT_call_file), 0);
551   CallLine = toUnsigned(find(DW_AT_call_line), 0);
552   CallColumn = toUnsigned(find(DW_AT_call_column), 0);
553   CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
554 }
555 
556 /// Helper to dump a DIE with all of its parents, but no siblings.
557 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
558                                 DIDumpOptions DumpOpts, unsigned Depth = 0) {
559   if (!Die)
560     return Indent;
561   if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
562     return Indent;
563   Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
564   Die.dump(OS, Indent, DumpOpts);
565   return Indent + 2;
566 }
567 
568 void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
569                     DIDumpOptions DumpOpts) const {
570   if (!isValid())
571     return;
572   DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
573   const uint64_t Offset = getOffset();
574   uint64_t offset = Offset;
575   if (DumpOpts.ShowParents) {
576     DIDumpOptions ParentDumpOpts = DumpOpts;
577     ParentDumpOpts.ShowParents = false;
578     ParentDumpOpts.ShowChildren = false;
579     Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
580   }
581 
582   if (debug_info_data.isValidOffset(offset)) {
583     uint32_t abbrCode = debug_info_data.getULEB128(&offset);
584     if (DumpOpts.ShowAddresses)
585       WithColor(OS, HighlightColor::Address).get()
586           << format("\n0x%8.8" PRIx64 ": ", Offset);
587 
588     if (abbrCode) {
589       auto AbbrevDecl = getAbbreviationDeclarationPtr();
590       if (AbbrevDecl) {
591         WithColor(OS, HighlightColor::Tag).get().indent(Indent)
592             << formatv("{0}", getTag());
593         if (DumpOpts.Verbose)
594           OS << format(" [%u] %c", abbrCode,
595                        AbbrevDecl->hasChildren() ? '*' : ' ');
596         OS << '\n';
597 
598         // Dump all data in the DIE for the attributes.
599         for (const auto &AttrSpec : AbbrevDecl->attributes()) {
600           if (AttrSpec.Form == DW_FORM_implicit_const) {
601             // We are dumping .debug_info section ,
602             // implicit_const attribute values are not really stored here,
603             // but in .debug_abbrev section. So we just skip such attrs.
604             continue;
605           }
606           dumpAttribute(OS, *this, &offset, AttrSpec.Attr, AttrSpec.Form,
607                         Indent, DumpOpts);
608         }
609 
610         DWARFDie child = getFirstChild();
611         if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0 && child) {
612           DumpOpts.ChildRecurseDepth--;
613           DIDumpOptions ChildDumpOpts = DumpOpts;
614           ChildDumpOpts.ShowParents = false;
615           while (child) {
616             child.dump(OS, Indent + 2, ChildDumpOpts);
617             child = child.getSibling();
618           }
619         }
620       } else {
621         OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
622            << abbrCode << '\n';
623       }
624     } else {
625       OS.indent(Indent) << "NULL\n";
626     }
627   }
628 }
629 
630 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
631 
632 DWARFDie DWARFDie::getParent() const {
633   if (isValid())
634     return U->getParent(Die);
635   return DWARFDie();
636 }
637 
638 DWARFDie DWARFDie::getSibling() const {
639   if (isValid())
640     return U->getSibling(Die);
641   return DWARFDie();
642 }
643 
644 DWARFDie DWARFDie::getPreviousSibling() const {
645   if (isValid())
646     return U->getPreviousSibling(Die);
647   return DWARFDie();
648 }
649 
650 DWARFDie DWARFDie::getFirstChild() const {
651   if (isValid())
652     return U->getFirstChild(Die);
653   return DWARFDie();
654 }
655 
656 DWARFDie DWARFDie::getLastChild() const {
657   if (isValid())
658     return U->getLastChild(Die);
659   return DWARFDie();
660 }
661 
662 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
663   return make_range(attribute_iterator(*this, false),
664                     attribute_iterator(*this, true));
665 }
666 
667 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
668     : Die(D), Index(0) {
669   auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
670   assert(AbbrDecl && "Must have abbreviation declaration");
671   if (End) {
672     // This is the end iterator so we set the index to the attribute count.
673     Index = AbbrDecl->getNumAttributes();
674   } else {
675     // This is the begin iterator so we extract the value for this->Index.
676     AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
677     updateForIndex(*AbbrDecl, 0);
678   }
679 }
680 
681 void DWARFDie::attribute_iterator::updateForIndex(
682     const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
683   Index = I;
684   // AbbrDecl must be valid before calling this function.
685   auto NumAttrs = AbbrDecl.getNumAttributes();
686   if (Index < NumAttrs) {
687     AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
688     // Add the previous byte size of any previous attribute value.
689     AttrValue.Offset += AttrValue.ByteSize;
690     uint64_t ParseOffset = AttrValue.Offset;
691     auto U = Die.getDwarfUnit();
692     assert(U && "Die must have valid DWARF unit");
693     AttrValue.Value = DWARFFormValue::createFromUnit(
694         AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
695     AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
696   } else {
697     assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
698     AttrValue = {};
699   }
700 }
701 
702 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
703   if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
704     updateForIndex(*AbbrDecl, Index + 1);
705   return *this;
706 }
707 
708 bool DWARFAttribute::mayHaveLocationDescription(dwarf::Attribute Attr) {
709   switch (Attr) {
710   // From the DWARF v5 specification.
711   case DW_AT_location:
712   case DW_AT_byte_size:
713   case DW_AT_bit_size:
714   case DW_AT_string_length:
715   case DW_AT_lower_bound:
716   case DW_AT_return_addr:
717   case DW_AT_bit_stride:
718   case DW_AT_upper_bound:
719   case DW_AT_count:
720   case DW_AT_data_member_location:
721   case DW_AT_frame_base:
722   case DW_AT_segment:
723   case DW_AT_static_link:
724   case DW_AT_use_location:
725   case DW_AT_vtable_elem_location:
726   case DW_AT_allocated:
727   case DW_AT_associated:
728   case DW_AT_byte_stride:
729   case DW_AT_rank:
730   case DW_AT_call_value:
731   case DW_AT_call_origin:
732   case DW_AT_call_target:
733   case DW_AT_call_target_clobbered:
734   case DW_AT_call_data_location:
735   case DW_AT_call_data_value:
736   // Extensions.
737   case DW_AT_GNU_call_site_value:
738   case DW_AT_GNU_call_site_target:
739     return true;
740   default:
741     return false;
742   }
743 }
744