dsymutil: Fix a comment. [-Wdocumentation]
[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 "MachOUtils.h"
14 #include "NonRelocatableStringpool.h"
15 #include "llvm/ADT/IntervalMap.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/DIE.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
23 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCDwarf.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/MachO.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/LEB128.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include <string>
41 #include <tuple>
42
43 namespace llvm {
44 namespace dsymutil {
45
46 namespace {
47
48 template <typename KeyT, typename ValT>
49 using HalfOpenIntervalMap =
50     IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
51                 IntervalMapHalfOpenInfo<KeyT>>;
52
53 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
54
55 // FIXME: Delete this structure.
56 struct PatchLocation {
57   DIE::value_iterator I;
58
59   PatchLocation() = default;
60   PatchLocation(DIE::value_iterator I) : I(I) {}
61
62   void set(uint64_t New) const {
63     assert(I);
64     const auto &Old = *I;
65     assert(Old.getType() == DIEValue::isInteger);
66     *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
67   }
68
69   uint64_t get() const {
70     assert(I);
71     return I->getDIEInteger().getValue();
72   }
73 };
74
75 class CompileUnit;
76 struct DeclMapInfo;
77
78 /// A DeclContext is a named program scope that is used for ODR
79 /// uniquing of types.
80 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
81 /// is expanded (and uniqued) with each new object file processed. We
82 /// need to determine the context of each DIE in an linked object file
83 /// to see if the corresponding type has already been emitted.
84 ///
85 /// The contexts are conceptually organised as a tree (eg. a function
86 /// scope is contained in a namespace scope that contains other
87 /// scopes), but storing/accessing them in an actual tree is too
88 /// inefficient: we need to be able to very quickly query a context
89 /// for a given child context by name. Storing a StringMap in each
90 /// DeclContext would be too space inefficient.
91 /// The solution here is to give each DeclContext a link to its parent
92 /// (this allows to walk up the tree), but to query the existance of a
93 /// specific DeclContext using a separate DenseMap keyed on the hash
94 /// of the fully qualified name of the context.
95 class DeclContext {
96   unsigned QualifiedNameHash;
97   uint32_t Line;
98   uint32_t ByteSize;
99   uint16_t Tag;
100   StringRef Name;
101   StringRef File;
102   const DeclContext &Parent;
103   const DWARFDebugInfoEntryMinimal *LastSeenDIE;
104   uint32_t LastSeenCompileUnitID;
105   uint32_t CanonicalDIEOffset;
106
107   friend DeclMapInfo;
108
109 public:
110   typedef DenseSet<DeclContext *, DeclMapInfo> Map;
111
112   DeclContext()
113       : QualifiedNameHash(0), Line(0), ByteSize(0),
114         Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
115         LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
116
117   DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
118               StringRef Name, StringRef File, const DeclContext &Parent,
119               const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
120               unsigned CUId = 0)
121       : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
122         Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
123         LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
124
125   uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
126
127   bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
128
129   uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
130   void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
131
132   uint16_t getTag() const { return Tag; }
133   StringRef getName() const { return Name; }
134 };
135
136 /// Info type for the DenseMap storing the DeclContext pointers.
137 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
138   using DenseMapInfo<DeclContext *>::getEmptyKey;
139   using DenseMapInfo<DeclContext *>::getTombstoneKey;
140
141   static unsigned getHashValue(const DeclContext *Ctxt) {
142     return Ctxt->QualifiedNameHash;
143   }
144
145   static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
146     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
147       return RHS == LHS;
148     return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
149            LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
150            LHS->Name.data() == RHS->Name.data() &&
151            LHS->File.data() == RHS->File.data() &&
152            LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
153   }
154 };
155
156 /// This class gives a tree-like API to the DenseMap that stores the
157 /// DeclContext objects. It also holds the BumpPtrAllocator where
158 /// these objects will be allocated.
159 class DeclContextTree {
160   BumpPtrAllocator Allocator;
161   DeclContext Root;
162   DeclContext::Map Contexts;
163
164 public:
165   /// Get the child of \a Context described by \a DIE in \a Unit. The
166   /// required strings will be interned in \a StringPool.
167   /// \returns The child DeclContext along with one bit that is set if
168   /// this context is invalid.
169   /// FIXME: the invalid bit along the return value is to emulate some
170   /// dsymutil-classic functionality. See the fucntion definition for
171   /// a more thorough discussion of its use.
172   PointerIntPair<DeclContext *, 1>
173   getChildDeclContext(DeclContext &Context,
174                       const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
175                       NonRelocatableStringpool &StringPool);
176
177   DeclContext &getRoot() { return Root; }
178 };
179
180 /// \brief Stores all information relating to a compile unit, be it in
181 /// its original instance in the object file to its brand new cloned
182 /// and linked DIE tree.
183 class CompileUnit {
184 public:
185   /// \brief Information gathered about a DIE in the object file.
186   struct DIEInfo {
187     int64_t AddrAdjust; ///< Address offset to apply to the described entity.
188     DeclContext *Ctxt;  ///< ODR Declaration context.
189     DIE *Clone;         ///< Cloned version of that DIE.
190     uint32_t ParentIdx; ///< The index of this DIE's parent.
191     bool Keep;          ///< Is the DIE part of the linked output?
192     bool InDebugMap;    ///< Was this DIE's entity found in the map?
193   };
194
195   CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
196       : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
197         Ranges(RangeAlloc) {
198     Info.resize(OrigUnit.getNumDIEs());
199
200     const auto *CUDie = OrigUnit.getUnitDIE(false);
201     unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
202         &OrigUnit, dwarf::DW_AT_language, 0);
203     HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
204                            Lang == dwarf::DW_LANG_C_plus_plus_03 ||
205                            Lang == dwarf::DW_LANG_C_plus_plus_11 ||
206                            Lang == dwarf::DW_LANG_C_plus_plus_14 ||
207                            Lang == dwarf::DW_LANG_ObjC_plus_plus);
208   }
209
210   CompileUnit(CompileUnit &&RHS)
211       : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
212         CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
213         NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
214     // The CompileUnit container has been 'reserve()'d with the right
215     // size. We cannot move the IntervalMap anyway.
216     llvm_unreachable("CompileUnits should not be moved.");
217   }
218
219   DWARFUnit &getOrigUnit() const { return OrigUnit; }
220
221   unsigned getUniqueID() const { return ID; }
222
223   DIE *getOutputUnitDIE() const { return CUDie; }
224   void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
225
226   bool hasODR() const { return HasODR; }
227
228   DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
229   const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
230
231   uint64_t getStartOffset() const { return StartOffset; }
232   uint64_t getNextUnitOffset() const { return NextUnitOffset; }
233   void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
234
235   uint64_t getLowPc() const { return LowPc; }
236   uint64_t getHighPc() const { return HighPc; }
237
238   Optional<PatchLocation> getUnitRangesAttribute() const {
239     return UnitRangeAttribute;
240   }
241   const FunctionIntervals &getFunctionRanges() const { return Ranges; }
242   const std::vector<PatchLocation> &getRangesAttributes() const {
243     return RangeAttributes;
244   }
245
246   const std::vector<std::pair<PatchLocation, int64_t>> &
247   getLocationAttributes() const {
248     return LocationAttributes;
249   }
250
251   void setHasInterestingContent() { HasInterestingContent = true; }
252   bool hasInterestingContent() { return HasInterestingContent; }
253
254   /// Mark every DIE in this unit as kept. This function also
255   /// marks variables as InDebugMap so that they appear in the
256   /// reconstructed accelerator tables.
257   void markEverythingAsKept();
258
259   /// \brief Compute the end offset for this unit. Must be
260   /// called after the CU's DIEs have been cloned.
261   /// \returns the next unit offset (which is also the current
262   /// debug_info section size).
263   uint64_t computeNextUnitOffset();
264
265   /// \brief Keep track of a forward reference to DIE \p Die in \p
266   /// RefUnit by \p Attr. The attribute should be fixed up later to
267   /// point to the absolute offset of \p Die in the debug_info section
268   /// or to the canonical offset of \p Ctxt if it is non-null.
269   void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
270                             DeclContext *Ctxt, PatchLocation Attr);
271
272   /// \brief Apply all fixups recored by noteForwardReference().
273   void fixupForwardReferences();
274
275   /// \brief Add a function range [\p LowPC, \p HighPC) that is
276   /// relocatad by applying offset \p PCOffset.
277   void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
278
279   /// \brief Keep track of a DW_AT_range attribute that we will need to
280   /// patch up later.
281   void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
282
283   /// \brief Keep track of a location attribute pointing to a location
284   /// list in the debug_loc section.
285   void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
286
287   /// \brief Add a name accelerator entry for \p Die with \p Name
288   /// which is stored in the string table at \p Offset.
289   void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
290                           bool SkipPubnamesSection = false);
291
292   /// \brief Add a type accelerator entry for \p Die with \p Name
293   /// which is stored in the string table at \p Offset.
294   void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
295
296   struct AccelInfo {
297     StringRef Name;      ///< Name of the entry.
298     const DIE *Die;      ///< DIE this entry describes.
299     uint32_t NameOffset; ///< Offset of Name in the string pool.
300     bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
301
302     AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
303               bool SkipPubSection = false)
304         : Name(Name), Die(Die), NameOffset(NameOffset),
305           SkipPubSection(SkipPubSection) {}
306   };
307
308   const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
309   const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
310
311   /// Get the full path for file \a FileNum in the line table
312   const char *getResolvedPath(unsigned FileNum) {
313     if (FileNum >= ResolvedPaths.size())
314       return nullptr;
315     return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
316                                          : nullptr;
317   }
318
319   /// Set the fully resolved path for the line-table's file \a FileNum
320   /// to \a Path.
321   void setResolvedPath(unsigned FileNum, const std::string &Path) {
322     if (ResolvedPaths.size() <= FileNum)
323       ResolvedPaths.resize(FileNum + 1);
324     ResolvedPaths[FileNum] = Path;
325   }
326
327 private:
328   DWARFUnit &OrigUnit;
329   unsigned ID;
330   std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
331   DIE *CUDie;                ///< Root of the linked DIE tree.
332
333   uint64_t StartOffset;
334   uint64_t NextUnitOffset;
335
336   uint64_t LowPc;
337   uint64_t HighPc;
338
339   /// \brief A list of attributes to fixup with the absolute offset of
340   /// a DIE in the debug_info section.
341   ///
342   /// The offsets for the attributes in this array couldn't be set while
343   /// cloning because for cross-cu forward refences the target DIE's
344   /// offset isn't known you emit the reference attribute.
345   std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
346                          PatchLocation>> ForwardDIEReferences;
347
348   FunctionIntervals::Allocator RangeAlloc;
349   /// \brief The ranges in that interval map are the PC ranges for
350   /// functions in this unit, associated with the PC offset to apply
351   /// to the addresses to get the linked address.
352   FunctionIntervals Ranges;
353
354   /// \brief DW_AT_ranges attributes to patch after we have gathered
355   /// all the unit's function addresses.
356   /// @{
357   std::vector<PatchLocation> RangeAttributes;
358   Optional<PatchLocation> UnitRangeAttribute;
359   /// @}
360
361   /// \brief Location attributes that need to be transfered from th
362   /// original debug_loc section to the liked one. They are stored
363   /// along with the PC offset that is to be applied to their
364   /// function's address.
365   std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
366
367   /// \brief Accelerator entries for the unit, both for the pub*
368   /// sections and the apple* ones.
369   /// @{
370   std::vector<AccelInfo> Pubnames;
371   std::vector<AccelInfo> Pubtypes;
372   /// @}
373
374   /// Cached resolved paths from the line table.
375   std::vector<std::string> ResolvedPaths;
376
377   /// Is this unit subject to the ODR rule?
378   bool HasODR;
379   /// Did a DIE actually contain a valid reloc?
380   bool HasInterestingContent;
381 };
382
383 void CompileUnit::markEverythingAsKept() {
384   for (auto &I : Info)
385     I.Keep = true;
386 }
387
388 uint64_t CompileUnit::computeNextUnitOffset() {
389   NextUnitOffset = StartOffset + 11 /* Header size */;
390   // The root DIE might be null, meaning that the Unit had nothing to
391   // contribute to the linked output. In that case, we will emit the
392   // unit header without any actual DIE.
393   if (CUDie)
394     NextUnitOffset += CUDie->getSize();
395   return NextUnitOffset;
396 }
397
398 /// \brief Keep track of a forward cross-cu reference from this unit
399 /// to \p Die that lives in \p RefUnit.
400 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
401                                        DeclContext *Ctxt, PatchLocation Attr) {
402   ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
403 }
404
405 /// \brief Apply all fixups recorded by noteForwardReference().
406 void CompileUnit::fixupForwardReferences() {
407   for (const auto &Ref : ForwardDIEReferences) {
408     DIE *RefDie;
409     const CompileUnit *RefUnit;
410     PatchLocation Attr;
411     DeclContext *Ctxt;
412     std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
413     if (Ctxt && Ctxt->getCanonicalDIEOffset())
414       Attr.set(Ctxt->getCanonicalDIEOffset());
415     else
416       Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
417   }
418 }
419
420 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
421                                    int64_t PcOffset) {
422   Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
423   this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
424   this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
425 }
426
427 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
428   if (Die.getTag() != dwarf::DW_TAG_compile_unit)
429     RangeAttributes.push_back(Attr);
430   else
431     UnitRangeAttribute = Attr;
432 }
433
434 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
435   LocationAttributes.emplace_back(Attr, PcOffset);
436 }
437
438 /// \brief Add a name accelerator entry for \p Die with \p Name
439 /// which is stored in the string table at \p Offset.
440 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
441                                      uint32_t Offset, bool SkipPubSection) {
442   Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
443 }
444
445 /// \brief Add a type accelerator entry for \p Die with \p Name
446 /// which is stored in the string table at \p Offset.
447 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
448                                      uint32_t Offset) {
449   Pubtypes.emplace_back(Name, Die, Offset, false);
450 }
451
452 /// \brief The Dwarf streaming logic
453 ///
454 /// All interactions with the MC layer that is used to build the debug
455 /// information binary representation are handled in this class.
456 class DwarfStreamer {
457   /// \defgroup MCObjects MC layer objects constructed by the streamer
458   /// @{
459   std::unique_ptr<MCRegisterInfo> MRI;
460   std::unique_ptr<MCAsmInfo> MAI;
461   std::unique_ptr<MCObjectFileInfo> MOFI;
462   std::unique_ptr<MCContext> MC;
463   MCAsmBackend *MAB; // Owned by MCStreamer
464   std::unique_ptr<MCInstrInfo> MII;
465   std::unique_ptr<MCSubtargetInfo> MSTI;
466   MCCodeEmitter *MCE; // Owned by MCStreamer
467   MCStreamer *MS;     // Owned by AsmPrinter
468   std::unique_ptr<TargetMachine> TM;
469   std::unique_ptr<AsmPrinter> Asm;
470   /// @}
471
472   /// \brief the file we stream the linked Dwarf to.
473   std::unique_ptr<raw_fd_ostream> OutFile;
474
475   uint32_t RangesSectionSize;
476   uint32_t LocSectionSize;
477   uint32_t LineSectionSize;
478   uint32_t FrameSectionSize;
479
480   /// \brief Emit the pubnames or pubtypes section contribution for \p
481   /// Unit into \p Sec. The data is provided in \p Names.
482   void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
483                              const CompileUnit &Unit,
484                              const std::vector<CompileUnit::AccelInfo> &Names);
485
486 public:
487   /// \brief Actually create the streamer and the ouptut file.
488   ///
489   /// This could be done directly in the constructor, but it feels
490   /// more natural to handle errors through return value.
491   bool init(Triple TheTriple, StringRef OutputFilename);
492
493   /// \brief Dump the file to the disk.
494   bool finish(const DebugMap &);
495
496   AsmPrinter &getAsmPrinter() const { return *Asm; }
497
498   /// \brief Set the current output section to debug_info and change
499   /// the MC Dwarf version to \p DwarfVersion.
500   void switchToDebugInfoSection(unsigned DwarfVersion);
501
502   /// \brief Emit the compilation unit header for \p Unit in the
503   /// debug_info section.
504   ///
505   /// As a side effect, this also switches the current Dwarf version
506   /// of the MC layer to the one of U.getOrigUnit().
507   void emitCompileUnitHeader(CompileUnit &Unit);
508
509   /// \brief Recursively emit the DIE tree rooted at \p Die.
510   void emitDIE(DIE &Die);
511
512   /// \brief Emit the abbreviation table \p Abbrevs to the
513   /// debug_abbrev section.
514   void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
515
516   /// \brief Emit the string table described by \p Pool.
517   void emitStrings(const NonRelocatableStringpool &Pool);
518
519   /// \brief Emit debug_ranges for \p FuncRange by translating the
520   /// original \p Entries.
521   void emitRangesEntries(
522       int64_t UnitPcOffset, uint64_t OrigLowPc,
523       FunctionIntervals::const_iterator FuncRange,
524       const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
525       unsigned AddressSize);
526
527   /// \brief Emit debug_aranges entries for \p Unit and if \p
528   /// DoRangesSection is true, also emit the debug_ranges entries for
529   /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
530   void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
531
532   uint32_t getRangesSectionSize() const { return RangesSectionSize; }
533
534   /// \brief Emit the debug_loc contribution for \p Unit by copying
535   /// the entries from \p Dwarf and offseting them. Update the
536   /// location attributes to point to the new entries.
537   void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
538
539   /// \brief Emit the line table described in \p Rows into the
540   /// debug_line section.
541   void emitLineTableForUnit(MCDwarfLineTableParams Params,
542                             StringRef PrologueBytes, unsigned MinInstLength,
543                             std::vector<DWARFDebugLine::Row> &Rows,
544                             unsigned AdddressSize);
545
546   uint32_t getLineSectionSize() const { return LineSectionSize; }
547
548   /// \brief Emit the .debug_pubnames contribution for \p Unit.
549   void emitPubNamesForUnit(const CompileUnit &Unit);
550
551   /// \brief Emit the .debug_pubtypes contribution for \p Unit.
552   void emitPubTypesForUnit(const CompileUnit &Unit);
553
554   /// \brief Emit a CIE.
555   void emitCIE(StringRef CIEBytes);
556
557   /// \brief Emit an FDE with data \p Bytes.
558   void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
559                StringRef Bytes);
560
561   uint32_t getFrameSectionSize() const { return FrameSectionSize; }
562 };
563
564 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
565   std::string ErrorStr;
566   std::string TripleName;
567   StringRef Context = "dwarf streamer init";
568
569   // Get the target.
570   const Target *TheTarget =
571       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
572   if (!TheTarget)
573     return error(ErrorStr, Context);
574   TripleName = TheTriple.getTriple();
575
576   // Create all the MC Objects.
577   MRI.reset(TheTarget->createMCRegInfo(TripleName));
578   if (!MRI)
579     return error(Twine("no register info for target ") + TripleName, Context);
580
581   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
582   if (!MAI)
583     return error("no asm info for target " + TripleName, Context);
584
585   MOFI.reset(new MCObjectFileInfo);
586   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
587   MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
588                              *MC);
589
590   MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
591   if (!MAB)
592     return error("no asm backend for target " + TripleName, Context);
593
594   MII.reset(TheTarget->createMCInstrInfo());
595   if (!MII)
596     return error("no instr info info for target " + TripleName, Context);
597
598   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
599   if (!MSTI)
600     return error("no subtarget info for target " + TripleName, Context);
601
602   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
603   if (!MCE)
604     return error("no code emitter for target " + TripleName, Context);
605
606   // Create the output file.
607   std::error_code EC;
608   OutFile =
609       llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
610   if (EC)
611     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
612
613   MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
614                                          *MSTI, false,
615                                          /*DWARFMustBeAtTheEnd*/ false);
616   if (!MS)
617     return error("no object streamer for target " + TripleName, Context);
618
619   // Finally create the AsmPrinter we'll use to emit the DIEs.
620   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
621   if (!TM)
622     return error("no target machine for target " + TripleName, Context);
623
624   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
625   if (!Asm)
626     return error("no asm printer for target " + TripleName, Context);
627
628   RangesSectionSize = 0;
629   LocSectionSize = 0;
630   LineSectionSize = 0;
631   FrameSectionSize = 0;
632
633   return true;
634 }
635
636 bool DwarfStreamer::finish(const DebugMap &DM) {
637   if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
638     return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
639
640   MS->Finish();
641   return true;
642 }
643
644 /// \brief Set the current output section to debug_info and change
645 /// the MC Dwarf version to \p DwarfVersion.
646 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
647   MS->SwitchSection(MOFI->getDwarfInfoSection());
648   MC->setDwarfVersion(DwarfVersion);
649 }
650
651 /// \brief Emit the compilation unit header for \p Unit in the
652 /// debug_info section.
653 ///
654 /// A Dwarf scetion header is encoded as:
655 ///  uint32_t   Unit length (omiting this field)
656 ///  uint16_t   Version
657 ///  uint32_t   Abbreviation table offset
658 ///  uint8_t    Address size
659 ///
660 /// Leading to a total of 11 bytes.
661 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
662   unsigned Version = Unit.getOrigUnit().getVersion();
663   switchToDebugInfoSection(Version);
664
665   // Emit size of content not including length itself. The size has
666   // already been computed in CompileUnit::computeOffsets(). Substract
667   // 4 to that size to account for the length field.
668   Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
669   Asm->EmitInt16(Version);
670   // We share one abbreviations table across all units so it's always at the
671   // start of the section.
672   Asm->EmitInt32(0);
673   Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
674 }
675
676 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
677 /// for the linked Dwarf file.
678 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
679   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
680   Asm->emitDwarfAbbrevs(Abbrevs);
681 }
682
683 /// \brief Recursively emit the DIE tree rooted at \p Die.
684 void DwarfStreamer::emitDIE(DIE &Die) {
685   MS->SwitchSection(MOFI->getDwarfInfoSection());
686   Asm->emitDwarfDIE(Die);
687 }
688
689 /// \brief Emit the debug_str section stored in \p Pool.
690 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
691   Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
692   for (auto *Entry = Pool.getFirstEntry(); Entry;
693        Entry = Pool.getNextEntry(Entry))
694     Asm->OutStreamer->EmitBytes(
695         StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
696 }
697
698 /// \brief Emit the debug_range section contents for \p FuncRange by
699 /// translating the original \p Entries. The debug_range section
700 /// format is totally trivial, consisting just of pairs of address
701 /// sized addresses describing the ranges.
702 void DwarfStreamer::emitRangesEntries(
703     int64_t UnitPcOffset, uint64_t OrigLowPc,
704     FunctionIntervals::const_iterator FuncRange,
705     const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
706     unsigned AddressSize) {
707   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
708
709   // Offset each range by the right amount.
710   int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
711   for (const auto &Range : Entries) {
712     if (Range.isBaseAddressSelectionEntry(AddressSize)) {
713       warn("unsupported base address selection operation",
714            "emitting debug_ranges");
715       break;
716     }
717     // Do not emit empty ranges.
718     if (Range.StartAddress == Range.EndAddress)
719       continue;
720
721     // All range entries should lie in the function range.
722     if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
723           Range.EndAddress + OrigLowPc <= FuncRange.stop()))
724       warn("inconsistent range data.", "emitting debug_ranges");
725     MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
726     MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
727     RangesSectionSize += 2 * AddressSize;
728   }
729
730   // Add the terminator entry.
731   MS->EmitIntValue(0, AddressSize);
732   MS->EmitIntValue(0, AddressSize);
733   RangesSectionSize += 2 * AddressSize;
734 }
735
736 /// \brief Emit the debug_aranges contribution of a unit and
737 /// if \p DoDebugRanges is true the debug_range contents for a
738 /// compile_unit level DW_AT_ranges attribute (Which are basically the
739 /// same thing with a different base address).
740 /// Just aggregate all the ranges gathered inside that unit.
741 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
742                                           bool DoDebugRanges) {
743   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
744   // Gather the ranges in a vector, so that we can simplify them. The
745   // IntervalMap will have coalesced the non-linked ranges, but here
746   // we want to coalesce the linked addresses.
747   std::vector<std::pair<uint64_t, uint64_t>> Ranges;
748   const auto &FunctionRanges = Unit.getFunctionRanges();
749   for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
750        Range != End; ++Range)
751     Ranges.push_back(std::make_pair(Range.start() + Range.value(),
752                                     Range.stop() + Range.value()));
753
754   // The object addresses where sorted, but again, the linked
755   // addresses might end up in a different order.
756   std::sort(Ranges.begin(), Ranges.end());
757
758   if (!Ranges.empty()) {
759     MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
760
761     MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
762     MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
763
764     unsigned HeaderSize =
765         sizeof(int32_t) + // Size of contents (w/o this field
766         sizeof(int16_t) + // DWARF ARange version number
767         sizeof(int32_t) + // Offset of CU in the .debug_info section
768         sizeof(int8_t) +  // Pointer Size (in bytes)
769         sizeof(int8_t);   // Segment Size (in bytes)
770
771     unsigned TupleSize = AddressSize * 2;
772     unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
773
774     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
775     Asm->OutStreamer->EmitLabel(BeginLabel);
776     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
777     Asm->EmitInt32(Unit.getStartOffset());     // Corresponding unit's offset
778     Asm->EmitInt8(AddressSize);                // Address size
779     Asm->EmitInt8(0);                          // Segment size
780
781     Asm->OutStreamer->EmitFill(Padding, 0x0);
782
783     for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
784          ++Range) {
785       uint64_t RangeStart = Range->first;
786       MS->EmitIntValue(RangeStart, AddressSize);
787       while ((Range + 1) != End && Range->second == (Range + 1)->first)
788         ++Range;
789       MS->EmitIntValue(Range->second - RangeStart, AddressSize);
790     }
791
792     // Emit terminator
793     Asm->OutStreamer->EmitIntValue(0, AddressSize);
794     Asm->OutStreamer->EmitIntValue(0, AddressSize);
795     Asm->OutStreamer->EmitLabel(EndLabel);
796   }
797
798   if (!DoDebugRanges)
799     return;
800
801   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
802   // Offset each range by the right amount.
803   int64_t PcOffset = -Unit.getLowPc();
804   // Emit coalesced ranges.
805   for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
806     MS->EmitIntValue(Range->first + PcOffset, AddressSize);
807     while (Range + 1 != End && Range->second == (Range + 1)->first)
808       ++Range;
809     MS->EmitIntValue(Range->second + PcOffset, AddressSize);
810     RangesSectionSize += 2 * AddressSize;
811   }
812
813   // Add the terminator entry.
814   MS->EmitIntValue(0, AddressSize);
815   MS->EmitIntValue(0, AddressSize);
816   RangesSectionSize += 2 * AddressSize;
817 }
818
819 /// \brief Emit location lists for \p Unit and update attribtues to
820 /// point to the new entries.
821 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
822                                          DWARFContext &Dwarf) {
823   const auto &Attributes = Unit.getLocationAttributes();
824
825   if (Attributes.empty())
826     return;
827
828   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
829
830   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
831   const DWARFSection &InputSec = Dwarf.getLocSection();
832   DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
833   DWARFUnit &OrigUnit = Unit.getOrigUnit();
834   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
835   int64_t UnitPcOffset = 0;
836   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
837       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
838   if (OrigLowPc != -1ULL)
839     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
840
841   for (const auto &Attr : Attributes) {
842     uint32_t Offset = Attr.first.get();
843     Attr.first.set(LocSectionSize);
844     // This is the quantity to add to the old location address to get
845     // the correct address for the new one.
846     int64_t LocPcOffset = Attr.second + UnitPcOffset;
847     while (Data.isValidOffset(Offset)) {
848       uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
849       uint64_t High = Data.getUnsigned(&Offset, AddressSize);
850       LocSectionSize += 2 * AddressSize;
851       if (Low == 0 && High == 0) {
852         Asm->OutStreamer->EmitIntValue(0, AddressSize);
853         Asm->OutStreamer->EmitIntValue(0, AddressSize);
854         break;
855       }
856       Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
857       Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
858       uint64_t Length = Data.getU16(&Offset);
859       Asm->OutStreamer->EmitIntValue(Length, 2);
860       // Just copy the bytes over.
861       Asm->OutStreamer->EmitBytes(
862           StringRef(InputSec.Data.substr(Offset, Length)));
863       Offset += Length;
864       LocSectionSize += Length + 2;
865     }
866   }
867 }
868
869 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
870                                          StringRef PrologueBytes,
871                                          unsigned MinInstLength,
872                                          std::vector<DWARFDebugLine::Row> &Rows,
873                                          unsigned PointerSize) {
874   // Switch to the section where the table will be emitted into.
875   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
876   MCSymbol *LineStartSym = MC->createTempSymbol();
877   MCSymbol *LineEndSym = MC->createTempSymbol();
878
879   // The first 4 bytes is the total length of the information for this
880   // compilation unit (not including these 4 bytes for the length).
881   Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
882   Asm->OutStreamer->EmitLabel(LineStartSym);
883   // Copy Prologue.
884   MS->EmitBytes(PrologueBytes);
885   LineSectionSize += PrologueBytes.size() + 4;
886
887   SmallString<128> EncodingBuffer;
888   raw_svector_ostream EncodingOS(EncodingBuffer);
889
890   if (Rows.empty()) {
891     // We only have the dummy entry, dsymutil emits an entry with a 0
892     // address in that case.
893     MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
894     MS->EmitBytes(EncodingOS.str());
895     LineSectionSize += EncodingBuffer.size();
896     MS->EmitLabel(LineEndSym);
897     return;
898   }
899
900   // Line table state machine fields
901   unsigned FileNum = 1;
902   unsigned LastLine = 1;
903   unsigned Column = 0;
904   unsigned IsStatement = 1;
905   unsigned Isa = 0;
906   uint64_t Address = -1ULL;
907
908   unsigned RowsSinceLastSequence = 0;
909
910   for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
911     auto &Row = Rows[Idx];
912
913     int64_t AddressDelta;
914     if (Address == -1ULL) {
915       MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
916       MS->EmitULEB128IntValue(PointerSize + 1);
917       MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
918       MS->EmitIntValue(Row.Address, PointerSize);
919       LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
920       AddressDelta = 0;
921     } else {
922       AddressDelta = (Row.Address - Address) / MinInstLength;
923     }
924
925     // FIXME: code copied and transfromed from
926     // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
927     // this code, but the current compatibility requirement with
928     // classic dsymutil makes it hard. Revisit that once this
929     // requirement is dropped.
930
931     if (FileNum != Row.File) {
932       FileNum = Row.File;
933       MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
934       MS->EmitULEB128IntValue(FileNum);
935       LineSectionSize += 1 + getULEB128Size(FileNum);
936     }
937     if (Column != Row.Column) {
938       Column = Row.Column;
939       MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
940       MS->EmitULEB128IntValue(Column);
941       LineSectionSize += 1 + getULEB128Size(Column);
942     }
943
944     // FIXME: We should handle the discriminator here, but dsymutil
945     // doesn' consider it, thus ignore it for now.
946
947     if (Isa != Row.Isa) {
948       Isa = Row.Isa;
949       MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
950       MS->EmitULEB128IntValue(Isa);
951       LineSectionSize += 1 + getULEB128Size(Isa);
952     }
953     if (IsStatement != Row.IsStmt) {
954       IsStatement = Row.IsStmt;
955       MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
956       LineSectionSize += 1;
957     }
958     if (Row.BasicBlock) {
959       MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
960       LineSectionSize += 1;
961     }
962
963     if (Row.PrologueEnd) {
964       MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
965       LineSectionSize += 1;
966     }
967
968     if (Row.EpilogueBegin) {
969       MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
970       LineSectionSize += 1;
971     }
972
973     int64_t LineDelta = int64_t(Row.Line) - LastLine;
974     if (!Row.EndSequence) {
975       MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
976       MS->EmitBytes(EncodingOS.str());
977       LineSectionSize += EncodingBuffer.size();
978       EncodingBuffer.resize(0);
979       Address = Row.Address;
980       LastLine = Row.Line;
981       RowsSinceLastSequence++;
982     } else {
983       if (LineDelta) {
984         MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
985         MS->EmitSLEB128IntValue(LineDelta);
986         LineSectionSize += 1 + getSLEB128Size(LineDelta);
987       }
988       if (AddressDelta) {
989         MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
990         MS->EmitULEB128IntValue(AddressDelta);
991         LineSectionSize += 1 + getULEB128Size(AddressDelta);
992       }
993       MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
994       MS->EmitBytes(EncodingOS.str());
995       LineSectionSize += EncodingBuffer.size();
996       EncodingBuffer.resize(0);
997       Address = -1ULL;
998       LastLine = FileNum = IsStatement = 1;
999       RowsSinceLastSequence = Column = Isa = 0;
1000     }
1001   }
1002
1003   if (RowsSinceLastSequence) {
1004     MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1005     MS->EmitBytes(EncodingOS.str());
1006     LineSectionSize += EncodingBuffer.size();
1007     EncodingBuffer.resize(0);
1008   }
1009
1010   MS->EmitLabel(LineEndSym);
1011 }
1012
1013 /// \brief Emit the pubnames or pubtypes section contribution for \p
1014 /// Unit into \p Sec. The data is provided in \p Names.
1015 void DwarfStreamer::emitPubSectionForUnit(
1016     MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1017     const std::vector<CompileUnit::AccelInfo> &Names) {
1018   if (Names.empty())
1019     return;
1020
1021   // Start the dwarf pubnames section.
1022   Asm->OutStreamer->SwitchSection(Sec);
1023   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1024   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1025
1026   bool HeaderEmitted = false;
1027   // Emit the pubnames for this compilation unit.
1028   for (const auto &Name : Names) {
1029     if (Name.SkipPubSection)
1030       continue;
1031
1032     if (!HeaderEmitted) {
1033       // Emit the header.
1034       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1035       Asm->OutStreamer->EmitLabel(BeginLabel);
1036       Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1037       Asm->EmitInt32(Unit.getStartOffset());      // Unit offset
1038       Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1039       HeaderEmitted = true;
1040     }
1041     Asm->EmitInt32(Name.Die->getOffset());
1042     Asm->OutStreamer->EmitBytes(
1043         StringRef(Name.Name.data(), Name.Name.size() + 1));
1044   }
1045
1046   if (!HeaderEmitted)
1047     return;
1048   Asm->EmitInt32(0); // End marker.
1049   Asm->OutStreamer->EmitLabel(EndLabel);
1050 }
1051
1052 /// \brief Emit .debug_pubnames for \p Unit.
1053 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1054   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1055                         "names", Unit, Unit.getPubnames());
1056 }
1057
1058 /// \brief Emit .debug_pubtypes for \p Unit.
1059 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1060   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1061                         "types", Unit, Unit.getPubtypes());
1062 }
1063
1064 /// \brief Emit a CIE into the debug_frame section.
1065 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1066   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1067
1068   MS->EmitBytes(CIEBytes);
1069   FrameSectionSize += CIEBytes.size();
1070 }
1071
1072 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1073 /// contains the FDE data without the length, CIE offset and address
1074 /// which will be replaced with the paramter values.
1075 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1076                             uint32_t Address, StringRef FDEBytes) {
1077   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1078
1079   MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1080   MS->EmitIntValue(CIEOffset, 4);
1081   MS->EmitIntValue(Address, AddrSize);
1082   MS->EmitBytes(FDEBytes);
1083   FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1084 }
1085
1086 /// \brief The core of the Dwarf linking logic.
1087 ///
1088 /// The link of the dwarf information from the object files will be
1089 /// driven by the selection of 'root DIEs', which are DIEs that
1090 /// describe variables or functions that are present in the linked
1091 /// binary (and thus have entries in the debug map). All the debug
1092 /// information that will be linked (the DIEs, but also the line
1093 /// tables, ranges, ...) is derived from that set of root DIEs.
1094 ///
1095 /// The root DIEs are identified because they contain relocations that
1096 /// correspond to a debug map entry at specific places (the low_pc for
1097 /// a function, the location for a variable). These relocations are
1098 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1099 /// first step when we start processing a DebugMapObject.
1100 class DwarfLinker {
1101 public:
1102   DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1103       : OutputFilename(OutputFilename), Options(Options),
1104         BinHolder(Options.Verbose), LastCIEOffset(0) {}
1105
1106   ~DwarfLinker() {
1107     for (auto *Abbrev : Abbreviations)
1108       delete Abbrev;
1109   }
1110
1111   /// \brief Link the contents of the DebugMap.
1112   bool link(const DebugMap &);
1113
1114   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1115                      const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1116
1117 private:
1118   /// \brief Called at the start of a debug object link.
1119   void startDebugObject(DWARFContext &, DebugMapObject &);
1120
1121   /// \brief Called at the end of a debug object link.
1122   void endDebugObject();
1123
1124   /// Keeps track of relocations.
1125   class RelocationManager {
1126     struct ValidReloc {
1127       uint32_t Offset;
1128       uint32_t Size;
1129       uint64_t Addend;
1130       const DebugMapObject::DebugMapEntry *Mapping;
1131
1132       ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1133                  const DebugMapObject::DebugMapEntry *Mapping)
1134           : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1135
1136       bool operator<(const ValidReloc &RHS) const {
1137         return Offset < RHS.Offset;
1138       }
1139     };
1140
1141     DwarfLinker &Linker;
1142
1143     /// \brief The valid relocations for the current DebugMapObject.
1144     /// This vector is sorted by relocation offset.
1145     std::vector<ValidReloc> ValidRelocs;
1146
1147     /// \brief Index into ValidRelocs of the next relocation to
1148     /// consider. As we walk the DIEs in acsending file offset and as
1149     /// ValidRelocs is sorted by file offset, keeping this index
1150     /// uptodate is all we have to do to have a cheap lookup during the
1151     /// root DIE selection and during DIE cloning.
1152     unsigned NextValidReloc;
1153
1154   public:
1155     RelocationManager(DwarfLinker &Linker)
1156         : Linker(Linker), NextValidReloc(0) {}
1157
1158     bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1159     /// \brief Reset the NextValidReloc counter.
1160     void resetValidRelocs() { NextValidReloc = 0; }
1161
1162     /// \defgroup FindValidRelocations Translate debug map into a list
1163     /// of relevant relocations
1164     ///
1165     /// @{
1166     bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1167                                     const DebugMapObject &DMO);
1168
1169     bool findValidRelocs(const object::SectionRef &Section,
1170                          const object::ObjectFile &Obj,
1171                          const DebugMapObject &DMO);
1172
1173     void findValidRelocsMachO(const object::SectionRef &Section,
1174                               const object::MachOObjectFile &Obj,
1175                               const DebugMapObject &DMO);
1176     /// @}
1177
1178     bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1179                             CompileUnit::DIEInfo &Info);
1180
1181     bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1182                           bool isLittleEndian);
1183   };
1184
1185   /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1186   ///
1187   /// @{
1188   /// \brief Recursively walk the \p DIE tree and look for DIEs to
1189   /// keep. Store that information in \p CU's DIEInfo.
1190   void lookForDIEsToKeep(RelocationManager &RelocMgr,
1191                          const DWARFDebugInfoEntryMinimal &DIE,
1192                          const DebugMapObject &DMO, CompileUnit &CU,
1193                          unsigned Flags);
1194
1195   /// If this compile unit is really a skeleton CU that points to a
1196   /// clang module, register it in ClangModules and return true.
1197   ///
1198   /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1199   /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1200   /// hash.
1201   bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1202                                const DWARFUnit &Unit, DebugMap &ModuleMap,
1203                                unsigned Indent = 0);
1204
1205   /// Recursively add the debug info in this clang module .pcm
1206   /// file (and all the modules imported by it in a bottom-up fashion)
1207   /// to Units.
1208   void loadClangModule(StringRef Filename, StringRef ModulePath,
1209                        DebugMap &ModuleMap, unsigned Indent = 0);
1210
1211   /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1212   enum TravesalFlags {
1213     TF_Keep = 1 << 0,            ///< Mark the traversed DIEs as kept.
1214     TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1215     TF_DependencyWalk = 1 << 2,  ///< Walking the dependencies of a kept DIE.
1216     TF_ParentWalk = 1 << 3,      ///< Walking up the parents of a kept DIE.
1217     TF_ODR = 1 << 4,             ///< Use the ODR whhile keeping dependants.
1218     TF_SkipPC = 1 << 5,          ///< Skip all location attributes.
1219   };
1220
1221   /// \brief Mark the passed DIE as well as all the ones it depends on
1222   /// as kept.
1223   void keepDIEAndDependencies(RelocationManager &RelocMgr,
1224                                const DWARFDebugInfoEntryMinimal &DIE,
1225                                CompileUnit::DIEInfo &MyInfo,
1226                                const DebugMapObject &DMO, CompileUnit &CU,
1227                                bool UseODR);
1228
1229   unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1230                          const DWARFDebugInfoEntryMinimal &DIE,
1231                          CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1232                          unsigned Flags);
1233
1234   unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1235                                  const DWARFDebugInfoEntryMinimal &DIE,
1236                                  CompileUnit &Unit,
1237                                  CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1238
1239   unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1240                                    const DWARFDebugInfoEntryMinimal &DIE,
1241                                    CompileUnit &Unit,
1242                                    CompileUnit::DIEInfo &MyInfo,
1243                                    unsigned Flags);
1244
1245   bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1246                           CompileUnit::DIEInfo &Info);
1247   /// @}
1248
1249   /// \defgroup Linking Methods used to link the debug information
1250   ///
1251   /// @{
1252
1253   class DIECloner {
1254     DwarfLinker &Linker;
1255     RelocationManager &RelocMgr;
1256     /// Allocator used for all the DIEValue objects.
1257     BumpPtrAllocator &DIEAlloc;
1258     MutableArrayRef<CompileUnit> CompileUnits;
1259     LinkOptions Options;
1260
1261   public:
1262     DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1263               BumpPtrAllocator &DIEAlloc,
1264               MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1265         : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1266           CompileUnits(CompileUnits), Options(Options) {}
1267
1268     /// Recursively clone \p InputDIE into an tree of DIE objects
1269     /// where useless (as decided by lookForDIEsToKeep()) bits have been
1270     /// stripped out and addresses have been rewritten according to the
1271     /// debug map.
1272     ///
1273     /// \param OutOffset is the offset the cloned DIE in the output
1274     /// compile unit.
1275     /// \param PCOffset (while cloning a function scope) is the offset
1276     /// applied to the entry point of the function to get the linked address.
1277     ///
1278     /// \returns the root of the cloned tree or null if nothing was selected.
1279     DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1280                   int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
1281
1282     /// Construct the output DIE tree by cloning the DIEs we
1283     /// chose to keep above. If there are no valid relocs, then there's
1284     /// nothing to clone/emit.
1285     void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
1286
1287   private:
1288     typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1289
1290     /// Information gathered and exchanged between the various
1291     /// clone*Attributes helpers about the attributes of a particular DIE.
1292     struct AttributesInfo {
1293       const char *Name, *MangledName;         ///< Names.
1294       uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1295
1296       uint64_t OrigLowPc;  ///< Value of AT_low_pc in the input DIE
1297       uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1298       int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1299
1300       bool HasLowPc;      ///< Does the DIE have a low_pc attribute?
1301       bool IsDeclaration; ///< Is this DIE only a declaration?
1302
1303       AttributesInfo()
1304           : Name(nullptr), MangledName(nullptr), NameOffset(0),
1305             MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1306             PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1307     };
1308
1309     /// Helper for cloneDIE.
1310     unsigned cloneAttribute(DIE &Die,
1311                             const DWARFDebugInfoEntryMinimal &InputDIE,
1312                             CompileUnit &U, const DWARFFormValue &Val,
1313                             const AttributeSpec AttrSpec, unsigned AttrSize,
1314                             AttributesInfo &AttrInfo);
1315
1316     /// Clone a string attribute described by \p AttrSpec and add
1317     /// it to \p Die.
1318     /// \returns the size of the new attribute.
1319     unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1320                                   const DWARFFormValue &Val,
1321                                   const DWARFUnit &U);
1322
1323     /// Clone an attribute referencing another DIE and add
1324     /// it to \p Die.
1325     /// \returns the size of the new attribute.
1326     unsigned
1327     cloneDieReferenceAttribute(DIE &Die,
1328                                const DWARFDebugInfoEntryMinimal &InputDIE,
1329                                AttributeSpec AttrSpec, unsigned AttrSize,
1330                                const DWARFFormValue &Val, CompileUnit &Unit);
1331
1332     /// Clone an attribute referencing another DIE and add
1333     /// it to \p Die.
1334     /// \returns the size of the new attribute.
1335     unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1336                                  const DWARFFormValue &Val, unsigned AttrSize);
1337
1338     /// Clone an attribute referencing another DIE and add
1339     /// it to \p Die.
1340     /// \returns the size of the new attribute.
1341     unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1342                                    const DWARFFormValue &Val,
1343                                    const CompileUnit &Unit,
1344                                    AttributesInfo &Info);
1345
1346     /// Clone a scalar attribute  and add it to \p Die.
1347     /// \returns the size of the new attribute.
1348     unsigned cloneScalarAttribute(DIE &Die,
1349                                   const DWARFDebugInfoEntryMinimal &InputDIE,
1350                                   CompileUnit &U, AttributeSpec AttrSpec,
1351                                   const DWARFFormValue &Val, unsigned AttrSize,
1352                                   AttributesInfo &Info);
1353
1354     /// Get the potential name and mangled name for the entity
1355     /// described by \p Die and store them in \Info if they are not
1356     /// already there.
1357     /// \returns is a name was found.
1358     bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1359                      AttributesInfo &Info);
1360
1361     /// Create a copy of abbreviation Abbrev.
1362     void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
1363   };
1364
1365   /// \brief Assign an abbreviation number to \p Abbrev
1366   void AssignAbbrev(DIEAbbrev &Abbrev);
1367
1368   /// \brief FoldingSet that uniques the abbreviations.
1369   FoldingSet<DIEAbbrev> AbbreviationsSet;
1370   /// \brief Storage for the unique Abbreviations.
1371   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1372   /// be changed to a vecot of unique_ptrs.
1373   std::vector<DIEAbbrev *> Abbreviations;
1374
1375   /// \brief Compute and emit debug_ranges section for \p Unit, and
1376   /// patch the attributes referencing it.
1377   void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1378
1379   /// \brief Generate and emit the DW_AT_ranges attribute for a
1380   /// compile_unit if it had one.
1381   void generateUnitRanges(CompileUnit &Unit) const;
1382
1383   /// \brief Extract the line tables fromt he original dwarf, extract
1384   /// the relevant parts according to the linked function ranges and
1385   /// emit the result in the debug_line section.
1386   void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1387
1388   /// \brief Emit the accelerator entries for \p Unit.
1389   void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1390
1391   /// \brief Patch the frame info for an object file and emit it.
1392   void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1393                                unsigned AddressSize);
1394
1395   /// \brief DIELoc objects that need to be destructed (but not freed!).
1396   std::vector<DIELoc *> DIELocs;
1397   /// \brief DIEBlock objects that need to be destructed (but not freed!).
1398   std::vector<DIEBlock *> DIEBlocks;
1399   /// \brief Allocator used for all the DIEValue objects.
1400   BumpPtrAllocator DIEAlloc;
1401   /// @}
1402
1403   /// ODR Contexts for that link.
1404   DeclContextTree ODRContexts;
1405
1406   /// \defgroup Helpers Various helper methods.
1407   ///
1408   /// @{
1409   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1410
1411   /// \brief Attempt to load a debug object from disk.
1412   ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1413                                                  DebugMapObject &Obj,
1414                                                  const DebugMap &Map);
1415   /// @}
1416
1417   std::string OutputFilename;
1418   LinkOptions Options;
1419   BinaryHolder BinHolder;
1420   std::unique_ptr<DwarfStreamer> Streamer;
1421   uint64_t OutputDebugInfoSize;
1422   unsigned UnitID; ///< A unique ID that identifies each compile unit.
1423
1424   /// The units of the current debug map object.
1425   std::vector<CompileUnit> Units;
1426
1427   /// The debug map object curently under consideration.
1428   DebugMapObject *CurrentDebugObject;
1429
1430   /// \brief The Dwarf string pool
1431   NonRelocatableStringpool StringPool;
1432
1433   /// \brief This map is keyed by the entry PC of functions in that
1434   /// debug object and the associated value is a pair storing the
1435   /// corresponding end PC and the offset to apply to get the linked
1436   /// address.
1437   ///
1438   /// See startDebugObject() for a more complete description of its use.
1439   std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1440
1441   /// \brief The CIEs that have been emitted in the output
1442   /// section. The actual CIE data serves a the key to this StringMap,
1443   /// this takes care of comparing the semantics of CIEs defined in
1444   /// different object files.
1445   StringMap<uint32_t> EmittedCIEs;
1446
1447   /// Offset of the last CIE that has been emitted in the output
1448   /// debug_frame section.
1449   uint32_t LastCIEOffset;
1450
1451   /// FIXME: We may need to use something more resilient than the PCM filename.
1452   StringSet<> ClangModules;
1453 };
1454
1455 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1456 /// CompileUnit object instead.
1457 static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1458                                      unsigned Offset) {
1459   auto CU =
1460       std::upper_bound(Units.begin(), Units.end(), Offset,
1461                        [](uint32_t LHS, const CompileUnit &RHS) {
1462                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
1463                        });
1464   return CU != Units.end() ? &*CU : nullptr;
1465 }
1466
1467 /// Resolve the DIE attribute reference that has been
1468 /// extracted in \p RefValue. The resulting DIE migh be in another
1469 /// CompileUnit which is stored into \p ReferencedCU.
1470 /// \returns null if resolving fails for any reason.
1471 static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1472     const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
1473     const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1474     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1475   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1476   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1477
1478   if ((RefCU = getUnitForOffset(Units, RefOffset)))
1479     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1480       return RefDie;
1481
1482   Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
1483   return nullptr;
1484 }
1485
1486 /// \returns whether the passed \a Attr type might contain a DIE
1487 /// reference suitable for ODR uniquing.
1488 static bool isODRAttribute(uint16_t Attr) {
1489   switch (Attr) {
1490   default:
1491     return false;
1492   case dwarf::DW_AT_type:
1493   case dwarf::DW_AT_containing_type:
1494   case dwarf::DW_AT_specification:
1495   case dwarf::DW_AT_abstract_origin:
1496   case dwarf::DW_AT_import:
1497     return true;
1498   }
1499   llvm_unreachable("Improper attribute.");
1500 }
1501
1502 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1503 /// the context if it is ambiguous.
1504 ///
1505 /// In the current implementation, we don't handle overloaded
1506 /// functions well, because the argument types are not taken into
1507 /// account when computing the DeclContext tree.
1508 ///
1509 /// Some of this is mitigated byt using mangled names that do contain
1510 /// the arguments types, but sometimes (eg. with function templates)
1511 /// we don't have that. In that case, just do not unique anything that
1512 /// refers to the contexts we are not able to distinguish.
1513 ///
1514 /// If a context that is not a namespace appears twice in the same CU,
1515 /// we know it is ambiguous. Make it invalid.
1516 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1517                                  const DWARFDebugInfoEntryMinimal *Die) {
1518   if (LastSeenCompileUnitID == U.getUniqueID()) {
1519     DWARFUnit &OrigUnit = U.getOrigUnit();
1520     uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1521     U.getInfo(FirstIdx).Ctxt = nullptr;
1522     return false;
1523   }
1524
1525   LastSeenCompileUnitID = U.getUniqueID();
1526   LastSeenDIE = Die;
1527   return true;
1528 }
1529
1530 /// Get the child context of \a Context corresponding to \a DIE.
1531 ///
1532 /// \returns the child context or null if we shouldn't track children
1533 /// contexts. It also returns an additional bit meaning 'invalid'. An
1534 /// invalid context means it shouldn't be considered for uniquing, but
1535 /// its not returning null, because some children of that context
1536 /// might be uniquing candidates.
1537 /// FIXME: this is for dsymutil-classic compatibility, I don't think
1538 /// it buys us much.
1539 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1540     DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1541     NonRelocatableStringpool &StringPool) {
1542   unsigned Tag = DIE->getTag();
1543
1544   // FIXME: dsymutil-classic compat: We should bail out here if we
1545   // have a specification or an abstract_origin. We will get the
1546   // parent context wrong here.
1547
1548   switch (Tag) {
1549   default:
1550     // By default stop gathering child contexts.
1551     return PointerIntPair<DeclContext *, 1>(nullptr);
1552   case dwarf::DW_TAG_compile_unit:
1553     // FIXME: Add support for DW_TAG_module.
1554     return PointerIntPair<DeclContext *, 1>(&Context);
1555   case dwarf::DW_TAG_subprogram:
1556     // Do not unique anything inside CU local functions.
1557     if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1558          Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1559         !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1560                                                   dwarf::DW_AT_external, 0))
1561       return PointerIntPair<DeclContext *, 1>(nullptr);
1562   // Fallthrough
1563   case dwarf::DW_TAG_member:
1564   case dwarf::DW_TAG_namespace:
1565   case dwarf::DW_TAG_structure_type:
1566   case dwarf::DW_TAG_class_type:
1567   case dwarf::DW_TAG_union_type:
1568   case dwarf::DW_TAG_enumeration_type:
1569   case dwarf::DW_TAG_typedef:
1570     // Artificial things might be ambiguous, because they might be
1571     // created on demand. For example implicitely defined constructors
1572     // are ambiguous because of the way we identify contexts, and they
1573     // won't be generated everytime everywhere.
1574     if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1575                                                  dwarf::DW_AT_artificial, 0))
1576       return PointerIntPair<DeclContext *, 1>(nullptr);
1577     break;
1578   }
1579
1580   const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1581   const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1582   StringRef NameRef;
1583   StringRef ShortNameRef;
1584   StringRef FileRef;
1585
1586   if (Name)
1587     NameRef = StringPool.internString(Name);
1588   else if (Tag == dwarf::DW_TAG_namespace)
1589     // FIXME: For dsymutil-classic compatibility. I think uniquing
1590     // within anonymous namespaces is wrong. There is no ODR guarantee
1591     // there.
1592     NameRef = StringPool.internString("(anonymous namespace)");
1593
1594   if (ShortName && ShortName != Name)
1595     ShortNameRef = StringPool.internString(ShortName);
1596   else
1597     ShortNameRef = NameRef;
1598
1599   if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1600       Tag != dwarf::DW_TAG_union_type &&
1601       Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1602     return PointerIntPair<DeclContext *, 1>(nullptr);
1603
1604   std::string File;
1605   unsigned Line = 0;
1606   unsigned ByteSize = 0;
1607
1608   // Gather some discriminating data about the DeclContext we will be
1609   // creating: File, line number and byte size. This shouldn't be
1610   // necessary, because the ODR is just about names, but given that we
1611   // do some approximations with overloaded functions and anonymous
1612   // namespaces, use these additional data points to make the process safer.
1613   ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1614       &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1615   if (Tag != dwarf::DW_TAG_namespace || !Name) {
1616     if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1617             &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1618       if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1619               &U.getOrigUnit())) {
1620         // FIXME: dsymutil-classic compatibility. I'd rather not
1621         // unique anything in anonymous namespaces, but if we do, then
1622         // verify that the file and line correspond.
1623         if (!Name && Tag == dwarf::DW_TAG_namespace)
1624           FileNum = 1;
1625
1626         // FIXME: Passing U.getOrigUnit().getCompilationDir()
1627         // instead of "" would allow more uniquing, but for now, do
1628         // it this way to match dsymutil-classic.
1629         if (LT->getFileNameByIndex(
1630                 FileNum, "",
1631                 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1632                 File)) {
1633           Line = DIE->getAttributeValueAsUnsignedConstant(
1634               &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1635 #ifdef HAVE_REALPATH
1636           // Cache the resolved paths, because calling realpath is expansive.
1637           if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1638             File = ResolvedPath;
1639           } else {
1640             char RealPath[PATH_MAX + 1];
1641             RealPath[PATH_MAX] = 0;
1642             if (::realpath(File.c_str(), RealPath))
1643               File = RealPath;
1644             U.setResolvedPath(FileNum, File);
1645           }
1646 #endif
1647           FileRef = StringPool.internString(File);
1648         }
1649       }
1650     }
1651   }
1652
1653   if (!Line && NameRef.empty())
1654     return PointerIntPair<DeclContext *, 1>(nullptr);
1655
1656   // FIXME: dsymutil-classic compat won't unique the same type
1657   // presented once as a struct and once as a class. Use the Tag in
1658   // the fully qualified name hash to get the same effect.
1659   // We hash NameRef, which is the mangled name, in order to get most
1660   // overloaded functions resolvec correctly.
1661   unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1662
1663   // FIXME: dsymutil-classic compatibility: when we don't have a name,
1664   // use the filename.
1665   if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1666     Hash = hash_combine(Hash, FileRef);
1667
1668   // Now look if this context already exists.
1669   DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1670   auto ContextIter = Contexts.find(&Key);
1671
1672   if (ContextIter == Contexts.end()) {
1673     // The context wasn't found.
1674     bool Inserted;
1675     DeclContext *NewContext =
1676         new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1677                                     Context, DIE, U.getUniqueID());
1678     std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1679     assert(Inserted && "Failed to insert DeclContext");
1680     (void)Inserted;
1681   } else if (Tag != dwarf::DW_TAG_namespace &&
1682              !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1683     // The context was found, but it is ambiguous with another context
1684     // in the same file. Mark it invalid.
1685     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1686   }
1687
1688   assert(ContextIter != Contexts.end());
1689   // FIXME: dsymutil-classic compatibility. Union types aren't
1690   // uniques, but their children might be.
1691   if ((Tag == dwarf::DW_TAG_subprogram &&
1692        Context.getTag() != dwarf::DW_TAG_structure_type &&
1693        Context.getTag() != dwarf::DW_TAG_class_type) ||
1694       (Tag == dwarf::DW_TAG_union_type))
1695     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1696
1697   return PointerIntPair<DeclContext *, 1>(*ContextIter);
1698 }
1699
1700 bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1701                                          DWARFUnit &U, AttributesInfo &Info) {
1702   // FIXME: a bit wasteful as the first getName might return the
1703   // short name.
1704   if (!Info.MangledName &&
1705       (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1706     Info.MangledNameOffset =
1707         Linker.StringPool.getStringOffset(Info.MangledName);
1708
1709   if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1710     Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
1711
1712   return Info.Name || Info.MangledName;
1713 }
1714
1715 /// \brief Report a warning to the user, optionaly including
1716 /// information about a specific \p DIE related to the warning.
1717 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1718                                 const DWARFDebugInfoEntryMinimal *DIE) const {
1719   StringRef Context = "<debug map>";
1720   if (CurrentDebugObject)
1721     Context = CurrentDebugObject->getObjectFilename();
1722   warn(Warning, Context);
1723
1724   if (!Options.Verbose || !DIE)
1725     return;
1726
1727   errs() << "    in DIE:\n";
1728   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1729             6 /* Indent */);
1730 }
1731
1732 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1733   if (Options.NoOutput)
1734     return true;
1735
1736   Streamer = llvm::make_unique<DwarfStreamer>();
1737   return Streamer->init(TheTriple, OutputFilename);
1738 }
1739
1740 /// \brief Recursive helper to gather the child->parent relationships in the
1741 /// original compile unit.
1742 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1743                              unsigned ParentIdx, CompileUnit &CU,
1744                              DeclContext *CurrentDeclContext,
1745                              NonRelocatableStringpool &StringPool,
1746                              DeclContextTree &Contexts) {
1747   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1748   CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1749
1750   Info.ParentIdx = ParentIdx;
1751   if (CU.hasODR()) {
1752     if (CurrentDeclContext) {
1753       auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1754                                                          DIE, CU, StringPool);
1755       CurrentDeclContext = PtrInvalidPair.getPointer();
1756       Info.Ctxt =
1757           PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1758     } else
1759       Info.Ctxt = CurrentDeclContext = nullptr;
1760   }
1761
1762   if (DIE->hasChildren())
1763     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1764          Child = Child->getSibling())
1765       gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1766                        Contexts);
1767 }
1768
1769 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1770   switch (Tag) {
1771   default:
1772     return false;
1773   case dwarf::DW_TAG_subprogram:
1774   case dwarf::DW_TAG_lexical_block:
1775   case dwarf::DW_TAG_subroutine_type:
1776   case dwarf::DW_TAG_structure_type:
1777   case dwarf::DW_TAG_class_type:
1778   case dwarf::DW_TAG_union_type:
1779     return true;
1780   }
1781   llvm_unreachable("Invalid Tag");
1782 }
1783
1784 static unsigned getRefAddrSize(const DWARFUnit &U) {
1785   if (U.getVersion() == 2)
1786     return U.getAddressByteSize();
1787   return 4;
1788 }
1789
1790 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1791   Units.reserve(Dwarf.getNumCompileUnits());
1792   // Iterate over the debug map entries and put all the ones that are
1793   // functions (because they have a size) into the Ranges map. This
1794   // map is very similar to the FunctionRanges that are stored in each
1795   // unit, with 2 notable differences:
1796   //  - obviously this one is global, while the other ones are per-unit.
1797   //  - this one contains not only the functions described in the DIE
1798   // tree, but also the ones that are only in the debug map.
1799   // The latter information is required to reproduce dsymutil's logic
1800   // while linking line tables. The cases where this information
1801   // matters look like bugs that need to be investigated, but for now
1802   // we need to reproduce dsymutil's behavior.
1803   // FIXME: Once we understood exactly if that information is needed,
1804   // maybe totally remove this (or try to use it to do a real
1805   // -gline-tables-only on Darwin.
1806   for (const auto &Entry : Obj.symbols()) {
1807     const auto &Mapping = Entry.getValue();
1808     if (Mapping.Size)
1809       Ranges[Mapping.ObjectAddress] = std::make_pair(
1810           Mapping.ObjectAddress + Mapping.Size,
1811           int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1812   }
1813 }
1814
1815 void DwarfLinker::endDebugObject() {
1816   Units.clear();
1817   Ranges.clear();
1818
1819   for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1820     (*I)->~DIEBlock();
1821   for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1822     (*I)->~DIELoc();
1823
1824   DIEBlocks.clear();
1825   DIELocs.clear();
1826   DIEAlloc.Reset();
1827 }
1828
1829 /// \brief Iterate over the relocations of the given \p Section and
1830 /// store the ones that correspond to debug map entries into the
1831 /// ValidRelocs array.
1832 void DwarfLinker::RelocationManager::
1833 findValidRelocsMachO(const object::SectionRef &Section,
1834                      const object::MachOObjectFile &Obj,
1835                      const DebugMapObject &DMO) {
1836   StringRef Contents;
1837   Section.getContents(Contents);
1838   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1839
1840   for (const object::RelocationRef &Reloc : Section.relocations()) {
1841     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1842     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1843     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1844     uint64_t Offset64 = Reloc.getOffset();
1845     if ((RelocSize != 4 && RelocSize != 8)) {
1846       Linker.reportWarning(" unsupported relocation in debug_info section.");
1847       continue;
1848     }
1849     uint32_t Offset = Offset64;
1850     // Mach-o uses REL relocations, the addend is at the relocation offset.
1851     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1852
1853     auto Sym = Reloc.getSymbol();
1854     if (Sym != Obj.symbol_end()) {
1855       ErrorOr<StringRef> SymbolName = Sym->getName();
1856       if (!SymbolName) {
1857         Linker.reportWarning("error getting relocation symbol name.");
1858         continue;
1859       }
1860       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1861         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1862     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1863       // Do not store the addend. The addend was the address of the
1864       // symbol in the object file, the address in the binary that is
1865       // stored in the debug map doesn't need to be offseted.
1866       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1867     }
1868   }
1869 }
1870
1871 /// \brief Dispatch the valid relocation finding logic to the
1872 /// appropriate handler depending on the object file format.
1873 bool DwarfLinker::RelocationManager::findValidRelocs(
1874     const object::SectionRef &Section, const object::ObjectFile &Obj,
1875     const DebugMapObject &DMO) {
1876   // Dispatch to the right handler depending on the file type.
1877   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1878     findValidRelocsMachO(Section, *MachOObj, DMO);
1879   else
1880     Linker.reportWarning(Twine("unsupported object file type: ") +
1881                          Obj.getFileName());
1882
1883   if (ValidRelocs.empty())
1884     return false;
1885
1886   // Sort the relocations by offset. We will walk the DIEs linearly in
1887   // the file, this allows us to just keep an index in the relocation
1888   // array that we advance during our walk, rather than resorting to
1889   // some associative container. See DwarfLinker::NextValidReloc.
1890   std::sort(ValidRelocs.begin(), ValidRelocs.end());
1891   return true;
1892 }
1893
1894 /// \brief Look for relocations in the debug_info section that match
1895 /// entries in the debug map. These relocations will drive the Dwarf
1896 /// link by indicating which DIEs refer to symbols present in the
1897 /// linked binary.
1898 /// \returns wether there are any valid relocations in the debug info.
1899 bool DwarfLinker::RelocationManager::
1900 findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1901                            const DebugMapObject &DMO) {
1902   // Find the debug_info section.
1903   for (const object::SectionRef &Section : Obj.sections()) {
1904     StringRef SectionName;
1905     Section.getName(SectionName);
1906     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1907     if (SectionName != "debug_info")
1908       continue;
1909     return findValidRelocs(Section, Obj, DMO);
1910   }
1911   return false;
1912 }
1913
1914 /// \brief Checks that there is a relocation against an actual debug
1915 /// map entry between \p StartOffset and \p NextOffset.
1916 ///
1917 /// This function must be called with offsets in strictly ascending
1918 /// order because it never looks back at relocations it already 'went past'.
1919 /// \returns true and sets Info.InDebugMap if it is the case.
1920 bool DwarfLinker::RelocationManager::
1921 hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1922                    CompileUnit::DIEInfo &Info) {
1923   assert(NextValidReloc == 0 ||
1924          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1925   if (NextValidReloc >= ValidRelocs.size())
1926     return false;
1927
1928   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1929
1930   // We might need to skip some relocs that we didn't consider. For
1931   // example the high_pc of a discarded DIE might contain a reloc that
1932   // is in the list because it actually corresponds to the start of a
1933   // function that is in the debug map.
1934   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1935     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1936
1937   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1938     return false;
1939
1940   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1941   const auto &Mapping = ValidReloc.Mapping->getValue();
1942   if (Linker.Options.Verbose)
1943     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1944            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1945                             uint64_t(Mapping.ObjectAddress),
1946                             uint64_t(Mapping.BinaryAddress));
1947
1948   Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1949                     Mapping.ObjectAddress;
1950   Info.InDebugMap = true;
1951   return true;
1952 }
1953
1954 /// \brief Get the starting and ending (exclusive) offset for the
1955 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1956 /// supposed to point to the position of the first attribute described
1957 /// by \p Abbrev.
1958 /// \return [StartOffset, EndOffset) as a pair.
1959 static std::pair<uint32_t, uint32_t>
1960 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1961                     unsigned Offset, const DWARFUnit &Unit) {
1962   DataExtractor Data = Unit.getDebugInfoExtractor();
1963
1964   for (unsigned i = 0; i < Idx; ++i)
1965     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1966
1967   uint32_t End = Offset;
1968   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1969
1970   return std::make_pair(Offset, End);
1971 }
1972
1973 /// \brief Check if a variable describing DIE should be kept.
1974 /// \returns updated TraversalFlags.
1975 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
1976                                             const DWARFDebugInfoEntryMinimal &DIE,
1977                                             CompileUnit &Unit,
1978                                             CompileUnit::DIEInfo &MyInfo,
1979                                             unsigned Flags) {
1980   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1981
1982   // Global variables with constant value can always be kept.
1983   if (!(Flags & TF_InFunctionScope) &&
1984       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1985     MyInfo.InDebugMap = true;
1986     return Flags | TF_Keep;
1987   }
1988
1989   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1990   if (LocationIdx == -1U)
1991     return Flags;
1992
1993   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1994   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1995   uint32_t LocationOffset, LocationEndOffset;
1996   std::tie(LocationOffset, LocationEndOffset) =
1997       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1998
1999   // See if there is a relocation to a valid debug map entry inside
2000   // this variable's location. The order is important here. We want to
2001   // always check in the variable has a valid relocation, so that the
2002   // DIEInfo is filled. However, we don't want a static variable in a
2003   // function to force us to keep the enclosing function.
2004   if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2005       (Flags & TF_InFunctionScope))
2006     return Flags;
2007
2008   if (Options.Verbose)
2009     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2010
2011   return Flags | TF_Keep;
2012 }
2013
2014 /// \brief Check if a function describing DIE should be kept.
2015 /// \returns updated TraversalFlags.
2016 unsigned DwarfLinker::shouldKeepSubprogramDIE(
2017     RelocationManager &RelocMgr,
2018     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2019     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2020   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2021
2022   Flags |= TF_InFunctionScope;
2023
2024   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2025   if (LowPcIdx == -1U)
2026     return Flags;
2027
2028   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2029   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2030   uint32_t LowPcOffset, LowPcEndOffset;
2031   std::tie(LowPcOffset, LowPcEndOffset) =
2032       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2033
2034   uint64_t LowPc =
2035       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2036   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2037   if (LowPc == -1ULL ||
2038       !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2039     return Flags;
2040
2041   if (Options.Verbose)
2042     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2043
2044   Flags |= TF_Keep;
2045
2046   DWARFFormValue HighPcValue;
2047   if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2048     reportWarning("Function without high_pc. Range will be discarded.\n",
2049                   &OrigUnit, &DIE);
2050     return Flags;
2051   }
2052
2053   uint64_t HighPc;
2054   if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2055     HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2056   } else {
2057     assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2058     HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2059   }
2060
2061   // Replace the debug map range with a more accurate one.
2062   Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2063   Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2064   return Flags;
2065 }
2066
2067 /// \brief Check if a DIE should be kept.
2068 /// \returns updated TraversalFlags.
2069 unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2070                                     const DWARFDebugInfoEntryMinimal &DIE,
2071                                     CompileUnit &Unit,
2072                                     CompileUnit::DIEInfo &MyInfo,
2073                                     unsigned Flags) {
2074   switch (DIE.getTag()) {
2075   case dwarf::DW_TAG_constant:
2076   case dwarf::DW_TAG_variable:
2077     return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2078   case dwarf::DW_TAG_subprogram:
2079     return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2080   case dwarf::DW_TAG_module:
2081   case dwarf::DW_TAG_imported_module:
2082   case dwarf::DW_TAG_imported_declaration:
2083   case dwarf::DW_TAG_imported_unit:
2084     // We always want to keep these.
2085     return Flags | TF_Keep;
2086   }
2087
2088   return Flags;
2089 }
2090
2091 /// \brief Mark the passed DIE as well as all the ones it depends on
2092 /// as kept.
2093 ///
2094 /// This function is called by lookForDIEsToKeep on DIEs that are
2095 /// newly discovered to be needed in the link. It recursively calls
2096 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2097 /// TraversalFlags to inform it that it's not doing the primary DIE
2098 /// tree walk.
2099 void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
2100                                           const DWARFDebugInfoEntryMinimal &Die,
2101                                           CompileUnit::DIEInfo &MyInfo,
2102                                           const DebugMapObject &DMO,
2103                                           CompileUnit &CU, bool UseODR) {
2104   const DWARFUnit &Unit = CU.getOrigUnit();
2105   MyInfo.Keep = true;
2106
2107   // First mark all the parent chain as kept.
2108   unsigned AncestorIdx = MyInfo.ParentIdx;
2109   while (!CU.getInfo(AncestorIdx).Keep) {
2110     unsigned ODRFlag = UseODR ? TF_ODR : 0;
2111     lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2112                       TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2113     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2114   }
2115
2116   // Then we need to mark all the DIEs referenced by this DIE's
2117   // attributes as kept.
2118   DataExtractor Data = Unit.getDebugInfoExtractor();
2119   const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2120   uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
2121
2122   // Mark all DIEs referenced through atttributes as kept.
2123   for (const auto &AttrSpec : Abbrev->attributes()) {
2124     DWARFFormValue Val(AttrSpec.Form);
2125
2126     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2127       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2128       continue;
2129     }
2130
2131     Val.extractValue(Data, &Offset, &Unit);
2132     CompileUnit *ReferencedCU;
2133     if (const auto *RefDIE =
2134             resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2135                                 Unit, Die, ReferencedCU)) {
2136       uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2137       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2138       // If the referenced DIE has a DeclContext that has already been
2139       // emitted, then do not keep the one in this CU. We'll link to
2140       // the canonical DIE in cloneDieReferenceAttribute.
2141       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2142       // be necessary and could be advantageously replaced by
2143       // ReferencedCU->hasODR() && CU.hasODR().
2144       // FIXME: compatibility with dsymutil-classic. There is no
2145       // reason not to unique ref_addr references.
2146       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2147           Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2148           Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2149         continue;
2150
2151       unsigned ODRFlag = UseODR ? TF_ODR : 0;
2152       lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
2153                         TF_Keep | TF_DependencyWalk | ODRFlag);
2154     }
2155   }
2156 }
2157
2158 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2159 /// keep. Store that information in \p CU's DIEInfo.
2160 ///
2161 /// This function is the entry point of the DIE selection
2162 /// algorithm. It is expected to walk the DIE tree in file order and
2163 /// (though the mediation of its helper) call hasValidRelocation() on
2164 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2165 /// comment).
2166 /// While walking the dependencies of root DIEs, this function is
2167 /// also called, but during these dependency walks the file order is
2168 /// not respected. The TF_DependencyWalk flag tells us which kind of
2169 /// traversal we are currently doing.
2170 void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2171                                     const DWARFDebugInfoEntryMinimal &Die,
2172                                     const DebugMapObject &DMO, CompileUnit &CU,
2173                                     unsigned Flags) {
2174   unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
2175   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2176   bool AlreadyKept = MyInfo.Keep;
2177
2178   // If the Keep flag is set, we are marking a required DIE's
2179   // dependencies. If our target is already marked as kept, we're all
2180   // set.
2181   if ((Flags & TF_DependencyWalk) && AlreadyKept)
2182     return;
2183
2184   // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
2185   // because it would screw up the relocation finding logic.
2186   if (!(Flags & TF_DependencyWalk))
2187     Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
2188
2189   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2190   if (!AlreadyKept && (Flags & TF_Keep)) {
2191     bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2192     keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
2193   }
2194   // The TF_ParentWalk flag tells us that we are currently walking up
2195   // the parent chain of a required DIE, and we don't want to mark all
2196   // the children of the parents as kept (consider for example a
2197   // DW_TAG_namespace node in the parent chain). There are however a
2198   // set of DIE types for which we want to ignore that directive and still
2199   // walk their children.
2200   if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
2201     Flags &= ~TF_ParentWalk;
2202
2203   if (!Die.hasChildren() || (Flags & TF_ParentWalk))
2204     return;
2205
2206   for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
2207        Child = Child->getSibling())
2208     lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
2209 }
2210
2211 /// \brief Assign an abbreviation numer to \p Abbrev.
2212 ///
2213 /// Our DIEs get freed after every DebugMapObject has been processed,
2214 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2215 /// the instances hold by the DIEs. When we encounter an abbreviation
2216 /// that we don't know, we create a permanent copy of it.
2217 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2218   // Check the set for priors.
2219   FoldingSetNodeID ID;
2220   Abbrev.Profile(ID);
2221   void *InsertToken;
2222   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2223
2224   // If it's newly added.
2225   if (InSet) {
2226     // Assign existing abbreviation number.
2227     Abbrev.setNumber(InSet->getNumber());
2228   } else {
2229     // Add to abbreviation list.
2230     Abbreviations.push_back(
2231         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2232     for (const auto &Attr : Abbrev.getData())
2233       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2234     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2235     // Assign the unique abbreviation number.
2236     Abbrev.setNumber(Abbreviations.size());
2237     Abbreviations.back()->setNumber(Abbreviations.size());
2238   }
2239 }
2240
2241 unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2242                                                       AttributeSpec AttrSpec,
2243                                                       const DWARFFormValue &Val,
2244                                                       const DWARFUnit &U) {
2245   // Switch everything to out of line strings.
2246   const char *String = *Val.getAsCString(&U);
2247   unsigned Offset = Linker.StringPool.getStringOffset(String);
2248   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2249                DIEInteger(Offset));
2250   return 4;
2251 }
2252
2253 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
2254     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2255     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2256     CompileUnit &Unit) {
2257   const DWARFUnit &U = Unit.getOrigUnit();
2258   uint32_t Ref = *Val.getAsReference(&U);
2259   DIE *NewRefDie = nullptr;
2260   CompileUnit *RefUnit = nullptr;
2261   DeclContext *Ctxt = nullptr;
2262
2263   const DWARFDebugInfoEntryMinimal *RefDie =
2264       resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
2265
2266   // If the referenced DIE is not found,  drop the attribute.
2267   if (!RefDie)
2268     return 0;
2269
2270   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2271   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2272
2273   // If we already have emitted an equivalent DeclContext, just point
2274   // at it.
2275   if (isODRAttribute(AttrSpec.Attr)) {
2276     Ctxt = RefInfo.Ctxt;
2277     if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2278       DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2279       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2280                    dwarf::DW_FORM_ref_addr, Attr);
2281       return getRefAddrSize(U);
2282     }
2283   }
2284
2285   if (!RefInfo.Clone) {
2286     assert(Ref > InputDIE.getOffset());
2287     // We haven't cloned this DIE yet. Just create an empty one and
2288     // store it. It'll get really cloned when we process it.
2289     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2290   }
2291   NewRefDie = RefInfo.Clone;
2292
2293   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2294       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2295     // We cannot currently rely on a DIEEntry to emit ref_addr
2296     // references, because the implementation calls back to DwarfDebug
2297     // to find the unit offset. (We don't have a DwarfDebug)
2298     // FIXME: we should be able to design DIEEntry reliance on
2299     // DwarfDebug away.
2300     uint64_t Attr;
2301     if (Ref < InputDIE.getOffset()) {
2302       // We must have already cloned that DIE.
2303       uint32_t NewRefOffset =
2304           RefUnit->getStartOffset() + NewRefDie->getOffset();
2305       Attr = NewRefOffset;
2306       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2307                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2308     } else {
2309       // A forward reference. Note and fixup later.
2310       Attr = 0xBADDEF;
2311       Unit.noteForwardReference(
2312           NewRefDie, RefUnit, Ctxt,
2313           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2314                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2315     }
2316     return getRefAddrSize(U);
2317   }
2318
2319   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2320                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2321   return AttrSize;
2322 }
2323
2324 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2325                                                      AttributeSpec AttrSpec,
2326                                                      const DWARFFormValue &Val,
2327                                                      unsigned AttrSize) {
2328   DIEValueList *Attr;
2329   DIEValue Value;
2330   DIELoc *Loc = nullptr;
2331   DIEBlock *Block = nullptr;
2332   // Just copy the block data over.
2333   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2334     Loc = new (DIEAlloc) DIELoc;
2335     Linker.DIELocs.push_back(Loc);
2336   } else {
2337     Block = new (DIEAlloc) DIEBlock;
2338     Linker.DIEBlocks.push_back(Block);
2339   }
2340   Attr = Loc ? static_cast<DIEValueList *>(Loc)
2341              : static_cast<DIEValueList *>(Block);
2342
2343   if (Loc)
2344     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2345                      dwarf::Form(AttrSpec.Form), Loc);
2346   else
2347     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2348                      dwarf::Form(AttrSpec.Form), Block);
2349   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2350   for (auto Byte : Bytes)
2351     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2352                    dwarf::DW_FORM_data1, DIEInteger(Byte));
2353   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2354   // the DIE class, this if could be replaced by
2355   // Attr->setSize(Bytes.size()).
2356   if (Linker.Streamer) {
2357     auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
2358     if (Loc)
2359       Loc->ComputeSize(AsmPrinter);
2360     else
2361       Block->ComputeSize(AsmPrinter);
2362   }
2363   Die.addValue(DIEAlloc, Value);
2364   return AttrSize;
2365 }
2366
2367 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2368     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2369     const CompileUnit &Unit, AttributesInfo &Info) {
2370   uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2371   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2372     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2373         Die.getTag() == dwarf::DW_TAG_lexical_block)
2374       // The low_pc of a block or inline subroutine might get
2375       // relocated because it happens to match the low_pc of the
2376       // enclosing subprogram. To prevent issues with that, always use
2377       // the low_pc from the input DIE if relocations have been applied.
2378       Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2379              Info.PCOffset;
2380     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2381       Addr = Unit.getLowPc();
2382       if (Addr == UINT64_MAX)
2383         return 0;
2384     }
2385     Info.HasLowPc = true;
2386   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2387     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2388       if (uint64_t HighPc = Unit.getHighPc())
2389         Addr = HighPc;
2390       else
2391         return 0;
2392     } else
2393       // If we have a high_pc recorded for the input DIE, use
2394       // it. Otherwise (when no relocations where applied) just use the
2395       // one we just decoded.
2396       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2397   }
2398
2399   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2400                static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2401   return Unit.getOrigUnit().getAddressByteSize();
2402 }
2403
2404 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
2405     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2406     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2407     AttributesInfo &Info) {
2408   uint64_t Value;
2409   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2410       Die.getTag() == dwarf::DW_TAG_compile_unit) {
2411     if (Unit.getLowPc() == -1ULL)
2412       return 0;
2413     // Dwarf >= 4 high_pc is an size, not an address.
2414     Value = Unit.getHighPc() - Unit.getLowPc();
2415   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2416     Value = *Val.getAsSectionOffset();
2417   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2418     Value = *Val.getAsSignedConstant();
2419   else if (auto OptionalValue = Val.getAsUnsignedConstant())
2420     Value = *OptionalValue;
2421   else {
2422     Linker.reportWarning(
2423         "Unsupported scalar attribute form. Dropping attribute.",
2424         &Unit.getOrigUnit(), &InputDIE);
2425     return 0;
2426   }
2427   PatchLocation Patch =
2428       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2429                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2430   if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2431     Unit.noteRangeAttribute(Die, Patch);
2432
2433   // A more generic way to check for location attributes would be
2434   // nice, but it's very unlikely that any other attribute needs a
2435   // location list.
2436   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2437            AttrSpec.Attr == dwarf::DW_AT_frame_base)
2438     Unit.noteLocationAttribute(Patch, Info.PCOffset);
2439   else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2440     Info.IsDeclaration = true;
2441
2442   return AttrSize;
2443 }
2444
2445 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2446 /// value \p Val, and add it to \p Die.
2447 /// \returns the size of the cloned attribute.
2448 unsigned DwarfLinker::DIECloner::cloneAttribute(
2449     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2450     const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2451     AttributesInfo &Info) {
2452   const DWARFUnit &U = Unit.getOrigUnit();
2453
2454   switch (AttrSpec.Form) {
2455   case dwarf::DW_FORM_strp:
2456   case dwarf::DW_FORM_string:
2457     return cloneStringAttribute(Die, AttrSpec, Val, U);
2458   case dwarf::DW_FORM_ref_addr:
2459   case dwarf::DW_FORM_ref1:
2460   case dwarf::DW_FORM_ref2:
2461   case dwarf::DW_FORM_ref4:
2462   case dwarf::DW_FORM_ref8:
2463     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2464                                       Unit);
2465   case dwarf::DW_FORM_block:
2466   case dwarf::DW_FORM_block1:
2467   case dwarf::DW_FORM_block2:
2468   case dwarf::DW_FORM_block4:
2469   case dwarf::DW_FORM_exprloc:
2470     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2471   case dwarf::DW_FORM_addr:
2472     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2473   case dwarf::DW_FORM_data1:
2474   case dwarf::DW_FORM_data2:
2475   case dwarf::DW_FORM_data4:
2476   case dwarf::DW_FORM_data8:
2477   case dwarf::DW_FORM_udata:
2478   case dwarf::DW_FORM_sdata:
2479   case dwarf::DW_FORM_sec_offset:
2480   case dwarf::DW_FORM_flag:
2481   case dwarf::DW_FORM_flag_present:
2482     return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2483                                 Info);
2484   default:
2485     Linker.reportWarning(
2486         "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2487         &InputDIE);
2488   }
2489
2490   return 0;
2491 }
2492
2493 /// \brief Apply the valid relocations found by findValidRelocs() to
2494 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2495 /// in the debug_info section.
2496 ///
2497 /// Like for findValidRelocs(), this function must be called with
2498 /// monotonic \p BaseOffset values.
2499 ///
2500 /// \returns wether any reloc has been applied.
2501 bool DwarfLinker::RelocationManager::
2502 applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2503                  bool isLittleEndian) {
2504   assert((NextValidReloc == 0 ||
2505           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2506          "BaseOffset should only be increasing.");
2507   if (NextValidReloc >= ValidRelocs.size())
2508     return false;
2509
2510   // Skip relocs that haven't been applied.
2511   while (NextValidReloc < ValidRelocs.size() &&
2512          ValidRelocs[NextValidReloc].Offset < BaseOffset)
2513     ++NextValidReloc;
2514
2515   bool Applied = false;
2516   uint64_t EndOffset = BaseOffset + Data.size();
2517   while (NextValidReloc < ValidRelocs.size() &&
2518          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2519          ValidRelocs[NextValidReloc].Offset < EndOffset) {
2520     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2521     assert(ValidReloc.Offset - BaseOffset < Data.size());
2522     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2523     char Buf[8];
2524     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2525     Value += ValidReloc.Addend;
2526     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2527       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2528       Buf[i] = uint8_t(Value >> (Index * 8));
2529     }
2530     assert(ValidReloc.Size <= sizeof(Buf));
2531     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2532     Applied = true;
2533   }
2534
2535   return Applied;
2536 }
2537
2538 static bool isTypeTag(uint16_t Tag) {
2539   switch (Tag) {
2540   case dwarf::DW_TAG_array_type:
2541   case dwarf::DW_TAG_class_type:
2542   case dwarf::DW_TAG_enumeration_type:
2543   case dwarf::DW_TAG_pointer_type:
2544   case dwarf::DW_TAG_reference_type:
2545   case dwarf::DW_TAG_string_type:
2546   case dwarf::DW_TAG_structure_type:
2547   case dwarf::DW_TAG_subroutine_type:
2548   case dwarf::DW_TAG_typedef:
2549   case dwarf::DW_TAG_union_type:
2550   case dwarf::DW_TAG_ptr_to_member_type:
2551   case dwarf::DW_TAG_set_type:
2552   case dwarf::DW_TAG_subrange_type:
2553   case dwarf::DW_TAG_base_type:
2554   case dwarf::DW_TAG_const_type:
2555   case dwarf::DW_TAG_constant:
2556   case dwarf::DW_TAG_file_type:
2557   case dwarf::DW_TAG_namelist:
2558   case dwarf::DW_TAG_packed_type:
2559   case dwarf::DW_TAG_volatile_type:
2560   case dwarf::DW_TAG_restrict_type:
2561   case dwarf::DW_TAG_interface_type:
2562   case dwarf::DW_TAG_unspecified_type:
2563   case dwarf::DW_TAG_shared_type:
2564     return true;
2565   default:
2566     break;
2567   }
2568   return false;
2569 }
2570
2571 static bool
2572 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2573                     uint16_t Tag, bool InDebugMap, bool SkipPC,
2574                     bool InFunctionScope) {
2575   switch (AttrSpec.Attr) {
2576   default:
2577     return false;
2578   case dwarf::DW_AT_low_pc:
2579   case dwarf::DW_AT_high_pc:
2580   case dwarf::DW_AT_ranges:
2581     return SkipPC;
2582   case dwarf::DW_AT_location:
2583   case dwarf::DW_AT_frame_base:
2584     // FIXME: for some reason dsymutil-classic keeps the location
2585     // attributes when they are of block type (ie. not location
2586     // lists). This is totally wrong for globals where we will keep a
2587     // wrong address. It is mostly harmless for locals, but there is
2588     // no point in keeping these anyway when the function wasn't linked.
2589     return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2590                        !InDebugMap)) &&
2591            !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2592   }
2593 }
2594
2595 DIE *DwarfLinker::DIECloner::cloneDIE(
2596     const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2597     int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
2598   DWARFUnit &U = Unit.getOrigUnit();
2599   unsigned Idx = U.getDIEIndex(&InputDIE);
2600   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2601
2602   // Should the DIE appear in the output?
2603   if (!Unit.getInfo(Idx).Keep)
2604     return nullptr;
2605
2606   uint32_t Offset = InputDIE.getOffset();
2607   // The DIE might have been already created by a forward reference
2608   // (see cloneDieReferenceAttribute()).
2609   DIE *Die = Info.Clone;
2610   if (!Die)
2611     Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2612   assert(Die->getTag() == InputDIE.getTag());
2613   Die->setOffset(OutOffset);
2614   if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2615       Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2616       !Info.Ctxt->getCanonicalDIEOffset()) {
2617     // We are about to emit a DIE that is the root of its own valid
2618     // DeclContext tree. Make the current offset the canonical offset
2619     // for this context.
2620     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2621   }
2622
2623   // Extract and clone every attribute.
2624   DataExtractor Data = U.getDebugInfoExtractor();
2625   // Point to the next DIE (generally there is always at least a NULL
2626   // entry after the current one). If this is a lone
2627   // DW_TAG_compile_unit without any children, point to the next unit.
2628   uint32_t NextOffset =
2629     (Idx + 1 < U.getNumDIEs())
2630     ? U.getDIEAtIndex(Idx + 1)->getOffset()
2631     : U.getNextUnitOffset();
2632   AttributesInfo AttrInfo;
2633
2634   // We could copy the data only if we need to aply a relocation to
2635   // it. After testing, it seems there is no performance downside to
2636   // doing the copy unconditionally, and it makes the code simpler.
2637   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2638   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2639   // Modify the copy with relocated addresses.
2640   if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2641     // If we applied relocations, we store the value of high_pc that was
2642     // potentially stored in the input DIE. If high_pc is an address
2643     // (Dwarf version == 2), then it might have been relocated to a
2644     // totally unrelated value (because the end address in the object
2645     // file might be start address of another function which got moved
2646     // independantly by the linker). The computation of the actual
2647     // high_pc value is done in cloneAddressAttribute().
2648     AttrInfo.OrigHighPc =
2649         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2650     // Also store the low_pc. It might get relocated in an
2651     // inline_subprogram that happens at the beginning of its
2652     // inlining function.
2653     AttrInfo.OrigLowPc =
2654         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
2655   }
2656
2657   // Reset the Offset to 0 as we will be working on the local copy of
2658   // the data.
2659   Offset = 0;
2660
2661   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2662   Offset += getULEB128Size(Abbrev->getCode());
2663
2664   // We are entering a subprogram. Get and propagate the PCOffset.
2665   if (Die->getTag() == dwarf::DW_TAG_subprogram)
2666     PCOffset = Info.AddrAdjust;
2667   AttrInfo.PCOffset = PCOffset;
2668
2669   if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2670     Flags |= TF_InFunctionScope;
2671     if (!Info.InDebugMap)
2672       Flags |= TF_SkipPC;
2673   }
2674
2675   bool Copied = false;
2676   for (const auto &AttrSpec : Abbrev->attributes()) {
2677     if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2678                             Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2679       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2680       // FIXME: dsymutil-classic keeps the old abbreviation around
2681       // even if it's not used. We can remove this (and the copyAbbrev
2682       // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2683       if (!Copied) {
2684         copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2685         Copied = true;
2686       }
2687       continue;
2688     }
2689
2690     DWARFFormValue Val(AttrSpec.Form);
2691     uint32_t AttrSize = Offset;
2692     Val.extractValue(Data, &Offset, &U);
2693     AttrSize = Offset - AttrSize;
2694
2695     OutOffset +=
2696         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2697   }
2698
2699   // Look for accelerator entries.
2700   uint16_t Tag = InputDIE.getTag();
2701   // FIXME: This is slightly wrong. An inline_subroutine without a
2702   // low_pc, but with AT_ranges might be interesting to get into the
2703   // accelerator tables too. For now stick with dsymutil's behavior.
2704   if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2705       Tag != dwarf::DW_TAG_compile_unit &&
2706       getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2707     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2708       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2709                               AttrInfo.MangledNameOffset,
2710                               Tag == dwarf::DW_TAG_inlined_subroutine);
2711     if (AttrInfo.Name)
2712       Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2713                               Tag == dwarf::DW_TAG_inlined_subroutine);
2714   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2715              getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2716     Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2717   }
2718
2719   DIEAbbrev NewAbbrev = Die->generateAbbrev();
2720   // If a scope DIE is kept, we must have kept at least one child. If
2721   // it's not the case, we'll just be emitting one wasteful end of
2722   // children marker, but things won't break.
2723   if (InputDIE.hasChildren())
2724     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2725   // Assign a permanent abbrev number
2726   Linker.AssignAbbrev(NewAbbrev);
2727   Die->setAbbrevNumber(NewAbbrev.getNumber());
2728
2729   // Add the size of the abbreviation number to the output offset.
2730   OutOffset += getULEB128Size(Die->getAbbrevNumber());
2731
2732   if (!Abbrev->hasChildren()) {
2733     // Update our size.
2734     Die->setSize(OutOffset - Die->getOffset());
2735     return Die;
2736   }
2737
2738   // Recursively clone children.
2739   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2740        Child = Child->getSibling()) {
2741     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
2742       Die->addChild(Clone);
2743       OutOffset = Clone->getOffset() + Clone->getSize();
2744     }
2745   }
2746
2747   // Account for the end of children marker.
2748   OutOffset += sizeof(int8_t);
2749   // Update our size.
2750   Die->setSize(OutOffset - Die->getOffset());
2751   return Die;
2752 }
2753
2754 /// \brief Patch the input object file relevant debug_ranges entries
2755 /// and emit them in the output file. Update the relevant attributes
2756 /// to point at the new entries.
2757 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2758                                      DWARFContext &OrigDwarf) const {
2759   DWARFDebugRangeList RangeList;
2760   const auto &FunctionRanges = Unit.getFunctionRanges();
2761   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2762   DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2763                                OrigDwarf.isLittleEndian(), AddressSize);
2764   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2765   DWARFUnit &OrigUnit = Unit.getOrigUnit();
2766   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2767   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2768       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2769   // Ranges addresses are based on the unit's low_pc. Compute the
2770   // offset we need to apply to adapt to the the new unit's low_pc.
2771   int64_t UnitPcOffset = 0;
2772   if (OrigLowPc != -1ULL)
2773     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2774
2775   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2776     uint32_t Offset = RangeAttribute.get();
2777     RangeAttribute.set(Streamer->getRangesSectionSize());
2778     RangeList.extract(RangeExtractor, &Offset);
2779     const auto &Entries = RangeList.getEntries();
2780     if (!Entries.empty()) {
2781       const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2782
2783       if (CurrRange == InvalidRange ||
2784           First.StartAddress + OrigLowPc < CurrRange.start() ||
2785           First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2786         CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2787         if (CurrRange == InvalidRange ||
2788             CurrRange.start() > First.StartAddress + OrigLowPc) {
2789           reportWarning("no mapping for range.");
2790           continue;
2791         }
2792       }
2793     }
2794
2795     Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2796                                 AddressSize);
2797   }
2798 }
2799
2800 /// \brief Generate the debug_aranges entries for \p Unit and if the
2801 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2802 /// contribution for this attribute.
2803 /// FIXME: this could actually be done right in patchRangesForUnit,
2804 /// but for the sake of initial bit-for-bit compatibility with legacy
2805 /// dsymutil, we have to do it in a delayed pass.
2806 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2807   auto Attr = Unit.getUnitRangesAttribute();
2808   if (Attr)
2809     Attr->set(Streamer->getRangesSectionSize());
2810   Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2811 }
2812
2813 /// \brief Insert the new line info sequence \p Seq into the current
2814 /// set of already linked line info \p Rows.
2815 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2816                                std::vector<DWARFDebugLine::Row> &Rows) {
2817   if (Seq.empty())
2818     return;
2819
2820   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2821     Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2822     Seq.clear();
2823     return;
2824   }
2825
2826   auto InsertPoint = std::lower_bound(
2827       Rows.begin(), Rows.end(), Seq.front(),
2828       [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2829         return LHS.Address < RHS.Address;
2830       });
2831
2832   // FIXME: this only removes the unneeded end_sequence if the
2833   // sequences have been inserted in order. using a global sort like
2834   // described in patchLineTableForUnit() and delaying the end_sequene
2835   // elimination to emitLineTableForUnit() we can get rid of all of them.
2836   if (InsertPoint != Rows.end() &&
2837       InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2838     *InsertPoint = Seq.front();
2839     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2840   } else {
2841     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2842   }
2843
2844   Seq.clear();
2845 }
2846
2847 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2848   for (auto &V : Die.values())
2849     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2850       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2851       return;
2852     }
2853
2854   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2855 }
2856
2857 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2858 /// recreate a relocated version of these for the address ranges that
2859 /// are present in the binary.
2860 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2861                                         DWARFContext &OrigDwarf) {
2862   const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2863   uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2864       &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2865   if (StmtList == -1ULL)
2866     return;
2867
2868   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2869   if (auto *OutputDIE = Unit.getOutputUnitDIE())
2870     patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2871
2872   // Parse the original line info for the unit.
2873   DWARFDebugLine::LineTable LineTable;
2874   uint32_t StmtOffset = StmtList;
2875   StringRef LineData = OrigDwarf.getLineSection().Data;
2876   DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2877                               Unit.getOrigUnit().getAddressByteSize());
2878   LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2879                   &StmtOffset);
2880
2881   // This vector is the output line table.
2882   std::vector<DWARFDebugLine::Row> NewRows;
2883   NewRows.reserve(LineTable.Rows.size());
2884
2885   // Current sequence of rows being extracted, before being inserted
2886   // in NewRows.
2887   std::vector<DWARFDebugLine::Row> Seq;
2888   const auto &FunctionRanges = Unit.getFunctionRanges();
2889   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2890
2891   // FIXME: This logic is meant to generate exactly the same output as
2892   // Darwin's classic dsynutil. There is a nicer way to implement this
2893   // by simply putting all the relocated line info in NewRows and simply
2894   // sorting NewRows before passing it to emitLineTableForUnit. This
2895   // should be correct as sequences for a function should stay
2896   // together in the sorted output. There are a few corner cases that
2897   // look suspicious though, and that required to implement the logic
2898   // this way. Revisit that once initial validation is finished.
2899
2900   // Iterate over the object file line info and extract the sequences
2901   // that correspond to linked functions.
2902   for (auto &Row : LineTable.Rows) {
2903     // Check wether we stepped out of the range. The range is
2904     // half-open, but consider accept the end address of the range if
2905     // it is marked as end_sequence in the input (because in that
2906     // case, the relocation offset is accurate and that entry won't
2907     // serve as the start of another function).
2908     if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2909         Row.Address > CurrRange.stop() ||
2910         (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2911       // We just stepped out of a known range. Insert a end_sequence
2912       // corresponding to the end of the range.
2913       uint64_t StopAddress = CurrRange != InvalidRange
2914                                  ? CurrRange.stop() + CurrRange.value()
2915                                  : -1ULL;
2916       CurrRange = FunctionRanges.find(Row.Address);
2917       bool CurrRangeValid =
2918           CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2919       if (!CurrRangeValid) {
2920         CurrRange = InvalidRange;
2921         if (StopAddress != -1ULL) {
2922           // Try harder by looking in the DebugMapObject function
2923           // ranges map. There are corner cases where this finds a
2924           // valid entry. It's unclear if this is right or wrong, but
2925           // for now do as dsymutil.
2926           // FIXME: Understand exactly what cases this addresses and
2927           // potentially remove it along with the Ranges map.
2928           auto Range = Ranges.lower_bound(Row.Address);
2929           if (Range != Ranges.begin() && Range != Ranges.end())
2930             --Range;
2931
2932           if (Range != Ranges.end() && Range->first <= Row.Address &&
2933               Range->second.first >= Row.Address) {
2934             StopAddress = Row.Address + Range->second.second;
2935           }
2936         }
2937       }
2938       if (StopAddress != -1ULL && !Seq.empty()) {
2939         // Insert end sequence row with the computed end address, but
2940         // the same line as the previous one.
2941         auto NextLine = Seq.back();
2942         NextLine.Address = StopAddress;
2943         NextLine.EndSequence = 1;
2944         NextLine.PrologueEnd = 0;
2945         NextLine.BasicBlock = 0;
2946         NextLine.EpilogueBegin = 0;
2947         Seq.push_back(NextLine);
2948         insertLineSequence(Seq, NewRows);
2949       }
2950
2951       if (!CurrRangeValid)
2952         continue;
2953     }
2954
2955     // Ignore empty sequences.
2956     if (Row.EndSequence && Seq.empty())
2957       continue;
2958
2959     // Relocate row address and add it to the current sequence.
2960     Row.Address += CurrRange.value();
2961     Seq.emplace_back(Row);
2962
2963     if (Row.EndSequence)
2964       insertLineSequence(Seq, NewRows);
2965   }
2966
2967   // Finished extracting, now emit the line tables.
2968   uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2969   // FIXME: LLVM hardcodes it's prologue values. We just copy the
2970   // prologue over and that works because we act as both producer and
2971   // consumer. It would be nicer to have a real configurable line
2972   // table emitter.
2973   if (LineTable.Prologue.Version != 2 ||
2974       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2975       LineTable.Prologue.OpcodeBase > 13)
2976     reportWarning("line table paramters mismatch. Cannot emit.");
2977   else {
2978     MCDwarfLineTableParams Params;
2979     Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2980     Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2981     Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2982     Streamer->emitLineTableForUnit(Params,
2983                                    LineData.slice(StmtList + 4, PrologueEnd),
2984                                    LineTable.Prologue.MinInstLength, NewRows,
2985                                    Unit.getOrigUnit().getAddressByteSize());
2986   }
2987 }
2988
2989 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2990   Streamer->emitPubNamesForUnit(Unit);
2991   Streamer->emitPubTypesForUnit(Unit);
2992 }
2993
2994 /// \brief Read the frame info stored in the object, and emit the
2995 /// patched frame descriptions for the linked binary.
2996 ///
2997 /// This is actually pretty easy as the data of the CIEs and FDEs can
2998 /// be considered as black boxes and moved as is. The only thing to do
2999 /// is to patch the addresses in the headers.
3000 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3001                                           DWARFContext &OrigDwarf,
3002                                           unsigned AddrSize) {
3003   StringRef FrameData = OrigDwarf.getDebugFrameSection();
3004   if (FrameData.empty())
3005     return;
3006
3007   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3008   uint32_t InputOffset = 0;
3009
3010   // Store the data of the CIEs defined in this object, keyed by their
3011   // offsets.
3012   DenseMap<uint32_t, StringRef> LocalCIES;
3013
3014   while (Data.isValidOffset(InputOffset)) {
3015     uint32_t EntryOffset = InputOffset;
3016     uint32_t InitialLength = Data.getU32(&InputOffset);
3017     if (InitialLength == 0xFFFFFFFF)
3018       return reportWarning("Dwarf64 bits no supported");
3019
3020     uint32_t CIEId = Data.getU32(&InputOffset);
3021     if (CIEId == 0xFFFFFFFF) {
3022       // This is a CIE, store it.
3023       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3024       LocalCIES[EntryOffset] = CIEData;
3025       // The -4 is to account for the CIEId we just read.
3026       InputOffset += InitialLength - 4;
3027       continue;
3028     }
3029
3030     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3031
3032     // Some compilers seem to emit frame info that doesn't start at
3033     // the function entry point, thus we can't just lookup the address
3034     // in the debug map. Use the linker's range map to see if the FDE
3035     // describes something that we can relocate.
3036     auto Range = Ranges.upper_bound(Loc);
3037     if (Range != Ranges.begin())
3038       --Range;
3039     if (Range == Ranges.end() || Range->first > Loc ||
3040         Range->second.first <= Loc) {
3041       // The +4 is to account for the size of the InitialLength field itself.
3042       InputOffset = EntryOffset + InitialLength + 4;
3043       continue;
3044     }
3045
3046     // This is an FDE, and we have a mapping.
3047     // Have we already emitted a corresponding CIE?
3048     StringRef CIEData = LocalCIES[CIEId];
3049     if (CIEData.empty())
3050       return reportWarning("Inconsistent debug_frame content. Dropping.");
3051
3052     // Look if we already emitted a CIE that corresponds to the
3053     // referenced one (the CIE data is the key of that lookup).
3054     auto IteratorInserted = EmittedCIEs.insert(
3055         std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3056     // If there is no CIE yet for this ID, emit it.
3057     if (IteratorInserted.second ||
3058         // FIXME: dsymutil-classic only caches the last used CIE for
3059         // reuse. Mimic that behavior for now. Just removing that
3060         // second half of the condition and the LastCIEOffset variable
3061         // makes the code DTRT.
3062         LastCIEOffset != IteratorInserted.first->getValue()) {
3063       LastCIEOffset = Streamer->getFrameSectionSize();
3064       IteratorInserted.first->getValue() = LastCIEOffset;
3065       Streamer->emitCIE(CIEData);
3066     }
3067
3068     // Emit the FDE with updated address and CIE pointer.
3069     // (4 + AddrSize) is the size of the CIEId + initial_location
3070     // fields that will get reconstructed by emitFDE().
3071     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3072     Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3073                       Loc + Range->second.second,
3074                       FrameData.substr(InputOffset, FDERemainingBytes));
3075     InputOffset += FDERemainingBytes;
3076   }
3077 }
3078
3079 void DwarfLinker::DIECloner::copyAbbrev(
3080     const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
3081   DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3082                  dwarf::Form(Abbrev.hasChildren()));
3083
3084   for (const auto &Attr : Abbrev.attributes()) {
3085     uint16_t Form = Attr.Form;
3086     if (hasODR && isODRAttribute(Attr.Attr))
3087       Form = dwarf::DW_FORM_ref_addr;
3088     Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3089   }
3090
3091   Linker.AssignAbbrev(Copy);
3092 }
3093
3094 bool DwarfLinker::registerModuleReference(
3095     const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3096     DebugMap &ModuleMap, unsigned Indent) {
3097   std::string PCMfile =
3098       CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
3099   if (PCMfile.empty())
3100     return false;
3101
3102   // Clang module DWARF skeleton CUs abuse this for the path to the module.
3103   std::string PCMpath =
3104       CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
3105
3106   if (Options.Verbose) {
3107     outs().indent(Indent);
3108     outs() << "Found clang module reference " << PCMfile;
3109   }
3110
3111   if (ClangModules.count(PCMfile)) {
3112     if (Options.Verbose)
3113       outs() << " [cached].\n";
3114     return true;
3115   }
3116   if (Options.Verbose)
3117     outs() << " ...\n";
3118
3119   // Cyclic dependencies are disallowed by Clang, but we still
3120   // shouldn't run into an infinite loop, so mark it as processed now.
3121   ClangModules.insert(PCMfile);
3122   loadClangModule(PCMfile, PCMpath, ModuleMap, Indent + 2);
3123   return true;
3124 }
3125
3126 ErrorOr<const object::ObjectFile &>
3127 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3128                         const DebugMap &Map) {
3129   auto ErrOrObjs =
3130       BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3131   if (std::error_code EC = ErrOrObjs.getError()) {
3132     reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3133     return EC;
3134   }
3135   auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3136   if (std::error_code EC = ErrOrObj.getError())
3137     reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3138   return ErrOrObj;
3139 }
3140
3141 void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
3142                                   DebugMap &ModuleMap, unsigned Indent) {
3143   SmallString<80> Path(Options.PrependPath);
3144   if (sys::path::is_relative(Filename))
3145     sys::path::append(Path, ModulePath, Filename);
3146   else
3147     sys::path::append(Path, Filename);
3148   BinaryHolder ObjHolder(Options.Verbose);
3149   auto &Obj =
3150       ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3151   auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3152   if (!ErrOrObj) {
3153     ClangModules.erase(ClangModules.find(Filename));
3154     return;
3155   }
3156
3157   // FIXME: At this point dsymutil should verify the DW_AT_gnu_dwo_id
3158   // against the module hash of the clang module.
3159
3160   CompileUnit *Unit = nullptr;
3161
3162   // Setup access to the debug info.
3163   DWARFContextInMemory DwarfContext(*ErrOrObj);
3164   RelocationManager RelocMgr(*this);
3165   for (const auto &CU : DwarfContext.compile_units()) {
3166     auto *CUDie = CU->getUnitDIE(false);
3167     // Recursively get all modules imported by this one.
3168     if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
3169       // Add this module.
3170       if (Unit) {
3171         errs() << Filename << ": Clang modules are expected to have exactly"
3172                << " 1 compile unit.\n";
3173         exitDsymutil(1);
3174       }
3175       Unit = new CompileUnit(*CU, UnitID++, !Options.NoODR);
3176       Unit->setHasInterestingContent();
3177       gatherDIEParents(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3178                        ODRContexts);
3179       // Keep everything.
3180       Unit->markEverythingAsKept();
3181     }
3182   }
3183   if (Options.Verbose) {
3184     outs().indent(Indent);
3185     outs() << "cloning .debug_info from " << Filename << "\n";
3186   }
3187
3188   DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3189             Options)
3190       .cloneAllCompileUnits(DwarfContext);
3191 }
3192
3193 void DwarfLinker::DIECloner::cloneAllCompileUnits(
3194     DWARFContextInMemory &DwarfContext) {
3195   if (!Linker.Streamer)
3196     return;
3197
3198   for (auto &CurrentUnit : CompileUnits) {
3199     const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3200     CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
3201     DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3202                               11 /* Unit Header size */, 0);
3203     CurrentUnit.setOutputUnitDIE(OutputDIE);
3204     Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3205     if (Linker.Options.NoOutput)
3206       continue;
3207     // FIXME: for compatibility with the classic dsymutil, we emit
3208     // an empty line table for the unit, even if the unit doesn't
3209     // actually exist in the DIE tree.
3210     Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
3211     if (!OutputDIE)
3212       continue;
3213     Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3214     Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3215     Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
3216   }
3217
3218   if (Linker.Options.NoOutput)
3219     return;
3220
3221   // Emit all the compile unit's debug information.
3222   for (auto &CurrentUnit : CompileUnits) {
3223     Linker.generateUnitRanges(CurrentUnit);
3224     CurrentUnit.fixupForwardReferences();
3225     Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
3226     if (!CurrentUnit.getOutputUnitDIE())
3227       continue;
3228     Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3229   }
3230 }
3231
3232 bool DwarfLinker::link(const DebugMap &Map) {
3233
3234   if (!createStreamer(Map.getTriple(), OutputFilename))
3235     return false;
3236
3237   // Size of the DIEs (and headers) generated for the linked output.
3238   OutputDebugInfoSize = 0;
3239   // A unique ID that identifies each compile unit.
3240   UnitID = 0;
3241   DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3242
3243   for (const auto &Obj : Map.objects()) {
3244     CurrentDebugObject = Obj.get();
3245
3246     if (Options.Verbose)
3247       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3248     auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3249     if (!ErrOrObj)
3250       continue;
3251
3252     // Look for relocations that correspond to debug map entries.
3253     RelocationManager RelocMgr(*this);
3254     if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3255       if (Options.Verbose)
3256         outs() << "No valid relocations found. Skipping.\n";
3257       continue;
3258     }
3259
3260     // Setup access to the debug info.
3261     DWARFContextInMemory DwarfContext(*ErrOrObj);
3262     startDebugObject(DwarfContext, *Obj);
3263
3264     // In a first phase, just read in the debug info and store the DIE
3265     // parent links that we will use during the next phase.
3266     for (const auto &CU : DwarfContext.compile_units()) {
3267       auto *CUDie = CU->getUnitDIE(false);
3268       if (Options.Verbose) {
3269         outs() << "Input compilation unit:";
3270         CUDie->dump(outs(), CU.get(), 0);
3271       }
3272       if (!registerModuleReference(*CUDie, *CU, ModuleMap)) {
3273         Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3274         gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3275                          StringPool, ODRContexts);
3276       }
3277     }
3278
3279     // Then mark all the DIEs that need to be present in the linked
3280     // output and collect some information about them. Note that this
3281     // loop can not be merged with the previous one becaue cross-cu
3282     // references require the ParentIdx to be setup for every CU in
3283     // the object file before calling this.
3284     for (auto &CurrentUnit : Units)
3285       lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
3286                         CurrentUnit, 0);
3287
3288     // The calls to applyValidRelocs inside cloneDIE will walk the
3289     // reloc array again (in the same way findValidRelocsInDebugInfo()
3290     // did). We need to reset the NextValidReloc index to the beginning.
3291     RelocMgr.resetValidRelocs();
3292     if (RelocMgr.hasValidRelocs())
3293       DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3294           .cloneAllCompileUnits(DwarfContext);
3295     if (!Options.NoOutput && !Units.empty())
3296       patchFrameInfoForObject(*Obj, DwarfContext,
3297                               Units[0].getOrigUnit().getAddressByteSize());
3298
3299     // Clean-up before starting working on the next object.
3300     endDebugObject();
3301   }
3302
3303   // Emit everything that's global.
3304   if (!Options.NoOutput) {
3305     Streamer->emitAbbrevs(Abbreviations);
3306     Streamer->emitStrings(StringPool);
3307   }
3308
3309   return Options.NoOutput ? true : Streamer->finish(Map);
3310 }
3311 }
3312
3313 /// \brief Get the offset of string \p S in the string table. This
3314 /// can insert a new element or return the offset of a preexisitng
3315 /// one.
3316 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3317   if (S.empty() && !Strings.empty())
3318     return 0;
3319
3320   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3321   MapTy::iterator It;
3322   bool Inserted;
3323
3324   // A non-empty string can't be at offset 0, so if we have an entry
3325   // with a 0 offset, it must be a previously interned string.
3326   std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3327   if (Inserted || It->getValue().first == 0) {
3328     // Set offset and chain at the end of the entries list.
3329     It->getValue().first = CurrentEndOffset;
3330     CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3331     Last->getValue().second = &*It;
3332     Last = &*It;
3333   }
3334   return It->getValue().first;
3335 }
3336
3337 /// \brief Put \p S into the StringMap so that it gets permanent
3338 /// storage, but do not actually link it in the chain of elements
3339 /// that go into the output section. A latter call to
3340 /// getStringOffset() with the same string will chain it though.
3341 StringRef NonRelocatableStringpool::internString(StringRef S) {
3342   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3343   auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3344   return InsertResult.first->getKey();
3345 }
3346
3347 void warn(const Twine &Warning, const Twine &Context) {
3348   errs() << Twine("while processing ") + Context + ":\n";
3349   errs() << Twine("warning: ") + Warning + "\n";
3350 }
3351
3352 bool error(const Twine &Error, const Twine &Context) {
3353   errs() << Twine("while processing ") + Context + ":\n";
3354   errs() << Twine("error: ") + Error + "\n";
3355   return false;
3356 }
3357
3358 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3359                const LinkOptions &Options) {
3360   DwarfLinker Linker(OutputFilename, Options);
3361   return Linker.link(DM);
3362 }
3363 }
3364 }