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