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