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