DWARFLinker.cpp 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634
  1. //=== DWARFLinker.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/DWARFLinker/DWARFLinker.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/BitVector.h"
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/CodeGen/NonRelocatableStringpool.h"
  14. #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
  15. #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
  16. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  17. #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
  18. #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
  19. #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFDie.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFSection.h"
  23. #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
  24. #include "llvm/Support/DataExtractor.h"
  25. #include "llvm/Support/Error.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/ErrorOr.h"
  28. #include "llvm/Support/FormatVariadic.h"
  29. #include "llvm/Support/LEB128.h"
  30. #include "llvm/Support/Path.h"
  31. #include "llvm/Support/ThreadPool.h"
  32. #include <vector>
  33. namespace llvm {
  34. /// Hold the input and output of the debug info size in bytes.
  35. struct DebugInfoSize {
  36. uint64_t Input;
  37. uint64_t Output;
  38. };
  39. /// Compute the total size of the debug info.
  40. static uint64_t getDebugInfoSize(DWARFContext &Dwarf) {
  41. uint64_t Size = 0;
  42. for (auto &Unit : Dwarf.compile_units()) {
  43. Size += Unit->getLength();
  44. }
  45. return Size;
  46. }
  47. /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
  48. /// CompileUnit object instead.
  49. static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
  50. auto CU = llvm::upper_bound(
  51. Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
  52. return LHS < RHS->getOrigUnit().getNextUnitOffset();
  53. });
  54. return CU != Units.end() ? CU->get() : nullptr;
  55. }
  56. /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
  57. /// The resulting DIE might be in another CompileUnit which is stored into \p
  58. /// ReferencedCU. \returns null if resolving fails for any reason.
  59. DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
  60. const UnitListTy &Units,
  61. const DWARFFormValue &RefValue,
  62. const DWARFDie &DIE,
  63. CompileUnit *&RefCU) {
  64. assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
  65. uint64_t RefOffset = *RefValue.getAsReference();
  66. if ((RefCU = getUnitForOffset(Units, RefOffset)))
  67. if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
  68. // In a file with broken references, an attribute might point to a NULL
  69. // DIE.
  70. if (!RefDie.isNULL())
  71. return RefDie;
  72. }
  73. reportWarning("could not find referenced DIE", File, &DIE);
  74. return DWARFDie();
  75. }
  76. /// \returns whether the passed \a Attr type might contain a DIE reference
  77. /// suitable for ODR uniquing.
  78. static bool isODRAttribute(uint16_t Attr) {
  79. switch (Attr) {
  80. default:
  81. return false;
  82. case dwarf::DW_AT_type:
  83. case dwarf::DW_AT_containing_type:
  84. case dwarf::DW_AT_specification:
  85. case dwarf::DW_AT_abstract_origin:
  86. case dwarf::DW_AT_import:
  87. return true;
  88. }
  89. llvm_unreachable("Improper attribute.");
  90. }
  91. static bool isTypeTag(uint16_t Tag) {
  92. switch (Tag) {
  93. case dwarf::DW_TAG_array_type:
  94. case dwarf::DW_TAG_class_type:
  95. case dwarf::DW_TAG_enumeration_type:
  96. case dwarf::DW_TAG_pointer_type:
  97. case dwarf::DW_TAG_reference_type:
  98. case dwarf::DW_TAG_string_type:
  99. case dwarf::DW_TAG_structure_type:
  100. case dwarf::DW_TAG_subroutine_type:
  101. case dwarf::DW_TAG_typedef:
  102. case dwarf::DW_TAG_union_type:
  103. case dwarf::DW_TAG_ptr_to_member_type:
  104. case dwarf::DW_TAG_set_type:
  105. case dwarf::DW_TAG_subrange_type:
  106. case dwarf::DW_TAG_base_type:
  107. case dwarf::DW_TAG_const_type:
  108. case dwarf::DW_TAG_constant:
  109. case dwarf::DW_TAG_file_type:
  110. case dwarf::DW_TAG_namelist:
  111. case dwarf::DW_TAG_packed_type:
  112. case dwarf::DW_TAG_volatile_type:
  113. case dwarf::DW_TAG_restrict_type:
  114. case dwarf::DW_TAG_atomic_type:
  115. case dwarf::DW_TAG_interface_type:
  116. case dwarf::DW_TAG_unspecified_type:
  117. case dwarf::DW_TAG_shared_type:
  118. case dwarf::DW_TAG_immutable_type:
  119. return true;
  120. default:
  121. break;
  122. }
  123. return false;
  124. }
  125. AddressesMap::~AddressesMap() {}
  126. DwarfEmitter::~DwarfEmitter() {}
  127. static Optional<StringRef> StripTemplateParameters(StringRef Name) {
  128. // We are looking for template parameters to strip from Name. e.g.
  129. //
  130. // operator<<B>
  131. //
  132. // We look for > at the end but if it does not contain any < then we
  133. // have something like operator>>. We check for the operator<=> case.
  134. if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
  135. return {};
  136. // How many < until we have the start of the template parameters.
  137. size_t NumLeftAnglesToSkip = 1;
  138. // If we have operator<=> then we need to skip its < as well.
  139. NumLeftAnglesToSkip += Name.count("<=>");
  140. size_t RightAngleCount = Name.count('>');
  141. size_t LeftAngleCount = Name.count('<');
  142. // If we have more < than > we have operator< or operator<<
  143. // we to account for their < as well.
  144. if (LeftAngleCount > RightAngleCount)
  145. NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
  146. size_t StartOfTemplate = 0;
  147. while (NumLeftAnglesToSkip--)
  148. StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
  149. return Name.substr(0, StartOfTemplate - 1);
  150. }
  151. bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
  152. AttributesInfo &Info,
  153. OffsetsStringPool &StringPool,
  154. bool StripTemplate) {
  155. // This function will be called on DIEs having low_pcs and
  156. // ranges. As getting the name might be more expansive, filter out
  157. // blocks directly.
  158. if (Die.getTag() == dwarf::DW_TAG_lexical_block)
  159. return false;
  160. if (!Info.MangledName)
  161. if (const char *MangledName = Die.getLinkageName())
  162. Info.MangledName = StringPool.getEntry(MangledName);
  163. if (!Info.Name)
  164. if (const char *Name = Die.getShortName())
  165. Info.Name = StringPool.getEntry(Name);
  166. if (!Info.MangledName)
  167. Info.MangledName = Info.Name;
  168. if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
  169. StringRef Name = Info.Name.getString();
  170. if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
  171. Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
  172. }
  173. return Info.Name || Info.MangledName;
  174. }
  175. /// Resolve the relative path to a build artifact referenced by DWARF by
  176. /// applying DW_AT_comp_dir.
  177. static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
  178. sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
  179. }
  180. /// Collect references to parseable Swift interfaces in imported
  181. /// DW_TAG_module blocks.
  182. static void analyzeImportedModule(
  183. const DWARFDie &DIE, CompileUnit &CU,
  184. swiftInterfacesMap *ParseableSwiftInterfaces,
  185. std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
  186. if (CU.getLanguage() != dwarf::DW_LANG_Swift)
  187. return;
  188. if (!ParseableSwiftInterfaces)
  189. return;
  190. StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
  191. if (!Path.endswith(".swiftinterface"))
  192. return;
  193. // Don't track interfaces that are part of the SDK.
  194. StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
  195. if (SysRoot.empty())
  196. SysRoot = CU.getSysRoot();
  197. if (!SysRoot.empty() && Path.startswith(SysRoot))
  198. return;
  199. Optional<const char*> Name = dwarf::toString(DIE.find(dwarf::DW_AT_name));
  200. if (!Name)
  201. return;
  202. auto &Entry = (*ParseableSwiftInterfaces)[*Name];
  203. // The prepend path is applied later when copying.
  204. DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
  205. SmallString<128> ResolvedPath;
  206. if (sys::path::is_relative(Path))
  207. resolveRelativeObjectPath(ResolvedPath, CUDie);
  208. sys::path::append(ResolvedPath, Path);
  209. if (!Entry.empty() && Entry != ResolvedPath)
  210. ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
  211. *Name + ": " + Entry + " and " + Path,
  212. DIE);
  213. Entry = std::string(ResolvedPath.str());
  214. }
  215. /// The distinct types of work performed by the work loop in
  216. /// analyzeContextInfo.
  217. enum class ContextWorklistItemType : uint8_t {
  218. AnalyzeContextInfo,
  219. UpdateChildPruning,
  220. UpdatePruning,
  221. };
  222. /// This class represents an item in the work list. The type defines what kind
  223. /// of work needs to be performed when processing the current item. Everything
  224. /// but the Type and Die fields are optional based on the type.
  225. struct ContextWorklistItem {
  226. DWARFDie Die;
  227. unsigned ParentIdx;
  228. union {
  229. CompileUnit::DIEInfo *OtherInfo;
  230. DeclContext *Context;
  231. };
  232. ContextWorklistItemType Type;
  233. bool InImportedModule;
  234. ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
  235. CompileUnit::DIEInfo *OtherInfo = nullptr)
  236. : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
  237. InImportedModule(false) {}
  238. ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
  239. bool InImportedModule)
  240. : Die(Die), ParentIdx(ParentIdx), Context(Context),
  241. Type(ContextWorklistItemType::AnalyzeContextInfo),
  242. InImportedModule(InImportedModule) {}
  243. };
  244. static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
  245. uint64_t ModulesEndOffset) {
  246. CompileUnit::DIEInfo &Info = CU.getInfo(Die);
  247. // Prune this DIE if it is either a forward declaration inside a
  248. // DW_TAG_module or a DW_TAG_module that contains nothing but
  249. // forward declarations.
  250. Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
  251. (isTypeTag(Die.getTag()) &&
  252. dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
  253. // Only prune forward declarations inside a DW_TAG_module for which a
  254. // definition exists elsewhere.
  255. if (ModulesEndOffset == 0)
  256. Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
  257. else
  258. Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
  259. Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
  260. return Info.Prune;
  261. }
  262. static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
  263. CompileUnit::DIEInfo &ChildInfo) {
  264. CompileUnit::DIEInfo &Info = CU.getInfo(Die);
  265. Info.Prune &= ChildInfo.Prune;
  266. }
  267. /// Recursive helper to build the global DeclContext information and
  268. /// gather the child->parent relationships in the original compile unit.
  269. ///
  270. /// This function uses the same work list approach as lookForDIEsToKeep.
  271. ///
  272. /// \return true when this DIE and all of its children are only
  273. /// forward declarations to types defined in external clang modules
  274. /// (i.e., forward declarations that are children of a DW_TAG_module).
  275. static bool analyzeContextInfo(
  276. const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
  277. DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
  278. uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
  279. std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
  280. bool InImportedModule = false) {
  281. // LIFO work list.
  282. std::vector<ContextWorklistItem> Worklist;
  283. Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
  284. while (!Worklist.empty()) {
  285. ContextWorklistItem Current = Worklist.back();
  286. Worklist.pop_back();
  287. switch (Current.Type) {
  288. case ContextWorklistItemType::UpdatePruning:
  289. updatePruning(Current.Die, CU, ModulesEndOffset);
  290. continue;
  291. case ContextWorklistItemType::UpdateChildPruning:
  292. updateChildPruning(Current.Die, CU, *Current.OtherInfo);
  293. continue;
  294. case ContextWorklistItemType::AnalyzeContextInfo:
  295. break;
  296. }
  297. unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
  298. CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
  299. // Clang imposes an ODR on modules(!) regardless of the language:
  300. // "The module-id should consist of only a single identifier,
  301. // which provides the name of the module being defined. Each
  302. // module shall have a single definition."
  303. //
  304. // This does not extend to the types inside the modules:
  305. // "[I]n C, this implies that if two structs are defined in
  306. // different submodules with the same name, those two types are
  307. // distinct types (but may be compatible types if their
  308. // definitions match)."
  309. //
  310. // We treat non-C++ modules like namespaces for this reason.
  311. if (Current.Die.getTag() == dwarf::DW_TAG_module &&
  312. Current.ParentIdx == 0 &&
  313. dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
  314. CU.getClangModuleName()) {
  315. Current.InImportedModule = true;
  316. analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
  317. ReportWarning);
  318. }
  319. Info.ParentIdx = Current.ParentIdx;
  320. bool InClangModule = CU.isClangModule() || Current.InImportedModule;
  321. if (CU.hasODR() || InClangModule) {
  322. if (Current.Context) {
  323. auto PtrInvalidPair = Contexts.getChildDeclContext(
  324. *Current.Context, Current.Die, CU, InClangModule);
  325. Current.Context = PtrInvalidPair.getPointer();
  326. Info.Ctxt =
  327. PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
  328. if (Info.Ctxt)
  329. Info.Ctxt->setDefinedInClangModule(InClangModule);
  330. } else
  331. Info.Ctxt = Current.Context = nullptr;
  332. }
  333. Info.Prune = Current.InImportedModule;
  334. // Add children in reverse order to the worklist to effectively process
  335. // them in order.
  336. Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
  337. for (auto Child : reverse(Current.Die.children())) {
  338. CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
  339. Worklist.emplace_back(
  340. Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
  341. Worklist.emplace_back(Child, Current.Context, Idx,
  342. Current.InImportedModule);
  343. }
  344. }
  345. return CU.getInfo(DIE).Prune;
  346. }
  347. static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
  348. switch (Tag) {
  349. default:
  350. return false;
  351. case dwarf::DW_TAG_class_type:
  352. case dwarf::DW_TAG_common_block:
  353. case dwarf::DW_TAG_lexical_block:
  354. case dwarf::DW_TAG_structure_type:
  355. case dwarf::DW_TAG_subprogram:
  356. case dwarf::DW_TAG_subroutine_type:
  357. case dwarf::DW_TAG_union_type:
  358. return true;
  359. }
  360. llvm_unreachable("Invalid Tag");
  361. }
  362. void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
  363. Context.clear();
  364. for (DIEBlock *I : DIEBlocks)
  365. I->~DIEBlock();
  366. for (DIELoc *I : DIELocs)
  367. I->~DIELoc();
  368. DIEBlocks.clear();
  369. DIELocs.clear();
  370. DIEAlloc.Reset();
  371. }
  372. /// Check if a variable describing DIE should be kept.
  373. /// \returns updated TraversalFlags.
  374. unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
  375. const DWARFDie &DIE,
  376. CompileUnit::DIEInfo &MyInfo,
  377. unsigned Flags) {
  378. const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
  379. // Global variables with constant value can always be kept.
  380. if (!(Flags & TF_InFunctionScope) &&
  381. Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
  382. MyInfo.InDebugMap = true;
  383. return Flags | TF_Keep;
  384. }
  385. // See if there is a relocation to a valid debug map entry inside this
  386. // variable's location. The order is important here. We want to always check
  387. // if the variable has a valid relocation, so that the DIEInfo is filled.
  388. // However, we don't want a static variable in a function to force us to keep
  389. // the enclosing function, unless requested explicitly.
  390. const bool HasLiveMemoryLocation =
  391. RelocMgr.hasLiveMemoryLocation(DIE, MyInfo);
  392. if (!HasLiveMemoryLocation || ((Flags & TF_InFunctionScope) &&
  393. !LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
  394. return Flags;
  395. if (Options.Verbose) {
  396. outs() << "Keeping variable DIE:";
  397. DIDumpOptions DumpOpts;
  398. DumpOpts.ChildRecurseDepth = 0;
  399. DumpOpts.Verbose = Options.Verbose;
  400. DIE.dump(outs(), 8 /* Indent */, DumpOpts);
  401. }
  402. return Flags | TF_Keep;
  403. }
  404. /// Check if a function describing DIE should be kept.
  405. /// \returns updated TraversalFlags.
  406. unsigned DWARFLinker::shouldKeepSubprogramDIE(
  407. AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
  408. const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
  409. unsigned Flags) {
  410. Flags |= TF_InFunctionScope;
  411. auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
  412. if (!LowPc)
  413. return Flags;
  414. assert(LowPc.hasValue() && "low_pc attribute is not an address.");
  415. if (!RelocMgr.hasLiveAddressRange(DIE, MyInfo))
  416. return Flags;
  417. if (Options.Verbose) {
  418. outs() << "Keeping subprogram DIE:";
  419. DIDumpOptions DumpOpts;
  420. DumpOpts.ChildRecurseDepth = 0;
  421. DumpOpts.Verbose = Options.Verbose;
  422. DIE.dump(outs(), 8 /* Indent */, DumpOpts);
  423. }
  424. if (DIE.getTag() == dwarf::DW_TAG_label) {
  425. if (Unit.hasLabelAt(*LowPc))
  426. return Flags;
  427. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  428. // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
  429. // that don't fall into the CU's aranges. This is wrong IMO. Debug info
  430. // generation bugs aside, this is really wrong in the case of labels, where
  431. // a label marking the end of a function will have a PC == CU's high_pc.
  432. if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
  433. .getValueOr(UINT64_MAX) <= LowPc)
  434. return Flags;
  435. Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
  436. return Flags | TF_Keep;
  437. }
  438. Flags |= TF_Keep;
  439. Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
  440. if (!HighPc) {
  441. reportWarning("Function without high_pc. Range will be discarded.\n", File,
  442. &DIE);
  443. return Flags;
  444. }
  445. // Replace the debug map range with a more accurate one.
  446. Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
  447. Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
  448. return Flags;
  449. }
  450. /// Check if a DIE should be kept.
  451. /// \returns updated TraversalFlags.
  452. unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
  453. const DWARFDie &DIE, const DWARFFile &File,
  454. CompileUnit &Unit,
  455. CompileUnit::DIEInfo &MyInfo,
  456. unsigned Flags) {
  457. switch (DIE.getTag()) {
  458. case dwarf::DW_TAG_constant:
  459. case dwarf::DW_TAG_variable:
  460. return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
  461. case dwarf::DW_TAG_subprogram:
  462. case dwarf::DW_TAG_label:
  463. return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
  464. Flags);
  465. case dwarf::DW_TAG_base_type:
  466. // DWARF Expressions may reference basic types, but scanning them
  467. // is expensive. Basic types are tiny, so just keep all of them.
  468. case dwarf::DW_TAG_imported_module:
  469. case dwarf::DW_TAG_imported_declaration:
  470. case dwarf::DW_TAG_imported_unit:
  471. // We always want to keep these.
  472. return Flags | TF_Keep;
  473. default:
  474. break;
  475. }
  476. return Flags;
  477. }
  478. /// Helper that updates the completeness of the current DIE based on the
  479. /// completeness of one of its children. It depends on the incompleteness of
  480. /// the children already being computed.
  481. static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
  482. CompileUnit::DIEInfo &ChildInfo) {
  483. switch (Die.getTag()) {
  484. case dwarf::DW_TAG_structure_type:
  485. case dwarf::DW_TAG_class_type:
  486. case dwarf::DW_TAG_union_type:
  487. break;
  488. default:
  489. return;
  490. }
  491. CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
  492. if (ChildInfo.Incomplete || ChildInfo.Prune)
  493. MyInfo.Incomplete = true;
  494. }
  495. /// Helper that updates the completeness of the current DIE based on the
  496. /// completeness of the DIEs it references. It depends on the incompleteness of
  497. /// the referenced DIE already being computed.
  498. static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
  499. CompileUnit::DIEInfo &RefInfo) {
  500. switch (Die.getTag()) {
  501. case dwarf::DW_TAG_typedef:
  502. case dwarf::DW_TAG_member:
  503. case dwarf::DW_TAG_reference_type:
  504. case dwarf::DW_TAG_ptr_to_member_type:
  505. case dwarf::DW_TAG_pointer_type:
  506. break;
  507. default:
  508. return;
  509. }
  510. CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
  511. if (MyInfo.Incomplete)
  512. return;
  513. if (RefInfo.Incomplete)
  514. MyInfo.Incomplete = true;
  515. }
  516. /// Look at the children of the given DIE and decide whether they should be
  517. /// kept.
  518. void DWARFLinker::lookForChildDIEsToKeep(
  519. const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
  520. SmallVectorImpl<WorklistItem> &Worklist) {
  521. // The TF_ParentWalk flag tells us that we are currently walking up the
  522. // parent chain of a required DIE, and we don't want to mark all the children
  523. // of the parents as kept (consider for example a DW_TAG_namespace node in
  524. // the parent chain). There are however a set of DIE types for which we want
  525. // to ignore that directive and still walk their children.
  526. if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
  527. Flags &= ~DWARFLinker::TF_ParentWalk;
  528. // We're finished if this DIE has no children or we're walking the parent
  529. // chain.
  530. if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
  531. return;
  532. // Add children in reverse order to the worklist to effectively process them
  533. // in order.
  534. for (auto Child : reverse(Die.children())) {
  535. // Add a worklist item before every child to calculate incompleteness right
  536. // after the current child is processed.
  537. CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
  538. Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
  539. &ChildInfo);
  540. Worklist.emplace_back(Child, CU, Flags);
  541. }
  542. }
  543. /// Look at DIEs referenced by the given DIE and decide whether they should be
  544. /// kept. All DIEs referenced though attributes should be kept.
  545. void DWARFLinker::lookForRefDIEsToKeep(
  546. const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
  547. const UnitListTy &Units, const DWARFFile &File,
  548. SmallVectorImpl<WorklistItem> &Worklist) {
  549. bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
  550. ? (Flags & DWARFLinker::TF_ODR)
  551. : CU.hasODR();
  552. DWARFUnit &Unit = CU.getOrigUnit();
  553. DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
  554. const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
  555. uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
  556. SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
  557. for (const auto &AttrSpec : Abbrev->attributes()) {
  558. DWARFFormValue Val(AttrSpec.Form);
  559. if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
  560. AttrSpec.Attr == dwarf::DW_AT_sibling) {
  561. DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
  562. Unit.getFormParams());
  563. continue;
  564. }
  565. Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
  566. CompileUnit *ReferencedCU;
  567. if (auto RefDie =
  568. resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
  569. CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
  570. bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
  571. Info.Ctxt->isDefinedInClangModule();
  572. // If the referenced DIE has a DeclContext that has already been
  573. // emitted, then do not keep the one in this CU. We'll link to
  574. // the canonical DIE in cloneDieReferenceAttribute.
  575. //
  576. // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
  577. // be necessary and could be advantageously replaced by
  578. // ReferencedCU->hasODR() && CU.hasODR().
  579. //
  580. // FIXME: compatibility with dsymutil-classic. There is no
  581. // reason not to unique ref_addr references.
  582. if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) &&
  583. Info.Ctxt &&
  584. Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
  585. Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
  586. continue;
  587. // Keep a module forward declaration if there is no definition.
  588. if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
  589. Info.Ctxt->getCanonicalDIEOffset()))
  590. Info.Prune = false;
  591. ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
  592. }
  593. }
  594. unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
  595. // Add referenced DIEs in reverse order to the worklist to effectively
  596. // process them in order.
  597. for (auto &P : reverse(ReferencedDIEs)) {
  598. // Add a worklist item before every child to calculate incompleteness right
  599. // after the current child is processed.
  600. CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
  601. Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
  602. &Info);
  603. Worklist.emplace_back(P.first, P.second,
  604. DWARFLinker::TF_Keep |
  605. DWARFLinker::TF_DependencyWalk | ODRFlag);
  606. }
  607. }
  608. /// Look at the parent of the given DIE and decide whether they should be kept.
  609. void DWARFLinker::lookForParentDIEsToKeep(
  610. unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
  611. SmallVectorImpl<WorklistItem> &Worklist) {
  612. // Stop if we encounter an ancestor that's already marked as kept.
  613. if (CU.getInfo(AncestorIdx).Keep)
  614. return;
  615. DWARFUnit &Unit = CU.getOrigUnit();
  616. DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
  617. Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
  618. Worklist.emplace_back(ParentDIE, CU, Flags);
  619. }
  620. /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
  621. /// information in \p CU's DIEInfo.
  622. ///
  623. /// This function is the entry point of the DIE selection algorithm. It is
  624. /// expected to walk the DIE tree in file order and (though the mediation of
  625. /// its helper) call hasValidRelocation() on each DIE that might be a 'root
  626. /// DIE' (See DwarfLinker class comment).
  627. ///
  628. /// While walking the dependencies of root DIEs, this function is also called,
  629. /// but during these dependency walks the file order is not respected. The
  630. /// TF_DependencyWalk flag tells us which kind of traversal we are currently
  631. /// doing.
  632. ///
  633. /// The recursive algorithm is implemented iteratively as a work list because
  634. /// very deep recursion could exhaust the stack for large projects. The work
  635. /// list acts as a scheduler for different types of work that need to be
  636. /// performed.
  637. ///
  638. /// The recursive nature of the algorithm is simulated by running the "main"
  639. /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
  640. /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
  641. /// fixing up a computed property (UpdateChildIncompleteness,
  642. /// UpdateRefIncompleteness).
  643. ///
  644. /// The return value indicates whether the DIE is incomplete.
  645. void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
  646. RangesTy &Ranges, const UnitListTy &Units,
  647. const DWARFDie &Die, const DWARFFile &File,
  648. CompileUnit &Cu, unsigned Flags) {
  649. // LIFO work list.
  650. SmallVector<WorklistItem, 4> Worklist;
  651. Worklist.emplace_back(Die, Cu, Flags);
  652. while (!Worklist.empty()) {
  653. WorklistItem Current = Worklist.pop_back_val();
  654. // Look at the worklist type to decide what kind of work to perform.
  655. switch (Current.Type) {
  656. case WorklistItemType::UpdateChildIncompleteness:
  657. updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
  658. continue;
  659. case WorklistItemType::UpdateRefIncompleteness:
  660. updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
  661. continue;
  662. case WorklistItemType::LookForChildDIEsToKeep:
  663. lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
  664. continue;
  665. case WorklistItemType::LookForRefDIEsToKeep:
  666. lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
  667. Worklist);
  668. continue;
  669. case WorklistItemType::LookForParentDIEsToKeep:
  670. lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
  671. Worklist);
  672. continue;
  673. case WorklistItemType::LookForDIEsToKeep:
  674. break;
  675. }
  676. unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
  677. CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
  678. if (MyInfo.Prune)
  679. continue;
  680. // If the Keep flag is set, we are marking a required DIE's dependencies.
  681. // If our target is already marked as kept, we're all set.
  682. bool AlreadyKept = MyInfo.Keep;
  683. if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
  684. continue;
  685. // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
  686. // because it would screw up the relocation finding logic.
  687. if (!(Current.Flags & TF_DependencyWalk))
  688. Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
  689. Current.CU, MyInfo, Current.Flags);
  690. // Finish by looking for child DIEs. Because of the LIFO worklist we need
  691. // to schedule that work before any subsequent items are added to the
  692. // worklist.
  693. Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
  694. WorklistItemType::LookForChildDIEsToKeep);
  695. if (AlreadyKept || !(Current.Flags & TF_Keep))
  696. continue;
  697. // If it is a newly kept DIE mark it as well as all its dependencies as
  698. // kept.
  699. MyInfo.Keep = true;
  700. // We're looking for incomplete types.
  701. MyInfo.Incomplete =
  702. Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
  703. Current.Die.getTag() != dwarf::DW_TAG_member &&
  704. dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
  705. // After looking at the parent chain, look for referenced DIEs. Because of
  706. // the LIFO worklist we need to schedule that work before any subsequent
  707. // items are added to the worklist.
  708. Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
  709. WorklistItemType::LookForRefDIEsToKeep);
  710. bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
  711. : Current.CU.hasODR();
  712. unsigned ODRFlag = UseOdr ? TF_ODR : 0;
  713. unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
  714. // Now schedule the parent walk.
  715. Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
  716. }
  717. }
  718. /// Assign an abbreviation number to \p Abbrev.
  719. ///
  720. /// Our DIEs get freed after every DebugMapObject has been processed,
  721. /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
  722. /// the instances hold by the DIEs. When we encounter an abbreviation
  723. /// that we don't know, we create a permanent copy of it.
  724. void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
  725. // Check the set for priors.
  726. FoldingSetNodeID ID;
  727. Abbrev.Profile(ID);
  728. void *InsertToken;
  729. DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
  730. // If it's newly added.
  731. if (InSet) {
  732. // Assign existing abbreviation number.
  733. Abbrev.setNumber(InSet->getNumber());
  734. } else {
  735. // Add to abbreviation list.
  736. Abbreviations.push_back(
  737. std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
  738. for (const auto &Attr : Abbrev.getData())
  739. Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
  740. AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
  741. // Assign the unique abbreviation number.
  742. Abbrev.setNumber(Abbreviations.size());
  743. Abbreviations.back()->setNumber(Abbreviations.size());
  744. }
  745. }
  746. unsigned DWARFLinker::DIECloner::cloneStringAttribute(
  747. DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
  748. const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
  749. Optional<const char *> String = dwarf::toString(Val);
  750. if (!String)
  751. return 0;
  752. // Switch everything to out of line strings.
  753. auto StringEntry = StringPool.getEntry(*String);
  754. // Update attributes info.
  755. if (AttrSpec.Attr == dwarf::DW_AT_name)
  756. Info.Name = StringEntry;
  757. else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
  758. AttrSpec.Attr == dwarf::DW_AT_linkage_name)
  759. Info.MangledName = StringEntry;
  760. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
  761. DIEInteger(StringEntry.getOffset()));
  762. return 4;
  763. }
  764. unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
  765. DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
  766. unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
  767. CompileUnit &Unit) {
  768. const DWARFUnit &U = Unit.getOrigUnit();
  769. uint64_t Ref = *Val.getAsReference();
  770. DIE *NewRefDie = nullptr;
  771. CompileUnit *RefUnit = nullptr;
  772. DeclContext *Ctxt = nullptr;
  773. DWARFDie RefDie =
  774. Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
  775. // If the referenced DIE is not found, drop the attribute.
  776. if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
  777. return 0;
  778. CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
  779. // If we already have emitted an equivalent DeclContext, just point
  780. // at it.
  781. if (isODRAttribute(AttrSpec.Attr)) {
  782. Ctxt = RefInfo.Ctxt;
  783. if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
  784. DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
  785. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  786. dwarf::DW_FORM_ref_addr, Attr);
  787. return U.getRefAddrByteSize();
  788. }
  789. }
  790. if (!RefInfo.Clone) {
  791. assert(Ref > InputDIE.getOffset());
  792. // We haven't cloned this DIE yet. Just create an empty one and
  793. // store it. It'll get really cloned when we process it.
  794. RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
  795. }
  796. NewRefDie = RefInfo.Clone;
  797. if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
  798. (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
  799. // We cannot currently rely on a DIEEntry to emit ref_addr
  800. // references, because the implementation calls back to DwarfDebug
  801. // to find the unit offset. (We don't have a DwarfDebug)
  802. // FIXME: we should be able to design DIEEntry reliance on
  803. // DwarfDebug away.
  804. uint64_t Attr;
  805. if (Ref < InputDIE.getOffset()) {
  806. // We must have already cloned that DIE.
  807. uint32_t NewRefOffset =
  808. RefUnit->getStartOffset() + NewRefDie->getOffset();
  809. Attr = NewRefOffset;
  810. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  811. dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
  812. } else {
  813. // A forward reference. Note and fixup later.
  814. Attr = 0xBADDEF;
  815. Unit.noteForwardReference(
  816. NewRefDie, RefUnit, Ctxt,
  817. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  818. dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
  819. }
  820. return U.getRefAddrByteSize();
  821. }
  822. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  823. dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
  824. return AttrSize;
  825. }
  826. void DWARFLinker::DIECloner::cloneExpression(
  827. DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
  828. CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
  829. using Encoding = DWARFExpression::Operation::Encoding;
  830. uint64_t OpOffset = 0;
  831. for (auto &Op : Expression) {
  832. auto Description = Op.getDescription();
  833. // DW_OP_const_type is variable-length and has 3
  834. // operands. DWARFExpression thus far only supports 2.
  835. auto Op0 = Description.Op[0];
  836. auto Op1 = Description.Op[1];
  837. if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
  838. (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
  839. Linker.reportWarning("Unsupported DW_OP encoding.", File);
  840. if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
  841. (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
  842. // This code assumes that the other non-typeref operand fits into 1 byte.
  843. assert(OpOffset < Op.getEndOffset());
  844. uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
  845. assert(ULEBsize <= 16);
  846. // Copy over the operation.
  847. OutputBuffer.push_back(Op.getCode());
  848. uint64_t RefOffset;
  849. if (Op1 == Encoding::SizeNA) {
  850. RefOffset = Op.getRawOperand(0);
  851. } else {
  852. OutputBuffer.push_back(Op.getRawOperand(0));
  853. RefOffset = Op.getRawOperand(1);
  854. }
  855. uint32_t Offset = 0;
  856. // Look up the base type. For DW_OP_convert, the operand may be 0 to
  857. // instead indicate the generic type. The same holds for
  858. // DW_OP_reinterpret, which is currently not supported.
  859. if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
  860. auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
  861. CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
  862. if (DIE *Clone = Info.Clone)
  863. Offset = Clone->getOffset();
  864. else
  865. Linker.reportWarning(
  866. "base type ref doesn't point to DW_TAG_base_type.", File);
  867. }
  868. uint8_t ULEB[16];
  869. unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
  870. if (RealSize > ULEBsize) {
  871. // Emit the generic type as a fallback.
  872. RealSize = encodeULEB128(0, ULEB, ULEBsize);
  873. Linker.reportWarning("base type ref doesn't fit.", File);
  874. }
  875. assert(RealSize == ULEBsize && "padding failed");
  876. ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
  877. OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
  878. } else {
  879. // Copy over everything else unmodified.
  880. StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
  881. OutputBuffer.append(Bytes.begin(), Bytes.end());
  882. }
  883. OpOffset = Op.getEndOffset();
  884. }
  885. }
  886. unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
  887. DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
  888. const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
  889. DIEValueList *Attr;
  890. DIEValue Value;
  891. DIELoc *Loc = nullptr;
  892. DIEBlock *Block = nullptr;
  893. if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
  894. Loc = new (DIEAlloc) DIELoc;
  895. Linker.DIELocs.push_back(Loc);
  896. } else {
  897. Block = new (DIEAlloc) DIEBlock;
  898. Linker.DIEBlocks.push_back(Block);
  899. }
  900. Attr = Loc ? static_cast<DIEValueList *>(Loc)
  901. : static_cast<DIEValueList *>(Block);
  902. if (Loc)
  903. Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
  904. dwarf::Form(AttrSpec.Form), Loc);
  905. else
  906. Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
  907. dwarf::Form(AttrSpec.Form), Block);
  908. // If the block is a DWARF Expression, clone it into the temporary
  909. // buffer using cloneExpression(), otherwise copy the data directly.
  910. SmallVector<uint8_t, 32> Buffer;
  911. ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
  912. if (DWARFAttribute::mayHaveLocationExpr(AttrSpec.Attr) &&
  913. (Val.isFormClass(DWARFFormValue::FC_Block) ||
  914. Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
  915. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  916. DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
  917. IsLittleEndian, OrigUnit.getAddressByteSize());
  918. DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
  919. OrigUnit.getFormParams().Format);
  920. cloneExpression(Data, Expr, File, Unit, Buffer);
  921. Bytes = Buffer;
  922. }
  923. for (auto Byte : Bytes)
  924. Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
  925. dwarf::DW_FORM_data1, DIEInteger(Byte));
  926. // FIXME: If DIEBlock and DIELoc just reuses the Size field of
  927. // the DIE class, this "if" could be replaced by
  928. // Attr->setSize(Bytes.size()).
  929. if (Loc)
  930. Loc->setSize(Bytes.size());
  931. else
  932. Block->setSize(Bytes.size());
  933. Die.addValue(DIEAlloc, Value);
  934. return AttrSize;
  935. }
  936. unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
  937. DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
  938. const CompileUnit &Unit, AttributesInfo &Info) {
  939. if (LLVM_UNLIKELY(Linker.Options.Update)) {
  940. if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
  941. Info.HasLowPc = true;
  942. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  943. dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
  944. return Unit.getOrigUnit().getAddressByteSize();
  945. }
  946. dwarf::Form Form = AttrSpec.Form;
  947. uint64_t Addr = 0;
  948. if (Form == dwarf::DW_FORM_addrx) {
  949. if (Optional<uint64_t> AddrOffsetSectionBase =
  950. Unit.getOrigUnit().getAddrOffsetSectionBase()) {
  951. uint64_t StartOffset = *AddrOffsetSectionBase + Val.getRawUValue();
  952. uint64_t EndOffset =
  953. StartOffset + Unit.getOrigUnit().getAddressByteSize();
  954. if (llvm::Expected<uint64_t> RelocAddr =
  955. ObjFile.Addresses->relocateIndexedAddr(StartOffset, EndOffset))
  956. Addr = *RelocAddr;
  957. else
  958. Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile);
  959. } else
  960. Linker.reportWarning("no base offset for address table", ObjFile);
  961. // If this is an indexed address emit the debug_info address.
  962. Form = dwarf::DW_FORM_addr;
  963. } else
  964. Addr = *Val.getAsAddress();
  965. if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
  966. if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
  967. Die.getTag() == dwarf::DW_TAG_lexical_block ||
  968. Die.getTag() == dwarf::DW_TAG_label) {
  969. // The low_pc of a block or inline subroutine might get
  970. // relocated because it happens to match the low_pc of the
  971. // enclosing subprogram. To prevent issues with that, always use
  972. // the low_pc from the input DIE if relocations have been applied.
  973. Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
  974. ? Info.OrigLowPc
  975. : Addr) +
  976. Info.PCOffset;
  977. } else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
  978. Addr = Unit.getLowPc();
  979. if (Addr == std::numeric_limits<uint64_t>::max())
  980. return 0;
  981. }
  982. Info.HasLowPc = true;
  983. } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
  984. if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
  985. if (uint64_t HighPc = Unit.getHighPc())
  986. Addr = HighPc;
  987. else
  988. return 0;
  989. } else
  990. // If we have a high_pc recorded for the input DIE, use
  991. // it. Otherwise (when no relocations where applied) just use the
  992. // one we just decoded.
  993. Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
  994. } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
  995. // Relocate a return PC address within a call site entry.
  996. if (Die.getTag() == dwarf::DW_TAG_call_site)
  997. Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
  998. Info.PCOffset;
  999. } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) {
  1000. // Relocate the address of a branch instruction within a call site entry.
  1001. if (Die.getTag() == dwarf::DW_TAG_call_site)
  1002. Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset;
  1003. }
  1004. Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
  1005. static_cast<dwarf::Form>(Form), DIEInteger(Addr));
  1006. return Unit.getOrigUnit().getAddressByteSize();
  1007. }
  1008. unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
  1009. DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
  1010. CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
  1011. unsigned AttrSize, AttributesInfo &Info) {
  1012. uint64_t Value;
  1013. if (LLVM_UNLIKELY(Linker.Options.Update)) {
  1014. if (auto OptionalValue = Val.getAsUnsignedConstant())
  1015. Value = *OptionalValue;
  1016. else if (auto OptionalValue = Val.getAsSignedConstant())
  1017. Value = *OptionalValue;
  1018. else if (auto OptionalValue = Val.getAsSectionOffset())
  1019. Value = *OptionalValue;
  1020. else {
  1021. Linker.reportWarning(
  1022. "Unsupported scalar attribute form. Dropping attribute.", File,
  1023. &InputDIE);
  1024. return 0;
  1025. }
  1026. if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
  1027. Info.IsDeclaration = true;
  1028. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  1029. dwarf::Form(AttrSpec.Form), DIEInteger(Value));
  1030. return AttrSize;
  1031. }
  1032. if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
  1033. Die.getTag() == dwarf::DW_TAG_compile_unit) {
  1034. if (Unit.getLowPc() == -1ULL)
  1035. return 0;
  1036. // Dwarf >= 4 high_pc is an size, not an address.
  1037. Value = Unit.getHighPc() - Unit.getLowPc();
  1038. } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
  1039. Value = *Val.getAsSectionOffset();
  1040. else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
  1041. Value = *Val.getAsSignedConstant();
  1042. else if (auto OptionalValue = Val.getAsUnsignedConstant())
  1043. Value = *OptionalValue;
  1044. else {
  1045. Linker.reportWarning(
  1046. "Unsupported scalar attribute form. Dropping attribute.", File,
  1047. &InputDIE);
  1048. return 0;
  1049. }
  1050. PatchLocation Patch =
  1051. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  1052. dwarf::Form(AttrSpec.Form), DIEInteger(Value));
  1053. if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
  1054. Unit.noteRangeAttribute(Die, Patch);
  1055. Info.HasRanges = true;
  1056. }
  1057. // A more generic way to check for location attributes would be
  1058. // nice, but it's very unlikely that any other attribute needs a
  1059. // location list.
  1060. // FIXME: use DWARFAttribute::mayHaveLocationDescription().
  1061. else if (AttrSpec.Attr == dwarf::DW_AT_location ||
  1062. AttrSpec.Attr == dwarf::DW_AT_frame_base) {
  1063. Unit.noteLocationAttribute(Patch, Info.PCOffset);
  1064. } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
  1065. Info.IsDeclaration = true;
  1066. return AttrSize;
  1067. }
  1068. /// Clone \p InputDIE's attribute described by \p AttrSpec with
  1069. /// value \p Val, and add it to \p Die.
  1070. /// \returns the size of the cloned attribute.
  1071. unsigned DWARFLinker::DIECloner::cloneAttribute(
  1072. DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
  1073. CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
  1074. const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
  1075. bool IsLittleEndian) {
  1076. const DWARFUnit &U = Unit.getOrigUnit();
  1077. switch (AttrSpec.Form) {
  1078. case dwarf::DW_FORM_strp:
  1079. case dwarf::DW_FORM_string:
  1080. case dwarf::DW_FORM_strx:
  1081. case dwarf::DW_FORM_strx1:
  1082. case dwarf::DW_FORM_strx2:
  1083. case dwarf::DW_FORM_strx3:
  1084. case dwarf::DW_FORM_strx4:
  1085. return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
  1086. case dwarf::DW_FORM_ref_addr:
  1087. case dwarf::DW_FORM_ref1:
  1088. case dwarf::DW_FORM_ref2:
  1089. case dwarf::DW_FORM_ref4:
  1090. case dwarf::DW_FORM_ref8:
  1091. return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
  1092. File, Unit);
  1093. case dwarf::DW_FORM_block:
  1094. case dwarf::DW_FORM_block1:
  1095. case dwarf::DW_FORM_block2:
  1096. case dwarf::DW_FORM_block4:
  1097. case dwarf::DW_FORM_exprloc:
  1098. return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
  1099. IsLittleEndian);
  1100. case dwarf::DW_FORM_addr:
  1101. case dwarf::DW_FORM_addrx:
  1102. return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
  1103. case dwarf::DW_FORM_data1:
  1104. case dwarf::DW_FORM_data2:
  1105. case dwarf::DW_FORM_data4:
  1106. case dwarf::DW_FORM_data8:
  1107. case dwarf::DW_FORM_udata:
  1108. case dwarf::DW_FORM_sdata:
  1109. case dwarf::DW_FORM_sec_offset:
  1110. case dwarf::DW_FORM_flag:
  1111. case dwarf::DW_FORM_flag_present:
  1112. return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
  1113. AttrSize, Info);
  1114. default:
  1115. Linker.reportWarning("Unsupported attribute form " +
  1116. dwarf::FormEncodingString(AttrSpec.Form) +
  1117. " in cloneAttribute. Dropping.",
  1118. File, &InputDIE);
  1119. }
  1120. return 0;
  1121. }
  1122. static bool isObjCSelector(StringRef Name) {
  1123. return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
  1124. (Name[1] == '[');
  1125. }
  1126. void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
  1127. const DIE *Die,
  1128. DwarfStringPoolEntryRef Name,
  1129. OffsetsStringPool &StringPool,
  1130. bool SkipPubSection) {
  1131. assert(isObjCSelector(Name.getString()) && "not an objc selector");
  1132. // Objective C method or class function.
  1133. // "- [Class(Category) selector :withArg ...]"
  1134. StringRef ClassNameStart(Name.getString().drop_front(2));
  1135. size_t FirstSpace = ClassNameStart.find(' ');
  1136. if (FirstSpace == StringRef::npos)
  1137. return;
  1138. StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
  1139. if (!SelectorStart.size())
  1140. return;
  1141. StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
  1142. Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
  1143. // Add an entry for the class name that points to this
  1144. // method/class function.
  1145. StringRef ClassName(ClassNameStart.data(), FirstSpace);
  1146. Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
  1147. if (ClassName[ClassName.size() - 1] == ')') {
  1148. size_t OpenParens = ClassName.find('(');
  1149. if (OpenParens != StringRef::npos) {
  1150. StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
  1151. Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
  1152. SkipPubSection);
  1153. std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
  1154. // FIXME: The missing space here may be a bug, but
  1155. // dsymutil-classic also does it this way.
  1156. MethodNameNoCategory.append(std::string(SelectorStart));
  1157. Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
  1158. SkipPubSection);
  1159. }
  1160. }
  1161. }
  1162. static bool
  1163. shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
  1164. uint16_t Tag, bool InDebugMap, bool SkipPC,
  1165. bool InFunctionScope) {
  1166. switch (AttrSpec.Attr) {
  1167. default:
  1168. return false;
  1169. case dwarf::DW_AT_low_pc:
  1170. case dwarf::DW_AT_high_pc:
  1171. case dwarf::DW_AT_ranges:
  1172. return SkipPC;
  1173. case dwarf::DW_AT_str_offsets_base:
  1174. // FIXME: Use the string offset table with Dwarf 5.
  1175. return true;
  1176. case dwarf::DW_AT_location:
  1177. case dwarf::DW_AT_frame_base:
  1178. // FIXME: for some reason dsymutil-classic keeps the location attributes
  1179. // when they are of block type (i.e. not location lists). This is totally
  1180. // wrong for globals where we will keep a wrong address. It is mostly
  1181. // harmless for locals, but there is no point in keeping these anyway when
  1182. // the function wasn't linked.
  1183. return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
  1184. !InDebugMap)) &&
  1185. !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
  1186. }
  1187. }
  1188. DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
  1189. const DWARFFile &File, CompileUnit &Unit,
  1190. OffsetsStringPool &StringPool,
  1191. int64_t PCOffset, uint32_t OutOffset,
  1192. unsigned Flags, bool IsLittleEndian,
  1193. DIE *Die) {
  1194. DWARFUnit &U = Unit.getOrigUnit();
  1195. unsigned Idx = U.getDIEIndex(InputDIE);
  1196. CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
  1197. // Should the DIE appear in the output?
  1198. if (!Unit.getInfo(Idx).Keep)
  1199. return nullptr;
  1200. uint64_t Offset = InputDIE.getOffset();
  1201. assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
  1202. if (!Die) {
  1203. // The DIE might have been already created by a forward reference
  1204. // (see cloneDieReferenceAttribute()).
  1205. if (!Info.Clone)
  1206. Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
  1207. Die = Info.Clone;
  1208. }
  1209. assert(Die->getTag() == InputDIE.getTag());
  1210. Die->setOffset(OutOffset);
  1211. if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
  1212. Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
  1213. Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
  1214. !Info.Ctxt->getCanonicalDIEOffset()) {
  1215. // We are about to emit a DIE that is the root of its own valid
  1216. // DeclContext tree. Make the current offset the canonical offset
  1217. // for this context.
  1218. Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
  1219. }
  1220. // Extract and clone every attribute.
  1221. DWARFDataExtractor Data = U.getDebugInfoExtractor();
  1222. // Point to the next DIE (generally there is always at least a NULL
  1223. // entry after the current one). If this is a lone
  1224. // DW_TAG_compile_unit without any children, point to the next unit.
  1225. uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
  1226. ? U.getDIEAtIndex(Idx + 1).getOffset()
  1227. : U.getNextUnitOffset();
  1228. AttributesInfo AttrInfo;
  1229. // We could copy the data only if we need to apply a relocation to it. After
  1230. // testing, it seems there is no performance downside to doing the copy
  1231. // unconditionally, and it makes the code simpler.
  1232. SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
  1233. Data =
  1234. DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
  1235. // Modify the copy with relocated addresses.
  1236. if (ObjFile.Addresses->areRelocationsResolved() &&
  1237. ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
  1238. Data.isLittleEndian())) {
  1239. // If we applied relocations, we store the value of high_pc that was
  1240. // potentially stored in the input DIE. If high_pc is an address
  1241. // (Dwarf version == 2), then it might have been relocated to a
  1242. // totally unrelated value (because the end address in the object
  1243. // file might be start address of another function which got moved
  1244. // independently by the linker). The computation of the actual
  1245. // high_pc value is done in cloneAddressAttribute().
  1246. AttrInfo.OrigHighPc =
  1247. dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
  1248. // Also store the low_pc. It might get relocated in an
  1249. // inline_subprogram that happens at the beginning of its
  1250. // inlining function.
  1251. AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
  1252. std::numeric_limits<uint64_t>::max());
  1253. AttrInfo.OrigCallReturnPc =
  1254. dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
  1255. AttrInfo.OrigCallPc =
  1256. dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0);
  1257. }
  1258. // Reset the Offset to 0 as we will be working on the local copy of
  1259. // the data.
  1260. Offset = 0;
  1261. const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
  1262. Offset += getULEB128Size(Abbrev->getCode());
  1263. // We are entering a subprogram. Get and propagate the PCOffset.
  1264. if (Die->getTag() == dwarf::DW_TAG_subprogram)
  1265. PCOffset = Info.AddrAdjust;
  1266. AttrInfo.PCOffset = PCOffset;
  1267. if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
  1268. Flags |= TF_InFunctionScope;
  1269. if (!Info.InDebugMap && LLVM_LIKELY(!Update))
  1270. Flags |= TF_SkipPC;
  1271. } else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
  1272. // Function-local globals could be in the debug map even when the function
  1273. // is not, e.g., inlined functions.
  1274. if ((Flags & TF_InFunctionScope) && Info.InDebugMap)
  1275. Flags &= ~TF_SkipPC;
  1276. }
  1277. for (const auto &AttrSpec : Abbrev->attributes()) {
  1278. if (LLVM_LIKELY(!Update) &&
  1279. shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
  1280. Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
  1281. DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
  1282. U.getFormParams());
  1283. continue;
  1284. }
  1285. DWARFFormValue Val(AttrSpec.Form);
  1286. uint64_t AttrSize = Offset;
  1287. Val.extractValue(Data, &Offset, U.getFormParams(), &U);
  1288. AttrSize = Offset - AttrSize;
  1289. OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val,
  1290. AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
  1291. }
  1292. // Look for accelerator entries.
  1293. uint16_t Tag = InputDIE.getTag();
  1294. // FIXME: This is slightly wrong. An inline_subroutine without a
  1295. // low_pc, but with AT_ranges might be interesting to get into the
  1296. // accelerator tables too. For now stick with dsymutil's behavior.
  1297. if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
  1298. Tag != dwarf::DW_TAG_compile_unit &&
  1299. getDIENames(InputDIE, AttrInfo, StringPool,
  1300. Tag != dwarf::DW_TAG_inlined_subroutine)) {
  1301. if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
  1302. Unit.addNameAccelerator(Die, AttrInfo.MangledName,
  1303. Tag == dwarf::DW_TAG_inlined_subroutine);
  1304. if (AttrInfo.Name) {
  1305. if (AttrInfo.NameWithoutTemplate)
  1306. Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
  1307. /* SkipPubSection */ true);
  1308. Unit.addNameAccelerator(Die, AttrInfo.Name,
  1309. Tag == dwarf::DW_TAG_inlined_subroutine);
  1310. }
  1311. if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
  1312. addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
  1313. /* SkipPubSection =*/true);
  1314. } else if (Tag == dwarf::DW_TAG_namespace) {
  1315. if (!AttrInfo.Name)
  1316. AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
  1317. Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
  1318. } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
  1319. getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
  1320. AttrInfo.Name.getString()[0]) {
  1321. uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
  1322. uint64_t RuntimeLang =
  1323. dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
  1324. .getValueOr(0);
  1325. bool ObjCClassIsImplementation =
  1326. (RuntimeLang == dwarf::DW_LANG_ObjC ||
  1327. RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
  1328. dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
  1329. .getValueOr(0);
  1330. Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
  1331. Hash);
  1332. }
  1333. // Determine whether there are any children that we want to keep.
  1334. bool HasChildren = false;
  1335. for (auto Child : InputDIE.children()) {
  1336. unsigned Idx = U.getDIEIndex(Child);
  1337. if (Unit.getInfo(Idx).Keep) {
  1338. HasChildren = true;
  1339. break;
  1340. }
  1341. }
  1342. DIEAbbrev NewAbbrev = Die->generateAbbrev();
  1343. if (HasChildren)
  1344. NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
  1345. // Assign a permanent abbrev number
  1346. Linker.assignAbbrev(NewAbbrev);
  1347. Die->setAbbrevNumber(NewAbbrev.getNumber());
  1348. // Add the size of the abbreviation number to the output offset.
  1349. OutOffset += getULEB128Size(Die->getAbbrevNumber());
  1350. if (!HasChildren) {
  1351. // Update our size.
  1352. Die->setSize(OutOffset - Die->getOffset());
  1353. return Die;
  1354. }
  1355. // Recursively clone children.
  1356. for (auto Child : InputDIE.children()) {
  1357. if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset,
  1358. OutOffset, Flags, IsLittleEndian)) {
  1359. Die->addChild(Clone);
  1360. OutOffset = Clone->getOffset() + Clone->getSize();
  1361. }
  1362. }
  1363. // Account for the end of children marker.
  1364. OutOffset += sizeof(int8_t);
  1365. // Update our size.
  1366. Die->setSize(OutOffset - Die->getOffset());
  1367. return Die;
  1368. }
  1369. /// Patch the input object file relevant debug_ranges entries
  1370. /// and emit them in the output file. Update the relevant attributes
  1371. /// to point at the new entries.
  1372. void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit,
  1373. DWARFContext &OrigDwarf,
  1374. const DWARFFile &File) const {
  1375. DWARFDebugRangeList RangeList;
  1376. const auto &FunctionRanges = Unit.getFunctionRanges();
  1377. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  1378. DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
  1379. OrigDwarf.getDWARFObj().getRangesSection(),
  1380. OrigDwarf.isLittleEndian(), AddressSize);
  1381. auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
  1382. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  1383. auto OrigUnitDie = OrigUnit.getUnitDIE(false);
  1384. uint64_t OrigLowPc =
  1385. dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
  1386. // Ranges addresses are based on the unit's low_pc. Compute the
  1387. // offset we need to apply to adapt to the new unit's low_pc.
  1388. int64_t UnitPcOffset = 0;
  1389. if (OrigLowPc != -1ULL)
  1390. UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
  1391. for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
  1392. uint64_t Offset = RangeAttribute.get();
  1393. RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize());
  1394. if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
  1395. llvm::consumeError(std::move(E));
  1396. reportWarning("invalid range list ignored.", File);
  1397. RangeList.clear();
  1398. }
  1399. const auto &Entries = RangeList.getEntries();
  1400. if (!Entries.empty()) {
  1401. const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
  1402. if (CurrRange == InvalidRange ||
  1403. First.StartAddress + OrigLowPc < CurrRange.start() ||
  1404. First.StartAddress + OrigLowPc >= CurrRange.stop()) {
  1405. CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
  1406. if (CurrRange == InvalidRange ||
  1407. CurrRange.start() > First.StartAddress + OrigLowPc) {
  1408. reportWarning("no mapping for range.", File);
  1409. continue;
  1410. }
  1411. }
  1412. }
  1413. TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange,
  1414. Entries, AddressSize);
  1415. }
  1416. }
  1417. /// Generate the debug_aranges entries for \p Unit and if the
  1418. /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
  1419. /// contribution for this attribute.
  1420. /// FIXME: this could actually be done right in patchRangesForUnit,
  1421. /// but for the sake of initial bit-for-bit compatibility with legacy
  1422. /// dsymutil, we have to do it in a delayed pass.
  1423. void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const {
  1424. auto Attr = Unit.getUnitRangesAttribute();
  1425. if (Attr)
  1426. Attr->set(TheDwarfEmitter->getRangesSectionSize());
  1427. TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
  1428. }
  1429. /// Insert the new line info sequence \p Seq into the current
  1430. /// set of already linked line info \p Rows.
  1431. static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
  1432. std::vector<DWARFDebugLine::Row> &Rows) {
  1433. if (Seq.empty())
  1434. return;
  1435. if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
  1436. llvm::append_range(Rows, Seq);
  1437. Seq.clear();
  1438. return;
  1439. }
  1440. object::SectionedAddress Front = Seq.front().Address;
  1441. auto InsertPoint = partition_point(
  1442. Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
  1443. // FIXME: this only removes the unneeded end_sequence if the
  1444. // sequences have been inserted in order. Using a global sort like
  1445. // described in patchLineTableForUnit() and delaying the end_sequene
  1446. // elimination to emitLineTableForUnit() we can get rid of all of them.
  1447. if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
  1448. InsertPoint->EndSequence) {
  1449. *InsertPoint = Seq.front();
  1450. Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
  1451. } else {
  1452. Rows.insert(InsertPoint, Seq.begin(), Seq.end());
  1453. }
  1454. Seq.clear();
  1455. }
  1456. static void patchStmtList(DIE &Die, DIEInteger Offset) {
  1457. for (auto &V : Die.values())
  1458. if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
  1459. V = DIEValue(V.getAttribute(), V.getForm(), Offset);
  1460. return;
  1461. }
  1462. llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
  1463. }
  1464. /// Extract the line table for \p Unit from \p OrigDwarf, and
  1465. /// recreate a relocated version of these for the address ranges that
  1466. /// are present in the binary.
  1467. void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit,
  1468. DWARFContext &OrigDwarf,
  1469. const DWARFFile &File) {
  1470. DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
  1471. auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
  1472. if (!StmtList)
  1473. return;
  1474. // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
  1475. if (auto *OutputDIE = Unit.getOutputUnitDIE())
  1476. patchStmtList(*OutputDIE,
  1477. DIEInteger(TheDwarfEmitter->getLineSectionSize()));
  1478. RangesTy &Ranges = File.Addresses->getValidAddressRanges();
  1479. // Parse the original line info for the unit.
  1480. DWARFDebugLine::LineTable LineTable;
  1481. uint64_t StmtOffset = *StmtList;
  1482. DWARFDataExtractor LineExtractor(
  1483. OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
  1484. OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
  1485. if (needToTranslateStrings())
  1486. return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset);
  1487. if (Error Err =
  1488. LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
  1489. &Unit.getOrigUnit(), OrigDwarf.getWarningHandler()))
  1490. OrigDwarf.getWarningHandler()(std::move(Err));
  1491. // This vector is the output line table.
  1492. std::vector<DWARFDebugLine::Row> NewRows;
  1493. NewRows.reserve(LineTable.Rows.size());
  1494. // Current sequence of rows being extracted, before being inserted
  1495. // in NewRows.
  1496. std::vector<DWARFDebugLine::Row> Seq;
  1497. const auto &FunctionRanges = Unit.getFunctionRanges();
  1498. auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
  1499. // FIXME: This logic is meant to generate exactly the same output as
  1500. // Darwin's classic dsymutil. There is a nicer way to implement this
  1501. // by simply putting all the relocated line info in NewRows and simply
  1502. // sorting NewRows before passing it to emitLineTableForUnit. This
  1503. // should be correct as sequences for a function should stay
  1504. // together in the sorted output. There are a few corner cases that
  1505. // look suspicious though, and that required to implement the logic
  1506. // this way. Revisit that once initial validation is finished.
  1507. // Iterate over the object file line info and extract the sequences
  1508. // that correspond to linked functions.
  1509. for (auto &Row : LineTable.Rows) {
  1510. // Check whether we stepped out of the range. The range is
  1511. // half-open, but consider accept the end address of the range if
  1512. // it is marked as end_sequence in the input (because in that
  1513. // case, the relocation offset is accurate and that entry won't
  1514. // serve as the start of another function).
  1515. if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
  1516. Row.Address.Address > CurrRange.stop() ||
  1517. (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
  1518. // We just stepped out of a known range. Insert a end_sequence
  1519. // corresponding to the end of the range.
  1520. uint64_t StopAddress = CurrRange != InvalidRange
  1521. ? CurrRange.stop() + CurrRange.value()
  1522. : -1ULL;
  1523. CurrRange = FunctionRanges.find(Row.Address.Address);
  1524. bool CurrRangeValid =
  1525. CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
  1526. if (!CurrRangeValid) {
  1527. CurrRange = InvalidRange;
  1528. if (StopAddress != -1ULL) {
  1529. // Try harder by looking in the Address ranges map.
  1530. // There are corner cases where this finds a
  1531. // valid entry. It's unclear if this is right or wrong, but
  1532. // for now do as dsymutil.
  1533. // FIXME: Understand exactly what cases this addresses and
  1534. // potentially remove it along with the Ranges map.
  1535. auto Range = Ranges.lower_bound(Row.Address.Address);
  1536. if (Range != Ranges.begin() && Range != Ranges.end())
  1537. --Range;
  1538. if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
  1539. Range->second.HighPC >= Row.Address.Address) {
  1540. StopAddress = Row.Address.Address + Range->second.Offset;
  1541. }
  1542. }
  1543. }
  1544. if (StopAddress != -1ULL && !Seq.empty()) {
  1545. // Insert end sequence row with the computed end address, but
  1546. // the same line as the previous one.
  1547. auto NextLine = Seq.back();
  1548. NextLine.Address.Address = StopAddress;
  1549. NextLine.EndSequence = 1;
  1550. NextLine.PrologueEnd = 0;
  1551. NextLine.BasicBlock = 0;
  1552. NextLine.EpilogueBegin = 0;
  1553. Seq.push_back(NextLine);
  1554. insertLineSequence(Seq, NewRows);
  1555. }
  1556. if (!CurrRangeValid)
  1557. continue;
  1558. }
  1559. // Ignore empty sequences.
  1560. if (Row.EndSequence && Seq.empty())
  1561. continue;
  1562. // Relocate row address and add it to the current sequence.
  1563. Row.Address.Address += CurrRange.value();
  1564. Seq.emplace_back(Row);
  1565. if (Row.EndSequence)
  1566. insertLineSequence(Seq, NewRows);
  1567. }
  1568. // Finished extracting, now emit the line tables.
  1569. // FIXME: LLVM hard-codes its prologue values. We just copy the
  1570. // prologue over and that works because we act as both producer and
  1571. // consumer. It would be nicer to have a real configurable line
  1572. // table emitter.
  1573. if (LineTable.Prologue.getVersion() < 2 ||
  1574. LineTable.Prologue.getVersion() > 5 ||
  1575. LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
  1576. LineTable.Prologue.OpcodeBase > 13)
  1577. reportWarning("line table parameters mismatch. Cannot emit.", File);
  1578. else {
  1579. uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
  1580. // DWARF v5 has an extra 2 bytes of information before the header_length
  1581. // field.
  1582. if (LineTable.Prologue.getVersion() == 5)
  1583. PrologueEnd += 2;
  1584. StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
  1585. MCDwarfLineTableParams Params;
  1586. Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
  1587. Params.DWARF2LineBase = LineTable.Prologue.LineBase;
  1588. Params.DWARF2LineRange = LineTable.Prologue.LineRange;
  1589. TheDwarfEmitter->emitLineTableForUnit(
  1590. Params, LineData.slice(*StmtList + 4, PrologueEnd),
  1591. LineTable.Prologue.MinInstLength, NewRows,
  1592. Unit.getOrigUnit().getAddressByteSize());
  1593. }
  1594. }
  1595. void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1596. switch (Options.TheAccelTableKind) {
  1597. case AccelTableKind::Apple:
  1598. emitAppleAcceleratorEntriesForUnit(Unit);
  1599. break;
  1600. case AccelTableKind::Dwarf:
  1601. emitDwarfAcceleratorEntriesForUnit(Unit);
  1602. break;
  1603. case AccelTableKind::Pub:
  1604. emitPubAcceleratorEntriesForUnit(Unit);
  1605. break;
  1606. case AccelTableKind::Default:
  1607. llvm_unreachable("The default must be updated to a concrete value.");
  1608. break;
  1609. }
  1610. }
  1611. void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1612. // Add namespaces.
  1613. for (const auto &Namespace : Unit.getNamespaces())
  1614. AppleNamespaces.addName(Namespace.Name,
  1615. Namespace.Die->getOffset() + Unit.getStartOffset());
  1616. /// Add names.
  1617. for (const auto &Pubname : Unit.getPubnames())
  1618. AppleNames.addName(Pubname.Name,
  1619. Pubname.Die->getOffset() + Unit.getStartOffset());
  1620. /// Add types.
  1621. for (const auto &Pubtype : Unit.getPubtypes())
  1622. AppleTypes.addName(
  1623. Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
  1624. Pubtype.Die->getTag(),
  1625. Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
  1626. : 0,
  1627. Pubtype.QualifiedNameHash);
  1628. /// Add ObjC names.
  1629. for (const auto &ObjC : Unit.getObjC())
  1630. AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
  1631. }
  1632. void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1633. for (const auto &Namespace : Unit.getNamespaces())
  1634. DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
  1635. Namespace.Die->getTag(), Unit.getUniqueID());
  1636. for (const auto &Pubname : Unit.getPubnames())
  1637. DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
  1638. Pubname.Die->getTag(), Unit.getUniqueID());
  1639. for (const auto &Pubtype : Unit.getPubtypes())
  1640. DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
  1641. Pubtype.Die->getTag(), Unit.getUniqueID());
  1642. }
  1643. void DWARFLinker::emitPubAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1644. TheDwarfEmitter->emitPubNamesForUnit(Unit);
  1645. TheDwarfEmitter->emitPubTypesForUnit(Unit);
  1646. }
  1647. /// Read the frame info stored in the object, and emit the
  1648. /// patched frame descriptions for the resulting file.
  1649. ///
  1650. /// This is actually pretty easy as the data of the CIEs and FDEs can
  1651. /// be considered as black boxes and moved as is. The only thing to do
  1652. /// is to patch the addresses in the headers.
  1653. void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File,
  1654. RangesTy &Ranges,
  1655. DWARFContext &OrigDwarf,
  1656. unsigned AddrSize) {
  1657. StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
  1658. if (FrameData.empty())
  1659. return;
  1660. DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
  1661. uint64_t InputOffset = 0;
  1662. // Store the data of the CIEs defined in this object, keyed by their
  1663. // offsets.
  1664. DenseMap<uint64_t, StringRef> LocalCIES;
  1665. while (Data.isValidOffset(InputOffset)) {
  1666. uint64_t EntryOffset = InputOffset;
  1667. uint32_t InitialLength = Data.getU32(&InputOffset);
  1668. if (InitialLength == 0xFFFFFFFF)
  1669. return reportWarning("Dwarf64 bits no supported", File);
  1670. uint32_t CIEId = Data.getU32(&InputOffset);
  1671. if (CIEId == 0xFFFFFFFF) {
  1672. // This is a CIE, store it.
  1673. StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
  1674. LocalCIES[EntryOffset] = CIEData;
  1675. // The -4 is to account for the CIEId we just read.
  1676. InputOffset += InitialLength - 4;
  1677. continue;
  1678. }
  1679. uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
  1680. // Some compilers seem to emit frame info that doesn't start at
  1681. // the function entry point, thus we can't just lookup the address
  1682. // in the debug map. Use the AddressInfo's range map to see if the FDE
  1683. // describes something that we can relocate.
  1684. auto Range = Ranges.upper_bound(Loc);
  1685. if (Range != Ranges.begin())
  1686. --Range;
  1687. if (Range == Ranges.end() || Range->first > Loc ||
  1688. Range->second.HighPC <= Loc) {
  1689. // The +4 is to account for the size of the InitialLength field itself.
  1690. InputOffset = EntryOffset + InitialLength + 4;
  1691. continue;
  1692. }
  1693. // This is an FDE, and we have a mapping.
  1694. // Have we already emitted a corresponding CIE?
  1695. StringRef CIEData = LocalCIES[CIEId];
  1696. if (CIEData.empty())
  1697. return reportWarning("Inconsistent debug_frame content. Dropping.", File);
  1698. // Look if we already emitted a CIE that corresponds to the
  1699. // referenced one (the CIE data is the key of that lookup).
  1700. auto IteratorInserted = EmittedCIEs.insert(
  1701. std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
  1702. // If there is no CIE yet for this ID, emit it.
  1703. if (IteratorInserted.second) {
  1704. LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
  1705. IteratorInserted.first->getValue() = LastCIEOffset;
  1706. TheDwarfEmitter->emitCIE(CIEData);
  1707. }
  1708. // Emit the FDE with updated address and CIE pointer.
  1709. // (4 + AddrSize) is the size of the CIEId + initial_location
  1710. // fields that will get reconstructed by emitFDE().
  1711. unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
  1712. TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
  1713. Loc + Range->second.Offset,
  1714. FrameData.substr(InputOffset, FDERemainingBytes));
  1715. InputOffset += FDERemainingBytes;
  1716. }
  1717. }
  1718. uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
  1719. CompileUnit &U,
  1720. const DWARFFile &File,
  1721. int ChildRecurseDepth) {
  1722. const char *Name = nullptr;
  1723. DWARFUnit *OrigUnit = &U.getOrigUnit();
  1724. CompileUnit *CU = &U;
  1725. Optional<DWARFFormValue> Ref;
  1726. while (true) {
  1727. if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
  1728. Name = CurrentName;
  1729. if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
  1730. !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
  1731. break;
  1732. if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
  1733. break;
  1734. CompileUnit *RefCU;
  1735. if (auto RefDIE =
  1736. Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
  1737. CU = RefCU;
  1738. OrigUnit = &RefCU->getOrigUnit();
  1739. DIE = RefDIE;
  1740. }
  1741. }
  1742. unsigned Idx = OrigUnit->getDIEIndex(DIE);
  1743. if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
  1744. Name = "(anonymous namespace)";
  1745. if (CU->getInfo(Idx).ParentIdx == 0 ||
  1746. // FIXME: dsymutil-classic compatibility. Ignore modules.
  1747. CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
  1748. dwarf::DW_TAG_module)
  1749. return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
  1750. DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
  1751. return djbHash(
  1752. (Name ? Name : ""),
  1753. djbHash((Name ? "::" : ""),
  1754. hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
  1755. }
  1756. static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
  1757. auto DwoId = dwarf::toUnsigned(
  1758. CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
  1759. if (DwoId)
  1760. return *DwoId;
  1761. return 0;
  1762. }
  1763. static std::string remapPath(StringRef Path,
  1764. const objectPrefixMap &ObjectPrefixMap) {
  1765. if (ObjectPrefixMap.empty())
  1766. return Path.str();
  1767. SmallString<256> p = Path;
  1768. for (const auto &Entry : ObjectPrefixMap)
  1769. if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
  1770. break;
  1771. return p.str().str();
  1772. }
  1773. bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit,
  1774. const DWARFFile &File,
  1775. OffsetsStringPool &StringPool,
  1776. DeclContextTree &ODRContexts,
  1777. uint64_t ModulesEndOffset,
  1778. unsigned &UnitID, bool IsLittleEndian,
  1779. unsigned Indent, bool Quiet) {
  1780. std::string PCMfile = dwarf::toString(
  1781. CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
  1782. if (PCMfile.empty())
  1783. return false;
  1784. if (Options.ObjectPrefixMap)
  1785. PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap);
  1786. // Clang module DWARF skeleton CUs abuse this for the path to the module.
  1787. uint64_t DwoId = getDwoId(CUDie, Unit);
  1788. std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
  1789. if (Name.empty()) {
  1790. if (!Quiet)
  1791. reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
  1792. return true;
  1793. }
  1794. if (!Quiet && Options.Verbose) {
  1795. outs().indent(Indent);
  1796. outs() << "Found clang module reference " << PCMfile;
  1797. }
  1798. auto Cached = ClangModules.find(PCMfile);
  1799. if (Cached != ClangModules.end()) {
  1800. // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
  1801. // fixed in clang, only warn about DWO_id mismatches in verbose mode.
  1802. // ASTFileSignatures will change randomly when a module is rebuilt.
  1803. if (!Quiet && Options.Verbose && (Cached->second != DwoId))
  1804. reportWarning(Twine("hash mismatch: this object file was built against a "
  1805. "different version of the module ") +
  1806. PCMfile,
  1807. File);
  1808. if (!Quiet && Options.Verbose)
  1809. outs() << " [cached].\n";
  1810. return true;
  1811. }
  1812. if (!Quiet && Options.Verbose)
  1813. outs() << " ...\n";
  1814. // Cyclic dependencies are disallowed by Clang, but we still
  1815. // shouldn't run into an infinite loop, so mark it as processed now.
  1816. ClangModules.insert({PCMfile, DwoId});
  1817. if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
  1818. ODRContexts, ModulesEndOffset, UnitID,
  1819. IsLittleEndian, Indent + 2, Quiet)) {
  1820. consumeError(std::move(E));
  1821. return false;
  1822. }
  1823. return true;
  1824. }
  1825. Error DWARFLinker::loadClangModule(
  1826. DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
  1827. const DWARFFile &File, OffsetsStringPool &StringPool,
  1828. DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
  1829. bool IsLittleEndian, unsigned Indent, bool Quiet) {
  1830. /// Using a SmallString<0> because loadClangModule() is recursive.
  1831. SmallString<0> Path(Options.PrependPath);
  1832. if (sys::path::is_relative(Filename))
  1833. resolveRelativeObjectPath(Path, CUDie);
  1834. sys::path::append(Path, Filename);
  1835. // Don't use the cached binary holder because we have no thread-safety
  1836. // guarantee and the lifetime is limited.
  1837. if (Options.ObjFileLoader == nullptr)
  1838. return Error::success();
  1839. auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
  1840. if (!ErrOrObj)
  1841. return Error::success();
  1842. std::unique_ptr<CompileUnit> Unit;
  1843. for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
  1844. updateDwarfVersion(CU->getVersion());
  1845. // Recursively get all modules imported by this one.
  1846. auto CUDie = CU->getUnitDIE(false);
  1847. if (!CUDie)
  1848. continue;
  1849. if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts,
  1850. ModulesEndOffset, UnitID, IsLittleEndian,
  1851. Indent, Quiet)) {
  1852. if (Unit) {
  1853. std::string Err =
  1854. (Filename +
  1855. ": Clang modules are expected to have exactly 1 compile unit.\n")
  1856. .str();
  1857. reportError(Err, File);
  1858. return make_error<StringError>(Err, inconvertibleErrorCode());
  1859. }
  1860. // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
  1861. // fixed in clang, only warn about DWO_id mismatches in verbose mode.
  1862. // ASTFileSignatures will change randomly when a module is rebuilt.
  1863. uint64_t PCMDwoId = getDwoId(CUDie, *CU);
  1864. if (PCMDwoId != DwoId) {
  1865. if (!Quiet && Options.Verbose)
  1866. reportWarning(
  1867. Twine("hash mismatch: this object file was built against a "
  1868. "different version of the module ") +
  1869. Filename,
  1870. File);
  1871. // Update the cache entry with the DwoId of the module loaded from disk.
  1872. ClangModules[Filename] = PCMDwoId;
  1873. }
  1874. // Add this module.
  1875. Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
  1876. ModuleName);
  1877. analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts,
  1878. ModulesEndOffset, Options.ParseableSwiftInterfaces,
  1879. [&](const Twine &Warning, const DWARFDie &DIE) {
  1880. reportWarning(Warning, File, &DIE);
  1881. });
  1882. // Keep everything.
  1883. Unit->markEverythingAsKept();
  1884. }
  1885. }
  1886. assert(Unit && "CompileUnit is not set!");
  1887. if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
  1888. return Error::success();
  1889. if (!Quiet && Options.Verbose) {
  1890. outs().indent(Indent);
  1891. outs() << "cloning .debug_info from " << Filename << "\n";
  1892. }
  1893. UnitListTy CompileUnits;
  1894. CompileUnits.push_back(std::move(Unit));
  1895. assert(TheDwarfEmitter);
  1896. DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
  1897. Options.Update)
  1898. .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
  1899. IsLittleEndian);
  1900. return Error::success();
  1901. }
  1902. uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits(
  1903. DWARFContext &DwarfContext, const DWARFFile &File,
  1904. OffsetsStringPool &StringPool, bool IsLittleEndian) {
  1905. uint64_t OutputDebugInfoSize =
  1906. Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
  1907. const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
  1908. for (auto &CurrentUnit : CompileUnits) {
  1909. const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
  1910. const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
  1911. auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
  1912. CurrentUnit->setStartOffset(OutputDebugInfoSize);
  1913. if (!InputDIE) {
  1914. OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
  1915. continue;
  1916. }
  1917. if (CurrentUnit->getInfo(0).Keep) {
  1918. // Clone the InputDIE into your Unit DIE in our compile unit since it
  1919. // already has a DIE inside of it.
  1920. CurrentUnit->createOutputDIE();
  1921. cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
  1922. UnitHeaderSize, 0, IsLittleEndian,
  1923. CurrentUnit->getOutputUnitDIE());
  1924. }
  1925. OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
  1926. if (!Linker.Options.NoOutput) {
  1927. assert(Emitter);
  1928. if (LLVM_LIKELY(!Linker.Options.Update) ||
  1929. Linker.needToTranslateStrings())
  1930. Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
  1931. Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
  1932. if (LLVM_UNLIKELY(Linker.Options.Update))
  1933. continue;
  1934. Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
  1935. auto ProcessExpr = [&](StringRef Bytes,
  1936. SmallVectorImpl<uint8_t> &Buffer) {
  1937. DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
  1938. DataExtractor Data(Bytes, IsLittleEndian,
  1939. OrigUnit.getAddressByteSize());
  1940. cloneExpression(Data,
  1941. DWARFExpression(Data, OrigUnit.getAddressByteSize(),
  1942. OrigUnit.getFormParams().Format),
  1943. File, *CurrentUnit, Buffer);
  1944. };
  1945. Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
  1946. }
  1947. }
  1948. if (!Linker.Options.NoOutput) {
  1949. assert(Emitter);
  1950. // Emit all the compile unit's debug information.
  1951. for (auto &CurrentUnit : CompileUnits) {
  1952. if (LLVM_LIKELY(!Linker.Options.Update))
  1953. Linker.generateUnitRanges(*CurrentUnit);
  1954. CurrentUnit->fixupForwardReferences();
  1955. if (!CurrentUnit->getOutputUnitDIE())
  1956. continue;
  1957. unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
  1958. assert(Emitter->getDebugInfoSectionSize() ==
  1959. CurrentUnit->getStartOffset());
  1960. Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
  1961. Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
  1962. assert(Emitter->getDebugInfoSectionSize() ==
  1963. CurrentUnit->computeNextUnitOffset(DwarfVersion));
  1964. }
  1965. }
  1966. return OutputDebugInfoSize - StartOutputDebugInfoSize;
  1967. }
  1968. void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
  1969. if (Options.TheAccelTableKind != AccelTableKind::Default)
  1970. return;
  1971. auto &DwarfObj = Dwarf.getDWARFObj();
  1972. if (!AtLeastOneDwarfAccelTable &&
  1973. (!DwarfObj.getAppleNamesSection().Data.empty() ||
  1974. !DwarfObj.getAppleTypesSection().Data.empty() ||
  1975. !DwarfObj.getAppleNamespacesSection().Data.empty() ||
  1976. !DwarfObj.getAppleObjCSection().Data.empty())) {
  1977. AtLeastOneAppleAccelTable = true;
  1978. }
  1979. if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
  1980. AtLeastOneDwarfAccelTable = true;
  1981. }
  1982. }
  1983. bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File,
  1984. OffsetsStringPool &StringPool) {
  1985. if (File.Warnings.empty())
  1986. return false;
  1987. DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
  1988. CUDie->setOffset(11);
  1989. StringRef Producer;
  1990. StringRef WarningHeader;
  1991. switch (DwarfLinkerClientID) {
  1992. case DwarfLinkerClient::Dsymutil:
  1993. Producer = StringPool.internString("dsymutil");
  1994. WarningHeader = "dsymutil_warning";
  1995. break;
  1996. default:
  1997. Producer = StringPool.internString("dwarfopt");
  1998. WarningHeader = "dwarfopt_warning";
  1999. break;
  2000. }
  2001. StringRef FileName = StringPool.internString(File.FileName);
  2002. CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
  2003. DIEInteger(StringPool.getStringOffset(Producer)));
  2004. DIEBlock *String = new (DIEAlloc) DIEBlock();
  2005. DIEBlocks.push_back(String);
  2006. for (auto &C : FileName)
  2007. String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
  2008. DIEInteger(C));
  2009. String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
  2010. DIEInteger(0));
  2011. CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
  2012. for (const auto &Warning : File.Warnings) {
  2013. DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
  2014. ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
  2015. DIEInteger(StringPool.getStringOffset(WarningHeader)));
  2016. ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
  2017. DIEInteger(1));
  2018. ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
  2019. DIEInteger(StringPool.getStringOffset(Warning)));
  2020. }
  2021. unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
  2022. File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
  2023. DIEAbbrev Abbrev = CUDie->generateAbbrev();
  2024. assignAbbrev(Abbrev);
  2025. CUDie->setAbbrevNumber(Abbrev.getNumber());
  2026. Size += getULEB128Size(Abbrev.getNumber());
  2027. // Abbreviation ordering needed for classic compatibility.
  2028. for (auto &Child : CUDie->children()) {
  2029. Abbrev = Child.generateAbbrev();
  2030. assignAbbrev(Abbrev);
  2031. Child.setAbbrevNumber(Abbrev.getNumber());
  2032. Size += getULEB128Size(Abbrev.getNumber());
  2033. }
  2034. CUDie->setSize(Size);
  2035. TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
  2036. return true;
  2037. }
  2038. void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
  2039. if (!needToTranslateStrings())
  2040. TheDwarfEmitter->emitSectionContents(
  2041. Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
  2042. TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
  2043. "debug_loc");
  2044. TheDwarfEmitter->emitSectionContents(
  2045. Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
  2046. TheDwarfEmitter->emitSectionContents(
  2047. Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
  2048. TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
  2049. "debug_aranges");
  2050. }
  2051. void DWARFLinker::addObjectFile(DWARFFile &File) {
  2052. ObjectContexts.emplace_back(LinkContext(File));
  2053. if (ObjectContexts.back().File.Dwarf)
  2054. updateAccelKind(*ObjectContexts.back().File.Dwarf);
  2055. }
  2056. bool DWARFLinker::link() {
  2057. assert(Options.NoOutput || TheDwarfEmitter);
  2058. // A unique ID that identifies each compile unit.
  2059. unsigned UnitID = 0;
  2060. // First populate the data structure we need for each iteration of the
  2061. // parallel loop.
  2062. unsigned NumObjects = ObjectContexts.size();
  2063. // This Dwarf string pool which is used for emission. It must be used
  2064. // serially as the order of calling getStringOffset matters for
  2065. // reproducibility.
  2066. OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
  2067. // ODR Contexts for the optimize.
  2068. DeclContextTree ODRContexts;
  2069. // If we haven't decided on an accelerator table kind yet, we base ourselves
  2070. // on the DWARF we have seen so far. At this point we haven't pulled in debug
  2071. // information from modules yet, so it is technically possible that they
  2072. // would affect the decision. However, as they're built with the same
  2073. // compiler and flags, it is safe to assume that they will follow the
  2074. // decision made here.
  2075. if (Options.TheAccelTableKind == AccelTableKind::Default) {
  2076. if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
  2077. Options.TheAccelTableKind = AccelTableKind::Dwarf;
  2078. else
  2079. Options.TheAccelTableKind = AccelTableKind::Apple;
  2080. }
  2081. for (LinkContext &OptContext : ObjectContexts) {
  2082. if (Options.Verbose) {
  2083. if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
  2084. outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
  2085. else
  2086. outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
  2087. }
  2088. if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
  2089. continue;
  2090. if (!OptContext.File.Dwarf)
  2091. continue;
  2092. // Look for relocations that correspond to address map entries.
  2093. // there was findvalidrelocations previously ... probably we need to gather
  2094. // info here
  2095. if (LLVM_LIKELY(!Options.Update) &&
  2096. !OptContext.File.Addresses->hasValidRelocs()) {
  2097. if (Options.Verbose)
  2098. outs() << "No valid relocations found. Skipping.\n";
  2099. // Set "Skip" flag as a signal to other loops that we should not
  2100. // process this iteration.
  2101. OptContext.Skip = true;
  2102. continue;
  2103. }
  2104. // Setup access to the debug info.
  2105. if (!OptContext.File.Dwarf)
  2106. continue;
  2107. // In a first phase, just read in the debug info and load all clang modules.
  2108. OptContext.CompileUnits.reserve(
  2109. OptContext.File.Dwarf->getNumCompileUnits());
  2110. for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
  2111. updateDwarfVersion(CU->getVersion());
  2112. auto CUDie = CU->getUnitDIE(false);
  2113. if (Options.Verbose) {
  2114. outs() << "Input compilation unit:";
  2115. DIDumpOptions DumpOpts;
  2116. DumpOpts.ChildRecurseDepth = 0;
  2117. DumpOpts.Verbose = Options.Verbose;
  2118. CUDie.dump(outs(), 0, DumpOpts);
  2119. }
  2120. if (CUDie && !LLVM_UNLIKELY(Options.Update))
  2121. registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
  2122. ODRContexts, 0, UnitID,
  2123. OptContext.File.Dwarf->isLittleEndian());
  2124. }
  2125. }
  2126. // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
  2127. if (MaxDwarfVersion == 0)
  2128. MaxDwarfVersion = 3;
  2129. // At this point we know how much data we have emitted. We use this value to
  2130. // compare canonical DIE offsets in analyzeContextInfo to see if a definition
  2131. // is already emitted, without being affected by canonical die offsets set
  2132. // later. This prevents undeterminism when analyze and clone execute
  2133. // concurrently, as clone set the canonical DIE offset and analyze reads it.
  2134. const uint64_t ModulesEndOffset =
  2135. Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
  2136. // These variables manage the list of processed object files.
  2137. // The mutex and condition variable are to ensure that this is thread safe.
  2138. std::mutex ProcessedFilesMutex;
  2139. std::condition_variable ProcessedFilesConditionVariable;
  2140. BitVector ProcessedFiles(NumObjects, false);
  2141. // Analyzing the context info is particularly expensive so it is executed in
  2142. // parallel with emitting the previous compile unit.
  2143. auto AnalyzeLambda = [&](size_t I) {
  2144. auto &Context = ObjectContexts[I];
  2145. if (Context.Skip || !Context.File.Dwarf)
  2146. return;
  2147. for (const auto &CU : Context.File.Dwarf->compile_units()) {
  2148. updateDwarfVersion(CU->getVersion());
  2149. // The !registerModuleReference() condition effectively skips
  2150. // over fully resolved skeleton units. This second pass of
  2151. // registerModuleReferences doesn't do any new work, but it
  2152. // will collect top-level errors, which are suppressed. Module
  2153. // warnings were already displayed in the first iteration.
  2154. bool Quiet = true;
  2155. auto CUDie = CU->getUnitDIE(false);
  2156. if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
  2157. !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
  2158. ODRContexts, ModulesEndOffset, UnitID,
  2159. Quiet)) {
  2160. Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
  2161. *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
  2162. }
  2163. }
  2164. // Now build the DIE parent links that we will use during the next phase.
  2165. for (auto &CurrentUnit : Context.CompileUnits) {
  2166. auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
  2167. if (!CUDie)
  2168. continue;
  2169. analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
  2170. *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
  2171. ModulesEndOffset, Options.ParseableSwiftInterfaces,
  2172. [&](const Twine &Warning, const DWARFDie &DIE) {
  2173. reportWarning(Warning, Context.File, &DIE);
  2174. });
  2175. }
  2176. };
  2177. // For each object file map how many bytes were emitted.
  2178. StringMap<DebugInfoSize> SizeByObject;
  2179. // And then the remaining work in serial again.
  2180. // Note, although this loop runs in serial, it can run in parallel with
  2181. // the analyzeContextInfo loop so long as we process files with indices >=
  2182. // than those processed by analyzeContextInfo.
  2183. auto CloneLambda = [&](size_t I) {
  2184. auto &OptContext = ObjectContexts[I];
  2185. if (OptContext.Skip || !OptContext.File.Dwarf)
  2186. return;
  2187. // Then mark all the DIEs that need to be present in the generated output
  2188. // and collect some information about them.
  2189. // Note that this loop can not be merged with the previous one because
  2190. // cross-cu references require the ParentIdx to be setup for every CU in
  2191. // the object file before calling this.
  2192. if (LLVM_UNLIKELY(Options.Update)) {
  2193. for (auto &CurrentUnit : OptContext.CompileUnits)
  2194. CurrentUnit->markEverythingAsKept();
  2195. copyInvariantDebugSection(*OptContext.File.Dwarf);
  2196. } else {
  2197. for (auto &CurrentUnit : OptContext.CompileUnits)
  2198. lookForDIEsToKeep(*OptContext.File.Addresses,
  2199. OptContext.File.Addresses->getValidAddressRanges(),
  2200. OptContext.CompileUnits,
  2201. CurrentUnit->getOrigUnit().getUnitDIE(),
  2202. OptContext.File, *CurrentUnit, 0);
  2203. }
  2204. // The calls to applyValidRelocs inside cloneDIE will walk the reloc
  2205. // array again (in the same way findValidRelocsInDebugInfo() did). We
  2206. // need to reset the NextValidReloc index to the beginning.
  2207. if (OptContext.File.Addresses->hasValidRelocs() ||
  2208. LLVM_UNLIKELY(Options.Update)) {
  2209. SizeByObject[OptContext.File.FileName].Input =
  2210. getDebugInfoSize(*OptContext.File.Dwarf);
  2211. SizeByObject[OptContext.File.FileName].Output =
  2212. DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
  2213. OptContext.CompileUnits, Options.Update)
  2214. .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
  2215. OffsetsStringPool,
  2216. OptContext.File.Dwarf->isLittleEndian());
  2217. }
  2218. if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
  2219. LLVM_LIKELY(!Options.Update))
  2220. patchFrameInfoForObject(
  2221. OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
  2222. *OptContext.File.Dwarf,
  2223. OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
  2224. // Clean-up before starting working on the next object.
  2225. cleanupAuxiliarryData(OptContext);
  2226. };
  2227. auto EmitLambda = [&]() {
  2228. // Emit everything that's global.
  2229. if (!Options.NoOutput) {
  2230. TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
  2231. TheDwarfEmitter->emitStrings(OffsetsStringPool);
  2232. switch (Options.TheAccelTableKind) {
  2233. case AccelTableKind::Apple:
  2234. TheDwarfEmitter->emitAppleNames(AppleNames);
  2235. TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
  2236. TheDwarfEmitter->emitAppleTypes(AppleTypes);
  2237. TheDwarfEmitter->emitAppleObjc(AppleObjc);
  2238. break;
  2239. case AccelTableKind::Dwarf:
  2240. TheDwarfEmitter->emitDebugNames(DebugNames);
  2241. break;
  2242. case AccelTableKind::Pub:
  2243. // Already emitted by emitPubAcceleratorEntriesForUnit.
  2244. break;
  2245. case AccelTableKind::Default:
  2246. llvm_unreachable("Default should have already been resolved.");
  2247. break;
  2248. }
  2249. }
  2250. };
  2251. auto AnalyzeAll = [&]() {
  2252. for (unsigned I = 0, E = NumObjects; I != E; ++I) {
  2253. AnalyzeLambda(I);
  2254. std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
  2255. ProcessedFiles.set(I);
  2256. ProcessedFilesConditionVariable.notify_one();
  2257. }
  2258. };
  2259. auto CloneAll = [&]() {
  2260. for (unsigned I = 0, E = NumObjects; I != E; ++I) {
  2261. {
  2262. std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
  2263. if (!ProcessedFiles[I]) {
  2264. ProcessedFilesConditionVariable.wait(
  2265. LockGuard, [&]() { return ProcessedFiles[I]; });
  2266. }
  2267. }
  2268. CloneLambda(I);
  2269. }
  2270. EmitLambda();
  2271. };
  2272. // To limit memory usage in the single threaded case, analyze and clone are
  2273. // run sequentially so the OptContext is freed after processing each object
  2274. // in endDebugObject.
  2275. if (Options.Threads == 1) {
  2276. for (unsigned I = 0, E = NumObjects; I != E; ++I) {
  2277. AnalyzeLambda(I);
  2278. CloneLambda(I);
  2279. }
  2280. EmitLambda();
  2281. } else {
  2282. ThreadPool Pool(hardware_concurrency(2));
  2283. Pool.async(AnalyzeAll);
  2284. Pool.async(CloneAll);
  2285. Pool.wait();
  2286. }
  2287. if (Options.Statistics) {
  2288. // Create a vector sorted in descending order by output size.
  2289. std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
  2290. for (auto &E : SizeByObject)
  2291. Sorted.emplace_back(E.first(), E.second);
  2292. llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
  2293. return LHS.second.Output > RHS.second.Output;
  2294. });
  2295. auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
  2296. const float Difference = Output - Input;
  2297. const float Sum = Input + Output;
  2298. if (Sum == 0)
  2299. return 0;
  2300. return (Difference / (Sum / 2));
  2301. };
  2302. int64_t InputTotal = 0;
  2303. int64_t OutputTotal = 0;
  2304. const char *FormatStr = "{0,-45} {1,10}b {2,10}b {3,8:P}\n";
  2305. // Print header.
  2306. outs() << ".debug_info section size (in bytes)\n";
  2307. outs() << "----------------------------------------------------------------"
  2308. "---------------\n";
  2309. outs() << "Filename Object "
  2310. " dSYM Change\n";
  2311. outs() << "----------------------------------------------------------------"
  2312. "---------------\n";
  2313. // Print body.
  2314. for (auto &E : Sorted) {
  2315. InputTotal += E.second.Input;
  2316. OutputTotal += E.second.Output;
  2317. llvm::outs() << formatv(
  2318. FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
  2319. E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
  2320. }
  2321. // Print total and footer.
  2322. outs() << "----------------------------------------------------------------"
  2323. "---------------\n";
  2324. llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
  2325. ComputePercentange(InputTotal, OutputTotal));
  2326. outs() << "----------------------------------------------------------------"
  2327. "---------------\n\n";
  2328. }
  2329. return true;
  2330. }
  2331. } // namespace llvm