LLVM 24.0.0git
DWARFDie.cpp
Go to the documentation of this file.
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
11#include "llvm/ADT/SmallSet.h"
12#include "llvm/ADT/StringRef.h"
29#include <cassert>
30#include <cstdint>
31#include <string>
32
33using namespace llvm;
34using namespace dwarf;
35using namespace object;
36
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("DW_APPLE_PROPERTY_{0:x}", 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(Indent);
65 R.dump(OS, AddressSize, DumpOpts, &Obj);
66 }
67}
68
69static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
70 DWARFUnit *U, unsigned Indent,
71 DIDumpOptions DumpOpts) {
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(Offset))
81 Offset = *LoclistOffset;
82 else
83 return;
84 }
85 U->getLocationTable().dumpLocationList(
86 &Offset, OS, U->getBaseAddress(), Ctx.getDWARFObj(), U, DumpOpts, Indent);
87}
88
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) {
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) {
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(&DE, OS, DumpOpts, U);
113}
114
116 return D.getAttributeValueAsReferencedDie(F).resolveTypeUnitReference();
117}
118
119static llvm::StringRef
121 const DWARFDie &Die) {
122 if (AttrValue.Attr != DW_AT_language_version)
123 return {};
124
125 auto NameForm = Die.find(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
138 static_cast<SourceLanguageName>(*LName), *LVersion);
139}
140
143 if (!PropDIE)
144 return llvm::createStringError("invalid DIE");
145
146 if (PropDIE.getTag() != DW_TAG_APPLE_property)
147 return llvm::createStringError("not referencing a DW_TAG_APPLE_property");
148
149 auto PropNameForm = PropDIE.find(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(Indent + 2);
168 dwarf::Attribute Attr = AttrValue.Attr;
169 WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
170
171 dwarf::Form Form = AttrValue.Value.getForm();
172 if (DumpOpts.Verbose || DumpOpts.ShowForm)
173 OS << formatv(" [{0}]", 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) {
185 if (const auto *LT = U->getContext().getLineTableForUnit(U)) {
186 if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant()) {
187 if (LT->getFileNameByIndex(
188 *Val, U->getCompilationDir(),
190 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);
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(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, Index))
237 DWARFFormValue::dumpAddress(OS, U->getAddressByteSize(), HighPC);
238 else
239 FormValue.dump(OS, DumpOpts);
240 }
241 } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
243 dumpLocationList(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
244 DumpOpts);
245 else if (FormValue.isFormClass(DWARFFormValue::FC_Exprloc) ||
248 dumpLocationExpr(OS, FormValue, U, 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 =
266 OS << Space << "\"" << Name << '\"';
267 } else if (Attr == DW_AT_property_forward) {
268 if (const char *Name =
271 OS << Space << "\"" << Name << '\"';
272 } else if (Attr == DW_AT_APPLE_property) {
273 auto PropDIE = Die.getAttributeValueAsReferencedDie(FormValue);
274 if (auto PropNameOrErr = getApplePropertyName(PropDIE))
275 OS << Space << "\"" << *PropNameOrErr << '\"';
276 else
279 llvm::formatv("decoding DW_AT_APPLE_property_name: {}",
280 toString(PropNameOrErr.takeError()))));
281 } else if (Attr == DW_AT_type || Attr == DW_AT_containing_type) {
282 DWARFDie D = resolveReferencedType(Die, FormValue);
283 if (D && !D.isNULL()) {
284 OS << Space << "\"";
286 OS << '"';
287 }
288 } else if (Attr == DW_AT_APPLE_property_attribute) {
289 if (std::optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
290 dumpApplePropertyAttribute(OS, *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(*FormValue.getAsSectionOffset())) {
299 dwarf::DW_FORM_sec_offset, *RangeListOffset);
300 FV.dump(OS, DumpOpts);
301 }
302 if (auto RangesOrError = Die.getAddressRanges())
303 dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
304 sizeof(BaseIndent) + Indent + 4, DumpOpts);
305 else
307 errc::invalid_argument, "decoding address ranges: %s",
308 toString(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
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(*this, OS, OriginalFullName);
326}
327
328bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
329
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(getOffset(), Attr, *U);
341 return std::nullopt;
342}
343
344std::optional<DWARFFormValue>
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(getOffset(), Attr, *U))
352 return Value;
353 }
354 }
355 return std::nullopt;
356}
357
358std::optional<DWARFFormValue>
361 Worklist.push_back(*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.
368 Seen.insert(*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(D).second)
383 Worklist.push_back(D);
384 }
385 }
386
387 return std::nullopt;
388}
389
392 if (std::optional<DWARFFormValue> F = find(Attr))
394 return DWARFDie();
395}
396
399 DWARFDie Result;
400 if (std::optional<uint64_t> Offset = V.getAsRelativeReference()) {
401 Result = const_cast<DWARFUnit *>(V.getUnit())
402 ->getDIEForOffset(V.getUnit()->getOffset() + *Offset);
403 } else if (Offset = V.getAsDebugInfoReference(); Offset) {
404 if (DWARFUnit *SpecUnit = U->getUnitVector().getUnitForOffset(*Offset))
405 Result = SpecUnit->getDIEForOffset(*Offset);
406 } else if (std::optional<uint64_t> Sig = V.getAsSignatureReference()) {
407 if (DWARFTypeUnit *TU =
408 U->getContext().getTypeUnitForHash(*Sig, U->isDWOUnit()))
409 Result = TU->getDIEForOffset(TU->getTypeOffset() + TU->getOffset());
410 }
411 return Result;
412}
413
415 if (auto Attr = find(DW_AT_signature)) {
416 if (std::optional<uint64_t> Sig = Attr->getAsReferenceUVal()) {
417 if (DWARFTypeUnit *TU =
418 U->getContext().getTypeUnitForHash(*Sig, U->isDWOUnit()))
419 return TU->getDIEForOffset(TU->getTypeOffset() + TU->getOffset());
420 }
421 }
422 return *this;
423}
424
431
432std::optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
433 return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
434}
435
436std::optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
437 return toSectionOffset(find(DW_AT_loclists_base));
438}
439
440std::optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
441 uint64_t Tombstone = dwarf::computeTombstoneAddress(U->getAddressByteSize());
442 if (LowPC == Tombstone)
443 return std::nullopt;
444 if (auto FormValue = find(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(DW_AT_low_pc);
460 auto LowPcAddr = toSectionedAddress(F);
461 if (!LowPcAddr)
462 return false;
463 if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
464 LowPC = LowPcAddr->Address;
465 HighPC = *HighPcAddr;
466 SectionIndex = LowPcAddr->SectionIndex;
467 return true;
468 }
469 return false;
470}
471
473 if (isNULL())
475 // Single range specified by low/high PC.
476 uint64_t LowPC, HighPC, Index;
477 if (getLowAndHighPC(LowPC, HighPC, Index))
478 return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
479
480 std::optional<DWARFFormValue> Value = find(DW_AT_ranges);
481 if (Value) {
482 if (Value->getForm() == DW_FORM_rnglistx)
483 return U->findRnglistFromIndex(*Value->getAsSectionOffset());
484 return U->findRnglistFromOffset(*Value->getAsSectionOffset());
485 }
487}
488
490 auto RangesOrError = getAddressRanges();
491 if (!RangesOrError) {
492 llvm::consumeError(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(dwarf::DW_AT_language))
513 return LV->getAsUnsignedConstant();
514
515 uint16_t Name =
516 dwarf::toUnsigned(Unit.find(dwarf::DW_AT_language_name), /*Default=*/0);
517 uint32_t Version = dwarf::toUnsigned(Unit.find(dwarf::DW_AT_language_version),
518 /*Default=*/0);
519
520 return llvm::dwarf::toDW_LANG(static_cast<SourceLanguageName>(Name), Version);
521}
522
525 std::optional<DWARFFormValue> Location = find(Attr);
526 if (!Location)
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(Offset))
535 Offset = *LoclistOffset;
536 else
538 "Loclist table not found");
539 }
540 return U->findLoclistFromOffset(Offset);
541 }
542
543 if (std::optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
545 DWARFLocationExpression{std::nullopt, to_vector<4>(*Expr)}};
546 }
547
548 return createStringError(
549 inconvertibleErrorCode(), "Unsupported %s encoding: %s",
551 dwarf::FormEncodingString(Location->getForm()).data());
552}
553
555 if (!isSubroutineDIE())
556 return nullptr;
557 return getName(Kind);
558}
559
561 if (!isValid() || Kind == DINameKind::None)
562 return nullptr;
563 // Try to get mangled name only if it was asked for.
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(findRecursively(dwarf::DW_AT_name), nullptr);
576}
577
578const char *DWARFDie::getLinkageName() const {
579 if (!isValid())
580 return nullptr;
581
582 return dwarf::toString(findRecursively({dwarf::DW_AT_MIPS_linkage_name,
583 dwarf::DW_AT_linkage_name}),
584 nullptr);
585}
586
587uint64_t DWARFDie::getDeclLine() const {
588 return toUnsigned(findRecursively(DW_AT_decl_line), 0);
589}
590
591std::string
593 if (auto FormValue = findRecursively(DW_AT_decl_file))
594 if (auto OptString = FormValue->getAsFile(Kind))
595 return *OptString;
596 return {};
597}
598
600 uint32_t &CallColumn,
601 uint32_t &CallDiscriminator) const {
602 CallFile = toUnsigned(find(DW_AT_call_file), 0);
603 CallLine = toUnsigned(find(DW_AT_call_line), 0);
604 CallColumn = toUnsigned(find(DW_AT_call_column), 0);
605 CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
606}
607
608static std::optional<uint64_t>
611 // Cycle detected?
612 if (!Visited.insert(Die.getDebugInfoEntry()).second)
613 return {};
614 if (auto SizeAttr = Die.find(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: {
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: {
636 return getTypeSizeImpl(BaseType, PointerSize, Visited);
637 break;
638 }
639 case DW_TAG_array_type: {
641 if (!BaseType)
642 return std::nullopt;
643 std::optional<uint64_t> BaseSize =
644 getTypeSizeImpl(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(DW_AT_count))
653 if (std::optional<uint64_t> ElemCount =
654 ElemCountAttr->getAsUnsignedConstant())
655 Size *= *ElemCount;
656 if (auto UpperBoundAttr = Child.find(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(DW_AT_lower_bound))
661 LowerBound = LowerBoundAttr->getAsSignedConstant().value_or(0);
662 Size *= *UpperBound - LowerBound + 1;
663 }
664 }
665 return Size;
666 }
667 default:
669 return getTypeSizeImpl(BaseType, PointerSize, Visited);
670 break;
671 }
672 return std::nullopt;
673}
674
675std::optional<uint64_t> DWARFDie::getTypeSize(uint64_t PointerSize) {
677 return getTypeSizeImpl(*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.getParent(), OS, Indent, DumpOpts, Depth + 1);
688 Die.dump(OS, 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(getParent(), OS, Indent, ParentDumpOpts);
704 }
705
706 if (debug_info_data.isValidOffset(offset)) {
707 uint32_t abbrCode = debug_info_data.getULEB128(&offset);
708 if (DumpOpts.ShowAddresses)
710 << formatv("\n{0:x8}: ", Offset);
711
712 if (abbrCode) {
713 auto AbbrevDecl = getAbbreviationDeclarationPtr();
714 if (AbbrevDecl) {
716 << formatv("{0}", getTag());
717 if (DumpOpts.Verbose) {
718 OS << formatv(" [{0}] {1}", abbrCode,
719 AbbrevDecl->hasChildren() ? '*' : ' ');
720 if (std::optional<uint32_t> ParentIdx = Die->getParentIdx())
721 OS << formatv(" ({0:x8})",
722 U->getDIEAtIndex(*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, *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(DumpOpts.FilterChildTag, Child.getTag()))
738 Child.dump(OS, Indent + 2, 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(Indent) << "NULL\n";
748 }
749 }
750}
751
753
755 if (isValid())
756 return U->getParent(Die);
757 return DWARFDie();
758}
759
761 if (isValid())
762 return U->getSibling(Die);
763 return DWARFDie();
764}
765
767 if (isValid())
768 return U->getPreviousSibling(Die);
769 return DWARFDie();
770}
771
773 if (isValid())
774 return U->getFirstChild(Die);
775 return DWARFDie();
776}
777
779 if (isValid())
780 return U->getLastChild(Die);
781 return DWARFDie();
782}
783
788
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, 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(Index);
810 // Add the previous byte size of any previous attribute value.
811 AttrValue.Offset += AttrValue.ByteSize;
812 uint64_t ParseOffset = AttrValue.Offset;
814 AttrValue.Value = DWARFFormValue::createFromSValue(
815 AbbrDecl.getFormByIndex(Index),
817 else {
818 auto U = Die.getDwarfUnit();
819 assert(U && "Die must have valid DWARF unit");
820 AttrValue.Value = DWARFFormValue::createFromUnit(
821 AbbrDecl.getFormByIndex(Index), U, &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
831 if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
832 updateForIndex(*AbbrDecl, Index + 1);
833 return *this;
834}
835
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
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
898
900 std::string *OriginalFullName) {
902}
903
904} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die, const DWARFAttribute &AttrValue, unsigned Indent, DIDumpOptions DumpOpts)
Definition DWARFDie.cpp:160
static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue, DWARFUnit *U, unsigned Indent, DIDumpOptions DumpOpts)
Definition DWARFDie.cpp:102
static void dumpDWARFAddressSpace(raw_ostream &OS, const DWARFFormValue &FormValue, const DIDumpOptions &DumpOpts)
Definition DWARFDie.cpp:89
static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent, DIDumpOptions DumpOpts, unsigned Depth=0)
Helper to dump a DIE with all of its parents, but no siblings.
Definition DWARFDie.cpp:681
static DWARFDie resolveReferencedType(DWARFDie D, DWARFFormValue F)
Definition DWARFDie.cpp:115
static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue, DWARFUnit *U, unsigned Indent, DIDumpOptions DumpOpts)
Definition DWARFDie.cpp:69
static llvm::StringRef prettyLanguageVersionString(const DWARFAttribute &AttrValue, const DWARFDie &Die)
Definition DWARFDie.cpp:120
static llvm::Expected< llvm::StringRef > getApplePropertyName(const DWARFDie &PropDIE)
Definition DWARFDie.cpp:142
static std::optional< uint64_t > getTypeSizeImpl(DWARFDie Die, uint64_t PointerSize, SmallPtrSetImpl< const DWARFDebugInfoEntry * > &Visited)
Definition DWARFDie.cpp:609
static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val)
Definition DWARFDie.cpp:37
static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS, const DWARFAddressRangesVector &Ranges, unsigned AddressSize, unsigned Indent, const DIDumpOptions &DumpOpts)
Definition DWARFDie.cpp:55
This file contains constants used for implementing Dwarf debug support.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
static Split data
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A structured debug information entry.
Definition DIE.h:835
dwarf::Attribute getAttrByIndex(uint32_t idx) const
int64_t getAttrImplicitConstValueByIndex(uint32_t idx) const
dwarf::Form getFormByIndex(uint32_t idx) const
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
DWARFTypeUnit * getTypeUnitForHash(uint64_t Hash, bool IsDWO)
const DWARFObject & getDWARFObj() const
A DWARFDataExtractor (typically for an in-memory copy of an object-file section) plus a relocation ma...
LLVM_ABI attribute_iterator & operator++()
Definition DWARFDie.cpp:830
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
LLVM_ABI void getFullName(raw_string_ostream &, std::string *OriginalFullName=nullptr) const
Definition DWARFDie.cpp:318
LLVM_ABI DWARFDie resolveTypeUnitReference() const
Definition DWARFDie.cpp:414
LLVM_ABI std::optional< uint64_t > getLocBaseAttribute() const
Definition DWARFDie.cpp:436
uint64_t getOffset() const
Get the absolute offset into the debug info or types section.
Definition DWARFDie.h:68
LLVM_ABI const char * getShortName() const
Return the DIE short name resolving DW_AT_specification or DW_AT_abstract_origin references if necess...
Definition DWARFDie.cpp:571
LLVM_ABI Expected< DWARFAddressRangesVector > getAddressRanges() const
Get the address ranges for this DIE.
Definition DWARFDie.cpp:472
LLVM_ABI DWARFDie getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE as the referenced DIE.
Definition DWARFDie.cpp:391
LLVM_ABI DWARFDie getParent() const
Get the parent of this DIE object.
Definition DWARFDie.cpp:754
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition DWARFDie.cpp:335
DWARFUnit * getDwarfUnit() const
Definition DWARFDie.h:55
const DWARFDebugInfoEntry * getDebugInfoEntry() const
Definition DWARFDie.h:54
LLVM_ABI const char * getSubroutineName(DINameKind Kind) const
If a DIE represents a subprogram (or inlined subroutine), returns its mangled name (or short name,...
Definition DWARFDie.cpp:554
LLVM_ABI DWARFDie getSibling() const
Get the sibling of this DIE object.
Definition DWARFDie.cpp:760
LLVM_ABI bool isSubroutineDIE() const
Returns true if DIE represents a subprogram or an inlined subroutine.
Definition DWARFDie.cpp:330
LLVM_ABI bool getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC, uint64_t &SectionIndex) const
Retrieves DW_AT_low_pc and DW_AT_high_pc from CU.
Definition DWARFDie.cpp:457
LLVM_ABI LLVM_DUMP_METHOD void dump() const
Convenience zero-argument overload for debugging.
Definition DWARFDie.cpp:752
LLVM_ABI void getCallerFrame(uint32_t &CallFile, uint32_t &CallLine, uint32_t &CallColumn, uint32_t &CallDiscriminator) const
Retrieves values of DW_AT_call_file, DW_AT_call_line and DW_AT_call_column from DIE (or zeroes if the...
Definition DWARFDie.cpp:599
LLVM_ABI bool isSubprogramDIE() const
Returns true if DIE represents a subprogram (not inlined).
Definition DWARFDie.cpp:328
LLVM_ABI bool addressRangeContainsAddress(const uint64_t Address) const
Definition DWARFDie.cpp:489
LLVM_ABI std::optional< DWARFFormValue > findRecursively(ArrayRef< dwarf::Attribute > Attrs) const
Extract the first value of any attribute in Attrs from this DIE and recurse into any DW_AT_specificat...
Definition DWARFDie.cpp:359
llvm::DWARFFormValue DWARFFormValue
Definition DWARFDie.h:48
LLVM_ABI std::optional< uint64_t > getHighPC(uint64_t LowPC) const
Get the DW_AT_high_pc attribute value as an address.
Definition DWARFDie.cpp:440
LLVM_ABI std::optional< uint64_t > getTypeSize(uint64_t PointerSize)
Gets the type size (in bytes) for this DIE.
Definition DWARFDie.cpp:675
LLVM_ABI DWARFDie resolveReferencedType(dwarf::Attribute Attr) const
Definition DWARFDie.cpp:425
LLVM_ABI const char * getName(DINameKind Kind) const
Return the DIE name resolving DW_AT_specification or DW_AT_abstract_origin references if necessary.
Definition DWARFDie.cpp:560
LLVM_ABI DWARFDie getLastChild() const
Get the last child of this DIE object.
Definition DWARFDie.cpp:778
LLVM_ABI DWARFDie getPreviousSibling() const
Get the previous sibling of this DIE object.
Definition DWARFDie.cpp:766
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Get the abbreviation declaration for this DIE.
Definition DWARFDie.h:60
DWARFDie()=default
LLVM_ABI std::string getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const
Definition DWARFDie.cpp:592
LLVM_ABI DWARFDie getFirstChild() const
Get the first child of this DIE object.
Definition DWARFDie.cpp:772
LLVM_ABI uint64_t getDeclLine() const
Returns the declaration line (start line) for a DIE, assuming it specifies a subprogram.
Definition DWARFDie.cpp:587
dwarf::Tag getTag() const
Definition DWARFDie.h:73
LLVM_ABI const char * getLinkageName() const
Return the DIE linkage name resolving DW_AT_specification or DW_AT_abstract_origin references if nece...
Definition DWARFDie.cpp:578
LLVM_ABI Expected< DWARFLocationExpressionsVector > getLocations(dwarf::Attribute Attr) const
Definition DWARFDie.cpp:524
LLVM_ABI std::optional< uint64_t > getRangesBaseAttribute() const
Extract the range base attribute from this DIE as absolute section offset.
Definition DWARFDie.cpp:432
bool isNULL() const
Returns true for a valid DIE that terminates a sibling chain.
Definition DWARFDie.h:86
LLVM_ABI std::optional< uint64_t > getLanguage() const
Returns the DW_LANG_ code for this DIE's DWARF unit, if it exists.
Definition DWARFDie.cpp:506
bool isValid() const
Definition DWARFDie.h:52
LLVM_ABI iterator_range< attribute_iterator > attributes() const
Get an iterator range to all attributes in the current DIE only.
Definition DWARFDie.cpp:784
LLVM_ABI void dump(raw_ostream &OS, unsigned indent=0, DIDumpOptions DumpOpts=DIDumpOptions()) const
Dump the DIE and all of its attributes to the supplied stream.
Definition DWARFDie.cpp:692
static LLVM_ABI DWARFFormValue createFromUValue(dwarf::Form F, uint64_t V)
LLVM_ABI std::optional< ArrayRef< uint8_t > > getAsBlock() const
LLVM_ABI std::optional< uint64_t > getAsSectionOffset() const
LLVM_ABI bool isFormClass(FormClass FC) const
LLVM_ABI void dumpAddress(raw_ostream &OS, uint64_t Address) const
LLVM_ABI std::optional< uint64_t > getAsAddress() const
LLVM_ABI void dump(raw_ostream &OS, DIDumpOptions DumpOpts=DIDumpOptions()) const
static LLVM_ABI DWARFFormValue createFromSValue(dwarf::Form F, int64_t V)
LLVM_ABI std::optional< uint64_t > getAsUnsignedConstant() const
static LLVM_ABI DWARFFormValue createFromUnit(dwarf::Form F, const DWARFUnit *Unit, uint64_t *OffsetPtr)
dwarf::Form getForm() const
LLVM_ABI DWARFUnit * getUnitForOffset(uint64_t Offset) const
DWARFContext & getContext() const
Definition DWARFUnit.h:326
DWARFDie getDIEForOffset(uint64_t Offset)
Return the DIE object for a given offset Offset inside the unit's DIE vector.
Definition DWARFUnit.h:550
const DWARFUnitVector & getUnitVector() const
Return the DWARFUnitVector containing this unit.
Definition DWARFUnit.h:518
LLVM_ABI uint64_t getULEB128(uint64_t *offset_ptr, llvm::Error *Err=nullptr) const
Extract a unsigned LEB128 value from *offset_ptr.
bool isValidOffset(uint64_t offset) const
Test the validity of offset.
Tagged union holding either a T or a Error.
Definition Error.h:485
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM Value Representation.
Definition Value.h:75
An RAII object that temporarily switches an output stream to a specific color.
Definition WithColor.h:54
raw_ostream & get()
Definition WithColor.h:81
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI StringRef AttributeString(unsigned Attribute)
Definition Dwarf.cpp:72
LLVM_ABI StringRef FormEncodingString(unsigned Encoding)
Definition Dwarf.cpp:105
LLVM_ABI StringRef ApplePropertyString(unsigned)
Definition Dwarf.cpp:831
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
Attribute
Attributes.
Definition Dwarf.h:125
SourceLanguageName
Definition Dwarf.h:229
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
std::optional< object::SectionedAddress > toSectionedAddress(const std::optional< DWARFFormValue > &V)
std::optional< SourceLanguage > toDW_LANG(SourceLanguageName name, uint32_t version)
Convert a DWARF 6 pair of language name and version to a DWARF 5 DW_LANG.
Definition Dwarf.h:237
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
LLVM_ABI StringRef AttributeValueString(uint16_t Attr, unsigned Val)
Returns the symbolic string representing Val when used as a value for attribute Attr.
Definition Dwarf.cpp:905
uint64_t computeTombstoneAddress(uint8_t AddressByteSize)
Definition Dwarf.h:1348
LLVM_ABI llvm::StringRef LanguageDescription(SourceLanguageName name)
Returns a version-independent language name.
Definition Dwarf.cpp:466
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS, DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH=false)
Print a Dwarf expression/.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
@ invalid_argument
Definition Errc.h:56
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void dumpTypeQualifiedName(const DWARFDie &DIE, raw_ostream &OS)
Definition DWARFDie.cpp:895
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition DIContext.h:143
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI void dumpTypeUnqualifiedName(const DWARFDie &DIE, raw_ostream &OS, std::string *OriginalFullName=nullptr)
Definition DWARFDie.cpp:899
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
std::vector< DWARFAddressRange > DWARFAddressRangesVector
DWARFAddressRangesVector - represents a set of absolute address ranges.
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:197
std::function< void(Error)> RecoverableErrorHandler
Definition DIContext.h:244
llvm::SmallVector< unsigned, 0 > FilterChildTag
List of DWARF tags to filter children by.
Definition DIContext.h:216
StringRef getNameForDWARFAddressSpace(uint64_t AS) const
Definition DIContext.h:222
unsigned ChildRecurseDepth
Definition DIContext.h:199
unsigned ParentRecurseDepth
Definition DIContext.h:200
Encapsulates a DWARF attribute value and all of the data required to describe the attribute value.
static LLVM_ABI bool mayHaveLocationList(dwarf::Attribute Attr)
Identify DWARF attributes that may contain a pointer to a location list.
Definition DWARFDie.cpp:836
DWARFFormValue Value
The form and value for this attribute.
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Definition DWARFDie.cpp:853
dwarf::Attribute Attr
The attribute enumeration of this attribute.
Represents a single DWARF expression, whose value is location-dependent.
void appendQualifiedName(DieType D)
void appendUnqualifiedName(DieType D, std::string *OriginalFullName=nullptr)
Recursively append the DIE type name when applicable.