[dsymutil] Add minimal code to emit DIE trees.
[oota-llvm.git] / tools / dsymutil / DwarfLinker.cpp
1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 #include "DebugMap.h"
10 #include "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "dsymutil.h"
13 #include "llvm/CodeGen/AsmPrinter.h"
14 #include "llvm/CodeGen/DIE.h"
15 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
16 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
17 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCCodeEmitter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/Object/MachO.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include <string>
33
34 namespace llvm {
35 namespace dsymutil {
36
37 namespace {
38
39 void warn(const Twine &Warning, const Twine &Context) {
40   errs() << Twine("while processing ") + Context + ":\n";
41   errs() << Twine("warning: ") + Warning + "\n";
42 }
43
44 bool error(const Twine &Error, const Twine &Context) {
45   errs() << Twine("while processing ") + Context + ":\n";
46   errs() << Twine("error: ") + Error + "\n";
47   return false;
48 }
49
50 /// \brief Stores all information relating to a compile unit, be it in
51 /// its original instance in the object file to its brand new cloned
52 /// and linked DIE tree.
53 class CompileUnit {
54 public:
55   /// \brief Information gathered about a DIE in the object file.
56   struct DIEInfo {
57     uint64_t Address;   ///< Linked address of the described entity.
58     uint32_t ParentIdx; ///< The index of this DIE's parent.
59     bool Keep;          ///< Is the DIE part of the linked output?
60     bool InDebugMap;    ///< Was this DIE's entity found in the map?
61   };
62
63   CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
64     Info.resize(OrigUnit.getNumDIEs());
65   }
66
67   DWARFUnit &getOrigUnit() const { return OrigUnit; }
68
69   DIE *getOutputUnitDIE() const { return CUDie.get(); }
70   void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
71
72   DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
73   const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
74
75   uint64_t getStartOffset() const { return StartOffset; }
76   uint64_t getNextUnitOffset() const { return NextUnitOffset; }
77
78   /// \brief Set the start and end offsets for this unit. Must be
79   /// called after the CU's DIEs have been cloned. The unit start
80   /// offset will be set to \p DebugInfoSize.
81   /// \returns the next unit offset (which is also the current
82   /// debug_info section size).
83   uint64_t computeOffsets(uint64_t DebugInfoSize);
84
85 private:
86   DWARFUnit &OrigUnit;
87   std::vector<DIEInfo> Info;  ///< DIE info indexed by DIE index.
88   std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
89
90   uint64_t StartOffset;
91   uint64_t NextUnitOffset;
92 };
93
94 uint64_t CompileUnit::computeOffsets(uint64_t DebugInfoSize) {
95   StartOffset = DebugInfoSize;
96   NextUnitOffset = StartOffset + 11 /* Header size */;
97   // The root DIE might be null, meaning that the Unit had nothing to
98   // contribute to the linked output. In that case, we will emit the
99   // unit header without any actual DIE.
100   if (CUDie)
101     NextUnitOffset += CUDie->getSize();
102   return NextUnitOffset;
103 }
104
105 /// \brief The Dwarf streaming logic
106 ///
107 /// All interactions with the MC layer that is used to build the debug
108 /// information binary representation are handled in this class.
109 class DwarfStreamer {
110   /// \defgroup MCObjects MC layer objects constructed by the streamer
111   /// @{
112   std::unique_ptr<MCRegisterInfo> MRI;
113   std::unique_ptr<MCAsmInfo> MAI;
114   std::unique_ptr<MCObjectFileInfo> MOFI;
115   std::unique_ptr<MCContext> MC;
116   MCAsmBackend *MAB; // Owned by MCStreamer
117   std::unique_ptr<MCInstrInfo> MII;
118   std::unique_ptr<MCSubtargetInfo> MSTI;
119   MCCodeEmitter *MCE; // Owned by MCStreamer
120   MCStreamer *MS;     // Owned by AsmPrinter
121   std::unique_ptr<TargetMachine> TM;
122   std::unique_ptr<AsmPrinter> Asm;
123   /// @}
124
125   /// \brief the file we stream the linked Dwarf to.
126   std::unique_ptr<raw_fd_ostream> OutFile;
127
128 public:
129   /// \brief Actually create the streamer and the ouptut file.
130   ///
131   /// This could be done directly in the constructor, but it feels
132   /// more natural to handle errors through return value.
133   bool init(Triple TheTriple, StringRef OutputFilename);
134
135   /// \brief Dump the file to the disk.
136   bool finish();
137
138   AsmPrinter &getAsmPrinter() const { return *Asm; }
139
140   /// \brief Set the current output section to debug_info and change
141   /// the MC Dwarf version to \p DwarfVersion.
142   void switchToDebugInfoSection(unsigned DwarfVersion);
143
144   /// \brief Emit the compilation unit header for \p Unit in the
145   /// debug_info section.
146   ///
147   /// As a side effect, this also switches the current Dwarf version
148   /// of the MC layer to the one of U.getOrigUnit().
149   void emitCompileUnitHeader(CompileUnit &Unit);
150
151   /// \brief Recursively emit the DIE tree rooted at \p Die.
152   void emitDIE(DIE &Die);
153
154   /// \brief Emit the abbreviation table \p Abbrevs to the
155   /// debug_abbrev section.
156   void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
157 };
158
159 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
160   std::string ErrorStr;
161   std::string TripleName;
162   StringRef Context = "dwarf streamer init";
163
164   // Get the target.
165   const Target *TheTarget =
166       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
167   if (!TheTarget)
168     return error(ErrorStr, Context);
169   TripleName = TheTriple.getTriple();
170
171   // Create all the MC Objects.
172   MRI.reset(TheTarget->createMCRegInfo(TripleName));
173   if (!MRI)
174     return error(Twine("no register info for target ") + TripleName, Context);
175
176   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
177   if (!MAI)
178     return error("no asm info for target " + TripleName, Context);
179
180   MOFI.reset(new MCObjectFileInfo);
181   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
182   MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
183                              *MC);
184
185   MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
186   if (!MAB)
187     return error("no asm backend for target " + TripleName, Context);
188
189   MII.reset(TheTarget->createMCInstrInfo());
190   if (!MII)
191     return error("no instr info info for target " + TripleName, Context);
192
193   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
194   if (!MSTI)
195     return error("no subtarget info for target " + TripleName, Context);
196
197   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MSTI, *MC);
198   if (!MCE)
199     return error("no code emitter for target " + TripleName, Context);
200
201   // Create the output file.
202   std::error_code EC;
203   OutFile =
204       llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
205   if (EC)
206     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
207
208   MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
209                                          *MSTI, false);
210   if (!MS)
211     return error("no object streamer for target " + TripleName, Context);
212
213   // Finally create the AsmPrinter we'll use to emit the DIEs.
214   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
215   if (!TM)
216     return error("no target machine for target " + TripleName, Context);
217
218   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
219   if (!Asm)
220     return error("no asm printer for target " + TripleName, Context);
221
222   return true;
223 }
224
225 bool DwarfStreamer::finish() {
226   MS->Finish();
227   return true;
228 }
229
230 /// \brief Set the current output section to debug_info and change
231 /// the MC Dwarf version to \p DwarfVersion.
232 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
233   MS->SwitchSection(MOFI->getDwarfInfoSection());
234   MC->setDwarfVersion(DwarfVersion);
235 }
236
237 /// \brief Emit the compilation unit header for \p Unit in the
238 /// debug_info section.
239 ///
240 /// A Dwarf scetion header is encoded as:
241 ///  uint32_t   Unit length (omiting this field)
242 ///  uint16_t   Version
243 ///  uint32_t   Abbreviation table offset
244 ///  uint8_t    Address size
245 ///
246 /// Leading to a total of 11 bytes.
247 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
248   unsigned Version = Unit.getOrigUnit().getVersion();
249   switchToDebugInfoSection(Version);
250
251   // Emit size of content not including length itself. The size has
252   // already been computed in CompileUnit::computeOffsets(). Substract
253   // 4 to that size to account for the length field.
254   Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
255   Asm->EmitInt16(Version);
256   // We share one abbreviations table across all units so it's always at the
257   // start of the section.
258   Asm->EmitInt32(0);
259   Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
260 }
261
262 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
263 /// for the linked Dwarf file.
264 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
265   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
266   Asm->emitDwarfAbbrevs(Abbrevs);
267 }
268
269 /// \brief Recursively emit the DIE tree rooted at \p Die.
270 void DwarfStreamer::emitDIE(DIE &Die) {
271   MS->SwitchSection(MOFI->getDwarfInfoSection());
272   Asm->emitDwarfDIE(Die);
273 }
274
275 /// \brief The core of the Dwarf linking logic.
276 ///
277 /// The link of the dwarf information from the object files will be
278 /// driven by the selection of 'root DIEs', which are DIEs that
279 /// describe variables or functions that are present in the linked
280 /// binary (and thus have entries in the debug map). All the debug
281 /// information that will be linked (the DIEs, but also the line
282 /// tables, ranges, ...) is derived from that set of root DIEs.
283 ///
284 /// The root DIEs are identified because they contain relocations that
285 /// correspond to a debug map entry at specific places (the low_pc for
286 /// a function, the location for a variable). These relocations are
287 /// called ValidRelocs in the DwarfLinker and are gathered as a very
288 /// first step when we start processing a DebugMapObject.
289 class DwarfLinker {
290 public:
291   DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
292       : OutputFilename(OutputFilename), Options(Options),
293         BinHolder(Options.Verbose) {}
294
295   ~DwarfLinker() {
296     for (auto *Abbrev : Abbreviations)
297       delete Abbrev;
298   }
299
300   /// \brief Link the contents of the DebugMap.
301   bool link(const DebugMap &);
302
303 private:
304   /// \brief Called at the start of a debug object link.
305   void startDebugObject(DWARFContext &);
306
307   /// \brief Called at the end of a debug object link.
308   void endDebugObject();
309
310   /// \defgroup FindValidRelocations Translate debug map into a list
311   /// of relevant relocations
312   ///
313   /// @{
314   struct ValidReloc {
315     uint32_t Offset;
316     uint32_t Size;
317     uint64_t Addend;
318     const DebugMapObject::DebugMapEntry *Mapping;
319
320     ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
321                const DebugMapObject::DebugMapEntry *Mapping)
322         : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
323
324     bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
325   };
326
327   /// \brief The valid relocations for the current DebugMapObject.
328   /// This vector is sorted by relocation offset.
329   std::vector<ValidReloc> ValidRelocs;
330
331   /// \brief Index into ValidRelocs of the next relocation to
332   /// consider. As we walk the DIEs in acsending file offset and as
333   /// ValidRelocs is sorted by file offset, keeping this index
334   /// uptodate is all we have to do to have a cheap lookup during the
335   /// root DIE selection.
336   unsigned NextValidReloc;
337
338   bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
339                                   const DebugMapObject &DMO);
340
341   bool findValidRelocs(const object::SectionRef &Section,
342                        const object::ObjectFile &Obj,
343                        const DebugMapObject &DMO);
344
345   void findValidRelocsMachO(const object::SectionRef &Section,
346                             const object::MachOObjectFile &Obj,
347                             const DebugMapObject &DMO);
348   /// @}
349
350   /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
351   ///
352   /// @{
353   /// \brief Recursively walk the \p DIE tree and look for DIEs to
354   /// keep. Store that information in \p CU's DIEInfo.
355   void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
356                          const DebugMapObject &DMO, CompileUnit &CU,
357                          unsigned Flags);
358
359   /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
360   enum TravesalFlags {
361     TF_Keep = 1 << 0,            ///< Mark the traversed DIEs as kept.
362     TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
363     TF_DependencyWalk = 1 << 2,  ///< Walking the dependencies of a kept DIE.
364     TF_ParentWalk = 1 << 3,      ///< Walking up the parents of a kept DIE.
365   };
366
367   /// \brief Mark the passed DIE as well as all the ones it depends on
368   /// as kept.
369   void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
370                                CompileUnit::DIEInfo &MyInfo,
371                                const DebugMapObject &DMO, CompileUnit &CU,
372                                unsigned Flags);
373
374   unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
375                          CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
376                          unsigned Flags);
377
378   unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
379                                  CompileUnit &Unit,
380                                  CompileUnit::DIEInfo &MyInfo, unsigned Flags);
381
382   unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
383                                    CompileUnit &Unit,
384                                    CompileUnit::DIEInfo &MyInfo,
385                                    unsigned Flags);
386
387   bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
388                           CompileUnit::DIEInfo &Info);
389   /// @}
390
391   /// \defgroup Linking Methods used to link the debug information
392   ///
393   /// @{
394   /// \brief Recursively clone \p InputDIE into an tree of DIE objects
395   /// where useless (as decided by lookForDIEsToKeep()) bits have been
396   /// stripped out and addresses have been rewritten according to the
397   /// debug map.
398   ///
399   /// \param OutOffset is the offset the cloned DIE in the output
400   /// compile unit.
401   ///
402   /// \returns the root of the cloned tree.
403   DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
404                 uint32_t OutOffset);
405
406   typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
407
408   /// \brief Helper for cloneDIE.
409   unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
410                           CompileUnit &U, const DWARFFormValue &Val,
411                           const AttributeSpec AttrSpec, unsigned AttrSize);
412
413   /// \brief Helper for cloneDIE.
414   unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec);
415
416   /// \brief Helper for cloneDIE.
417   unsigned cloneDieReferenceAttribute(DIE &Die, AttributeSpec AttrSpec,
418                                       unsigned AttrSize);
419
420   /// \brief Helper for cloneDIE.
421   unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
422                                const DWARFFormValue &Val, unsigned AttrSize);
423
424   /// \brief Helper for cloneDIE.
425   unsigned cloneScalarAttribute(DIE &Die,
426                                 const DWARFDebugInfoEntryMinimal &InputDIE,
427                                 const DWARFUnit &U, AttributeSpec AttrSpec,
428                                 const DWARFFormValue &Val, unsigned AttrSize);
429
430   /// \brief Assign an abbreviation number to \p Abbrev
431   void AssignAbbrev(DIEAbbrev &Abbrev);
432
433   /// \brief FoldingSet that uniques the abbreviations.
434   FoldingSet<DIEAbbrev> AbbreviationsSet;
435   /// \brief Storage for the unique Abbreviations.
436   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
437   /// be changed to a vecot of unique_ptrs.
438   std::vector<DIEAbbrev *> Abbreviations;
439
440   /// \brief DIELoc objects that need to be destructed (but not freed!).
441   std::vector<DIELoc *> DIELocs;
442   /// \brief DIEBlock objects that need to be destructed (but not freed!).
443   std::vector<DIEBlock *> DIEBlocks;
444   /// \brief Allocator used for all the DIEValue objects.
445   BumpPtrAllocator DIEAlloc;
446   /// @}
447
448   /// \defgroup Helpers Various helper methods.
449   ///
450   /// @{
451   const DWARFDebugInfoEntryMinimal *
452   resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
453                       const DWARFDebugInfoEntryMinimal &DIE,
454                       CompileUnit *&ReferencedCU);
455
456   CompileUnit *getUnitForOffset(unsigned Offset);
457
458   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
459                      const DWARFDebugInfoEntryMinimal *DIE = nullptr);
460
461   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
462   /// @}
463
464 private:
465   std::string OutputFilename;
466   LinkOptions Options;
467   BinaryHolder BinHolder;
468   std::unique_ptr<DwarfStreamer> Streamer;
469
470   /// The units of the current debug map object.
471   std::vector<CompileUnit> Units;
472
473   /// The debug map object curently under consideration.
474   DebugMapObject *CurrentDebugObject;
475 };
476
477 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
478 /// returning our CompileUnit object instead.
479 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
480   auto CU =
481       std::upper_bound(Units.begin(), Units.end(), Offset,
482                        [](uint32_t LHS, const CompileUnit &RHS) {
483                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
484                        });
485   return CU != Units.end() ? &*CU : nullptr;
486 }
487
488 /// \brief Resolve the DIE attribute reference that has been
489 /// extracted in \p RefValue. The resulting DIE migh be in another
490 /// CompileUnit which is stored into \p ReferencedCU.
491 /// \returns null if resolving fails for any reason.
492 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
493     DWARFFormValue &RefValue, const DWARFUnit &Unit,
494     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
495   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
496   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
497
498   if ((RefCU = getUnitForOffset(RefOffset)))
499     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
500       return RefDie;
501
502   reportWarning("could not find referenced DIE", &Unit, &DIE);
503   return nullptr;
504 }
505
506 /// \brief Report a warning to the user, optionaly including
507 /// information about a specific \p DIE related to the warning.
508 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
509                                 const DWARFDebugInfoEntryMinimal *DIE) {
510   StringRef Context = "<debug map>";
511   if (CurrentDebugObject)
512     Context = CurrentDebugObject->getObjectFilename();
513   warn(Warning, Context);
514
515   if (!Options.Verbose || !DIE)
516     return;
517
518   errs() << "    in DIE:\n";
519   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
520             6 /* Indent */);
521 }
522
523 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
524   if (Options.NoOutput)
525     return true;
526
527   Streamer = llvm::make_unique<DwarfStreamer>();
528   return Streamer->init(TheTriple, OutputFilename);
529 }
530
531 /// \brief Recursive helper to gather the child->parent relationships in the
532 /// original compile unit.
533 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
534                              unsigned ParentIdx, CompileUnit &CU) {
535   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
536   CU.getInfo(MyIdx).ParentIdx = ParentIdx;
537
538   if (DIE->hasChildren())
539     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
540          Child = Child->getSibling())
541       gatherDIEParents(Child, MyIdx, CU);
542 }
543
544 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
545   switch (Tag) {
546   default:
547     return false;
548   case dwarf::DW_TAG_subprogram:
549   case dwarf::DW_TAG_lexical_block:
550   case dwarf::DW_TAG_subroutine_type:
551   case dwarf::DW_TAG_structure_type:
552   case dwarf::DW_TAG_class_type:
553   case dwarf::DW_TAG_union_type:
554     return true;
555   }
556   llvm_unreachable("Invalid Tag");
557 }
558
559 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
560   Units.reserve(Dwarf.getNumCompileUnits());
561   NextValidReloc = 0;
562 }
563
564 void DwarfLinker::endDebugObject() {
565   Units.clear();
566   ValidRelocs.clear();
567
568   for (auto *Block : DIEBlocks)
569     Block->~DIEBlock();
570   for (auto *Loc : DIELocs)
571     Loc->~DIELoc();
572
573   DIEBlocks.clear();
574   DIELocs.clear();
575   DIEAlloc.Reset();
576 }
577
578 /// \brief Iterate over the relocations of the given \p Section and
579 /// store the ones that correspond to debug map entries into the
580 /// ValidRelocs array.
581 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
582                                        const object::MachOObjectFile &Obj,
583                                        const DebugMapObject &DMO) {
584   StringRef Contents;
585   Section.getContents(Contents);
586   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
587
588   for (const object::RelocationRef &Reloc : Section.relocations()) {
589     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
590     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
591     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
592     uint64_t Offset64;
593     if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
594       reportWarning(" unsupported relocation in debug_info section.");
595       continue;
596     }
597     uint32_t Offset = Offset64;
598     // Mach-o uses REL relocations, the addend is at the relocation offset.
599     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
600
601     auto Sym = Reloc.getSymbol();
602     if (Sym != Obj.symbol_end()) {
603       StringRef SymbolName;
604       if (Sym->getName(SymbolName)) {
605         reportWarning("error getting relocation symbol name.");
606         continue;
607       }
608       if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
609         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
610     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
611       // Do not store the addend. The addend was the address of the
612       // symbol in the object file, the address in the binary that is
613       // stored in the debug map doesn't need to be offseted.
614       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
615     }
616   }
617 }
618
619 /// \brief Dispatch the valid relocation finding logic to the
620 /// appropriate handler depending on the object file format.
621 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
622                                   const object::ObjectFile &Obj,
623                                   const DebugMapObject &DMO) {
624   // Dispatch to the right handler depending on the file type.
625   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
626     findValidRelocsMachO(Section, *MachOObj, DMO);
627   else
628     reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
629
630   if (ValidRelocs.empty())
631     return false;
632
633   // Sort the relocations by offset. We will walk the DIEs linearly in
634   // the file, this allows us to just keep an index in the relocation
635   // array that we advance during our walk, rather than resorting to
636   // some associative container. See DwarfLinker::NextValidReloc.
637   std::sort(ValidRelocs.begin(), ValidRelocs.end());
638   return true;
639 }
640
641 /// \brief Look for relocations in the debug_info section that match
642 /// entries in the debug map. These relocations will drive the Dwarf
643 /// link by indicating which DIEs refer to symbols present in the
644 /// linked binary.
645 /// \returns wether there are any valid relocations in the debug info.
646 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
647                                              const DebugMapObject &DMO) {
648   // Find the debug_info section.
649   for (const object::SectionRef &Section : Obj.sections()) {
650     StringRef SectionName;
651     Section.getName(SectionName);
652     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
653     if (SectionName != "debug_info")
654       continue;
655     return findValidRelocs(Section, Obj, DMO);
656   }
657   return false;
658 }
659
660 /// \brief Checks that there is a relocation against an actual debug
661 /// map entry between \p StartOffset and \p NextOffset.
662 ///
663 /// This function must be called with offsets in strictly ascending
664 /// order because it never looks back at relocations it already 'went past'.
665 /// \returns true and sets Info.InDebugMap if it is the case.
666 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
667                                      CompileUnit::DIEInfo &Info) {
668   assert(NextValidReloc == 0 ||
669          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
670   if (NextValidReloc >= ValidRelocs.size())
671     return false;
672
673   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
674
675   // We might need to skip some relocs that we didn't consider. For
676   // example the high_pc of a discarded DIE might contain a reloc that
677   // is in the list because it actually corresponds to the start of a
678   // function that is in the debug map.
679   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
680     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
681
682   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
683     return false;
684
685   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
686   if (Options.Verbose)
687     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
688            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
689                             ValidReloc.Mapping->getValue().ObjectAddress,
690                             ValidReloc.Mapping->getValue().BinaryAddress);
691
692   Info.Address =
693       ValidReloc.Mapping->getValue().BinaryAddress + ValidReloc.Addend;
694   Info.InDebugMap = true;
695   return true;
696 }
697
698 /// \brief Get the starting and ending (exclusive) offset for the
699 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
700 /// supposed to point to the position of the first attribute described
701 /// by \p Abbrev.
702 /// \return [StartOffset, EndOffset) as a pair.
703 static std::pair<uint32_t, uint32_t>
704 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
705                     unsigned Offset, const DWARFUnit &Unit) {
706   DataExtractor Data = Unit.getDebugInfoExtractor();
707
708   for (unsigned i = 0; i < Idx; ++i)
709     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
710
711   uint32_t End = Offset;
712   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
713
714   return std::make_pair(Offset, End);
715 }
716
717 /// \brief Check if a variable describing DIE should be kept.
718 /// \returns updated TraversalFlags.
719 unsigned DwarfLinker::shouldKeepVariableDIE(
720     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
721     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
722   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
723
724   // Global variables with constant value can always be kept.
725   if (!(Flags & TF_InFunctionScope) &&
726       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
727     MyInfo.InDebugMap = true;
728     return Flags | TF_Keep;
729   }
730
731   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
732   if (LocationIdx == -1U)
733     return Flags;
734
735   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
736   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
737   uint32_t LocationOffset, LocationEndOffset;
738   std::tie(LocationOffset, LocationEndOffset) =
739       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
740
741   // See if there is a relocation to a valid debug map entry inside
742   // this variable's location. The order is important here. We want to
743   // always check in the variable has a valid relocation, so that the
744   // DIEInfo is filled. However, we don't want a static variable in a
745   // function to force us to keep the enclosing function.
746   if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
747       (Flags & TF_InFunctionScope))
748     return Flags;
749
750   if (Options.Verbose)
751     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
752
753   return Flags | TF_Keep;
754 }
755
756 /// \brief Check if a function describing DIE should be kept.
757 /// \returns updated TraversalFlags.
758 unsigned DwarfLinker::shouldKeepSubprogramDIE(
759     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
760     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
761   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
762
763   Flags |= TF_InFunctionScope;
764
765   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
766   if (LowPcIdx == -1U)
767     return Flags;
768
769   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
770   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
771   uint32_t LowPcOffset, LowPcEndOffset;
772   std::tie(LowPcOffset, LowPcEndOffset) =
773       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
774
775   uint64_t LowPc =
776       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
777   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
778   if (LowPc == -1ULL ||
779       !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
780     return Flags;
781
782   if (Options.Verbose)
783     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
784
785   return Flags | TF_Keep;
786 }
787
788 /// \brief Check if a DIE should be kept.
789 /// \returns updated TraversalFlags.
790 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
791                                     CompileUnit &Unit,
792                                     CompileUnit::DIEInfo &MyInfo,
793                                     unsigned Flags) {
794   switch (DIE.getTag()) {
795   case dwarf::DW_TAG_constant:
796   case dwarf::DW_TAG_variable:
797     return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
798   case dwarf::DW_TAG_subprogram:
799     return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
800   case dwarf::DW_TAG_module:
801   case dwarf::DW_TAG_imported_module:
802   case dwarf::DW_TAG_imported_declaration:
803   case dwarf::DW_TAG_imported_unit:
804     // We always want to keep these.
805     return Flags | TF_Keep;
806   }
807
808   return Flags;
809 }
810
811 /// \brief Mark the passed DIE as well as all the ones it depends on
812 /// as kept.
813 ///
814 /// This function is called by lookForDIEsToKeep on DIEs that are
815 /// newly discovered to be needed in the link. It recursively calls
816 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
817 /// TraversalFlags to inform it that it's not doing the primary DIE
818 /// tree walk.
819 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
820                                           CompileUnit::DIEInfo &MyInfo,
821                                           const DebugMapObject &DMO,
822                                           CompileUnit &CU, unsigned Flags) {
823   const DWARFUnit &Unit = CU.getOrigUnit();
824   MyInfo.Keep = true;
825
826   // First mark all the parent chain as kept.
827   unsigned AncestorIdx = MyInfo.ParentIdx;
828   while (!CU.getInfo(AncestorIdx).Keep) {
829     lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
830                       TF_ParentWalk | TF_Keep | TF_DependencyWalk);
831     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
832   }
833
834   // Then we need to mark all the DIEs referenced by this DIE's
835   // attributes as kept.
836   DataExtractor Data = Unit.getDebugInfoExtractor();
837   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
838   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
839
840   // Mark all DIEs referenced through atttributes as kept.
841   for (const auto &AttrSpec : Abbrev->attributes()) {
842     DWARFFormValue Val(AttrSpec.Form);
843
844     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
845       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
846       continue;
847     }
848
849     Val.extractValue(Data, &Offset, &Unit);
850     CompileUnit *ReferencedCU;
851     if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
852       lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
853                         TF_Keep | TF_DependencyWalk);
854   }
855 }
856
857 /// \brief Recursively walk the \p DIE tree and look for DIEs to
858 /// keep. Store that information in \p CU's DIEInfo.
859 ///
860 /// This function is the entry point of the DIE selection
861 /// algorithm. It is expected to walk the DIE tree in file order and
862 /// (though the mediation of its helper) call hasValidRelocation() on
863 /// each DIE that might be a 'root DIE' (See DwarfLinker class
864 /// comment).
865 /// While walking the dependencies of root DIEs, this function is
866 /// also called, but during these dependency walks the file order is
867 /// not respected. The TF_DependencyWalk flag tells us which kind of
868 /// traversal we are currently doing.
869 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
870                                     const DebugMapObject &DMO, CompileUnit &CU,
871                                     unsigned Flags) {
872   unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
873   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
874   bool AlreadyKept = MyInfo.Keep;
875
876   // If the Keep flag is set, we are marking a required DIE's
877   // dependencies. If our target is already marked as kept, we're all
878   // set.
879   if ((Flags & TF_DependencyWalk) && AlreadyKept)
880     return;
881
882   // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
883   // because it would screw up the relocation finding logic.
884   if (!(Flags & TF_DependencyWalk))
885     Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
886
887   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
888   if (!AlreadyKept && (Flags & TF_Keep))
889     keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
890
891   // The TF_ParentWalk flag tells us that we are currently walking up
892   // the parent chain of a required DIE, and we don't want to mark all
893   // the children of the parents as kept (consider for example a
894   // DW_TAG_namespace node in the parent chain). There are however a
895   // set of DIE types for which we want to ignore that directive and still
896   // walk their children.
897   if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
898     Flags &= ~TF_ParentWalk;
899
900   if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
901     return;
902
903   for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
904        Child = Child->getSibling())
905     lookForDIEsToKeep(*Child, DMO, CU, Flags);
906 }
907
908 /// \brief Assign an abbreviation numer to \p Abbrev.
909 ///
910 /// Our DIEs get freed after every DebugMapObject has been processed,
911 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
912 /// the instances hold by the DIEs. When we encounter an abbreviation
913 /// that we don't know, we create a permanent copy of it.
914 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
915   // Check the set for priors.
916   FoldingSetNodeID ID;
917   Abbrev.Profile(ID);
918   void *InsertToken;
919   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
920
921   // If it's newly added.
922   if (InSet) {
923     // Assign existing abbreviation number.
924     Abbrev.setNumber(InSet->getNumber());
925   } else {
926     // Add to abbreviation list.
927     Abbreviations.push_back(
928         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
929     for (const auto &Attr : Abbrev.getData())
930       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
931     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
932     // Assign the unique abbreviation number.
933     Abbrev.setNumber(Abbreviations.size());
934     Abbreviations.back()->setNumber(Abbreviations.size());
935   }
936 }
937
938 /// \brief Clone a string attribute described by \p AttrSpec and add
939 /// it to \p Die.
940 /// \returns the size of the new attribute.
941 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec) {
942   // Switch everything to out of line strings.
943   // FIXME: Construct the actual string table.
944   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
945                new (DIEAlloc) DIEInteger(0));
946   return 4;
947 }
948
949 /// \brief Clone an attribute referencing another DIE and add
950 /// it to \p Die.
951 /// \returns the size of the new attribute.
952 unsigned DwarfLinker::cloneDieReferenceAttribute(DIE &Die,
953                                                  AttributeSpec AttrSpec,
954                                                  unsigned AttrSize) {
955   // FIXME: Handle DIE references.
956   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
957                new (DIEAlloc) DIEInteger(0));
958   return AttrSize;
959 }
960
961 /// \brief Clone an attribute of block form (locations, constants) and add
962 /// it to \p Die.
963 /// \returns the size of the new attribute.
964 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
965                                           const DWARFFormValue &Val,
966                                           unsigned AttrSize) {
967   DIE *Attr;
968   DIEValue *Value;
969   DIELoc *Loc = nullptr;
970   DIEBlock *Block = nullptr;
971   // Just copy the block data over.
972   if (AttrSpec.Attr == dwarf::DW_FORM_exprloc) {
973     Loc = new (DIEAlloc) DIELoc();
974     DIELocs.push_back(Loc);
975   } else {
976     Block = new (DIEAlloc) DIEBlock();
977     DIEBlocks.push_back(Block);
978   }
979   Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
980   Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
981   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
982   for (auto Byte : Bytes)
983     Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
984                    new (DIEAlloc) DIEInteger(Byte));
985   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
986   // the DIE class, this if could be replaced by
987   // Attr->setSize(Bytes.size()).
988   if (Streamer) {
989     if (Loc)
990       Loc->ComputeSize(&Streamer->getAsmPrinter());
991     else
992       Block->ComputeSize(&Streamer->getAsmPrinter());
993   }
994   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
995                Value);
996   return AttrSize;
997 }
998
999 /// \brief Clone a scalar attribute  and add it to \p Die.
1000 /// \returns the size of the new attribute.
1001 unsigned DwarfLinker::cloneScalarAttribute(
1002     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1003     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1004   uint64_t Value;
1005   if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1006     Value = *Val.getAsSectionOffset();
1007   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1008     Value = *Val.getAsSignedConstant();
1009   else if (AttrSpec.Form == dwarf::DW_FORM_addr)
1010     Value = *Val.getAsAddress(&U);
1011   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1012     Value = *OptionalValue;
1013   else {
1014     reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1015                   &InputDIE);
1016     return 0;
1017   }
1018   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1019                new (DIEAlloc) DIEInteger(Value));
1020   return AttrSize;
1021 }
1022
1023 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1024 /// value \p Val, and add it to \p Die.
1025 /// \returns the size of the cloned attribute.
1026 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1027                                      const DWARFDebugInfoEntryMinimal &InputDIE,
1028                                      CompileUnit &Unit,
1029                                      const DWARFFormValue &Val,
1030                                      const AttributeSpec AttrSpec,
1031                                      unsigned AttrSize) {
1032   const DWARFUnit &U = Unit.getOrigUnit();
1033
1034   switch (AttrSpec.Form) {
1035   case dwarf::DW_FORM_strp:
1036   case dwarf::DW_FORM_string:
1037     return cloneStringAttribute(Die, AttrSpec);
1038   case dwarf::DW_FORM_ref_addr:
1039   case dwarf::DW_FORM_ref1:
1040   case dwarf::DW_FORM_ref2:
1041   case dwarf::DW_FORM_ref4:
1042   case dwarf::DW_FORM_ref8:
1043     return cloneDieReferenceAttribute(Die, AttrSpec, AttrSize);
1044   case dwarf::DW_FORM_block:
1045   case dwarf::DW_FORM_block1:
1046   case dwarf::DW_FORM_block2:
1047   case dwarf::DW_FORM_block4:
1048   case dwarf::DW_FORM_exprloc:
1049     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1050   case dwarf::DW_FORM_addr:
1051   case dwarf::DW_FORM_data1:
1052   case dwarf::DW_FORM_data2:
1053   case dwarf::DW_FORM_data4:
1054   case dwarf::DW_FORM_data8:
1055   case dwarf::DW_FORM_udata:
1056   case dwarf::DW_FORM_sdata:
1057   case dwarf::DW_FORM_sec_offset:
1058   case dwarf::DW_FORM_flag:
1059   case dwarf::DW_FORM_flag_present:
1060     return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1061   default:
1062     reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1063                   &InputDIE);
1064   }
1065
1066   return 0;
1067 }
1068
1069 /// \brief Recursively clone \p InputDIE's subtrees that have been
1070 /// selected to appear in the linked output.
1071 ///
1072 /// \param OutOffset is the Offset where the newly created DIE will
1073 /// lie in the linked compile unit.
1074 ///
1075 /// \returns the cloned DIE object or null if nothing was selected.
1076 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1077                            CompileUnit &Unit, uint32_t OutOffset) {
1078   DWARFUnit &U = Unit.getOrigUnit();
1079   unsigned Idx = U.getDIEIndex(&InputDIE);
1080
1081   // Should the DIE appear in the output?
1082   if (!Unit.getInfo(Idx).Keep)
1083     return nullptr;
1084
1085   uint32_t Offset = InputDIE.getOffset();
1086
1087   DIE *Die = new DIE(static_cast<dwarf::Tag>(InputDIE.getTag()));
1088   Die->setOffset(OutOffset);
1089
1090   // Extract and clone every attribute.
1091   DataExtractor Data = U.getDebugInfoExtractor();
1092   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1093   Offset += getULEB128Size(Abbrev->getCode());
1094
1095   for (const auto &AttrSpec : Abbrev->attributes()) {
1096     DWARFFormValue Val(AttrSpec.Form);
1097     uint32_t AttrSize = Offset;
1098     Val.extractValue(Data, &Offset, &U);
1099     AttrSize = Offset - AttrSize;
1100
1101     OutOffset += cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize);
1102   }
1103
1104   DIEAbbrev &NewAbbrev = Die->getAbbrev();
1105   // If a scope DIE is kept, we must have kept at least one child. If
1106   // it's not the case, we'll just be emitting one wasteful end of
1107   // children marker, but things won't break.
1108   if (InputDIE.hasChildren())
1109     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1110   // Assign a permanent abbrev number
1111   AssignAbbrev(Die->getAbbrev());
1112
1113   // Add the size of the abbreviation number to the output offset.
1114   OutOffset += getULEB128Size(Die->getAbbrevNumber());
1115
1116   if (!Abbrev->hasChildren()) {
1117     // Update our size.
1118     Die->setSize(OutOffset - Die->getOffset());
1119     return Die;
1120   }
1121
1122   // Recursively clone children.
1123   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1124        Child = Child->getSibling()) {
1125     if (DIE *Clone = cloneDIE(*Child, Unit, OutOffset)) {
1126       Die->addChild(std::unique_ptr<DIE>(Clone));
1127       OutOffset = Clone->getOffset() + Clone->getSize();
1128     }
1129   }
1130
1131   // Account for the end of children marker.
1132   OutOffset += sizeof(int8_t);
1133   // Update our size.
1134   Die->setSize(OutOffset - Die->getOffset());
1135   return Die;
1136 }
1137
1138 bool DwarfLinker::link(const DebugMap &Map) {
1139
1140   if (Map.begin() == Map.end()) {
1141     errs() << "Empty debug map.\n";
1142     return false;
1143   }
1144
1145   if (!createStreamer(Map.getTriple(), OutputFilename))
1146     return false;
1147
1148   // Size of the DIEs (and headers) generated for the linked output.
1149   uint64_t OutputDebugInfoSize = 0;
1150
1151   for (const auto &Obj : Map.objects()) {
1152     CurrentDebugObject = Obj.get();
1153
1154     if (Options.Verbose)
1155       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1156     auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1157     if (std::error_code EC = ErrOrObj.getError()) {
1158       reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1159       continue;
1160     }
1161
1162     // Look for relocations that correspond to debug map entries.
1163     if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1164       if (Options.Verbose)
1165         outs() << "No valid relocations found. Skipping.\n";
1166       continue;
1167     }
1168
1169     // Setup access to the debug info.
1170     DWARFContextInMemory DwarfContext(*ErrOrObj);
1171     startDebugObject(DwarfContext);
1172
1173     // In a first phase, just read in the debug info and store the DIE
1174     // parent links that we will use during the next phase.
1175     for (const auto &CU : DwarfContext.compile_units()) {
1176       auto *CUDie = CU->getCompileUnitDIE(false);
1177       if (Options.Verbose) {
1178         outs() << "Input compilation unit:";
1179         CUDie->dump(outs(), CU.get(), 0);
1180       }
1181       Units.emplace_back(*CU);
1182       gatherDIEParents(CUDie, 0, Units.back());
1183     }
1184
1185     // Then mark all the DIEs that need to be present in the linked
1186     // output and collect some information about them. Note that this
1187     // loop can not be merged with the previous one becaue cross-cu
1188     // references require the ParentIdx to be setup for every CU in
1189     // the object file before calling this.
1190     for (auto &CurrentUnit : Units)
1191       lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1192                         CurrentUnit, 0);
1193
1194     // Construct the output DIE tree by cloning the DIEs we chose to
1195     // keep above. If there are no valid relocs, then there's nothing
1196     // to clone/emit.
1197     if (!ValidRelocs.empty())
1198       for (auto &CurrentUnit : Units) {
1199         const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1200         DIE *OutputDIE =
1201             cloneDIE(*InputDIE, CurrentUnit, 11 /* Unit Header size */);
1202         CurrentUnit.setOutputUnitDIE(OutputDIE);
1203         OutputDebugInfoSize = CurrentUnit.computeOffsets(OutputDebugInfoSize);
1204       }
1205
1206     // Emit all the compile unit's debug information.
1207     if (!ValidRelocs.empty() && !Options.NoOutput)
1208       for (auto &CurrentUnit : Units) {
1209         Streamer->emitCompileUnitHeader(CurrentUnit);
1210         if (!CurrentUnit.getOutputUnitDIE())
1211           continue;
1212         Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1213       }
1214
1215     // Clean-up before starting working on the next object.
1216     endDebugObject();
1217   }
1218
1219   // Emit everything that's global.
1220   if (!Options.NoOutput)
1221     Streamer->emitAbbrevs(Abbreviations);
1222
1223   return Options.NoOutput ? true : Streamer->finish();
1224 }
1225 }
1226
1227 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1228                const LinkOptions &Options) {
1229   DwarfLinker Linker(OutputFilename, Options);
1230   return Linker.link(DM);
1231 }
1232 }
1233 }