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