[dsymutil] Add relocation of compile_units low_pc/high_pc.
[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/ADT/IntervalMap.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCObjectFileInfo.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Object/MachO.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include <string>
36
37 namespace llvm {
38 namespace dsymutil {
39
40 namespace {
41
42 void warn(const Twine &Warning, const Twine &Context) {
43   errs() << Twine("while processing ") + Context + ":\n";
44   errs() << Twine("warning: ") + Warning + "\n";
45 }
46
47 bool error(const Twine &Error, const Twine &Context) {
48   errs() << Twine("while processing ") + Context + ":\n";
49   errs() << Twine("error: ") + Error + "\n";
50   return false;
51 }
52
53 template <typename KeyT, typename ValT>
54 using HalfOpenIntervalMap =
55     IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
56                 IntervalMapHalfOpenInfo<KeyT>>;
57
58 /// \brief Stores all information relating to a compile unit, be it in
59 /// its original instance in the object file to its brand new cloned
60 /// and linked DIE tree.
61 class CompileUnit {
62 public:
63   /// \brief Information gathered about a DIE in the object file.
64   struct DIEInfo {
65     int64_t AddrAdjust; ///< Address offset to apply to the described entity.
66     DIE *Clone;         ///< Cloned version of that DIE.
67     uint32_t ParentIdx; ///< The index of this DIE's parent.
68     bool Keep;          ///< Is the DIE part of the linked output?
69     bool InDebugMap;    ///< Was this DIE's entity found in the map?
70   };
71
72   CompileUnit(DWARFUnit &OrigUnit)
73     : OrigUnit(OrigUnit), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
74       Ranges(RangeAlloc) {
75     Info.resize(OrigUnit.getNumDIEs());
76   }
77
78   CompileUnit(CompileUnit &&RHS)
79       : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
80         CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
81         NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
82     // The CompileUnit container has been 'reserve()'d with the right
83     // size. We cannot move the IntervalMap anyway.
84     llvm_unreachable("CompileUnits should not be moved.");
85   }
86
87   DWARFUnit &getOrigUnit() const { return OrigUnit; }
88
89   DIE *getOutputUnitDIE() const { return CUDie.get(); }
90   void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
91
92   DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
93   const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
94
95   uint64_t getStartOffset() const { return StartOffset; }
96   uint64_t getNextUnitOffset() const { return NextUnitOffset; }
97
98   uint64_t getLowPc() const { return LowPc; }
99   uint64_t getHighPc() const { return HighPc; }
100
101   void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
102
103   /// \brief Compute the end offset for this unit. Must be
104   /// called after the CU's DIEs have been cloned.
105   /// \returns the next unit offset (which is also the current
106   /// debug_info section size).
107   uint64_t computeNextUnitOffset();
108
109   /// \brief Keep track of a forward reference to DIE \p Die by
110   /// \p Attr. The attribute should be fixed up later to point to the
111   /// absolute offset of \p Die in the debug_info section.
112   void noteForwardReference(DIE *Die, DIEInteger *Attr);
113
114   /// \brief Apply all fixups recored by noteForwardReference().
115   void fixupForwardReferences();
116
117   /// \brief Add a function range [\p LowPC, \p HighPC) that is
118   /// relocatad by applying offset \p PCOffset.
119   void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
120
121 private:
122   DWARFUnit &OrigUnit;
123   std::vector<DIEInfo> Info;  ///< DIE info indexed by DIE index.
124   std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
125
126   uint64_t StartOffset;
127   uint64_t NextUnitOffset;
128
129   uint64_t LowPc;
130   uint64_t HighPc;
131
132   /// \brief A list of attributes to fixup with the absolute offset of
133   /// a DIE in the debug_info section.
134   ///
135   /// The offsets for the attributes in this array couldn't be set while
136   /// cloning because for forward refences the target DIE's offset isn't
137   /// known you emit the reference attribute.
138   std::vector<std::pair<DIE *, DIEInteger *>> ForwardDIEReferences;
139
140   HalfOpenIntervalMap<uint64_t, int64_t>::Allocator RangeAlloc;
141   /// \brief The ranges in that interval map are the PC ranges for
142   /// functions in this unit, associated with the PC offset to apply
143   /// to the addresses to get the linked address.
144   HalfOpenIntervalMap<uint64_t, int64_t> Ranges;
145 };
146
147 uint64_t CompileUnit::computeNextUnitOffset() {
148   NextUnitOffset = StartOffset + 11 /* Header size */;
149   // The root DIE might be null, meaning that the Unit had nothing to
150   // contribute to the linked output. In that case, we will emit the
151   // unit header without any actual DIE.
152   if (CUDie)
153     NextUnitOffset += CUDie->getSize();
154   return NextUnitOffset;
155 }
156
157 /// \brief Keep track of a forward reference to \p Die.
158 void CompileUnit::noteForwardReference(DIE *Die, DIEInteger *Attr) {
159   ForwardDIEReferences.emplace_back(Die, Attr);
160 }
161
162 /// \brief Apply all fixups recorded by noteForwardReference().
163 void CompileUnit::fixupForwardReferences() {
164   for (const auto &Ref : ForwardDIEReferences)
165     Ref.second->setValue(Ref.first->getOffset() + getStartOffset());
166 }
167
168 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
169                                    int64_t PcOffset) {
170   Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
171   this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
172   this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
173 }
174
175 /// \brief A string table that doesn't need relocations.
176 ///
177 /// We are doing a final link, no need for a string table that
178 /// has relocation entries for every reference to it. This class
179 /// provides this ablitity by just associating offsets with
180 /// strings.
181 class NonRelocatableStringpool {
182 public:
183   /// \brief Entries are stored into the StringMap and simply linked
184   /// together through the second element of this pair in order to
185   /// keep track of insertion order.
186   typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
187       MapTy;
188
189   NonRelocatableStringpool()
190       : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
191     // Legacy dsymutil puts an empty string at the start of the line
192     // table.
193     getStringOffset("");
194   }
195
196   /// \brief Get the offset of string \p S in the string table. This
197   /// can insert a new element or return the offset of a preexisitng
198   /// one.
199   uint32_t getStringOffset(StringRef S);
200
201   /// \brief Get permanent storage for \p S (but do not necessarily
202   /// emit \p S in the output section).
203   /// \returns The StringRef that points to permanent storage to use
204   /// in place of \p S.
205   StringRef internString(StringRef S);
206
207   // \brief Return the first entry of the string table.
208   const MapTy::MapEntryTy *getFirstEntry() const {
209     return getNextEntry(&Sentinel);
210   }
211
212   // \brief Get the entry following \p E in the string table or null
213   // if \p E was the last entry.
214   const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
215     return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
216   }
217
218   uint64_t getSize() { return CurrentEndOffset; }
219
220 private:
221   MapTy Strings;
222   uint32_t CurrentEndOffset;
223   MapTy::MapEntryTy Sentinel, *Last;
224 };
225
226 /// \brief Get the offset of string \p S in the string table. This
227 /// can insert a new element or return the offset of a preexisitng
228 /// one.
229 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
230   if (S.empty() && !Strings.empty())
231     return 0;
232
233   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
234   MapTy::iterator It;
235   bool Inserted;
236
237   // A non-empty string can't be at offset 0, so if we have an entry
238   // with a 0 offset, it must be a previously interned string.
239   std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
240   if (Inserted || It->getValue().first == 0) {
241     // Set offset and chain at the end of the entries list.
242     It->getValue().first = CurrentEndOffset;
243     CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
244     Last->getValue().second = &*It;
245     Last = &*It;
246   }
247   return It->getValue().first;
248 }
249
250 /// \brief Put \p S into the StringMap so that it gets permanent
251 /// storage, but do not actually link it in the chain of elements
252 /// that go into the output section. A latter call to
253 /// getStringOffset() with the same string will chain it though.
254 StringRef NonRelocatableStringpool::internString(StringRef S) {
255   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
256   auto InsertResult = Strings.insert(std::make_pair(S, Entry));
257   return InsertResult.first->getKey();
258 }
259
260 /// \brief The Dwarf streaming logic
261 ///
262 /// All interactions with the MC layer that is used to build the debug
263 /// information binary representation are handled in this class.
264 class DwarfStreamer {
265   /// \defgroup MCObjects MC layer objects constructed by the streamer
266   /// @{
267   std::unique_ptr<MCRegisterInfo> MRI;
268   std::unique_ptr<MCAsmInfo> MAI;
269   std::unique_ptr<MCObjectFileInfo> MOFI;
270   std::unique_ptr<MCContext> MC;
271   MCAsmBackend *MAB; // Owned by MCStreamer
272   std::unique_ptr<MCInstrInfo> MII;
273   std::unique_ptr<MCSubtargetInfo> MSTI;
274   MCCodeEmitter *MCE; // Owned by MCStreamer
275   MCStreamer *MS;     // Owned by AsmPrinter
276   std::unique_ptr<TargetMachine> TM;
277   std::unique_ptr<AsmPrinter> Asm;
278   /// @}
279
280   /// \brief the file we stream the linked Dwarf to.
281   std::unique_ptr<raw_fd_ostream> OutFile;
282
283 public:
284   /// \brief Actually create the streamer and the ouptut file.
285   ///
286   /// This could be done directly in the constructor, but it feels
287   /// more natural to handle errors through return value.
288   bool init(Triple TheTriple, StringRef OutputFilename);
289
290   /// \brief Dump the file to the disk.
291   bool finish();
292
293   AsmPrinter &getAsmPrinter() const { return *Asm; }
294
295   /// \brief Set the current output section to debug_info and change
296   /// the MC Dwarf version to \p DwarfVersion.
297   void switchToDebugInfoSection(unsigned DwarfVersion);
298
299   /// \brief Emit the compilation unit header for \p Unit in the
300   /// debug_info section.
301   ///
302   /// As a side effect, this also switches the current Dwarf version
303   /// of the MC layer to the one of U.getOrigUnit().
304   void emitCompileUnitHeader(CompileUnit &Unit);
305
306   /// \brief Recursively emit the DIE tree rooted at \p Die.
307   void emitDIE(DIE &Die);
308
309   /// \brief Emit the abbreviation table \p Abbrevs to the
310   /// debug_abbrev section.
311   void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
312
313   /// \brief Emit the string table described by \p Pool.
314   void emitStrings(const NonRelocatableStringpool &Pool);
315 };
316
317 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
318   std::string ErrorStr;
319   std::string TripleName;
320   StringRef Context = "dwarf streamer init";
321
322   // Get the target.
323   const Target *TheTarget =
324       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
325   if (!TheTarget)
326     return error(ErrorStr, Context);
327   TripleName = TheTriple.getTriple();
328
329   // Create all the MC Objects.
330   MRI.reset(TheTarget->createMCRegInfo(TripleName));
331   if (!MRI)
332     return error(Twine("no register info for target ") + TripleName, Context);
333
334   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
335   if (!MAI)
336     return error("no asm info for target " + TripleName, Context);
337
338   MOFI.reset(new MCObjectFileInfo);
339   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
340   MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
341                              *MC);
342
343   MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
344   if (!MAB)
345     return error("no asm backend for target " + TripleName, Context);
346
347   MII.reset(TheTarget->createMCInstrInfo());
348   if (!MII)
349     return error("no instr info info for target " + TripleName, Context);
350
351   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
352   if (!MSTI)
353     return error("no subtarget info for target " + TripleName, Context);
354
355   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
356   if (!MCE)
357     return error("no code emitter for target " + TripleName, Context);
358
359   // Create the output file.
360   std::error_code EC;
361   OutFile =
362       llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
363   if (EC)
364     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
365
366   MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
367                                          *MSTI, false);
368   if (!MS)
369     return error("no object streamer for target " + TripleName, Context);
370
371   // Finally create the AsmPrinter we'll use to emit the DIEs.
372   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
373   if (!TM)
374     return error("no target machine for target " + TripleName, Context);
375
376   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
377   if (!Asm)
378     return error("no asm printer for target " + TripleName, Context);
379
380   return true;
381 }
382
383 bool DwarfStreamer::finish() {
384   MS->Finish();
385   return true;
386 }
387
388 /// \brief Set the current output section to debug_info and change
389 /// the MC Dwarf version to \p DwarfVersion.
390 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
391   MS->SwitchSection(MOFI->getDwarfInfoSection());
392   MC->setDwarfVersion(DwarfVersion);
393 }
394
395 /// \brief Emit the compilation unit header for \p Unit in the
396 /// debug_info section.
397 ///
398 /// A Dwarf scetion header is encoded as:
399 ///  uint32_t   Unit length (omiting this field)
400 ///  uint16_t   Version
401 ///  uint32_t   Abbreviation table offset
402 ///  uint8_t    Address size
403 ///
404 /// Leading to a total of 11 bytes.
405 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
406   unsigned Version = Unit.getOrigUnit().getVersion();
407   switchToDebugInfoSection(Version);
408
409   // Emit size of content not including length itself. The size has
410   // already been computed in CompileUnit::computeOffsets(). Substract
411   // 4 to that size to account for the length field.
412   Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
413   Asm->EmitInt16(Version);
414   // We share one abbreviations table across all units so it's always at the
415   // start of the section.
416   Asm->EmitInt32(0);
417   Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
418 }
419
420 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
421 /// for the linked Dwarf file.
422 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
423   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
424   Asm->emitDwarfAbbrevs(Abbrevs);
425 }
426
427 /// \brief Recursively emit the DIE tree rooted at \p Die.
428 void DwarfStreamer::emitDIE(DIE &Die) {
429   MS->SwitchSection(MOFI->getDwarfInfoSection());
430   Asm->emitDwarfDIE(Die);
431 }
432
433 /// \brief Emit the debug_str section stored in \p Pool.
434 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
435   Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
436   for (auto *Entry = Pool.getFirstEntry(); Entry;
437        Entry = Pool.getNextEntry(Entry))
438     Asm->OutStreamer.EmitBytes(
439         StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
440 }
441
442 /// \brief The core of the Dwarf linking logic.
443 ///
444 /// The link of the dwarf information from the object files will be
445 /// driven by the selection of 'root DIEs', which are DIEs that
446 /// describe variables or functions that are present in the linked
447 /// binary (and thus have entries in the debug map). All the debug
448 /// information that will be linked (the DIEs, but also the line
449 /// tables, ranges, ...) is derived from that set of root DIEs.
450 ///
451 /// The root DIEs are identified because they contain relocations that
452 /// correspond to a debug map entry at specific places (the low_pc for
453 /// a function, the location for a variable). These relocations are
454 /// called ValidRelocs in the DwarfLinker and are gathered as a very
455 /// first step when we start processing a DebugMapObject.
456 class DwarfLinker {
457 public:
458   DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
459       : OutputFilename(OutputFilename), Options(Options),
460         BinHolder(Options.Verbose) {}
461
462   ~DwarfLinker() {
463     for (auto *Abbrev : Abbreviations)
464       delete Abbrev;
465   }
466
467   /// \brief Link the contents of the DebugMap.
468   bool link(const DebugMap &);
469
470 private:
471   /// \brief Called at the start of a debug object link.
472   void startDebugObject(DWARFContext &);
473
474   /// \brief Called at the end of a debug object link.
475   void endDebugObject();
476
477   /// \defgroup FindValidRelocations Translate debug map into a list
478   /// of relevant relocations
479   ///
480   /// @{
481   struct ValidReloc {
482     uint32_t Offset;
483     uint32_t Size;
484     uint64_t Addend;
485     const DebugMapObject::DebugMapEntry *Mapping;
486
487     ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
488                const DebugMapObject::DebugMapEntry *Mapping)
489         : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
490
491     bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
492   };
493
494   /// \brief The valid relocations for the current DebugMapObject.
495   /// This vector is sorted by relocation offset.
496   std::vector<ValidReloc> ValidRelocs;
497
498   /// \brief Index into ValidRelocs of the next relocation to
499   /// consider. As we walk the DIEs in acsending file offset and as
500   /// ValidRelocs is sorted by file offset, keeping this index
501   /// uptodate is all we have to do to have a cheap lookup during the
502   /// root DIE selection and during DIE cloning.
503   unsigned NextValidReloc;
504
505   bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
506                                   const DebugMapObject &DMO);
507
508   bool findValidRelocs(const object::SectionRef &Section,
509                        const object::ObjectFile &Obj,
510                        const DebugMapObject &DMO);
511
512   void findValidRelocsMachO(const object::SectionRef &Section,
513                             const object::MachOObjectFile &Obj,
514                             const DebugMapObject &DMO);
515   /// @}
516
517   /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
518   ///
519   /// @{
520   /// \brief Recursively walk the \p DIE tree and look for DIEs to
521   /// keep. Store that information in \p CU's DIEInfo.
522   void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
523                          const DebugMapObject &DMO, CompileUnit &CU,
524                          unsigned Flags);
525
526   /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
527   enum TravesalFlags {
528     TF_Keep = 1 << 0,            ///< Mark the traversed DIEs as kept.
529     TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
530     TF_DependencyWalk = 1 << 2,  ///< Walking the dependencies of a kept DIE.
531     TF_ParentWalk = 1 << 3,      ///< Walking up the parents of a kept DIE.
532   };
533
534   /// \brief Mark the passed DIE as well as all the ones it depends on
535   /// as kept.
536   void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
537                                CompileUnit::DIEInfo &MyInfo,
538                                const DebugMapObject &DMO, CompileUnit &CU,
539                                unsigned Flags);
540
541   unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
542                          CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
543                          unsigned Flags);
544
545   unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
546                                  CompileUnit &Unit,
547                                  CompileUnit::DIEInfo &MyInfo, unsigned Flags);
548
549   unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
550                                    CompileUnit &Unit,
551                                    CompileUnit::DIEInfo &MyInfo,
552                                    unsigned Flags);
553
554   bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
555                           CompileUnit::DIEInfo &Info);
556   /// @}
557
558   /// \defgroup Linking Methods used to link the debug information
559   ///
560   /// @{
561   /// \brief Recursively clone \p InputDIE into an tree of DIE objects
562   /// where useless (as decided by lookForDIEsToKeep()) bits have been
563   /// stripped out and addresses have been rewritten according to the
564   /// debug map.
565   ///
566   /// \param OutOffset is the offset the cloned DIE in the output
567   /// compile unit.
568   /// \param PCOffset (while cloning a function scope) is the offset
569   /// applied to the entry point of the function to get the linked address.
570   ///
571   /// \returns the root of the cloned tree.
572   DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
573                 int64_t PCOffset, uint32_t OutOffset);
574
575   typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
576
577   /// \brief Information gathered and exchanged between the various
578   /// clone*Attributes helpers about the attributes of a particular DIE.
579   struct AttributesInfo {
580     uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
581     int64_t PCOffset;    ///< Offset to apply to PC addresses inside a function.
582
583     AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
584   };
585
586   /// \brief Helper for cloneDIE.
587   unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
588                           CompileUnit &U, const DWARFFormValue &Val,
589                           const AttributeSpec AttrSpec, unsigned AttrSize,
590                           AttributesInfo &AttrInfo);
591
592   /// \brief Helper for cloneDIE.
593   unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
594                                 const DWARFFormValue &Val, const DWARFUnit &U);
595
596   /// \brief Helper for cloneDIE.
597   unsigned
598   cloneDieReferenceAttribute(DIE &Die,
599                              const DWARFDebugInfoEntryMinimal &InputDIE,
600                              AttributeSpec AttrSpec, unsigned AttrSize,
601                              const DWARFFormValue &Val, const DWARFUnit &U);
602
603   /// \brief Helper for cloneDIE.
604   unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
605                                const DWARFFormValue &Val, unsigned AttrSize);
606
607   /// \brief Helper for cloneDIE.
608   unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
609                                  const DWARFFormValue &Val,
610                                  const CompileUnit &Unit, AttributesInfo &Info);
611
612   /// \brief Helper for cloneDIE.
613   unsigned cloneScalarAttribute(DIE &Die,
614                                 const DWARFDebugInfoEntryMinimal &InputDIE,
615                                 const CompileUnit &U, AttributeSpec AttrSpec,
616                                 const DWARFFormValue &Val, unsigned AttrSize);
617
618   /// \brief Helper for cloneDIE.
619   bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
620                         bool isLittleEndian);
621
622   /// \brief Assign an abbreviation number to \p Abbrev
623   void AssignAbbrev(DIEAbbrev &Abbrev);
624
625   /// \brief FoldingSet that uniques the abbreviations.
626   FoldingSet<DIEAbbrev> AbbreviationsSet;
627   /// \brief Storage for the unique Abbreviations.
628   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
629   /// be changed to a vecot of unique_ptrs.
630   std::vector<DIEAbbrev *> Abbreviations;
631
632   /// \brief DIELoc objects that need to be destructed (but not freed!).
633   std::vector<DIELoc *> DIELocs;
634   /// \brief DIEBlock objects that need to be destructed (but not freed!).
635   std::vector<DIEBlock *> DIEBlocks;
636   /// \brief Allocator used for all the DIEValue objects.
637   BumpPtrAllocator DIEAlloc;
638   /// @}
639
640   /// \defgroup Helpers Various helper methods.
641   ///
642   /// @{
643   const DWARFDebugInfoEntryMinimal *
644   resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
645                       const DWARFDebugInfoEntryMinimal &DIE,
646                       CompileUnit *&ReferencedCU);
647
648   CompileUnit *getUnitForOffset(unsigned Offset);
649
650   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
651                      const DWARFDebugInfoEntryMinimal *DIE = nullptr);
652
653   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
654   /// @}
655
656 private:
657   std::string OutputFilename;
658   LinkOptions Options;
659   BinaryHolder BinHolder;
660   std::unique_ptr<DwarfStreamer> Streamer;
661
662   /// The units of the current debug map object.
663   std::vector<CompileUnit> Units;
664
665   /// The debug map object curently under consideration.
666   DebugMapObject *CurrentDebugObject;
667
668   /// \brief The Dwarf string pool
669   NonRelocatableStringpool StringPool;
670 };
671
672 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
673 /// returning our CompileUnit object instead.
674 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
675   auto CU =
676       std::upper_bound(Units.begin(), Units.end(), Offset,
677                        [](uint32_t LHS, const CompileUnit &RHS) {
678                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
679                        });
680   return CU != Units.end() ? &*CU : nullptr;
681 }
682
683 /// \brief Resolve the DIE attribute reference that has been
684 /// extracted in \p RefValue. The resulting DIE migh be in another
685 /// CompileUnit which is stored into \p ReferencedCU.
686 /// \returns null if resolving fails for any reason.
687 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
688     DWARFFormValue &RefValue, const DWARFUnit &Unit,
689     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
690   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
691   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
692
693   if ((RefCU = getUnitForOffset(RefOffset)))
694     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
695       return RefDie;
696
697   reportWarning("could not find referenced DIE", &Unit, &DIE);
698   return nullptr;
699 }
700
701 /// \brief Report a warning to the user, optionaly including
702 /// information about a specific \p DIE related to the warning.
703 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
704                                 const DWARFDebugInfoEntryMinimal *DIE) {
705   StringRef Context = "<debug map>";
706   if (CurrentDebugObject)
707     Context = CurrentDebugObject->getObjectFilename();
708   warn(Warning, Context);
709
710   if (!Options.Verbose || !DIE)
711     return;
712
713   errs() << "    in DIE:\n";
714   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
715             6 /* Indent */);
716 }
717
718 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
719   if (Options.NoOutput)
720     return true;
721
722   Streamer = llvm::make_unique<DwarfStreamer>();
723   return Streamer->init(TheTriple, OutputFilename);
724 }
725
726 /// \brief Recursive helper to gather the child->parent relationships in the
727 /// original compile unit.
728 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
729                              unsigned ParentIdx, CompileUnit &CU) {
730   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
731   CU.getInfo(MyIdx).ParentIdx = ParentIdx;
732
733   if (DIE->hasChildren())
734     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
735          Child = Child->getSibling())
736       gatherDIEParents(Child, MyIdx, CU);
737 }
738
739 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
740   switch (Tag) {
741   default:
742     return false;
743   case dwarf::DW_TAG_subprogram:
744   case dwarf::DW_TAG_lexical_block:
745   case dwarf::DW_TAG_subroutine_type:
746   case dwarf::DW_TAG_structure_type:
747   case dwarf::DW_TAG_class_type:
748   case dwarf::DW_TAG_union_type:
749     return true;
750   }
751   llvm_unreachable("Invalid Tag");
752 }
753
754 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
755   Units.reserve(Dwarf.getNumCompileUnits());
756   NextValidReloc = 0;
757 }
758
759 void DwarfLinker::endDebugObject() {
760   Units.clear();
761   ValidRelocs.clear();
762
763   for (auto *Block : DIEBlocks)
764     Block->~DIEBlock();
765   for (auto *Loc : DIELocs)
766     Loc->~DIELoc();
767
768   DIEBlocks.clear();
769   DIELocs.clear();
770   DIEAlloc.Reset();
771 }
772
773 /// \brief Iterate over the relocations of the given \p Section and
774 /// store the ones that correspond to debug map entries into the
775 /// ValidRelocs array.
776 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
777                                        const object::MachOObjectFile &Obj,
778                                        const DebugMapObject &DMO) {
779   StringRef Contents;
780   Section.getContents(Contents);
781   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
782
783   for (const object::RelocationRef &Reloc : Section.relocations()) {
784     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
785     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
786     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
787     uint64_t Offset64;
788     if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
789       reportWarning(" unsupported relocation in debug_info section.");
790       continue;
791     }
792     uint32_t Offset = Offset64;
793     // Mach-o uses REL relocations, the addend is at the relocation offset.
794     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
795
796     auto Sym = Reloc.getSymbol();
797     if (Sym != Obj.symbol_end()) {
798       StringRef SymbolName;
799       if (Sym->getName(SymbolName)) {
800         reportWarning("error getting relocation symbol name.");
801         continue;
802       }
803       if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
804         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
805     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
806       // Do not store the addend. The addend was the address of the
807       // symbol in the object file, the address in the binary that is
808       // stored in the debug map doesn't need to be offseted.
809       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
810     }
811   }
812 }
813
814 /// \brief Dispatch the valid relocation finding logic to the
815 /// appropriate handler depending on the object file format.
816 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
817                                   const object::ObjectFile &Obj,
818                                   const DebugMapObject &DMO) {
819   // Dispatch to the right handler depending on the file type.
820   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
821     findValidRelocsMachO(Section, *MachOObj, DMO);
822   else
823     reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
824
825   if (ValidRelocs.empty())
826     return false;
827
828   // Sort the relocations by offset. We will walk the DIEs linearly in
829   // the file, this allows us to just keep an index in the relocation
830   // array that we advance during our walk, rather than resorting to
831   // some associative container. See DwarfLinker::NextValidReloc.
832   std::sort(ValidRelocs.begin(), ValidRelocs.end());
833   return true;
834 }
835
836 /// \brief Look for relocations in the debug_info section that match
837 /// entries in the debug map. These relocations will drive the Dwarf
838 /// link by indicating which DIEs refer to symbols present in the
839 /// linked binary.
840 /// \returns wether there are any valid relocations in the debug info.
841 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
842                                              const DebugMapObject &DMO) {
843   // Find the debug_info section.
844   for (const object::SectionRef &Section : Obj.sections()) {
845     StringRef SectionName;
846     Section.getName(SectionName);
847     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
848     if (SectionName != "debug_info")
849       continue;
850     return findValidRelocs(Section, Obj, DMO);
851   }
852   return false;
853 }
854
855 /// \brief Checks that there is a relocation against an actual debug
856 /// map entry between \p StartOffset and \p NextOffset.
857 ///
858 /// This function must be called with offsets in strictly ascending
859 /// order because it never looks back at relocations it already 'went past'.
860 /// \returns true and sets Info.InDebugMap if it is the case.
861 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
862                                      CompileUnit::DIEInfo &Info) {
863   assert(NextValidReloc == 0 ||
864          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
865   if (NextValidReloc >= ValidRelocs.size())
866     return false;
867
868   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
869
870   // We might need to skip some relocs that we didn't consider. For
871   // example the high_pc of a discarded DIE might contain a reloc that
872   // is in the list because it actually corresponds to the start of a
873   // function that is in the debug map.
874   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
875     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
876
877   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
878     return false;
879
880   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
881   if (Options.Verbose)
882     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
883            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
884                             ValidReloc.Mapping->getValue().ObjectAddress,
885                             ValidReloc.Mapping->getValue().BinaryAddress);
886
887   Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
888                     ValidReloc.Addend -
889                     ValidReloc.Mapping->getValue().ObjectAddress;
890   Info.InDebugMap = true;
891   return true;
892 }
893
894 /// \brief Get the starting and ending (exclusive) offset for the
895 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
896 /// supposed to point to the position of the first attribute described
897 /// by \p Abbrev.
898 /// \return [StartOffset, EndOffset) as a pair.
899 static std::pair<uint32_t, uint32_t>
900 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
901                     unsigned Offset, const DWARFUnit &Unit) {
902   DataExtractor Data = Unit.getDebugInfoExtractor();
903
904   for (unsigned i = 0; i < Idx; ++i)
905     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
906
907   uint32_t End = Offset;
908   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
909
910   return std::make_pair(Offset, End);
911 }
912
913 /// \brief Check if a variable describing DIE should be kept.
914 /// \returns updated TraversalFlags.
915 unsigned DwarfLinker::shouldKeepVariableDIE(
916     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
917     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
918   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
919
920   // Global variables with constant value can always be kept.
921   if (!(Flags & TF_InFunctionScope) &&
922       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
923     MyInfo.InDebugMap = true;
924     return Flags | TF_Keep;
925   }
926
927   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
928   if (LocationIdx == -1U)
929     return Flags;
930
931   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
932   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
933   uint32_t LocationOffset, LocationEndOffset;
934   std::tie(LocationOffset, LocationEndOffset) =
935       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
936
937   // See if there is a relocation to a valid debug map entry inside
938   // this variable's location. The order is important here. We want to
939   // always check in the variable has a valid relocation, so that the
940   // DIEInfo is filled. However, we don't want a static variable in a
941   // function to force us to keep the enclosing function.
942   if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
943       (Flags & TF_InFunctionScope))
944     return Flags;
945
946   if (Options.Verbose)
947     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
948
949   return Flags | TF_Keep;
950 }
951
952 /// \brief Check if a function describing DIE should be kept.
953 /// \returns updated TraversalFlags.
954 unsigned DwarfLinker::shouldKeepSubprogramDIE(
955     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
956     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
957   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
958
959   Flags |= TF_InFunctionScope;
960
961   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
962   if (LowPcIdx == -1U)
963     return Flags;
964
965   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
966   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
967   uint32_t LowPcOffset, LowPcEndOffset;
968   std::tie(LowPcOffset, LowPcEndOffset) =
969       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
970
971   uint64_t LowPc =
972       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
973   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
974   if (LowPc == -1ULL ||
975       !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
976     return Flags;
977
978   if (Options.Verbose)
979     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
980
981   Flags |= TF_Keep;
982
983   DWARFFormValue HighPcValue;
984   if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
985     reportWarning("Function without high_pc. Range will be discarded.\n",
986                   &OrigUnit, &DIE);
987     return Flags;
988   }
989
990   uint64_t HighPc;
991   if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
992     HighPc = *HighPcValue.getAsAddress(&OrigUnit);
993   } else {
994     assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
995     HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
996   }
997
998   Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
999   return Flags;
1000 }
1001
1002 /// \brief Check if a DIE should be kept.
1003 /// \returns updated TraversalFlags.
1004 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1005                                     CompileUnit &Unit,
1006                                     CompileUnit::DIEInfo &MyInfo,
1007                                     unsigned Flags) {
1008   switch (DIE.getTag()) {
1009   case dwarf::DW_TAG_constant:
1010   case dwarf::DW_TAG_variable:
1011     return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1012   case dwarf::DW_TAG_subprogram:
1013     return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1014   case dwarf::DW_TAG_module:
1015   case dwarf::DW_TAG_imported_module:
1016   case dwarf::DW_TAG_imported_declaration:
1017   case dwarf::DW_TAG_imported_unit:
1018     // We always want to keep these.
1019     return Flags | TF_Keep;
1020   }
1021
1022   return Flags;
1023 }
1024
1025 /// \brief Mark the passed DIE as well as all the ones it depends on
1026 /// as kept.
1027 ///
1028 /// This function is called by lookForDIEsToKeep on DIEs that are
1029 /// newly discovered to be needed in the link. It recursively calls
1030 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1031 /// TraversalFlags to inform it that it's not doing the primary DIE
1032 /// tree walk.
1033 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1034                                           CompileUnit::DIEInfo &MyInfo,
1035                                           const DebugMapObject &DMO,
1036                                           CompileUnit &CU, unsigned Flags) {
1037   const DWARFUnit &Unit = CU.getOrigUnit();
1038   MyInfo.Keep = true;
1039
1040   // First mark all the parent chain as kept.
1041   unsigned AncestorIdx = MyInfo.ParentIdx;
1042   while (!CU.getInfo(AncestorIdx).Keep) {
1043     lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1044                       TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1045     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1046   }
1047
1048   // Then we need to mark all the DIEs referenced by this DIE's
1049   // attributes as kept.
1050   DataExtractor Data = Unit.getDebugInfoExtractor();
1051   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1052   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1053
1054   // Mark all DIEs referenced through atttributes as kept.
1055   for (const auto &AttrSpec : Abbrev->attributes()) {
1056     DWARFFormValue Val(AttrSpec.Form);
1057
1058     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1059       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1060       continue;
1061     }
1062
1063     Val.extractValue(Data, &Offset, &Unit);
1064     CompileUnit *ReferencedCU;
1065     if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1066       lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1067                         TF_Keep | TF_DependencyWalk);
1068   }
1069 }
1070
1071 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1072 /// keep. Store that information in \p CU's DIEInfo.
1073 ///
1074 /// This function is the entry point of the DIE selection
1075 /// algorithm. It is expected to walk the DIE tree in file order and
1076 /// (though the mediation of its helper) call hasValidRelocation() on
1077 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1078 /// comment).
1079 /// While walking the dependencies of root DIEs, this function is
1080 /// also called, but during these dependency walks the file order is
1081 /// not respected. The TF_DependencyWalk flag tells us which kind of
1082 /// traversal we are currently doing.
1083 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1084                                     const DebugMapObject &DMO, CompileUnit &CU,
1085                                     unsigned Flags) {
1086   unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1087   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1088   bool AlreadyKept = MyInfo.Keep;
1089
1090   // If the Keep flag is set, we are marking a required DIE's
1091   // dependencies. If our target is already marked as kept, we're all
1092   // set.
1093   if ((Flags & TF_DependencyWalk) && AlreadyKept)
1094     return;
1095
1096   // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1097   // because it would screw up the relocation finding logic.
1098   if (!(Flags & TF_DependencyWalk))
1099     Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1100
1101   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1102   if (!AlreadyKept && (Flags & TF_Keep))
1103     keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1104
1105   // The TF_ParentWalk flag tells us that we are currently walking up
1106   // the parent chain of a required DIE, and we don't want to mark all
1107   // the children of the parents as kept (consider for example a
1108   // DW_TAG_namespace node in the parent chain). There are however a
1109   // set of DIE types for which we want to ignore that directive and still
1110   // walk their children.
1111   if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1112     Flags &= ~TF_ParentWalk;
1113
1114   if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1115     return;
1116
1117   for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1118        Child = Child->getSibling())
1119     lookForDIEsToKeep(*Child, DMO, CU, Flags);
1120 }
1121
1122 /// \brief Assign an abbreviation numer to \p Abbrev.
1123 ///
1124 /// Our DIEs get freed after every DebugMapObject has been processed,
1125 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1126 /// the instances hold by the DIEs. When we encounter an abbreviation
1127 /// that we don't know, we create a permanent copy of it.
1128 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1129   // Check the set for priors.
1130   FoldingSetNodeID ID;
1131   Abbrev.Profile(ID);
1132   void *InsertToken;
1133   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1134
1135   // If it's newly added.
1136   if (InSet) {
1137     // Assign existing abbreviation number.
1138     Abbrev.setNumber(InSet->getNumber());
1139   } else {
1140     // Add to abbreviation list.
1141     Abbreviations.push_back(
1142         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1143     for (const auto &Attr : Abbrev.getData())
1144       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1145     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1146     // Assign the unique abbreviation number.
1147     Abbrev.setNumber(Abbreviations.size());
1148     Abbreviations.back()->setNumber(Abbreviations.size());
1149   }
1150 }
1151
1152 /// \brief Clone a string attribute described by \p AttrSpec and add
1153 /// it to \p Die.
1154 /// \returns the size of the new attribute.
1155 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1156                                            const DWARFFormValue &Val,
1157                                            const DWARFUnit &U) {
1158   // Switch everything to out of line strings.
1159   const char *String = *Val.getAsCString(&U);
1160   unsigned Offset = StringPool.getStringOffset(String);
1161   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1162                new (DIEAlloc) DIEInteger(Offset));
1163   return 4;
1164 }
1165
1166 /// \brief Clone an attribute referencing another DIE and add
1167 /// it to \p Die.
1168 /// \returns the size of the new attribute.
1169 unsigned DwarfLinker::cloneDieReferenceAttribute(
1170     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1171     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1172     const DWARFUnit &U) {
1173   uint32_t Ref = *Val.getAsReference(&U);
1174   DIE *NewRefDie = nullptr;
1175   CompileUnit *RefUnit = nullptr;
1176   const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1177
1178   if (!(RefUnit = getUnitForOffset(Ref)) ||
1179       !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1180     const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1181     if (!AttributeString)
1182       AttributeString = "DW_AT_???";
1183     reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1184                       ". Dropping.",
1185                   &U, &InputDIE);
1186     return 0;
1187   }
1188
1189   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1190   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1191   if (!RefInfo.Clone) {
1192     assert(Ref > InputDIE.getOffset());
1193     // We haven't cloned this DIE yet. Just create an empty one and
1194     // store it. It'll get really cloned when we process it.
1195     RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1196   }
1197   NewRefDie = RefInfo.Clone;
1198
1199   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1200     // We cannot currently rely on a DIEEntry to emit ref_addr
1201     // references, because the implementation calls back to DwarfDebug
1202     // to find the unit offset. (We don't have a DwarfDebug)
1203     // FIXME: we should be able to design DIEEntry reliance on
1204     // DwarfDebug away.
1205     DIEInteger *Attr;
1206     if (Ref < InputDIE.getOffset()) {
1207       // We must have already cloned that DIE.
1208       uint32_t NewRefOffset =
1209           RefUnit->getStartOffset() + NewRefDie->getOffset();
1210       Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1211     } else {
1212       // A forward reference. Note and fixup later.
1213       Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1214       RefUnit->noteForwardReference(NewRefDie, Attr);
1215     }
1216     Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1217                  Attr);
1218     return AttrSize;
1219   }
1220
1221   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1222                new (DIEAlloc) DIEEntry(*NewRefDie));
1223   return AttrSize;
1224 }
1225
1226 /// \brief Clone an attribute of block form (locations, constants) and add
1227 /// it to \p Die.
1228 /// \returns the size of the new attribute.
1229 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1230                                           const DWARFFormValue &Val,
1231                                           unsigned AttrSize) {
1232   DIE *Attr;
1233   DIEValue *Value;
1234   DIELoc *Loc = nullptr;
1235   DIEBlock *Block = nullptr;
1236   // Just copy the block data over.
1237   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1238     Loc = new (DIEAlloc) DIELoc();
1239     DIELocs.push_back(Loc);
1240   } else {
1241     Block = new (DIEAlloc) DIEBlock();
1242     DIEBlocks.push_back(Block);
1243   }
1244   Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1245   Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1246   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1247   for (auto Byte : Bytes)
1248     Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1249                    new (DIEAlloc) DIEInteger(Byte));
1250   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1251   // the DIE class, this if could be replaced by
1252   // Attr->setSize(Bytes.size()).
1253   if (Streamer) {
1254     if (Loc)
1255       Loc->ComputeSize(&Streamer->getAsmPrinter());
1256     else
1257       Block->ComputeSize(&Streamer->getAsmPrinter());
1258   }
1259   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1260                Value);
1261   return AttrSize;
1262 }
1263
1264 /// \brief Clone an address attribute and add it to \p Die.
1265 /// \returns the size of the new attribute.
1266 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1267                                             const DWARFFormValue &Val,
1268                                             const CompileUnit &Unit,
1269                                             AttributesInfo &Info) {
1270   uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1271   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1272     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1273         Die.getTag() == dwarf::DW_TAG_lexical_block)
1274       Addr += Info.PCOffset;
1275     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1276       Addr = Unit.getLowPc();
1277       if (Addr == UINT64_MAX)
1278         return 0;
1279     }
1280   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1281     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1282       if (uint64_t HighPc = Unit.getHighPc())
1283         Addr = HighPc;
1284       else
1285         return 0;
1286     } else
1287       // If we have a high_pc recorded for the input DIE, use
1288       // it. Otherwise (when no relocations where applied) just use the
1289       // one we just decoded.
1290       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1291   }
1292
1293   Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1294                static_cast<dwarf::Form>(AttrSpec.Form),
1295                new (DIEAlloc) DIEInteger(Addr));
1296   return Unit.getOrigUnit().getAddressByteSize();
1297 }
1298
1299 /// \brief Clone a scalar attribute  and add it to \p Die.
1300 /// \returns the size of the new attribute.
1301 unsigned DwarfLinker::cloneScalarAttribute(
1302     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1303     const CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1304     unsigned AttrSize) {
1305   uint64_t Value;
1306   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1307       Die.getTag() == dwarf::DW_TAG_compile_unit) {
1308     if (Unit.getLowPc() == -1ULL)
1309       return 0;
1310     // Dwarf >= 4 high_pc is an size, not an address.
1311     Value = Unit.getHighPc() - Unit.getLowPc();
1312   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1313     Value = *Val.getAsSectionOffset();
1314   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1315     Value = *Val.getAsSignedConstant();
1316   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1317     Value = *OptionalValue;
1318   else {
1319     reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1320                   &Unit.getOrigUnit(), &InputDIE);
1321     return 0;
1322   }
1323   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1324                new (DIEAlloc) DIEInteger(Value));
1325   return AttrSize;
1326 }
1327
1328 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1329 /// value \p Val, and add it to \p Die.
1330 /// \returns the size of the cloned attribute.
1331 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1332                                      const DWARFDebugInfoEntryMinimal &InputDIE,
1333                                      CompileUnit &Unit,
1334                                      const DWARFFormValue &Val,
1335                                      const AttributeSpec AttrSpec,
1336                                      unsigned AttrSize, AttributesInfo &Info) {
1337   const DWARFUnit &U = Unit.getOrigUnit();
1338
1339   switch (AttrSpec.Form) {
1340   case dwarf::DW_FORM_strp:
1341   case dwarf::DW_FORM_string:
1342     return cloneStringAttribute(Die, AttrSpec, Val, U);
1343   case dwarf::DW_FORM_ref_addr:
1344   case dwarf::DW_FORM_ref1:
1345   case dwarf::DW_FORM_ref2:
1346   case dwarf::DW_FORM_ref4:
1347   case dwarf::DW_FORM_ref8:
1348     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1349                                       U);
1350   case dwarf::DW_FORM_block:
1351   case dwarf::DW_FORM_block1:
1352   case dwarf::DW_FORM_block2:
1353   case dwarf::DW_FORM_block4:
1354   case dwarf::DW_FORM_exprloc:
1355     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1356   case dwarf::DW_FORM_addr:
1357     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1358   case dwarf::DW_FORM_data1:
1359   case dwarf::DW_FORM_data2:
1360   case dwarf::DW_FORM_data4:
1361   case dwarf::DW_FORM_data8:
1362   case dwarf::DW_FORM_udata:
1363   case dwarf::DW_FORM_sdata:
1364   case dwarf::DW_FORM_sec_offset:
1365   case dwarf::DW_FORM_flag:
1366   case dwarf::DW_FORM_flag_present:
1367     return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize);
1368   default:
1369     reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1370                   &InputDIE);
1371   }
1372
1373   return 0;
1374 }
1375
1376 /// \brief Apply the valid relocations found by findValidRelocs() to
1377 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1378 /// in the debug_info section.
1379 ///
1380 /// Like for findValidRelocs(), this function must be called with
1381 /// monotonic \p BaseOffset values.
1382 ///
1383 /// \returns wether any reloc has been applied.
1384 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1385                                    uint32_t BaseOffset, bool isLittleEndian) {
1386   assert((NextValidReloc == 0 ||
1387           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1388          "BaseOffset should only be increasing.");
1389   if (NextValidReloc >= ValidRelocs.size())
1390     return false;
1391
1392   // Skip relocs that haven't been applied.
1393   while (NextValidReloc < ValidRelocs.size() &&
1394          ValidRelocs[NextValidReloc].Offset < BaseOffset)
1395     ++NextValidReloc;
1396
1397   bool Applied = false;
1398   uint64_t EndOffset = BaseOffset + Data.size();
1399   while (NextValidReloc < ValidRelocs.size() &&
1400          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1401          ValidRelocs[NextValidReloc].Offset < EndOffset) {
1402     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1403     assert(ValidReloc.Offset - BaseOffset < Data.size());
1404     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1405     char Buf[8];
1406     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1407     Value += ValidReloc.Addend;
1408     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1409       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1410       Buf[i] = uint8_t(Value >> (Index * 8));
1411     }
1412     assert(ValidReloc.Size <= sizeof(Buf));
1413     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1414     Applied = true;
1415   }
1416
1417   return Applied;
1418 }
1419
1420 /// \brief Recursively clone \p InputDIE's subtrees that have been
1421 /// selected to appear in the linked output.
1422 ///
1423 /// \param OutOffset is the Offset where the newly created DIE will
1424 /// lie in the linked compile unit.
1425 ///
1426 /// \returns the cloned DIE object or null if nothing was selected.
1427 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1428                            CompileUnit &Unit, int64_t PCOffset,
1429                            uint32_t OutOffset) {
1430   DWARFUnit &U = Unit.getOrigUnit();
1431   unsigned Idx = U.getDIEIndex(&InputDIE);
1432   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1433
1434   // Should the DIE appear in the output?
1435   if (!Unit.getInfo(Idx).Keep)
1436     return nullptr;
1437
1438   uint32_t Offset = InputDIE.getOffset();
1439   // The DIE might have been already created by a forward reference
1440   // (see cloneDieReferenceAttribute()).
1441   DIE *Die = Info.Clone;
1442   if (!Die)
1443     Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1444   assert(Die->getTag() == InputDIE.getTag());
1445   Die->setOffset(OutOffset);
1446
1447   // Extract and clone every attribute.
1448   DataExtractor Data = U.getDebugInfoExtractor();
1449   uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1450   AttributesInfo AttrInfo;
1451
1452   // We could copy the data only if we need to aply a relocation to
1453   // it. After testing, it seems there is no performance downside to
1454   // doing the copy unconditionally, and it makes the code simpler.
1455   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1456   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1457   // Modify the copy with relocated addresses.
1458   if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1459     // If we applied relocations, we store the value of high_pc that was
1460     // potentially stored in the input DIE. If high_pc is an address
1461     // (Dwarf version == 2), then it might have been relocated to a
1462     // totally unrelated value (because the end address in the object
1463     // file might be start address of another function which got moved
1464     // independantly by the linker). The computation of the actual
1465     // high_pc value is done in cloneAddressAttribute().
1466     AttrInfo.OrigHighPc =
1467         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1468   }
1469
1470   // Reset the Offset to 0 as we will be working on the local copy of
1471   // the data.
1472   Offset = 0;
1473
1474   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1475   Offset += getULEB128Size(Abbrev->getCode());
1476
1477   // We are entering a subprogram. Get and propagate the PCOffset.
1478   if (Die->getTag() == dwarf::DW_TAG_subprogram)
1479     PCOffset = Info.AddrAdjust;
1480   AttrInfo.PCOffset = PCOffset;
1481
1482   for (const auto &AttrSpec : Abbrev->attributes()) {
1483     DWARFFormValue Val(AttrSpec.Form);
1484     uint32_t AttrSize = Offset;
1485     Val.extractValue(Data, &Offset, &U);
1486     AttrSize = Offset - AttrSize;
1487
1488     OutOffset +=
1489         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
1490   }
1491
1492   DIEAbbrev &NewAbbrev = Die->getAbbrev();
1493   // If a scope DIE is kept, we must have kept at least one child. If
1494   // it's not the case, we'll just be emitting one wasteful end of
1495   // children marker, but things won't break.
1496   if (InputDIE.hasChildren())
1497     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1498   // Assign a permanent abbrev number
1499   AssignAbbrev(Die->getAbbrev());
1500
1501   // Add the size of the abbreviation number to the output offset.
1502   OutOffset += getULEB128Size(Die->getAbbrevNumber());
1503
1504   if (!Abbrev->hasChildren()) {
1505     // Update our size.
1506     Die->setSize(OutOffset - Die->getOffset());
1507     return Die;
1508   }
1509
1510   // Recursively clone children.
1511   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1512        Child = Child->getSibling()) {
1513     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
1514       Die->addChild(std::unique_ptr<DIE>(Clone));
1515       OutOffset = Clone->getOffset() + Clone->getSize();
1516     }
1517   }
1518
1519   // Account for the end of children marker.
1520   OutOffset += sizeof(int8_t);
1521   // Update our size.
1522   Die->setSize(OutOffset - Die->getOffset());
1523   return Die;
1524 }
1525
1526 bool DwarfLinker::link(const DebugMap &Map) {
1527
1528   if (Map.begin() == Map.end()) {
1529     errs() << "Empty debug map.\n";
1530     return false;
1531   }
1532
1533   if (!createStreamer(Map.getTriple(), OutputFilename))
1534     return false;
1535
1536   // Size of the DIEs (and headers) generated for the linked output.
1537   uint64_t OutputDebugInfoSize = 0;
1538
1539   for (const auto &Obj : Map.objects()) {
1540     CurrentDebugObject = Obj.get();
1541
1542     if (Options.Verbose)
1543       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1544     auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1545     if (std::error_code EC = ErrOrObj.getError()) {
1546       reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1547       continue;
1548     }
1549
1550     // Look for relocations that correspond to debug map entries.
1551     if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1552       if (Options.Verbose)
1553         outs() << "No valid relocations found. Skipping.\n";
1554       continue;
1555     }
1556
1557     // Setup access to the debug info.
1558     DWARFContextInMemory DwarfContext(*ErrOrObj);
1559     startDebugObject(DwarfContext);
1560
1561     // In a first phase, just read in the debug info and store the DIE
1562     // parent links that we will use during the next phase.
1563     for (const auto &CU : DwarfContext.compile_units()) {
1564       auto *CUDie = CU->getCompileUnitDIE(false);
1565       if (Options.Verbose) {
1566         outs() << "Input compilation unit:";
1567         CUDie->dump(outs(), CU.get(), 0);
1568       }
1569       Units.emplace_back(*CU);
1570       gatherDIEParents(CUDie, 0, Units.back());
1571     }
1572
1573     // Then mark all the DIEs that need to be present in the linked
1574     // output and collect some information about them. Note that this
1575     // loop can not be merged with the previous one becaue cross-cu
1576     // references require the ParentIdx to be setup for every CU in
1577     // the object file before calling this.
1578     for (auto &CurrentUnit : Units)
1579       lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1580                         CurrentUnit, 0);
1581
1582     // The calls to applyValidRelocs inside cloneDIE will walk the
1583     // reloc array again (in the same way findValidRelocsInDebugInfo()
1584     // did). We need to reset the NextValidReloc index to the beginning.
1585     NextValidReloc = 0;
1586
1587     // Construct the output DIE tree by cloning the DIEs we chose to
1588     // keep above. If there are no valid relocs, then there's nothing
1589     // to clone/emit.
1590     if (!ValidRelocs.empty())
1591       for (auto &CurrentUnit : Units) {
1592         const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1593         CurrentUnit.setStartOffset(OutputDebugInfoSize);
1594         DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1595                                   11 /* Unit Header size */);
1596         CurrentUnit.setOutputUnitDIE(OutputDIE);
1597         OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1598       }
1599
1600     // Emit all the compile unit's debug information.
1601     if (!ValidRelocs.empty() && !Options.NoOutput)
1602       for (auto &CurrentUnit : Units) {
1603         CurrentUnit.fixupForwardReferences();
1604         Streamer->emitCompileUnitHeader(CurrentUnit);
1605         if (!CurrentUnit.getOutputUnitDIE())
1606           continue;
1607         Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1608       }
1609
1610     // Clean-up before starting working on the next object.
1611     endDebugObject();
1612   }
1613
1614   // Emit everything that's global.
1615   if (!Options.NoOutput) {
1616     Streamer->emitAbbrevs(Abbreviations);
1617     Streamer->emitStrings(StringPool);
1618   }
1619
1620   return Options.NoOutput ? true : Streamer->finish();
1621 }
1622 }
1623
1624 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1625                const LinkOptions &Options) {
1626   DwarfLinker Linker(OutputFilename, Options);
1627   return Linker.link(DM);
1628 }
1629 }
1630 }