DWARFDie.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. #include "llvm/DebugInfo/DWARF/DWARFDie.h"
  9. #include "llvm/ADT/None.h"
  10. #include "llvm/ADT/Optional.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/DWARFDebugRangeList.h"
  17. #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
  18. #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
  19. #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
  20. #include "llvm/Object/ObjectFile.h"
  21. #include "llvm/Support/DataExtractor.h"
  22. #include "llvm/Support/Format.h"
  23. #include "llvm/Support/FormatAdapters.h"
  24. #include "llvm/Support/FormatVariadic.h"
  25. #include "llvm/Support/MathExtras.h"
  26. #include "llvm/Support/WithColor.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cinttypes>
  31. #include <cstdint>
  32. #include <string>
  33. #include <utility>
  34. using namespace llvm;
  35. using namespace dwarf;
  36. using namespace object;
  37. static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
  38. OS << " (";
  39. do {
  40. uint64_t Shift = countTrailingZeros(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 << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
  48. if (!(Val ^= Bit))
  49. break;
  50. OS << ", ";
  51. } while (true);
  52. OS << ")";
  53. }
  54. static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
  55. const DWARFAddressRangesVector &Ranges,
  56. unsigned AddressSize, unsigned Indent,
  57. const DIDumpOptions &DumpOpts) {
  58. if (!DumpOpts.ShowAddresses)
  59. return;
  60. for (const DWARFAddressRange &R : Ranges) {
  61. OS << '\n';
  62. OS.indent(Indent);
  63. R.dump(OS, AddressSize, DumpOpts, &Obj);
  64. }
  65. }
  66. static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
  67. DWARFUnit *U, unsigned Indent,
  68. DIDumpOptions DumpOpts) {
  69. assert(FormValue.isFormClass(DWARFFormValue::FC_SectionOffset) &&
  70. "bad FORM for location list");
  71. DWARFContext &Ctx = U->getContext();
  72. const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
  73. uint64_t Offset = *FormValue.getAsSectionOffset();
  74. if (FormValue.getForm() == DW_FORM_loclistx) {
  75. FormValue.dump(OS, DumpOpts);
  76. if (auto LoclistOffset = U->getLoclistOffset(Offset))
  77. Offset = *LoclistOffset;
  78. else
  79. return;
  80. }
  81. U->getLocationTable().dumpLocationList(&Offset, OS, U->getBaseAddress(), MRI,
  82. Ctx.getDWARFObj(), U, DumpOpts,
  83. Indent);
  84. }
  85. static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue,
  86. DWARFUnit *U, unsigned Indent,
  87. DIDumpOptions DumpOpts) {
  88. assert((FormValue.isFormClass(DWARFFormValue::FC_Block) ||
  89. FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) &&
  90. "bad FORM for location expression");
  91. DWARFContext &Ctx = U->getContext();
  92. const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
  93. ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
  94. DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
  95. Ctx.isLittleEndian(), 0);
  96. DWARFExpression(Data, U->getAddressByteSize(), U->getFormParams().Format)
  97. .print(OS, DumpOpts, MRI, U);
  98. }
  99. static DWARFDie resolveReferencedType(DWARFDie D,
  100. dwarf::Attribute Attr = DW_AT_type) {
  101. return D.getAttributeValueAsReferencedDie(Attr).resolveTypeUnitReference();
  102. }
  103. static DWARFDie resolveReferencedType(DWARFDie D, DWARFFormValue F) {
  104. return D.getAttributeValueAsReferencedDie(F).resolveTypeUnitReference();
  105. }
  106. namespace {
  107. // FIXME: We should have pretty printers per language. Currently we print
  108. // everything as if it was C++ and fall back to the TAG type name.
  109. struct DWARFTypePrinter {
  110. raw_ostream &OS;
  111. bool Word = true;
  112. bool EndedWithTemplate = false;
  113. DWARFTypePrinter(raw_ostream &OS) : OS(OS) {}
  114. /// Dump the name encoded in the type tag.
  115. void appendTypeTagName(dwarf::Tag T) {
  116. StringRef TagStr = TagString(T);
  117. static constexpr StringRef Prefix = "DW_TAG_";
  118. static constexpr StringRef Suffix = "_type";
  119. if (!TagStr.startswith(Prefix) || !TagStr.endswith(Suffix))
  120. return;
  121. OS << TagStr.substr(Prefix.size(),
  122. TagStr.size() - (Prefix.size() + Suffix.size()))
  123. << " ";
  124. }
  125. void appendArrayType(const DWARFDie &D) {
  126. for (const DWARFDie &C : D.children()) {
  127. if (C.getTag() != DW_TAG_subrange_type)
  128. continue;
  129. Optional<uint64_t> LB;
  130. Optional<uint64_t> Count;
  131. Optional<uint64_t> UB;
  132. Optional<unsigned> DefaultLB;
  133. if (Optional<DWARFFormValue> L = C.find(DW_AT_lower_bound))
  134. LB = L->getAsUnsignedConstant();
  135. if (Optional<DWARFFormValue> CountV = C.find(DW_AT_count))
  136. Count = CountV->getAsUnsignedConstant();
  137. if (Optional<DWARFFormValue> UpperV = C.find(DW_AT_upper_bound))
  138. UB = UpperV->getAsUnsignedConstant();
  139. if (Optional<DWARFFormValue> LV =
  140. D.getDwarfUnit()->getUnitDIE().find(DW_AT_language))
  141. if (Optional<uint64_t> LC = LV->getAsUnsignedConstant())
  142. if ((DefaultLB =
  143. LanguageLowerBound(static_cast<dwarf::SourceLanguage>(*LC))))
  144. if (LB && *LB == *DefaultLB)
  145. LB = None;
  146. if (!LB && !Count && !UB)
  147. OS << "[]";
  148. else if (!LB && (Count || UB) && DefaultLB)
  149. OS << '[' << (Count ? *Count : *UB - *DefaultLB + 1) << ']';
  150. else {
  151. OS << "[[";
  152. if (LB)
  153. OS << *LB;
  154. else
  155. OS << '?';
  156. OS << ", ";
  157. if (Count)
  158. if (LB)
  159. OS << *LB + *Count;
  160. else
  161. OS << "? + " << *Count;
  162. else if (UB)
  163. OS << *UB + 1;
  164. else
  165. OS << '?';
  166. OS << ")]";
  167. }
  168. }
  169. EndedWithTemplate = false;
  170. }
  171. DWARFDie skipQualifiers(DWARFDie D) {
  172. while (D && (D.getTag() == DW_TAG_const_type ||
  173. D.getTag() == DW_TAG_volatile_type))
  174. D = resolveReferencedType(D);
  175. return D;
  176. }
  177. bool needsParens(DWARFDie D) {
  178. D = skipQualifiers(D);
  179. return D && (D.getTag() == DW_TAG_subroutine_type || D.getTag() == DW_TAG_array_type);
  180. }
  181. void appendPointerLikeTypeBefore(DWARFDie D, DWARFDie Inner, StringRef Ptr) {
  182. appendQualifiedNameBefore(Inner);
  183. if (Word)
  184. OS << ' ';
  185. if (needsParens(Inner))
  186. OS << '(';
  187. OS << Ptr;
  188. Word = false;
  189. EndedWithTemplate = false;
  190. }
  191. DWARFDie
  192. appendUnqualifiedNameBefore(DWARFDie D,
  193. std::string *OriginalFullName = nullptr) {
  194. Word = true;
  195. if (!D) {
  196. OS << "void";
  197. return DWARFDie();
  198. }
  199. DWARFDie InnerDIE;
  200. auto Inner = [&] { return InnerDIE = resolveReferencedType(D); };
  201. const dwarf::Tag T = D.getTag();
  202. switch (T) {
  203. case DW_TAG_pointer_type: {
  204. appendPointerLikeTypeBefore(D, Inner(), "*");
  205. break;
  206. }
  207. case DW_TAG_subroutine_type: {
  208. appendQualifiedNameBefore(Inner());
  209. if (Word) {
  210. OS << ' ';
  211. }
  212. Word = false;
  213. break;
  214. }
  215. case DW_TAG_array_type: {
  216. appendQualifiedNameBefore(Inner());
  217. break;
  218. }
  219. case DW_TAG_reference_type:
  220. appendPointerLikeTypeBefore(D, Inner(), "&");
  221. break;
  222. case DW_TAG_rvalue_reference_type:
  223. appendPointerLikeTypeBefore(D, Inner(), "&&");
  224. break;
  225. case DW_TAG_ptr_to_member_type: {
  226. appendQualifiedNameBefore(Inner());
  227. if (needsParens(InnerDIE))
  228. OS << '(';
  229. else if (Word)
  230. OS << ' ';
  231. if (DWARFDie Cont = resolveReferencedType(D, DW_AT_containing_type)) {
  232. appendQualifiedName(Cont);
  233. OS << "::";
  234. }
  235. OS << "*";
  236. Word = false;
  237. break;
  238. }
  239. case DW_TAG_const_type:
  240. case DW_TAG_volatile_type:
  241. appendConstVolatileQualifierBefore(D);
  242. break;
  243. case DW_TAG_namespace: {
  244. if (const char *Name = dwarf::toString(D.find(DW_AT_name), nullptr))
  245. OS << Name;
  246. else
  247. OS << "(anonymous namespace)";
  248. break;
  249. }
  250. case DW_TAG_unspecified_type: {
  251. StringRef TypeName = D.getShortName();
  252. if (TypeName == "decltype(nullptr)")
  253. TypeName = "std::nullptr_t";
  254. Word = true;
  255. OS << TypeName;
  256. EndedWithTemplate = false;
  257. break;
  258. }
  259. /*
  260. case DW_TAG_structure_type:
  261. case DW_TAG_class_type:
  262. case DW_TAG_enumeration_type:
  263. case DW_TAG_base_type:
  264. */
  265. default: {
  266. const char *NamePtr = dwarf::toString(D.find(DW_AT_name), nullptr);
  267. if (!NamePtr) {
  268. appendTypeTagName(D.getTag());
  269. return DWARFDie();
  270. }
  271. Word = true;
  272. StringRef Name = NamePtr;
  273. static constexpr StringRef MangledPrefix = "_STN";
  274. if (Name.startswith(MangledPrefix)) {
  275. Name = Name.drop_front(MangledPrefix.size());
  276. auto Separator = Name.find('|');
  277. assert(Separator != StringRef::npos);
  278. StringRef BaseName = Name.substr(0, Separator);
  279. StringRef TemplateArgs = Name.substr(Separator + 1);
  280. if (OriginalFullName)
  281. *OriginalFullName = (BaseName + TemplateArgs).str();
  282. Name = BaseName;
  283. } else
  284. EndedWithTemplate = Name.endswith(">");
  285. OS << Name;
  286. // This check would be insufficient for operator overloads like
  287. // "operator>>" - but for now Clang doesn't try to simplify them, so this
  288. // is OK. Add more nuanced operator overload handling here if/when needed.
  289. if (Name.endswith(">"))
  290. break;
  291. if (!appendTemplateParameters(D))
  292. break;
  293. if (EndedWithTemplate)
  294. OS << ' ';
  295. OS << '>';
  296. EndedWithTemplate = true;
  297. Word = true;
  298. break;
  299. }
  300. }
  301. return InnerDIE;
  302. }
  303. void appendUnqualifiedNameAfter(DWARFDie D, DWARFDie Inner,
  304. bool SkipFirstParamIfArtificial = false) {
  305. if (!D)
  306. return;
  307. switch (D.getTag()) {
  308. case DW_TAG_subroutine_type: {
  309. appendSubroutineNameAfter(D, Inner, SkipFirstParamIfArtificial, false,
  310. false);
  311. break;
  312. }
  313. case DW_TAG_array_type: {
  314. appendArrayType(D);
  315. break;
  316. }
  317. case DW_TAG_const_type:
  318. case DW_TAG_volatile_type:
  319. appendConstVolatileQualifierAfter(D);
  320. break;
  321. case DW_TAG_ptr_to_member_type:
  322. case DW_TAG_reference_type:
  323. case DW_TAG_rvalue_reference_type:
  324. case DW_TAG_pointer_type: {
  325. if (needsParens(Inner))
  326. OS << ')';
  327. appendUnqualifiedNameAfter(Inner, resolveReferencedType(Inner),
  328. /*SkipFirstParamIfArtificial=*/D.getTag() ==
  329. DW_TAG_ptr_to_member_type);
  330. break;
  331. }
  332. /*
  333. case DW_TAG_structure_type:
  334. case DW_TAG_class_type:
  335. case DW_TAG_enumeration_type:
  336. case DW_TAG_base_type:
  337. case DW_TAG_namespace:
  338. */
  339. default:
  340. break;
  341. }
  342. }
  343. void appendQualifiedName(DWARFDie D) {
  344. if (D)
  345. appendScopes(D.getParent());
  346. appendUnqualifiedName(D);
  347. }
  348. DWARFDie appendQualifiedNameBefore(DWARFDie D) {
  349. if (D)
  350. appendScopes(D.getParent());
  351. return appendUnqualifiedNameBefore(D);
  352. }
  353. bool appendTemplateParameters(DWARFDie D, bool *FirstParameter = nullptr) {
  354. bool FirstParameterValue = true;
  355. bool IsTemplate = false;
  356. if (!FirstParameter)
  357. FirstParameter = &FirstParameterValue;
  358. for (const DWARFDie &C : D) {
  359. auto Sep = [&] {
  360. if (*FirstParameter)
  361. OS << '<';
  362. else
  363. OS << ", ";
  364. IsTemplate = true;
  365. EndedWithTemplate = false;
  366. *FirstParameter = false;
  367. };
  368. if (C.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
  369. IsTemplate = true;
  370. appendTemplateParameters(C, FirstParameter);
  371. }
  372. if (C.getTag() == dwarf::DW_TAG_template_value_parameter) {
  373. DWARFDie T = resolveReferencedType(C);
  374. Sep();
  375. if (T.getTag() == DW_TAG_enumeration_type) {
  376. auto V = C.find(DW_AT_const_value);
  377. bool FoundEnumerator = false;
  378. for (const DWARFDie &Enumerator : T) {
  379. auto EV = Enumerator.find(DW_AT_const_value);
  380. if (V && EV &&
  381. V->getAsSignedConstant() == EV->getAsSignedConstant()) {
  382. if (T.find(DW_AT_enum_class)) {
  383. appendQualifiedName(T);
  384. OS << "::";
  385. } else
  386. appendScopes(T.getParent());
  387. OS << Enumerator.getShortName();
  388. FoundEnumerator = true;
  389. break;
  390. }
  391. }
  392. if (FoundEnumerator)
  393. continue;
  394. OS << '(';
  395. appendQualifiedName(T);
  396. OS << ')';
  397. OS << to_string(*V->getAsSignedConstant());
  398. continue;
  399. }
  400. // /Maybe/ we could do pointer type parameters, looking for the
  401. // symbol in the ELF symbol table to get back to the variable...
  402. // but probably not worth it.
  403. if (T.getTag() == DW_TAG_pointer_type)
  404. continue;
  405. const char *RawName = dwarf::toString(T.find(DW_AT_name), nullptr);
  406. assert(RawName);
  407. StringRef Name = RawName;
  408. auto V = C.find(DW_AT_const_value);
  409. bool IsQualifiedChar = false;
  410. if (Name == "bool") {
  411. OS << (*V->getAsUnsignedConstant() ? "true" : "false");
  412. } else if (Name == "short") {
  413. OS << "(short)";
  414. OS << to_string(*V->getAsSignedConstant());
  415. } else if (Name == "unsigned short") {
  416. OS << "(unsigned short)";
  417. OS << to_string(*V->getAsSignedConstant());
  418. } else if (Name == "int")
  419. OS << to_string(*V->getAsSignedConstant());
  420. else if (Name == "long") {
  421. OS << to_string(*V->getAsSignedConstant());
  422. OS << "L";
  423. } else if (Name == "long long") {
  424. OS << to_string(*V->getAsSignedConstant());
  425. OS << "LL";
  426. } else if (Name == "unsigned int") {
  427. OS << to_string(*V->getAsUnsignedConstant());
  428. OS << "U";
  429. } else if (Name == "unsigned long") {
  430. OS << to_string(*V->getAsUnsignedConstant());
  431. OS << "UL";
  432. } else if (Name == "unsigned long long") {
  433. OS << to_string(*V->getAsUnsignedConstant());
  434. OS << "ULL";
  435. } else if (Name == "char" ||
  436. (IsQualifiedChar =
  437. (Name == "unsigned char" || Name == "signed char"))) {
  438. // FIXME: check T's DW_AT_type to see if it's signed or not (since
  439. // char signedness is implementation defined).
  440. auto Val = *V->getAsSignedConstant();
  441. // Copied/hacked up from Clang's CharacterLiteral::print - incomplete
  442. // (doesn't actually support different character types/widths, sign
  443. // handling's not done, and doesn't correctly test if a character is
  444. // printable or needs to use a numeric escape sequence instead)
  445. if (IsQualifiedChar) {
  446. OS << '(';
  447. OS << Name;
  448. OS << ')';
  449. }
  450. switch (Val) {
  451. case '\\':
  452. OS << "'\\\\'";
  453. break;
  454. case '\'':
  455. OS << "'\\''";
  456. break;
  457. case '\a':
  458. // TODO: K&R: the meaning of '\\a' is different in traditional C
  459. OS << "'\\a'";
  460. break;
  461. case '\b':
  462. OS << "'\\b'";
  463. break;
  464. case '\f':
  465. OS << "'\\f'";
  466. break;
  467. case '\n':
  468. OS << "'\\n'";
  469. break;
  470. case '\r':
  471. OS << "'\\r'";
  472. break;
  473. case '\t':
  474. OS << "'\\t'";
  475. break;
  476. case '\v':
  477. OS << "'\\v'";
  478. break;
  479. default:
  480. if ((Val & ~0xFFu) == ~0xFFu)
  481. Val &= 0xFFu;
  482. if (Val < 127 && Val >= 32) {
  483. OS << "'";
  484. OS << (char)Val;
  485. OS << "'";
  486. } else if (Val < 256)
  487. OS << to_string(llvm::format("'\\x%02x'", Val));
  488. else if (Val <= 0xFFFF)
  489. OS << to_string(llvm::format("'\\u%04x'", Val));
  490. else
  491. OS << to_string(llvm::format("'\\U%08x'", Val));
  492. }
  493. }
  494. continue;
  495. }
  496. if (C.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
  497. const char *RawName =
  498. dwarf::toString(C.find(DW_AT_GNU_template_name), nullptr);
  499. assert(RawName);
  500. StringRef Name = RawName;
  501. Sep();
  502. OS << Name;
  503. continue;
  504. }
  505. if (C.getTag() != dwarf::DW_TAG_template_type_parameter)
  506. continue;
  507. auto TypeAttr = C.find(DW_AT_type);
  508. Sep();
  509. appendQualifiedName(TypeAttr ? resolveReferencedType(C, *TypeAttr)
  510. : DWARFDie());
  511. }
  512. if (IsTemplate && *FirstParameter && FirstParameter == &FirstParameterValue)
  513. OS << '<';
  514. return IsTemplate;
  515. }
  516. void decomposeConstVolatile(DWARFDie &N, DWARFDie &T, DWARFDie &C,
  517. DWARFDie &V) {
  518. (N.getTag() == DW_TAG_const_type ? C : V) = N;
  519. T = resolveReferencedType(N);
  520. if (T) {
  521. auto Tag = T.getTag();
  522. if (Tag == DW_TAG_const_type) {
  523. C = T;
  524. T = resolveReferencedType(T);
  525. } else if (Tag == DW_TAG_volatile_type) {
  526. V = T;
  527. T = resolveReferencedType(T);
  528. }
  529. }
  530. }
  531. void appendConstVolatileQualifierAfter(DWARFDie N) {
  532. DWARFDie C;
  533. DWARFDie V;
  534. DWARFDie T;
  535. decomposeConstVolatile(N, T, C, V);
  536. if (T && T.getTag() == DW_TAG_subroutine_type)
  537. appendSubroutineNameAfter(T, resolveReferencedType(T), false, C.isValid(),
  538. V.isValid());
  539. else
  540. appendUnqualifiedNameAfter(T, resolveReferencedType(T));
  541. }
  542. void appendConstVolatileQualifierBefore(DWARFDie N) {
  543. DWARFDie C;
  544. DWARFDie V;
  545. DWARFDie T;
  546. decomposeConstVolatile(N, T, C, V);
  547. bool Subroutine = T && T.getTag() == DW_TAG_subroutine_type;
  548. DWARFDie A = T;
  549. while (A && A.getTag() == DW_TAG_array_type)
  550. A = resolveReferencedType(A);
  551. bool Leading =
  552. (!A || (A.getTag() != DW_TAG_pointer_type &&
  553. A.getTag() != llvm::dwarf::DW_TAG_ptr_to_member_type)) &&
  554. !Subroutine;
  555. if (Leading) {
  556. if (C)
  557. OS << "const ";
  558. if (V)
  559. OS << "volatile ";
  560. }
  561. appendQualifiedNameBefore(T);
  562. if (!Leading && !Subroutine) {
  563. Word = true;
  564. if (C)
  565. OS << "const";
  566. if (V) {
  567. if (C)
  568. OS << ' ';
  569. OS << "volatile";
  570. }
  571. }
  572. }
  573. /// Recursively append the DIE type name when applicable.
  574. void appendUnqualifiedName(DWARFDie D,
  575. std::string *OriginalFullName = nullptr) {
  576. // FIXME: We should have pretty printers per language. Currently we print
  577. // everything as if it was C++ and fall back to the TAG type name.
  578. DWARFDie Inner = appendUnqualifiedNameBefore(D, OriginalFullName);
  579. appendUnqualifiedNameAfter(D, Inner);
  580. }
  581. void appendSubroutineNameAfter(DWARFDie D, DWARFDie Inner,
  582. bool SkipFirstParamIfArtificial, bool Const,
  583. bool Volatile) {
  584. DWARFDie FirstParamIfArtificial;
  585. OS << '(';
  586. EndedWithTemplate = false;
  587. bool First = true;
  588. bool RealFirst = true;
  589. for (DWARFDie P : D) {
  590. if (P.getTag() != DW_TAG_formal_parameter &&
  591. P.getTag() != DW_TAG_unspecified_parameters)
  592. return;
  593. DWARFDie T = resolveReferencedType(P);
  594. if (SkipFirstParamIfArtificial && RealFirst && P.find(DW_AT_artificial)) {
  595. FirstParamIfArtificial = T;
  596. RealFirst = false;
  597. continue;
  598. }
  599. if (!First) {
  600. OS << ", ";
  601. }
  602. First = false;
  603. if (P.getTag() == DW_TAG_unspecified_parameters)
  604. OS << "...";
  605. else
  606. appendQualifiedName(T);
  607. }
  608. EndedWithTemplate = false;
  609. OS << ')';
  610. if (FirstParamIfArtificial) {
  611. if (DWARFDie P = FirstParamIfArtificial) {
  612. if (P.getTag() == DW_TAG_pointer_type) {
  613. DWARFDie C;
  614. DWARFDie V;
  615. auto CVStep = [&](DWARFDie CV) {
  616. if (DWARFDie U = resolveReferencedType(CV)) {
  617. if (U.getTag() == DW_TAG_const_type)
  618. return C = U;
  619. if (U.getTag() == DW_TAG_volatile_type)
  620. return V = U;
  621. }
  622. return DWARFDie();
  623. };
  624. if (DWARFDie CV = CVStep(P)) {
  625. CVStep(CV);
  626. }
  627. if (C)
  628. OS << " const";
  629. if (V)
  630. OS << " volatile";
  631. }
  632. }
  633. } else {
  634. if (Const)
  635. OS << " const";
  636. if (Volatile)
  637. OS << " volatile";
  638. }
  639. if (D.find(DW_AT_reference))
  640. OS << " &";
  641. if (D.find(DW_AT_rvalue_reference))
  642. OS << " &&";
  643. appendUnqualifiedNameAfter(Inner, resolveReferencedType(Inner));
  644. }
  645. void appendScopes(DWARFDie D) {
  646. if (D.getTag() == DW_TAG_compile_unit)
  647. return;
  648. if (D.getTag() == DW_TAG_type_unit)
  649. return;
  650. if (D.getTag() == DW_TAG_skeleton_unit)
  651. return;
  652. if (D.getTag() == DW_TAG_subprogram)
  653. return;
  654. if (D.getTag() == DW_TAG_lexical_block)
  655. return;
  656. D = D.resolveTypeUnitReference();
  657. if (DWARFDie P = D.getParent())
  658. appendScopes(P);
  659. appendUnqualifiedName(D);
  660. OS << "::";
  661. }
  662. };
  663. } // anonymous namespace
  664. static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
  665. const DWARFAttribute &AttrValue, unsigned Indent,
  666. DIDumpOptions DumpOpts) {
  667. if (!Die.isValid())
  668. return;
  669. const char BaseIndent[] = " ";
  670. OS << BaseIndent;
  671. OS.indent(Indent + 2);
  672. dwarf::Attribute Attr = AttrValue.Attr;
  673. WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
  674. dwarf::Form Form = AttrValue.Value.getForm();
  675. if (DumpOpts.Verbose || DumpOpts.ShowForm)
  676. OS << formatv(" [{0}]", Form);
  677. DWARFUnit *U = Die.getDwarfUnit();
  678. const DWARFFormValue &FormValue = AttrValue.Value;
  679. OS << "\t(";
  680. StringRef Name;
  681. std::string File;
  682. auto Color = HighlightColor::Enumerator;
  683. if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
  684. Color = HighlightColor::String;
  685. if (const auto *LT = U->getContext().getLineTableForUnit(U))
  686. if (LT->getFileNameByIndex(
  687. FormValue.getAsUnsignedConstant().getValue(),
  688. U->getCompilationDir(),
  689. DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
  690. File = '"' + File + '"';
  691. Name = File;
  692. }
  693. } else if (Optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
  694. Name = AttributeValueString(Attr, *Val);
  695. if (!Name.empty())
  696. WithColor(OS, Color) << Name;
  697. else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
  698. OS << *FormValue.getAsUnsignedConstant();
  699. else if (Attr == DW_AT_low_pc &&
  700. (FormValue.getAsAddress() ==
  701. dwarf::computeTombstoneAddress(U->getAddressByteSize()))) {
  702. if (DumpOpts.Verbose) {
  703. FormValue.dump(OS, DumpOpts);
  704. OS << " (";
  705. }
  706. OS << "dead code";
  707. if (DumpOpts.Verbose)
  708. OS << ')';
  709. } else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
  710. FormValue.getAsUnsignedConstant()) {
  711. if (DumpOpts.ShowAddresses) {
  712. // Print the actual address rather than the offset.
  713. uint64_t LowPC, HighPC, Index;
  714. if (Die.getLowAndHighPC(LowPC, HighPC, Index))
  715. DWARFFormValue::dumpAddress(OS, U->getAddressByteSize(), HighPC);
  716. else
  717. FormValue.dump(OS, DumpOpts);
  718. }
  719. } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
  720. FormValue.isFormClass(DWARFFormValue::FC_SectionOffset))
  721. dumpLocationList(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
  722. DumpOpts);
  723. else if (FormValue.isFormClass(DWARFFormValue::FC_Exprloc) ||
  724. (DWARFAttribute::mayHaveLocationExpr(Attr) &&
  725. FormValue.isFormClass(DWARFFormValue::FC_Block)))
  726. dumpLocationExpr(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
  727. DumpOpts);
  728. else
  729. FormValue.dump(OS, DumpOpts);
  730. std::string Space = DumpOpts.ShowAddresses ? " " : "";
  731. // We have dumped the attribute raw value. For some attributes
  732. // having both the raw value and the pretty-printed value is
  733. // interesting. These attributes are handled below.
  734. if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
  735. if (const char *Name =
  736. Die.getAttributeValueAsReferencedDie(FormValue).getName(
  737. DINameKind::LinkageName))
  738. OS << Space << "\"" << Name << '\"';
  739. } else if (Attr == DW_AT_type) {
  740. DWARFDie D = resolveReferencedType(Die, FormValue);
  741. if (D && !D.isNULL()) {
  742. OS << Space << "\"";
  743. dumpTypeQualifiedName(D, OS);
  744. OS << '"';
  745. }
  746. } else if (Attr == DW_AT_APPLE_property_attribute) {
  747. if (Optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
  748. dumpApplePropertyAttribute(OS, *OptVal);
  749. } else if (Attr == DW_AT_ranges) {
  750. const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
  751. // For DW_FORM_rnglistx we need to dump the offset separately, since
  752. // we have only dumped the index so far.
  753. if (FormValue.getForm() == DW_FORM_rnglistx)
  754. if (auto RangeListOffset =
  755. U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
  756. DWARFFormValue FV = DWARFFormValue::createFromUValue(
  757. dwarf::DW_FORM_sec_offset, *RangeListOffset);
  758. FV.dump(OS, DumpOpts);
  759. }
  760. if (auto RangesOrError = Die.getAddressRanges())
  761. dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
  762. sizeof(BaseIndent) + Indent + 4, DumpOpts);
  763. else
  764. DumpOpts.RecoverableErrorHandler(createStringError(
  765. errc::invalid_argument, "decoding address ranges: %s",
  766. toString(RangesOrError.takeError()).c_str()));
  767. }
  768. OS << ")\n";
  769. }
  770. void DWARFDie::getFullName(raw_string_ostream &OS,
  771. std::string *OriginalFullName) const {
  772. const char *NamePtr = getShortName();
  773. if (!NamePtr)
  774. return;
  775. if (getTag() == DW_TAG_GNU_template_parameter_pack)
  776. return;
  777. dumpTypeUnqualifiedName(*this, OS, OriginalFullName);
  778. }
  779. bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
  780. bool DWARFDie::isSubroutineDIE() const {
  781. auto Tag = getTag();
  782. return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
  783. }
  784. Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
  785. if (!isValid())
  786. return None;
  787. auto AbbrevDecl = getAbbreviationDeclarationPtr();
  788. if (AbbrevDecl)
  789. return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
  790. return None;
  791. }
  792. Optional<DWARFFormValue>
  793. DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
  794. if (!isValid())
  795. return None;
  796. auto AbbrevDecl = getAbbreviationDeclarationPtr();
  797. if (AbbrevDecl) {
  798. for (auto Attr : Attrs) {
  799. if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
  800. return Value;
  801. }
  802. }
  803. return None;
  804. }
  805. Optional<DWARFFormValue>
  806. DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
  807. SmallVector<DWARFDie, 3> Worklist;
  808. Worklist.push_back(*this);
  809. // Keep track if DIEs already seen to prevent infinite recursion.
  810. // Empirically we rarely see a depth of more than 3 when dealing with valid
  811. // DWARF. This corresponds to following the DW_AT_abstract_origin and
  812. // DW_AT_specification just once.
  813. SmallSet<DWARFDie, 3> Seen;
  814. Seen.insert(*this);
  815. while (!Worklist.empty()) {
  816. DWARFDie Die = Worklist.pop_back_val();
  817. if (!Die.isValid())
  818. continue;
  819. if (auto Value = Die.find(Attrs))
  820. return Value;
  821. if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
  822. if (Seen.insert(D).second)
  823. Worklist.push_back(D);
  824. if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
  825. if (Seen.insert(D).second)
  826. Worklist.push_back(D);
  827. }
  828. return None;
  829. }
  830. DWARFDie
  831. DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
  832. if (Optional<DWARFFormValue> F = find(Attr))
  833. return getAttributeValueAsReferencedDie(*F);
  834. return DWARFDie();
  835. }
  836. DWARFDie
  837. DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
  838. DWARFDie Result;
  839. if (auto SpecRef = V.getAsRelativeReference()) {
  840. if (SpecRef->Unit)
  841. Result = SpecRef->Unit->getDIEForOffset(SpecRef->Unit->getOffset() +
  842. SpecRef->Offset);
  843. else if (auto SpecUnit =
  844. U->getUnitVector().getUnitForOffset(SpecRef->Offset))
  845. Result = SpecUnit->getDIEForOffset(SpecRef->Offset);
  846. }
  847. return Result;
  848. }
  849. DWARFDie DWARFDie::resolveTypeUnitReference() const {
  850. if (auto Attr = find(DW_AT_signature)) {
  851. if (Optional<uint64_t> Sig = Attr->getAsReferenceUVal()) {
  852. if (DWARFTypeUnit *TU = U->getContext().getTypeUnitForHash(
  853. U->getVersion(), *Sig, U->isDWOUnit()))
  854. return TU->getDIEForOffset(TU->getTypeOffset() + TU->getOffset());
  855. }
  856. }
  857. return *this;
  858. }
  859. Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
  860. return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
  861. }
  862. Optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
  863. return toSectionOffset(find(DW_AT_loclists_base));
  864. }
  865. Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
  866. uint64_t Tombstone = dwarf::computeTombstoneAddress(U->getAddressByteSize());
  867. if (LowPC == Tombstone)
  868. return None;
  869. if (auto FormValue = find(DW_AT_high_pc)) {
  870. if (auto Address = FormValue->getAsAddress()) {
  871. // High PC is an address.
  872. return Address;
  873. }
  874. if (auto Offset = FormValue->getAsUnsignedConstant()) {
  875. // High PC is an offset from LowPC.
  876. return LowPC + *Offset;
  877. }
  878. }
  879. return None;
  880. }
  881. bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
  882. uint64_t &SectionIndex) const {
  883. auto F = find(DW_AT_low_pc);
  884. auto LowPcAddr = toSectionedAddress(F);
  885. if (!LowPcAddr)
  886. return false;
  887. if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
  888. LowPC = LowPcAddr->Address;
  889. HighPC = *HighPcAddr;
  890. SectionIndex = LowPcAddr->SectionIndex;
  891. return true;
  892. }
  893. return false;
  894. }
  895. Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
  896. if (isNULL())
  897. return DWARFAddressRangesVector();
  898. // Single range specified by low/high PC.
  899. uint64_t LowPC, HighPC, Index;
  900. if (getLowAndHighPC(LowPC, HighPC, Index))
  901. return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
  902. Optional<DWARFFormValue> Value = find(DW_AT_ranges);
  903. if (Value) {
  904. if (Value->getForm() == DW_FORM_rnglistx)
  905. return U->findRnglistFromIndex(*Value->getAsSectionOffset());
  906. return U->findRnglistFromOffset(*Value->getAsSectionOffset());
  907. }
  908. return DWARFAddressRangesVector();
  909. }
  910. bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
  911. auto RangesOrError = getAddressRanges();
  912. if (!RangesOrError) {
  913. llvm::consumeError(RangesOrError.takeError());
  914. return false;
  915. }
  916. for (const auto &R : RangesOrError.get())
  917. if (R.LowPC <= Address && Address < R.HighPC)
  918. return true;
  919. return false;
  920. }
  921. Expected<DWARFLocationExpressionsVector>
  922. DWARFDie::getLocations(dwarf::Attribute Attr) const {
  923. Optional<DWARFFormValue> Location = find(Attr);
  924. if (!Location)
  925. return createStringError(inconvertibleErrorCode(), "No %s",
  926. dwarf::AttributeString(Attr).data());
  927. if (Optional<uint64_t> Off = Location->getAsSectionOffset()) {
  928. uint64_t Offset = *Off;
  929. if (Location->getForm() == DW_FORM_loclistx) {
  930. if (auto LoclistOffset = U->getLoclistOffset(Offset))
  931. Offset = *LoclistOffset;
  932. else
  933. return createStringError(inconvertibleErrorCode(),
  934. "Loclist table not found");
  935. }
  936. return U->findLoclistFromOffset(Offset);
  937. }
  938. if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
  939. return DWARFLocationExpressionsVector{
  940. DWARFLocationExpression{None, to_vector<4>(*Expr)}};
  941. }
  942. return createStringError(
  943. inconvertibleErrorCode(), "Unsupported %s encoding: %s",
  944. dwarf::AttributeString(Attr).data(),
  945. dwarf::FormEncodingString(Location->getForm()).data());
  946. }
  947. const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
  948. if (!isSubroutineDIE())
  949. return nullptr;
  950. return getName(Kind);
  951. }
  952. const char *DWARFDie::getName(DINameKind Kind) const {
  953. if (!isValid() || Kind == DINameKind::None)
  954. return nullptr;
  955. // Try to get mangled name only if it was asked for.
  956. if (Kind == DINameKind::LinkageName) {
  957. if (auto Name = getLinkageName())
  958. return Name;
  959. }
  960. return getShortName();
  961. }
  962. const char *DWARFDie::getShortName() const {
  963. if (!isValid())
  964. return nullptr;
  965. return dwarf::toString(findRecursively(dwarf::DW_AT_name), nullptr);
  966. }
  967. const char *DWARFDie::getLinkageName() const {
  968. if (!isValid())
  969. return nullptr;
  970. return dwarf::toString(findRecursively({dwarf::DW_AT_MIPS_linkage_name,
  971. dwarf::DW_AT_linkage_name}),
  972. nullptr);
  973. }
  974. uint64_t DWARFDie::getDeclLine() const {
  975. return toUnsigned(findRecursively(DW_AT_decl_line), 0);
  976. }
  977. std::string
  978. DWARFDie::getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const {
  979. if (auto FormValue = findRecursively(DW_AT_decl_file))
  980. if (auto OptString = FormValue->getAsFile(Kind))
  981. return *OptString;
  982. return {};
  983. }
  984. void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
  985. uint32_t &CallColumn,
  986. uint32_t &CallDiscriminator) const {
  987. CallFile = toUnsigned(find(DW_AT_call_file), 0);
  988. CallLine = toUnsigned(find(DW_AT_call_line), 0);
  989. CallColumn = toUnsigned(find(DW_AT_call_column), 0);
  990. CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
  991. }
  992. /// Helper to dump a DIE with all of its parents, but no siblings.
  993. static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
  994. DIDumpOptions DumpOpts, unsigned Depth = 0) {
  995. if (!Die)
  996. return Indent;
  997. if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
  998. return Indent;
  999. Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
  1000. Die.dump(OS, Indent, DumpOpts);
  1001. return Indent + 2;
  1002. }
  1003. void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
  1004. DIDumpOptions DumpOpts) const {
  1005. if (!isValid())
  1006. return;
  1007. DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
  1008. const uint64_t Offset = getOffset();
  1009. uint64_t offset = Offset;
  1010. if (DumpOpts.ShowParents) {
  1011. DIDumpOptions ParentDumpOpts = DumpOpts;
  1012. ParentDumpOpts.ShowParents = false;
  1013. ParentDumpOpts.ShowChildren = false;
  1014. Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
  1015. }
  1016. if (debug_info_data.isValidOffset(offset)) {
  1017. uint32_t abbrCode = debug_info_data.getULEB128(&offset);
  1018. if (DumpOpts.ShowAddresses)
  1019. WithColor(OS, HighlightColor::Address).get()
  1020. << format("\n0x%8.8" PRIx64 ": ", Offset);
  1021. if (abbrCode) {
  1022. auto AbbrevDecl = getAbbreviationDeclarationPtr();
  1023. if (AbbrevDecl) {
  1024. WithColor(OS, HighlightColor::Tag).get().indent(Indent)
  1025. << formatv("{0}", getTag());
  1026. if (DumpOpts.Verbose) {
  1027. OS << format(" [%u] %c", abbrCode,
  1028. AbbrevDecl->hasChildren() ? '*' : ' ');
  1029. if (Optional<uint32_t> ParentIdx = Die->getParentIdx())
  1030. OS << format(" (0x%8.8" PRIx64 ")",
  1031. U->getDIEAtIndex(*ParentIdx).getOffset());
  1032. }
  1033. OS << '\n';
  1034. // Dump all data in the DIE for the attributes.
  1035. for (const DWARFAttribute &AttrValue : attributes())
  1036. dumpAttribute(OS, *this, AttrValue, Indent, DumpOpts);
  1037. if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0) {
  1038. DWARFDie Child = getFirstChild();
  1039. DumpOpts.ChildRecurseDepth--;
  1040. DIDumpOptions ChildDumpOpts = DumpOpts;
  1041. ChildDumpOpts.ShowParents = false;
  1042. while (Child) {
  1043. Child.dump(OS, Indent + 2, ChildDumpOpts);
  1044. Child = Child.getSibling();
  1045. }
  1046. }
  1047. } else {
  1048. OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
  1049. << abbrCode << '\n';
  1050. }
  1051. } else {
  1052. OS.indent(Indent) << "NULL\n";
  1053. }
  1054. }
  1055. }
  1056. LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
  1057. DWARFDie DWARFDie::getParent() const {
  1058. if (isValid())
  1059. return U->getParent(Die);
  1060. return DWARFDie();
  1061. }
  1062. DWARFDie DWARFDie::getSibling() const {
  1063. if (isValid())
  1064. return U->getSibling(Die);
  1065. return DWARFDie();
  1066. }
  1067. DWARFDie DWARFDie::getPreviousSibling() const {
  1068. if (isValid())
  1069. return U->getPreviousSibling(Die);
  1070. return DWARFDie();
  1071. }
  1072. DWARFDie DWARFDie::getFirstChild() const {
  1073. if (isValid())
  1074. return U->getFirstChild(Die);
  1075. return DWARFDie();
  1076. }
  1077. DWARFDie DWARFDie::getLastChild() const {
  1078. if (isValid())
  1079. return U->getLastChild(Die);
  1080. return DWARFDie();
  1081. }
  1082. iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
  1083. return make_range(attribute_iterator(*this, false),
  1084. attribute_iterator(*this, true));
  1085. }
  1086. DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
  1087. : Die(D), Index(0) {
  1088. auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
  1089. assert(AbbrDecl && "Must have abbreviation declaration");
  1090. if (End) {
  1091. // This is the end iterator so we set the index to the attribute count.
  1092. Index = AbbrDecl->getNumAttributes();
  1093. } else {
  1094. // This is the begin iterator so we extract the value for this->Index.
  1095. AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
  1096. updateForIndex(*AbbrDecl, 0);
  1097. }
  1098. }
  1099. void DWARFDie::attribute_iterator::updateForIndex(
  1100. const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
  1101. Index = I;
  1102. // AbbrDecl must be valid before calling this function.
  1103. auto NumAttrs = AbbrDecl.getNumAttributes();
  1104. if (Index < NumAttrs) {
  1105. AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
  1106. // Add the previous byte size of any previous attribute value.
  1107. AttrValue.Offset += AttrValue.ByteSize;
  1108. uint64_t ParseOffset = AttrValue.Offset;
  1109. if (AbbrDecl.getAttrIsImplicitConstByIndex(Index))
  1110. AttrValue.Value = DWARFFormValue::createFromSValue(
  1111. AbbrDecl.getFormByIndex(Index),
  1112. AbbrDecl.getAttrImplicitConstValueByIndex(Index));
  1113. else {
  1114. auto U = Die.getDwarfUnit();
  1115. assert(U && "Die must have valid DWARF unit");
  1116. AttrValue.Value = DWARFFormValue::createFromUnit(
  1117. AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
  1118. }
  1119. AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
  1120. } else {
  1121. assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
  1122. AttrValue = {};
  1123. }
  1124. }
  1125. DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
  1126. if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
  1127. updateForIndex(*AbbrDecl, Index + 1);
  1128. return *this;
  1129. }
  1130. bool DWARFAttribute::mayHaveLocationList(dwarf::Attribute Attr) {
  1131. switch(Attr) {
  1132. case DW_AT_location:
  1133. case DW_AT_string_length:
  1134. case DW_AT_return_addr:
  1135. case DW_AT_data_member_location:
  1136. case DW_AT_frame_base:
  1137. case DW_AT_static_link:
  1138. case DW_AT_segment:
  1139. case DW_AT_use_location:
  1140. case DW_AT_vtable_elem_location:
  1141. return true;
  1142. default:
  1143. return false;
  1144. }
  1145. }
  1146. bool DWARFAttribute::mayHaveLocationExpr(dwarf::Attribute Attr) {
  1147. switch (Attr) {
  1148. // From the DWARF v5 specification.
  1149. case DW_AT_location:
  1150. case DW_AT_byte_size:
  1151. case DW_AT_bit_offset:
  1152. case DW_AT_bit_size:
  1153. case DW_AT_string_length:
  1154. case DW_AT_lower_bound:
  1155. case DW_AT_return_addr:
  1156. case DW_AT_bit_stride:
  1157. case DW_AT_upper_bound:
  1158. case DW_AT_count:
  1159. case DW_AT_data_member_location:
  1160. case DW_AT_frame_base:
  1161. case DW_AT_segment:
  1162. case DW_AT_static_link:
  1163. case DW_AT_use_location:
  1164. case DW_AT_vtable_elem_location:
  1165. case DW_AT_allocated:
  1166. case DW_AT_associated:
  1167. case DW_AT_data_location:
  1168. case DW_AT_byte_stride:
  1169. case DW_AT_rank:
  1170. case DW_AT_call_value:
  1171. case DW_AT_call_origin:
  1172. case DW_AT_call_target:
  1173. case DW_AT_call_target_clobbered:
  1174. case DW_AT_call_data_location:
  1175. case DW_AT_call_data_value:
  1176. // Extensions.
  1177. case DW_AT_GNU_call_site_value:
  1178. case DW_AT_GNU_call_site_target:
  1179. return true;
  1180. default:
  1181. return false;
  1182. }
  1183. }
  1184. namespace llvm {
  1185. void dumpTypeQualifiedName(const DWARFDie &DIE, raw_ostream &OS) {
  1186. DWARFTypePrinter(OS).appendQualifiedName(DIE);
  1187. }
  1188. void dumpTypeUnqualifiedName(const DWARFDie &DIE, raw_ostream &OS,
  1189. std::string *OriginalFullName) {
  1190. DWARFTypePrinter(OS).appendUnqualifiedName(DIE, OriginalFullName);
  1191. }
  1192. } // namespace llvm