1 //=== DWARFLinker.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/DWARFLinker/DWARFLinker.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/BitVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/CodeGen/NonRelocatableStringpool.h"
15 #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
16 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
24 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
25 #include "llvm/Support/DataExtractor.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ErrorOr.h"
29 #include "llvm/Support/FormatVariadic.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/ThreadPool.h"
33 #include <vector>
34 
35 namespace llvm {
36 
37 /// Hold the input and output of the debug info size in bytes.
38 struct DebugInfoSize {
39   uint64_t Input;
40   uint64_t Output;
41 };
42 
43 /// Compute the total size of the debug info.
44 static uint64_t getDebugInfoSize(DWARFContext &Dwarf) {
45   uint64_t Size = 0;
46   for (auto &Unit : Dwarf.compile_units()) {
47     Size += Unit->getLength();
48   }
49   return Size;
50 }
51 
52 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
53 /// CompileUnit object instead.
54 static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
55   auto CU = llvm::upper_bound(
56       Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
57         return LHS < RHS->getOrigUnit().getNextUnitOffset();
58       });
59   return CU != Units.end() ? CU->get() : nullptr;
60 }
61 
62 /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
63 /// The resulting DIE might be in another CompileUnit which is stored into \p
64 /// ReferencedCU. \returns null if resolving fails for any reason.
65 DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
66                                           const UnitListTy &Units,
67                                           const DWARFFormValue &RefValue,
68                                           const DWARFDie &DIE,
69                                           CompileUnit *&RefCU) {
70   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
71   uint64_t RefOffset = *RefValue.getAsReference();
72   if ((RefCU = getUnitForOffset(Units, RefOffset)))
73     if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
74       // In a file with broken references, an attribute might point to a NULL
75       // DIE.
76       if (!RefDie.isNULL())
77         return RefDie;
78     }
79 
80   reportWarning("could not find referenced DIE", File, &DIE);
81   return DWARFDie();
82 }
83 
84 /// \returns whether the passed \a Attr type might contain a DIE reference
85 /// suitable for ODR uniquing.
86 static bool isODRAttribute(uint16_t Attr) {
87   switch (Attr) {
88   default:
89     return false;
90   case dwarf::DW_AT_type:
91   case dwarf::DW_AT_containing_type:
92   case dwarf::DW_AT_specification:
93   case dwarf::DW_AT_abstract_origin:
94   case dwarf::DW_AT_import:
95     return true;
96   }
97   llvm_unreachable("Improper attribute.");
98 }
99 
100 static bool isTypeTag(uint16_t Tag) {
101   switch (Tag) {
102   case dwarf::DW_TAG_array_type:
103   case dwarf::DW_TAG_class_type:
104   case dwarf::DW_TAG_enumeration_type:
105   case dwarf::DW_TAG_pointer_type:
106   case dwarf::DW_TAG_reference_type:
107   case dwarf::DW_TAG_string_type:
108   case dwarf::DW_TAG_structure_type:
109   case dwarf::DW_TAG_subroutine_type:
110   case dwarf::DW_TAG_typedef:
111   case dwarf::DW_TAG_union_type:
112   case dwarf::DW_TAG_ptr_to_member_type:
113   case dwarf::DW_TAG_set_type:
114   case dwarf::DW_TAG_subrange_type:
115   case dwarf::DW_TAG_base_type:
116   case dwarf::DW_TAG_const_type:
117   case dwarf::DW_TAG_constant:
118   case dwarf::DW_TAG_file_type:
119   case dwarf::DW_TAG_namelist:
120   case dwarf::DW_TAG_packed_type:
121   case dwarf::DW_TAG_volatile_type:
122   case dwarf::DW_TAG_restrict_type:
123   case dwarf::DW_TAG_atomic_type:
124   case dwarf::DW_TAG_interface_type:
125   case dwarf::DW_TAG_unspecified_type:
126   case dwarf::DW_TAG_shared_type:
127     return true;
128   default:
129     break;
130   }
131   return false;
132 }
133 
134 AddressesMap::~AddressesMap() {}
135 
136 DwarfEmitter::~DwarfEmitter() {}
137 
138 static Optional<StringRef> StripTemplateParameters(StringRef Name) {
139   // We are looking for template parameters to strip from Name. e.g.
140   //
141   //  operator<<B>
142   //
143   // We look for > at the end but if it does not contain any < then we
144   // have something like operator>>. We check for the operator<=> case.
145   if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
146     return {};
147 
148   // How many < until we have the start of the template parameters.
149   size_t NumLeftAnglesToSkip = 1;
150 
151   // If we have operator<=> then we need to skip its < as well.
152   NumLeftAnglesToSkip += Name.count("<=>");
153 
154   size_t RightAngleCount = Name.count('>');
155   size_t LeftAngleCount = Name.count('<');
156 
157   // If we have more < than > we have operator< or operator<<
158   // we to account for their < as well.
159   if (LeftAngleCount > RightAngleCount)
160     NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
161 
162   size_t StartOfTemplate = 0;
163   while (NumLeftAnglesToSkip--)
164     StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
165 
166   return Name.substr(0, StartOfTemplate - 1);
167 }
168 
169 bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
170                                          AttributesInfo &Info,
171                                          OffsetsStringPool &StringPool,
172                                          bool StripTemplate) {
173   // This function will be called on DIEs having low_pcs and
174   // ranges. As getting the name might be more expansive, filter out
175   // blocks directly.
176   if (Die.getTag() == dwarf::DW_TAG_lexical_block)
177     return false;
178 
179   if (!Info.MangledName)
180     if (const char *MangledName = Die.getLinkageName())
181       Info.MangledName = StringPool.getEntry(MangledName);
182 
183   if (!Info.Name)
184     if (const char *Name = Die.getShortName())
185       Info.Name = StringPool.getEntry(Name);
186 
187   if (!Info.MangledName)
188     Info.MangledName = Info.Name;
189 
190   if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
191     StringRef Name = Info.Name.getString();
192     if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
193       Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
194   }
195 
196   return Info.Name || Info.MangledName;
197 }
198 
199 /// Resolve the relative path to a build artifact referenced by DWARF by
200 /// applying DW_AT_comp_dir.
201 static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
202   sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
203 }
204 
205 /// Collect references to parseable Swift interfaces in imported
206 /// DW_TAG_module blocks.
207 static void analyzeImportedModule(
208     const DWARFDie &DIE, CompileUnit &CU,
209     swiftInterfacesMap *ParseableSwiftInterfaces,
210     std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
211   if (CU.getLanguage() != dwarf::DW_LANG_Swift)
212     return;
213 
214   if (!ParseableSwiftInterfaces)
215     return;
216 
217   StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
218   if (!Path.endswith(".swiftinterface"))
219     return;
220   // Don't track interfaces that are part of the SDK.
221   StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
222   if (SysRoot.empty())
223     SysRoot = CU.getSysRoot();
224   if (!SysRoot.empty() && Path.startswith(SysRoot))
225     return;
226   Optional<const char*> Name = dwarf::toString(DIE.find(dwarf::DW_AT_name));
227   if (!Name)
228     return;
229   auto &Entry = (*ParseableSwiftInterfaces)[*Name];
230   // The prepend path is applied later when copying.
231   DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
232   SmallString<128> ResolvedPath;
233   if (sys::path::is_relative(Path))
234     resolveRelativeObjectPath(ResolvedPath, CUDie);
235   sys::path::append(ResolvedPath, Path);
236   if (!Entry.empty() && Entry != ResolvedPath)
237     ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
238                       *Name + ": " + Entry + " and " + Path,
239                   DIE);
240   Entry = std::string(ResolvedPath.str());
241 }
242 
243 /// The distinct types of work performed by the work loop in
244 /// analyzeContextInfo.
245 enum class ContextWorklistItemType : uint8_t {
246   AnalyzeContextInfo,
247   UpdateChildPruning,
248   UpdatePruning,
249 };
250 
251 /// This class represents an item in the work list. The type defines what kind
252 /// of work needs to be performed when processing the current item. Everything
253 /// but the Type and Die fields are optional based on the type.
254 struct ContextWorklistItem {
255   DWARFDie Die;
256   unsigned ParentIdx;
257   union {
258     CompileUnit::DIEInfo *OtherInfo;
259     DeclContext *Context;
260   };
261   ContextWorklistItemType Type;
262   bool InImportedModule;
263 
264   ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
265                       CompileUnit::DIEInfo *OtherInfo = nullptr)
266       : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
267         InImportedModule(false) {}
268 
269   ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
270                       bool InImportedModule)
271       : Die(Die), ParentIdx(ParentIdx), Context(Context),
272         Type(ContextWorklistItemType::AnalyzeContextInfo),
273         InImportedModule(InImportedModule) {}
274 };
275 
276 static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
277                           uint64_t ModulesEndOffset) {
278   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
279 
280   // Prune this DIE if it is either a forward declaration inside a
281   // DW_TAG_module or a DW_TAG_module that contains nothing but
282   // forward declarations.
283   Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
284                 (isTypeTag(Die.getTag()) &&
285                  dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
286 
287   // Only prune forward declarations inside a DW_TAG_module for which a
288   // definition exists elsewhere.
289   if (ModulesEndOffset == 0)
290     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
291   else
292     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
293                   Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
294 
295   return Info.Prune;
296 }
297 
298 static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
299                                CompileUnit::DIEInfo &ChildInfo) {
300   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
301   Info.Prune &= ChildInfo.Prune;
302 }
303 
304 /// Recursive helper to build the global DeclContext information and
305 /// gather the child->parent relationships in the original compile unit.
306 ///
307 /// This function uses the same work list approach as lookForDIEsToKeep.
308 ///
309 /// \return true when this DIE and all of its children are only
310 /// forward declarations to types defined in external clang modules
311 /// (i.e., forward declarations that are children of a DW_TAG_module).
312 static bool analyzeContextInfo(
313     const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
314     DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
315     uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
316     std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
317     bool InImportedModule = false) {
318   // LIFO work list.
319   std::vector<ContextWorklistItem> Worklist;
320   Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
321 
322   while (!Worklist.empty()) {
323     ContextWorklistItem Current = Worklist.back();
324     Worklist.pop_back();
325 
326     switch (Current.Type) {
327     case ContextWorklistItemType::UpdatePruning:
328       updatePruning(Current.Die, CU, ModulesEndOffset);
329       continue;
330     case ContextWorklistItemType::UpdateChildPruning:
331       updateChildPruning(Current.Die, CU, *Current.OtherInfo);
332       continue;
333     case ContextWorklistItemType::AnalyzeContextInfo:
334       break;
335     }
336 
337     unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
338     CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
339 
340     // Clang imposes an ODR on modules(!) regardless of the language:
341     //  "The module-id should consist of only a single identifier,
342     //   which provides the name of the module being defined. Each
343     //   module shall have a single definition."
344     //
345     // This does not extend to the types inside the modules:
346     //  "[I]n C, this implies that if two structs are defined in
347     //   different submodules with the same name, those two types are
348     //   distinct types (but may be compatible types if their
349     //   definitions match)."
350     //
351     // We treat non-C++ modules like namespaces for this reason.
352     if (Current.Die.getTag() == dwarf::DW_TAG_module &&
353         Current.ParentIdx == 0 &&
354         dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
355             CU.getClangModuleName()) {
356       Current.InImportedModule = true;
357       analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
358                             ReportWarning);
359     }
360 
361     Info.ParentIdx = Current.ParentIdx;
362     bool InClangModule = CU.isClangModule() || Current.InImportedModule;
363     if (CU.hasODR() || InClangModule) {
364       if (Current.Context) {
365         auto PtrInvalidPair = Contexts.getChildDeclContext(
366             *Current.Context, Current.Die, CU, InClangModule);
367         Current.Context = PtrInvalidPair.getPointer();
368         Info.Ctxt =
369             PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
370         if (Info.Ctxt)
371           Info.Ctxt->setDefinedInClangModule(InClangModule);
372       } else
373         Info.Ctxt = Current.Context = nullptr;
374     }
375 
376     Info.Prune = Current.InImportedModule;
377     // Add children in reverse order to the worklist to effectively process
378     // them in order.
379     Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
380     for (auto Child : reverse(Current.Die.children())) {
381       CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
382       Worklist.emplace_back(
383           Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
384       Worklist.emplace_back(Child, Current.Context, Idx,
385                             Current.InImportedModule);
386     }
387   }
388 
389   return CU.getInfo(DIE).Prune;
390 }
391 
392 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
393   switch (Tag) {
394   default:
395     return false;
396   case dwarf::DW_TAG_class_type:
397   case dwarf::DW_TAG_common_block:
398   case dwarf::DW_TAG_lexical_block:
399   case dwarf::DW_TAG_structure_type:
400   case dwarf::DW_TAG_subprogram:
401   case dwarf::DW_TAG_subroutine_type:
402   case dwarf::DW_TAG_union_type:
403     return true;
404   }
405   llvm_unreachable("Invalid Tag");
406 }
407 
408 void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
409   Context.clear();
410 
411   for (DIEBlock *I : DIEBlocks)
412     I->~DIEBlock();
413   for (DIELoc *I : DIELocs)
414     I->~DIELoc();
415 
416   DIEBlocks.clear();
417   DIELocs.clear();
418   DIEAlloc.Reset();
419 }
420 
421 /// Check if a variable describing DIE should be kept.
422 /// \returns updated TraversalFlags.
423 unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
424                                             const DWARFDie &DIE,
425                                             CompileUnit::DIEInfo &MyInfo,
426                                             unsigned Flags) {
427   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
428 
429   // Global variables with constant value can always be kept.
430   if (!(Flags & TF_InFunctionScope) &&
431       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
432     MyInfo.InDebugMap = true;
433     return Flags | TF_Keep;
434   }
435 
436   // See if there is a relocation to a valid debug map entry inside this
437   // variable's location. The order is important here. We want to always check
438   // if the variable has a valid relocation, so that the DIEInfo is filled.
439   // However, we don't want a static variable in a function to force us to keep
440   // the enclosing function, unless requested explicitly.
441   const bool HasLiveMemoryLocation =
442       RelocMgr.hasLiveMemoryLocation(DIE, MyInfo);
443   if (!HasLiveMemoryLocation || ((Flags & TF_InFunctionScope) &&
444                                  !LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
445     return Flags;
446 
447   if (Options.Verbose) {
448     outs() << "Keeping variable DIE:";
449     DIDumpOptions DumpOpts;
450     DumpOpts.ChildRecurseDepth = 0;
451     DumpOpts.Verbose = Options.Verbose;
452     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
453   }
454 
455   return Flags | TF_Keep;
456 }
457 
458 /// Check if a function describing DIE should be kept.
459 /// \returns updated TraversalFlags.
460 unsigned DWARFLinker::shouldKeepSubprogramDIE(
461     AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
462     const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
463     unsigned Flags) {
464   Flags |= TF_InFunctionScope;
465 
466   auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
467   if (!LowPc)
468     return Flags;
469 
470   assert(LowPc.hasValue() && "low_pc attribute is not an address.");
471   if (!RelocMgr.hasLiveAddressRange(DIE, MyInfo))
472     return Flags;
473 
474   if (Options.Verbose) {
475     outs() << "Keeping subprogram DIE:";
476     DIDumpOptions DumpOpts;
477     DumpOpts.ChildRecurseDepth = 0;
478     DumpOpts.Verbose = Options.Verbose;
479     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
480   }
481 
482   if (DIE.getTag() == dwarf::DW_TAG_label) {
483     if (Unit.hasLabelAt(*LowPc))
484       return Flags;
485 
486     DWARFUnit &OrigUnit = Unit.getOrigUnit();
487     // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
488     // that don't fall into the CU's aranges. This is wrong IMO. Debug info
489     // generation bugs aside, this is really wrong in the case of labels, where
490     // a label marking the end of a function will have a PC == CU's high_pc.
491     if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
492             .getValueOr(UINT64_MAX) <= LowPc)
493       return Flags;
494     Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
495     return Flags | TF_Keep;
496   }
497 
498   Flags |= TF_Keep;
499 
500   Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
501   if (!HighPc) {
502     reportWarning("Function without high_pc. Range will be discarded.\n", File,
503                   &DIE);
504     return Flags;
505   }
506 
507   // Replace the debug map range with a more accurate one.
508   Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
509   Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
510   return Flags;
511 }
512 
513 /// Check if a DIE should be kept.
514 /// \returns updated TraversalFlags.
515 unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
516                                     const DWARFDie &DIE, const DWARFFile &File,
517                                     CompileUnit &Unit,
518                                     CompileUnit::DIEInfo &MyInfo,
519                                     unsigned Flags) {
520   switch (DIE.getTag()) {
521   case dwarf::DW_TAG_constant:
522   case dwarf::DW_TAG_variable:
523     return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
524   case dwarf::DW_TAG_subprogram:
525   case dwarf::DW_TAG_label:
526     return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
527                                    Flags);
528   case dwarf::DW_TAG_base_type:
529     // DWARF Expressions may reference basic types, but scanning them
530     // is expensive. Basic types are tiny, so just keep all of them.
531   case dwarf::DW_TAG_imported_module:
532   case dwarf::DW_TAG_imported_declaration:
533   case dwarf::DW_TAG_imported_unit:
534     // We always want to keep these.
535     return Flags | TF_Keep;
536   default:
537     break;
538   }
539 
540   return Flags;
541 }
542 
543 /// Helper that updates the completeness of the current DIE based on the
544 /// completeness of one of its children. It depends on the incompleteness of
545 /// the children already being computed.
546 static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
547                                       CompileUnit::DIEInfo &ChildInfo) {
548   switch (Die.getTag()) {
549   case dwarf::DW_TAG_structure_type:
550   case dwarf::DW_TAG_class_type:
551   case dwarf::DW_TAG_union_type:
552     break;
553   default:
554     return;
555   }
556 
557   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
558 
559   if (ChildInfo.Incomplete || ChildInfo.Prune)
560     MyInfo.Incomplete = true;
561 }
562 
563 /// Helper that updates the completeness of the current DIE based on the
564 /// completeness of the DIEs it references. It depends on the incompleteness of
565 /// the referenced DIE already being computed.
566 static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
567                                     CompileUnit::DIEInfo &RefInfo) {
568   switch (Die.getTag()) {
569   case dwarf::DW_TAG_typedef:
570   case dwarf::DW_TAG_member:
571   case dwarf::DW_TAG_reference_type:
572   case dwarf::DW_TAG_ptr_to_member_type:
573   case dwarf::DW_TAG_pointer_type:
574     break;
575   default:
576     return;
577   }
578 
579   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
580 
581   if (MyInfo.Incomplete)
582     return;
583 
584   if (RefInfo.Incomplete)
585     MyInfo.Incomplete = true;
586 }
587 
588 /// Look at the children of the given DIE and decide whether they should be
589 /// kept.
590 void DWARFLinker::lookForChildDIEsToKeep(
591     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
592     SmallVectorImpl<WorklistItem> &Worklist) {
593   // The TF_ParentWalk flag tells us that we are currently walking up the
594   // parent chain of a required DIE, and we don't want to mark all the children
595   // of the parents as kept (consider for example a DW_TAG_namespace node in
596   // the parent chain). There are however a set of DIE types for which we want
597   // to ignore that directive and still walk their children.
598   if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
599     Flags &= ~DWARFLinker::TF_ParentWalk;
600 
601   // We're finished if this DIE has no children or we're walking the parent
602   // chain.
603   if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
604     return;
605 
606   // Add children in reverse order to the worklist to effectively process them
607   // in order.
608   for (auto Child : reverse(Die.children())) {
609     // Add a worklist item before every child to calculate incompleteness right
610     // after the current child is processed.
611     CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
612     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
613                           &ChildInfo);
614     Worklist.emplace_back(Child, CU, Flags);
615   }
616 }
617 
618 /// Look at DIEs referenced by the given DIE and decide whether they should be
619 /// kept. All DIEs referenced though attributes should be kept.
620 void DWARFLinker::lookForRefDIEsToKeep(
621     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
622     const UnitListTy &Units, const DWARFFile &File,
623     SmallVectorImpl<WorklistItem> &Worklist) {
624   bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
625                     ? (Flags & DWARFLinker::TF_ODR)
626                     : CU.hasODR();
627   DWARFUnit &Unit = CU.getOrigUnit();
628   DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
629   const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
630   uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
631 
632   SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
633   for (const auto &AttrSpec : Abbrev->attributes()) {
634     DWARFFormValue Val(AttrSpec.Form);
635     if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
636         AttrSpec.Attr == dwarf::DW_AT_sibling) {
637       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
638                                 Unit.getFormParams());
639       continue;
640     }
641 
642     Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
643     CompileUnit *ReferencedCU;
644     if (auto RefDie =
645             resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
646       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
647       bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
648                          Info.Ctxt->isDefinedInClangModule();
649       // If the referenced DIE has a DeclContext that has already been
650       // emitted, then do not keep the one in this CU. We'll link to
651       // the canonical DIE in cloneDieReferenceAttribute.
652       //
653       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
654       // be necessary and could be advantageously replaced by
655       // ReferencedCU->hasODR() && CU.hasODR().
656       //
657       // FIXME: compatibility with dsymutil-classic. There is no
658       // reason not to unique ref_addr references.
659       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) &&
660           Info.Ctxt &&
661           Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
662           Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
663         continue;
664 
665       // Keep a module forward declaration if there is no definition.
666       if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
667             Info.Ctxt->getCanonicalDIEOffset()))
668         Info.Prune = false;
669       ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
670     }
671   }
672 
673   unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
674 
675   // Add referenced DIEs in reverse order to the worklist to effectively
676   // process them in order.
677   for (auto &P : reverse(ReferencedDIEs)) {
678     // Add a worklist item before every child to calculate incompleteness right
679     // after the current child is processed.
680     CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
681     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
682                           &Info);
683     Worklist.emplace_back(P.first, P.second,
684                           DWARFLinker::TF_Keep |
685                               DWARFLinker::TF_DependencyWalk | ODRFlag);
686   }
687 }
688 
689 /// Look at the parent of the given DIE and decide whether they should be kept.
690 void DWARFLinker::lookForParentDIEsToKeep(
691     unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
692     SmallVectorImpl<WorklistItem> &Worklist) {
693   // Stop if we encounter an ancestor that's already marked as kept.
694   if (CU.getInfo(AncestorIdx).Keep)
695     return;
696 
697   DWARFUnit &Unit = CU.getOrigUnit();
698   DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
699   Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
700   Worklist.emplace_back(ParentDIE, CU, Flags);
701 }
702 
703 /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
704 /// information in \p CU's DIEInfo.
705 ///
706 /// This function is the entry point of the DIE selection algorithm. It is
707 /// expected to walk the DIE tree in file order and (though the mediation of
708 /// its helper) call hasValidRelocation() on each DIE that might be a 'root
709 /// DIE' (See DwarfLinker class comment).
710 ///
711 /// While walking the dependencies of root DIEs, this function is also called,
712 /// but during these dependency walks the file order is not respected. The
713 /// TF_DependencyWalk flag tells us which kind of traversal we are currently
714 /// doing.
715 ///
716 /// The recursive algorithm is implemented iteratively as a work list because
717 /// very deep recursion could exhaust the stack for large projects. The work
718 /// list acts as a scheduler for different types of work that need to be
719 /// performed.
720 ///
721 /// The recursive nature of the algorithm is simulated by running the "main"
722 /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
723 /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
724 /// fixing up a computed property (UpdateChildIncompleteness,
725 /// UpdateRefIncompleteness).
726 ///
727 /// The return value indicates whether the DIE is incomplete.
728 void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
729                                     RangesTy &Ranges, const UnitListTy &Units,
730                                     const DWARFDie &Die, const DWARFFile &File,
731                                     CompileUnit &Cu, unsigned Flags) {
732   // LIFO work list.
733   SmallVector<WorklistItem, 4> Worklist;
734   Worklist.emplace_back(Die, Cu, Flags);
735 
736   while (!Worklist.empty()) {
737     WorklistItem Current = Worklist.pop_back_val();
738 
739     // Look at the worklist type to decide what kind of work to perform.
740     switch (Current.Type) {
741     case WorklistItemType::UpdateChildIncompleteness:
742       updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
743       continue;
744     case WorklistItemType::UpdateRefIncompleteness:
745       updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
746       continue;
747     case WorklistItemType::LookForChildDIEsToKeep:
748       lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
749       continue;
750     case WorklistItemType::LookForRefDIEsToKeep:
751       lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
752                            Worklist);
753       continue;
754     case WorklistItemType::LookForParentDIEsToKeep:
755       lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
756                               Worklist);
757       continue;
758     case WorklistItemType::LookForDIEsToKeep:
759       break;
760     }
761 
762     unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
763     CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
764 
765     if (MyInfo.Prune)
766       continue;
767 
768     // If the Keep flag is set, we are marking a required DIE's dependencies.
769     // If our target is already marked as kept, we're all set.
770     bool AlreadyKept = MyInfo.Keep;
771     if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
772       continue;
773 
774     // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
775     // because it would screw up the relocation finding logic.
776     if (!(Current.Flags & TF_DependencyWalk))
777       Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
778                                     Current.CU, MyInfo, Current.Flags);
779 
780     // Finish by looking for child DIEs. Because of the LIFO worklist we need
781     // to schedule that work before any subsequent items are added to the
782     // worklist.
783     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
784                           WorklistItemType::LookForChildDIEsToKeep);
785 
786     if (AlreadyKept || !(Current.Flags & TF_Keep))
787       continue;
788 
789     // If it is a newly kept DIE mark it as well as all its dependencies as
790     // kept.
791     MyInfo.Keep = true;
792 
793     // We're looking for incomplete types.
794     MyInfo.Incomplete =
795         Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
796         Current.Die.getTag() != dwarf::DW_TAG_member &&
797         dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
798 
799     // After looking at the parent chain, look for referenced DIEs. Because of
800     // the LIFO worklist we need to schedule that work before any subsequent
801     // items are added to the worklist.
802     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
803                           WorklistItemType::LookForRefDIEsToKeep);
804 
805     bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
806                                                       : Current.CU.hasODR();
807     unsigned ODRFlag = UseOdr ? TF_ODR : 0;
808     unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
809 
810     // Now schedule the parent walk.
811     Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
812   }
813 }
814 
815 /// Assign an abbreviation number to \p Abbrev.
816 ///
817 /// Our DIEs get freed after every DebugMapObject has been processed,
818 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
819 /// the instances hold by the DIEs. When we encounter an abbreviation
820 /// that we don't know, we create a permanent copy of it.
821 void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
822   // Check the set for priors.
823   FoldingSetNodeID ID;
824   Abbrev.Profile(ID);
825   void *InsertToken;
826   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
827 
828   // If it's newly added.
829   if (InSet) {
830     // Assign existing abbreviation number.
831     Abbrev.setNumber(InSet->getNumber());
832   } else {
833     // Add to abbreviation list.
834     Abbreviations.push_back(
835         std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
836     for (const auto &Attr : Abbrev.getData())
837       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
838     AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
839     // Assign the unique abbreviation number.
840     Abbrev.setNumber(Abbreviations.size());
841     Abbreviations.back()->setNumber(Abbreviations.size());
842   }
843 }
844 
845 unsigned DWARFLinker::DIECloner::cloneStringAttribute(
846     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
847     const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
848   Optional<const char *> String = dwarf::toString(Val);
849   if (!String)
850     return 0;
851 
852   // Switch everything to out of line strings.
853   auto StringEntry = StringPool.getEntry(*String);
854 
855   // Update attributes info.
856   if (AttrSpec.Attr == dwarf::DW_AT_name)
857     Info.Name = StringEntry;
858   else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
859            AttrSpec.Attr == dwarf::DW_AT_linkage_name)
860     Info.MangledName = StringEntry;
861 
862   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
863                DIEInteger(StringEntry.getOffset()));
864 
865   return 4;
866 }
867 
868 unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
869     DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
870     unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
871     CompileUnit &Unit) {
872   const DWARFUnit &U = Unit.getOrigUnit();
873   uint64_t Ref = *Val.getAsReference();
874 
875   DIE *NewRefDie = nullptr;
876   CompileUnit *RefUnit = nullptr;
877   DeclContext *Ctxt = nullptr;
878 
879   DWARFDie RefDie =
880       Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
881 
882   // If the referenced DIE is not found,  drop the attribute.
883   if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
884     return 0;
885 
886   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
887 
888   // If we already have emitted an equivalent DeclContext, just point
889   // at it.
890   if (isODRAttribute(AttrSpec.Attr)) {
891     Ctxt = RefInfo.Ctxt;
892     if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
893       DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
894       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
895                    dwarf::DW_FORM_ref_addr, Attr);
896       return U.getRefAddrByteSize();
897     }
898   }
899 
900   if (!RefInfo.Clone) {
901     assert(Ref > InputDIE.getOffset());
902     // We haven't cloned this DIE yet. Just create an empty one and
903     // store it. It'll get really cloned when we process it.
904     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
905   }
906   NewRefDie = RefInfo.Clone;
907 
908   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
909       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
910     // We cannot currently rely on a DIEEntry to emit ref_addr
911     // references, because the implementation calls back to DwarfDebug
912     // to find the unit offset. (We don't have a DwarfDebug)
913     // FIXME: we should be able to design DIEEntry reliance on
914     // DwarfDebug away.
915     uint64_t Attr;
916     if (Ref < InputDIE.getOffset()) {
917       // We must have already cloned that DIE.
918       uint32_t NewRefOffset =
919           RefUnit->getStartOffset() + NewRefDie->getOffset();
920       Attr = NewRefOffset;
921       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
922                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
923     } else {
924       // A forward reference. Note and fixup later.
925       Attr = 0xBADDEF;
926       Unit.noteForwardReference(
927           NewRefDie, RefUnit, Ctxt,
928           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
929                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
930     }
931     return U.getRefAddrByteSize();
932   }
933 
934   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
935                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
936 
937   return AttrSize;
938 }
939 
940 void DWARFLinker::DIECloner::cloneExpression(
941     DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
942     CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
943   using Encoding = DWARFExpression::Operation::Encoding;
944 
945   uint64_t OpOffset = 0;
946   for (auto &Op : Expression) {
947     auto Description = Op.getDescription();
948     // DW_OP_const_type is variable-length and has 3
949     // operands. DWARFExpression thus far only supports 2.
950     auto Op0 = Description.Op[0];
951     auto Op1 = Description.Op[1];
952     if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
953         (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
954       Linker.reportWarning("Unsupported DW_OP encoding.", File);
955 
956     if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
957         (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
958       // This code assumes that the other non-typeref operand fits into 1 byte.
959       assert(OpOffset < Op.getEndOffset());
960       uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
961       assert(ULEBsize <= 16);
962 
963       // Copy over the operation.
964       OutputBuffer.push_back(Op.getCode());
965       uint64_t RefOffset;
966       if (Op1 == Encoding::SizeNA) {
967         RefOffset = Op.getRawOperand(0);
968       } else {
969         OutputBuffer.push_back(Op.getRawOperand(0));
970         RefOffset = Op.getRawOperand(1);
971       }
972       uint32_t Offset = 0;
973       // Look up the base type. For DW_OP_convert, the operand may be 0 to
974       // instead indicate the generic type. The same holds for
975       // DW_OP_reinterpret, which is currently not supported.
976       if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
977         auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
978         CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
979         if (DIE *Clone = Info.Clone)
980           Offset = Clone->getOffset();
981         else
982           Linker.reportWarning(
983               "base type ref doesn't point to DW_TAG_base_type.", File);
984       }
985       uint8_t ULEB[16];
986       unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
987       if (RealSize > ULEBsize) {
988         // Emit the generic type as a fallback.
989         RealSize = encodeULEB128(0, ULEB, ULEBsize);
990         Linker.reportWarning("base type ref doesn't fit.", File);
991       }
992       assert(RealSize == ULEBsize && "padding failed");
993       ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
994       OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
995     } else {
996       // Copy over everything else unmodified.
997       StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
998       OutputBuffer.append(Bytes.begin(), Bytes.end());
999     }
1000     OpOffset = Op.getEndOffset();
1001   }
1002 }
1003 
1004 unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1005     DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
1006     const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
1007   DIEValueList *Attr;
1008   DIEValue Value;
1009   DIELoc *Loc = nullptr;
1010   DIEBlock *Block = nullptr;
1011   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1012     Loc = new (DIEAlloc) DIELoc;
1013     Linker.DIELocs.push_back(Loc);
1014   } else {
1015     Block = new (DIEAlloc) DIEBlock;
1016     Linker.DIEBlocks.push_back(Block);
1017   }
1018   Attr = Loc ? static_cast<DIEValueList *>(Loc)
1019              : static_cast<DIEValueList *>(Block);
1020 
1021   if (Loc)
1022     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1023                      dwarf::Form(AttrSpec.Form), Loc);
1024   else
1025     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1026                      dwarf::Form(AttrSpec.Form), Block);
1027 
1028   // If the block is a DWARF Expression, clone it into the temporary
1029   // buffer using cloneExpression(), otherwise copy the data directly.
1030   SmallVector<uint8_t, 32> Buffer;
1031   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1032   if (DWARFAttribute::mayHaveLocationExpr(AttrSpec.Attr) &&
1033       (Val.isFormClass(DWARFFormValue::FC_Block) ||
1034        Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1035     DWARFUnit &OrigUnit = Unit.getOrigUnit();
1036     DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1037                        IsLittleEndian, OrigUnit.getAddressByteSize());
1038     DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1039                          OrigUnit.getFormParams().Format);
1040     cloneExpression(Data, Expr, File, Unit, Buffer);
1041     Bytes = Buffer;
1042   }
1043   for (auto Byte : Bytes)
1044     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1045                    dwarf::DW_FORM_data1, DIEInteger(Byte));
1046 
1047   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1048   // the DIE class, this "if" could be replaced by
1049   // Attr->setSize(Bytes.size()).
1050   if (Loc)
1051     Loc->setSize(Bytes.size());
1052   else
1053     Block->setSize(Bytes.size());
1054 
1055   Die.addValue(DIEAlloc, Value);
1056   return AttrSize;
1057 }
1058 
1059 unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1060     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1061     const CompileUnit &Unit, AttributesInfo &Info) {
1062   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1063     if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1064       Info.HasLowPc = true;
1065     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1066                  dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1067     return Unit.getOrigUnit().getAddressByteSize();
1068   }
1069 
1070   dwarf::Form Form = AttrSpec.Form;
1071   uint64_t Addr = 0;
1072   if (Form == dwarf::DW_FORM_addrx) {
1073     if (Optional<uint64_t> AddrOffsetSectionBase =
1074             Unit.getOrigUnit().getAddrOffsetSectionBase()) {
1075       uint64_t StartOffset = *AddrOffsetSectionBase + Val.getRawUValue();
1076       uint64_t EndOffset =
1077           StartOffset + Unit.getOrigUnit().getAddressByteSize();
1078       if (llvm::Expected<uint64_t> RelocAddr =
1079               ObjFile.Addresses->relocateIndexedAddr(StartOffset, EndOffset))
1080         Addr = *RelocAddr;
1081       else
1082         Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile);
1083     } else
1084       Linker.reportWarning("no base offset for address table", ObjFile);
1085 
1086     // If this is an indexed address emit the debug_info address.
1087     Form = dwarf::DW_FORM_addr;
1088   } else
1089     Addr = *Val.getAsAddress();
1090 
1091   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1092     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1093         Die.getTag() == dwarf::DW_TAG_lexical_block ||
1094         Die.getTag() == dwarf::DW_TAG_label) {
1095       // The low_pc of a block or inline subroutine might get
1096       // relocated because it happens to match the low_pc of the
1097       // enclosing subprogram. To prevent issues with that, always use
1098       // the low_pc from the input DIE if relocations have been applied.
1099       Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1100                   ? Info.OrigLowPc
1101                   : Addr) +
1102              Info.PCOffset;
1103     } else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1104       Addr = Unit.getLowPc();
1105       if (Addr == std::numeric_limits<uint64_t>::max())
1106         return 0;
1107     }
1108     Info.HasLowPc = true;
1109   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1110     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1111       if (uint64_t HighPc = Unit.getHighPc())
1112         Addr = HighPc;
1113       else
1114         return 0;
1115     } else
1116       // If we have a high_pc recorded for the input DIE, use
1117       // it. Otherwise (when no relocations where applied) just use the
1118       // one we just decoded.
1119       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1120   } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
1121     // Relocate a return PC address within a call site entry.
1122     if (Die.getTag() == dwarf::DW_TAG_call_site)
1123       Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
1124              Info.PCOffset;
1125   } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) {
1126     // Relocate the address of a branch instruction within a call site entry.
1127     if (Die.getTag() == dwarf::DW_TAG_call_site)
1128       Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset;
1129   }
1130 
1131   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1132                static_cast<dwarf::Form>(Form), DIEInteger(Addr));
1133   return Unit.getOrigUnit().getAddressByteSize();
1134 }
1135 
1136 unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1137     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1138     CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1139     unsigned AttrSize, AttributesInfo &Info) {
1140   uint64_t Value;
1141 
1142   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1143     if (auto OptionalValue = Val.getAsUnsignedConstant())
1144       Value = *OptionalValue;
1145     else if (auto OptionalValue = Val.getAsSignedConstant())
1146       Value = *OptionalValue;
1147     else if (auto OptionalValue = Val.getAsSectionOffset())
1148       Value = *OptionalValue;
1149     else {
1150       Linker.reportWarning(
1151           "Unsupported scalar attribute form. Dropping attribute.", File,
1152           &InputDIE);
1153       return 0;
1154     }
1155     if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1156       Info.IsDeclaration = true;
1157     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1158                  dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1159     return AttrSize;
1160   }
1161 
1162   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1163       Die.getTag() == dwarf::DW_TAG_compile_unit) {
1164     if (Unit.getLowPc() == -1ULL)
1165       return 0;
1166     // Dwarf >= 4 high_pc is an size, not an address.
1167     Value = Unit.getHighPc() - Unit.getLowPc();
1168   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1169     Value = *Val.getAsSectionOffset();
1170   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1171     Value = *Val.getAsSignedConstant();
1172   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1173     Value = *OptionalValue;
1174   else {
1175     Linker.reportWarning(
1176         "Unsupported scalar attribute form. Dropping attribute.", File,
1177         &InputDIE);
1178     return 0;
1179   }
1180   PatchLocation Patch =
1181       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1182                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1183   if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1184     Unit.noteRangeAttribute(Die, Patch);
1185     Info.HasRanges = true;
1186   }
1187 
1188   // A more generic way to check for location attributes would be
1189   // nice, but it's very unlikely that any other attribute needs a
1190   // location list.
1191   // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1192   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1193            AttrSpec.Attr == dwarf::DW_AT_frame_base) {
1194     Unit.noteLocationAttribute(Patch, Info.PCOffset);
1195   } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1196     Info.IsDeclaration = true;
1197 
1198   return AttrSize;
1199 }
1200 
1201 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1202 /// value \p Val, and add it to \p Die.
1203 /// \returns the size of the cloned attribute.
1204 unsigned DWARFLinker::DIECloner::cloneAttribute(
1205     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1206     CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1207     const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1208     bool IsLittleEndian) {
1209   const DWARFUnit &U = Unit.getOrigUnit();
1210 
1211   switch (AttrSpec.Form) {
1212   case dwarf::DW_FORM_strp:
1213   case dwarf::DW_FORM_string:
1214   case dwarf::DW_FORM_strx:
1215   case dwarf::DW_FORM_strx1:
1216   case dwarf::DW_FORM_strx2:
1217   case dwarf::DW_FORM_strx3:
1218   case dwarf::DW_FORM_strx4:
1219     return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1220   case dwarf::DW_FORM_ref_addr:
1221   case dwarf::DW_FORM_ref1:
1222   case dwarf::DW_FORM_ref2:
1223   case dwarf::DW_FORM_ref4:
1224   case dwarf::DW_FORM_ref8:
1225     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1226                                       File, Unit);
1227   case dwarf::DW_FORM_block:
1228   case dwarf::DW_FORM_block1:
1229   case dwarf::DW_FORM_block2:
1230   case dwarf::DW_FORM_block4:
1231   case dwarf::DW_FORM_exprloc:
1232     return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
1233                                IsLittleEndian);
1234   case dwarf::DW_FORM_addr:
1235   case dwarf::DW_FORM_addrx:
1236     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1237   case dwarf::DW_FORM_data1:
1238   case dwarf::DW_FORM_data2:
1239   case dwarf::DW_FORM_data4:
1240   case dwarf::DW_FORM_data8:
1241   case dwarf::DW_FORM_udata:
1242   case dwarf::DW_FORM_sdata:
1243   case dwarf::DW_FORM_sec_offset:
1244   case dwarf::DW_FORM_flag:
1245   case dwarf::DW_FORM_flag_present:
1246     return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1247                                 AttrSize, Info);
1248   default:
1249     Linker.reportWarning("Unsupported attribute form " +
1250                              dwarf::FormEncodingString(AttrSpec.Form) +
1251                              " in cloneAttribute. Dropping.",
1252                          File, &InputDIE);
1253   }
1254 
1255   return 0;
1256 }
1257 
1258 static bool isObjCSelector(StringRef Name) {
1259   return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1260          (Name[1] == '[');
1261 }
1262 
1263 void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1264                                                 const DIE *Die,
1265                                                 DwarfStringPoolEntryRef Name,
1266                                                 OffsetsStringPool &StringPool,
1267                                                 bool SkipPubSection) {
1268   assert(isObjCSelector(Name.getString()) && "not an objc selector");
1269   // Objective C method or class function.
1270   // "- [Class(Category) selector :withArg ...]"
1271   StringRef ClassNameStart(Name.getString().drop_front(2));
1272   size_t FirstSpace = ClassNameStart.find(' ');
1273   if (FirstSpace == StringRef::npos)
1274     return;
1275 
1276   StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1277   if (!SelectorStart.size())
1278     return;
1279 
1280   StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1281   Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1282 
1283   // Add an entry for the class name that points to this
1284   // method/class function.
1285   StringRef ClassName(ClassNameStart.data(), FirstSpace);
1286   Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1287 
1288   if (ClassName[ClassName.size() - 1] == ')') {
1289     size_t OpenParens = ClassName.find('(');
1290     if (OpenParens != StringRef::npos) {
1291       StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1292       Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1293                               SkipPubSection);
1294 
1295       std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1296       // FIXME: The missing space here may be a bug, but
1297       //        dsymutil-classic also does it this way.
1298       MethodNameNoCategory.append(std::string(SelectorStart));
1299       Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1300                               SkipPubSection);
1301     }
1302   }
1303 }
1304 
1305 static bool
1306 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1307                     uint16_t Tag, bool InDebugMap, bool SkipPC,
1308                     bool InFunctionScope) {
1309   switch (AttrSpec.Attr) {
1310   default:
1311     return false;
1312   case dwarf::DW_AT_low_pc:
1313   case dwarf::DW_AT_high_pc:
1314   case dwarf::DW_AT_ranges:
1315     return SkipPC;
1316   case dwarf::DW_AT_str_offsets_base:
1317     // FIXME: Use the string offset table with Dwarf 5.
1318     return true;
1319   case dwarf::DW_AT_location:
1320   case dwarf::DW_AT_frame_base:
1321     // FIXME: for some reason dsymutil-classic keeps the location attributes
1322     // when they are of block type (i.e. not location lists). This is totally
1323     // wrong for globals where we will keep a wrong address. It is mostly
1324     // harmless for locals, but there is no point in keeping these anyway when
1325     // the function wasn't linked.
1326     return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1327                        !InDebugMap)) &&
1328            !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1329   }
1330 }
1331 
1332 DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1333                                       const DWARFFile &File, CompileUnit &Unit,
1334                                       OffsetsStringPool &StringPool,
1335                                       int64_t PCOffset, uint32_t OutOffset,
1336                                       unsigned Flags, bool IsLittleEndian,
1337                                       DIE *Die) {
1338   DWARFUnit &U = Unit.getOrigUnit();
1339   unsigned Idx = U.getDIEIndex(InputDIE);
1340   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1341 
1342   // Should the DIE appear in the output?
1343   if (!Unit.getInfo(Idx).Keep)
1344     return nullptr;
1345 
1346   uint64_t Offset = InputDIE.getOffset();
1347   assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1348   if (!Die) {
1349     // The DIE might have been already created by a forward reference
1350     // (see cloneDieReferenceAttribute()).
1351     if (!Info.Clone)
1352       Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1353     Die = Info.Clone;
1354   }
1355 
1356   assert(Die->getTag() == InputDIE.getTag());
1357   Die->setOffset(OutOffset);
1358   if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
1359       Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
1360       Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
1361       !Info.Ctxt->getCanonicalDIEOffset()) {
1362     // We are about to emit a DIE that is the root of its own valid
1363     // DeclContext tree. Make the current offset the canonical offset
1364     // for this context.
1365     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1366   }
1367 
1368   // Extract and clone every attribute.
1369   DWARFDataExtractor Data = U.getDebugInfoExtractor();
1370   // Point to the next DIE (generally there is always at least a NULL
1371   // entry after the current one). If this is a lone
1372   // DW_TAG_compile_unit without any children, point to the next unit.
1373   uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1374                             ? U.getDIEAtIndex(Idx + 1).getOffset()
1375                             : U.getNextUnitOffset();
1376   AttributesInfo AttrInfo;
1377 
1378   // We could copy the data only if we need to apply a relocation to it. After
1379   // testing, it seems there is no performance downside to doing the copy
1380   // unconditionally, and it makes the code simpler.
1381   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1382   Data =
1383       DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1384 
1385   // Modify the copy with relocated addresses.
1386   if (ObjFile.Addresses->areRelocationsResolved() &&
1387       ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
1388                                           Data.isLittleEndian())) {
1389     // If we applied relocations, we store the value of high_pc that was
1390     // potentially stored in the input DIE. If high_pc is an address
1391     // (Dwarf version == 2), then it might have been relocated to a
1392     // totally unrelated value (because the end address in the object
1393     // file might be start address of another function which got moved
1394     // independently by the linker). The computation of the actual
1395     // high_pc value is done in cloneAddressAttribute().
1396     AttrInfo.OrigHighPc =
1397         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1398     // Also store the low_pc. It might get relocated in an
1399     // inline_subprogram that happens at the beginning of its
1400     // inlining function.
1401     AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1402                                           std::numeric_limits<uint64_t>::max());
1403     AttrInfo.OrigCallReturnPc =
1404         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
1405     AttrInfo.OrigCallPc =
1406         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0);
1407   }
1408 
1409   // Reset the Offset to 0 as we will be working on the local copy of
1410   // the data.
1411   Offset = 0;
1412 
1413   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1414   Offset += getULEB128Size(Abbrev->getCode());
1415 
1416   // We are entering a subprogram. Get and propagate the PCOffset.
1417   if (Die->getTag() == dwarf::DW_TAG_subprogram)
1418     PCOffset = Info.AddrAdjust;
1419   AttrInfo.PCOffset = PCOffset;
1420 
1421   if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1422     Flags |= TF_InFunctionScope;
1423     if (!Info.InDebugMap && LLVM_LIKELY(!Update))
1424       Flags |= TF_SkipPC;
1425   } else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1426     // Function-local globals could be in the debug map even when the function
1427     // is not, e.g., inlined functions.
1428     if ((Flags & TF_InFunctionScope) && Info.InDebugMap)
1429       Flags &= ~TF_SkipPC;
1430   }
1431 
1432   for (const auto &AttrSpec : Abbrev->attributes()) {
1433     if (LLVM_LIKELY(!Update) &&
1434         shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1435                             Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1436       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1437                                 U.getFormParams());
1438       continue;
1439     }
1440 
1441     DWARFFormValue Val(AttrSpec.Form);
1442     uint64_t AttrSize = Offset;
1443     Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1444     AttrSize = Offset - AttrSize;
1445 
1446     OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val,
1447                                 AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
1448   }
1449 
1450   // Look for accelerator entries.
1451   uint16_t Tag = InputDIE.getTag();
1452   // FIXME: This is slightly wrong. An inline_subroutine without a
1453   // low_pc, but with AT_ranges might be interesting to get into the
1454   // accelerator tables too. For now stick with dsymutil's behavior.
1455   if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1456       Tag != dwarf::DW_TAG_compile_unit &&
1457       getDIENames(InputDIE, AttrInfo, StringPool,
1458                   Tag != dwarf::DW_TAG_inlined_subroutine)) {
1459     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1460       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1461                               Tag == dwarf::DW_TAG_inlined_subroutine);
1462     if (AttrInfo.Name) {
1463       if (AttrInfo.NameWithoutTemplate)
1464         Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1465                                 /* SkipPubSection */ true);
1466       Unit.addNameAccelerator(Die, AttrInfo.Name,
1467                               Tag == dwarf::DW_TAG_inlined_subroutine);
1468     }
1469     if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
1470       addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
1471                          /* SkipPubSection =*/true);
1472 
1473   } else if (Tag == dwarf::DW_TAG_namespace) {
1474     if (!AttrInfo.Name)
1475       AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
1476     Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1477   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
1478              getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
1479              AttrInfo.Name.getString()[0]) {
1480     uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
1481     uint64_t RuntimeLang =
1482         dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1483             .getValueOr(0);
1484     bool ObjCClassIsImplementation =
1485         (RuntimeLang == dwarf::DW_LANG_ObjC ||
1486          RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1487         dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1488             .getValueOr(0);
1489     Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1490                             Hash);
1491   }
1492 
1493   // Determine whether there are any children that we want to keep.
1494   bool HasChildren = false;
1495   for (auto Child : InputDIE.children()) {
1496     unsigned Idx = U.getDIEIndex(Child);
1497     if (Unit.getInfo(Idx).Keep) {
1498       HasChildren = true;
1499       break;
1500     }
1501   }
1502 
1503   DIEAbbrev NewAbbrev = Die->generateAbbrev();
1504   if (HasChildren)
1505     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1506   // Assign a permanent abbrev number
1507   Linker.assignAbbrev(NewAbbrev);
1508   Die->setAbbrevNumber(NewAbbrev.getNumber());
1509 
1510   // Add the size of the abbreviation number to the output offset.
1511   OutOffset += getULEB128Size(Die->getAbbrevNumber());
1512 
1513   if (!HasChildren) {
1514     // Update our size.
1515     Die->setSize(OutOffset - Die->getOffset());
1516     return Die;
1517   }
1518 
1519   // Recursively clone children.
1520   for (auto Child : InputDIE.children()) {
1521     if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset,
1522                               OutOffset, Flags, IsLittleEndian)) {
1523       Die->addChild(Clone);
1524       OutOffset = Clone->getOffset() + Clone->getSize();
1525     }
1526   }
1527 
1528   // Account for the end of children marker.
1529   OutOffset += sizeof(int8_t);
1530   // Update our size.
1531   Die->setSize(OutOffset - Die->getOffset());
1532   return Die;
1533 }
1534 
1535 /// Patch the input object file relevant debug_ranges entries
1536 /// and emit them in the output file. Update the relevant attributes
1537 /// to point at the new entries.
1538 void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit,
1539                                      DWARFContext &OrigDwarf,
1540                                      const DWARFFile &File) const {
1541   DWARFDebugRangeList RangeList;
1542   const auto &FunctionRanges = Unit.getFunctionRanges();
1543   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1544   DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
1545                                     OrigDwarf.getDWARFObj().getRangesSection(),
1546                                     OrigDwarf.isLittleEndian(), AddressSize);
1547   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1548   DWARFUnit &OrigUnit = Unit.getOrigUnit();
1549   auto OrigUnitDie = OrigUnit.getUnitDIE(false);
1550   uint64_t OrigLowPc =
1551       dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
1552   // Ranges addresses are based on the unit's low_pc. Compute the
1553   // offset we need to apply to adapt to the new unit's low_pc.
1554   int64_t UnitPcOffset = 0;
1555   if (OrigLowPc != -1ULL)
1556     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1557 
1558   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1559     uint64_t Offset = RangeAttribute.get();
1560     RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize());
1561     if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
1562       llvm::consumeError(std::move(E));
1563       reportWarning("invalid range list ignored.", File);
1564       RangeList.clear();
1565     }
1566     const auto &Entries = RangeList.getEntries();
1567     if (!Entries.empty()) {
1568       const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1569 
1570       if (CurrRange == InvalidRange ||
1571           First.StartAddress + OrigLowPc < CurrRange.start() ||
1572           First.StartAddress + OrigLowPc >= CurrRange.stop()) {
1573         CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1574         if (CurrRange == InvalidRange ||
1575             CurrRange.start() > First.StartAddress + OrigLowPc) {
1576           reportWarning("no mapping for range.", File);
1577           continue;
1578         }
1579       }
1580     }
1581 
1582     TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange,
1583                                        Entries, AddressSize);
1584   }
1585 }
1586 
1587 /// Generate the debug_aranges entries for \p Unit and if the
1588 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1589 /// contribution for this attribute.
1590 /// FIXME: this could actually be done right in patchRangesForUnit,
1591 /// but for the sake of initial bit-for-bit compatibility with legacy
1592 /// dsymutil, we have to do it in a delayed pass.
1593 void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const {
1594   auto Attr = Unit.getUnitRangesAttribute();
1595   if (Attr)
1596     Attr->set(TheDwarfEmitter->getRangesSectionSize());
1597   TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
1598 }
1599 
1600 /// Insert the new line info sequence \p Seq into the current
1601 /// set of already linked line info \p Rows.
1602 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1603                                std::vector<DWARFDebugLine::Row> &Rows) {
1604   if (Seq.empty())
1605     return;
1606 
1607   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1608     llvm::append_range(Rows, Seq);
1609     Seq.clear();
1610     return;
1611   }
1612 
1613   object::SectionedAddress Front = Seq.front().Address;
1614   auto InsertPoint = partition_point(
1615       Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1616 
1617   // FIXME: this only removes the unneeded end_sequence if the
1618   // sequences have been inserted in order. Using a global sort like
1619   // described in patchLineTableForUnit() and delaying the end_sequene
1620   // elimination to emitLineTableForUnit() we can get rid of all of them.
1621   if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1622       InsertPoint->EndSequence) {
1623     *InsertPoint = Seq.front();
1624     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1625   } else {
1626     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1627   }
1628 
1629   Seq.clear();
1630 }
1631 
1632 static void patchStmtList(DIE &Die, DIEInteger Offset) {
1633   for (auto &V : Die.values())
1634     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1635       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
1636       return;
1637     }
1638 
1639   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1640 }
1641 
1642 /// Extract the line table for \p Unit from \p OrigDwarf, and
1643 /// recreate a relocated version of these for the address ranges that
1644 /// are present in the binary.
1645 void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit,
1646                                         DWARFContext &OrigDwarf,
1647                                         const DWARFFile &File) {
1648   DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
1649   auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1650   if (!StmtList)
1651     return;
1652 
1653   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1654   if (auto *OutputDIE = Unit.getOutputUnitDIE())
1655     patchStmtList(*OutputDIE,
1656                   DIEInteger(TheDwarfEmitter->getLineSectionSize()));
1657 
1658   RangesTy &Ranges = File.Addresses->getValidAddressRanges();
1659 
1660   // Parse the original line info for the unit.
1661   DWARFDebugLine::LineTable LineTable;
1662   uint64_t StmtOffset = *StmtList;
1663   DWARFDataExtractor LineExtractor(
1664       OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
1665       OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
1666   if (needToTranslateStrings())
1667     return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset);
1668 
1669   if (Error Err =
1670           LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
1671                           &Unit.getOrigUnit(), OrigDwarf.getWarningHandler()))
1672     OrigDwarf.getWarningHandler()(std::move(Err));
1673 
1674   // This vector is the output line table.
1675   std::vector<DWARFDebugLine::Row> NewRows;
1676   NewRows.reserve(LineTable.Rows.size());
1677 
1678   // Current sequence of rows being extracted, before being inserted
1679   // in NewRows.
1680   std::vector<DWARFDebugLine::Row> Seq;
1681   const auto &FunctionRanges = Unit.getFunctionRanges();
1682   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1683 
1684   // FIXME: This logic is meant to generate exactly the same output as
1685   // Darwin's classic dsymutil. There is a nicer way to implement this
1686   // by simply putting all the relocated line info in NewRows and simply
1687   // sorting NewRows before passing it to emitLineTableForUnit. This
1688   // should be correct as sequences for a function should stay
1689   // together in the sorted output. There are a few corner cases that
1690   // look suspicious though, and that required to implement the logic
1691   // this way. Revisit that once initial validation is finished.
1692 
1693   // Iterate over the object file line info and extract the sequences
1694   // that correspond to linked functions.
1695   for (auto &Row : LineTable.Rows) {
1696     // Check whether we stepped out of the range. The range is
1697     // half-open, but consider accept the end address of the range if
1698     // it is marked as end_sequence in the input (because in that
1699     // case, the relocation offset is accurate and that entry won't
1700     // serve as the start of another function).
1701     if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
1702         Row.Address.Address > CurrRange.stop() ||
1703         (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
1704       // We just stepped out of a known range. Insert a end_sequence
1705       // corresponding to the end of the range.
1706       uint64_t StopAddress = CurrRange != InvalidRange
1707                                  ? CurrRange.stop() + CurrRange.value()
1708                                  : -1ULL;
1709       CurrRange = FunctionRanges.find(Row.Address.Address);
1710       bool CurrRangeValid =
1711           CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
1712       if (!CurrRangeValid) {
1713         CurrRange = InvalidRange;
1714         if (StopAddress != -1ULL) {
1715           // Try harder by looking in the Address ranges map.
1716           // There are corner cases where this finds a
1717           // valid entry. It's unclear if this is right or wrong, but
1718           // for now do as dsymutil.
1719           // FIXME: Understand exactly what cases this addresses and
1720           // potentially remove it along with the Ranges map.
1721           auto Range = Ranges.lower_bound(Row.Address.Address);
1722           if (Range != Ranges.begin() && Range != Ranges.end())
1723             --Range;
1724 
1725           if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
1726               Range->second.HighPC >= Row.Address.Address) {
1727             StopAddress = Row.Address.Address + Range->second.Offset;
1728           }
1729         }
1730       }
1731       if (StopAddress != -1ULL && !Seq.empty()) {
1732         // Insert end sequence row with the computed end address, but
1733         // the same line as the previous one.
1734         auto NextLine = Seq.back();
1735         NextLine.Address.Address = StopAddress;
1736         NextLine.EndSequence = 1;
1737         NextLine.PrologueEnd = 0;
1738         NextLine.BasicBlock = 0;
1739         NextLine.EpilogueBegin = 0;
1740         Seq.push_back(NextLine);
1741         insertLineSequence(Seq, NewRows);
1742       }
1743 
1744       if (!CurrRangeValid)
1745         continue;
1746     }
1747 
1748     // Ignore empty sequences.
1749     if (Row.EndSequence && Seq.empty())
1750       continue;
1751 
1752     // Relocate row address and add it to the current sequence.
1753     Row.Address.Address += CurrRange.value();
1754     Seq.emplace_back(Row);
1755 
1756     if (Row.EndSequence)
1757       insertLineSequence(Seq, NewRows);
1758   }
1759 
1760   // Finished extracting, now emit the line tables.
1761   // FIXME: LLVM hard-codes its prologue values. We just copy the
1762   // prologue over and that works because we act as both producer and
1763   // consumer. It would be nicer to have a real configurable line
1764   // table emitter.
1765   if (LineTable.Prologue.getVersion() < 2 ||
1766       LineTable.Prologue.getVersion() > 5 ||
1767       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
1768       LineTable.Prologue.OpcodeBase > 13)
1769     reportWarning("line table parameters mismatch. Cannot emit.", File);
1770   else {
1771     uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
1772     // DWARF v5 has an extra 2 bytes of information before the header_length
1773     // field.
1774     if (LineTable.Prologue.getVersion() == 5)
1775       PrologueEnd += 2;
1776     StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
1777     MCDwarfLineTableParams Params;
1778     Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1779     Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1780     Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1781     TheDwarfEmitter->emitLineTableForUnit(
1782         Params, LineData.slice(*StmtList + 4, PrologueEnd),
1783         LineTable.Prologue.MinInstLength, NewRows,
1784         Unit.getOrigUnit().getAddressByteSize());
1785   }
1786 }
1787 
1788 void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
1789   switch (Options.TheAccelTableKind) {
1790   case AccelTableKind::Apple:
1791     emitAppleAcceleratorEntriesForUnit(Unit);
1792     break;
1793   case AccelTableKind::Dwarf:
1794     emitDwarfAcceleratorEntriesForUnit(Unit);
1795     break;
1796   case AccelTableKind::Pub:
1797     emitPubAcceleratorEntriesForUnit(Unit);
1798     break;
1799   case AccelTableKind::Default:
1800     llvm_unreachable("The default must be updated to a concrete value.");
1801     break;
1802   }
1803 }
1804 
1805 void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1806   // Add namespaces.
1807   for (const auto &Namespace : Unit.getNamespaces())
1808     AppleNamespaces.addName(Namespace.Name,
1809                             Namespace.Die->getOffset() + Unit.getStartOffset());
1810 
1811   /// Add names.
1812   for (const auto &Pubname : Unit.getPubnames())
1813     AppleNames.addName(Pubname.Name,
1814                        Pubname.Die->getOffset() + Unit.getStartOffset());
1815 
1816   /// Add types.
1817   for (const auto &Pubtype : Unit.getPubtypes())
1818     AppleTypes.addName(
1819         Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1820         Pubtype.Die->getTag(),
1821         Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1822                                         : 0,
1823         Pubtype.QualifiedNameHash);
1824 
1825   /// Add ObjC names.
1826   for (const auto &ObjC : Unit.getObjC())
1827     AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1828 }
1829 
1830 void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1831   for (const auto &Namespace : Unit.getNamespaces())
1832     DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1833                        Namespace.Die->getTag(), Unit.getUniqueID());
1834   for (const auto &Pubname : Unit.getPubnames())
1835     DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1836                        Pubname.Die->getTag(), Unit.getUniqueID());
1837   for (const auto &Pubtype : Unit.getPubtypes())
1838     DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
1839                        Pubtype.Die->getTag(), Unit.getUniqueID());
1840 }
1841 
1842 void DWARFLinker::emitPubAcceleratorEntriesForUnit(CompileUnit &Unit) {
1843   TheDwarfEmitter->emitPubNamesForUnit(Unit);
1844   TheDwarfEmitter->emitPubTypesForUnit(Unit);
1845 }
1846 
1847 /// Read the frame info stored in the object, and emit the
1848 /// patched frame descriptions for the resulting file.
1849 ///
1850 /// This is actually pretty easy as the data of the CIEs and FDEs can
1851 /// be considered as black boxes and moved as is. The only thing to do
1852 /// is to patch the addresses in the headers.
1853 void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File,
1854                                           RangesTy &Ranges,
1855                                           DWARFContext &OrigDwarf,
1856                                           unsigned AddrSize) {
1857   StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
1858   if (FrameData.empty())
1859     return;
1860 
1861   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
1862   uint64_t InputOffset = 0;
1863 
1864   // Store the data of the CIEs defined in this object, keyed by their
1865   // offsets.
1866   DenseMap<uint64_t, StringRef> LocalCIES;
1867 
1868   while (Data.isValidOffset(InputOffset)) {
1869     uint64_t EntryOffset = InputOffset;
1870     uint32_t InitialLength = Data.getU32(&InputOffset);
1871     if (InitialLength == 0xFFFFFFFF)
1872       return reportWarning("Dwarf64 bits no supported", File);
1873 
1874     uint32_t CIEId = Data.getU32(&InputOffset);
1875     if (CIEId == 0xFFFFFFFF) {
1876       // This is a CIE, store it.
1877       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
1878       LocalCIES[EntryOffset] = CIEData;
1879       // The -4 is to account for the CIEId we just read.
1880       InputOffset += InitialLength - 4;
1881       continue;
1882     }
1883 
1884     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
1885 
1886     // Some compilers seem to emit frame info that doesn't start at
1887     // the function entry point, thus we can't just lookup the address
1888     // in the debug map. Use the AddressInfo's range map to see if the FDE
1889     // describes something that we can relocate.
1890     auto Range = Ranges.upper_bound(Loc);
1891     if (Range != Ranges.begin())
1892       --Range;
1893     if (Range == Ranges.end() || Range->first > Loc ||
1894         Range->second.HighPC <= Loc) {
1895       // The +4 is to account for the size of the InitialLength field itself.
1896       InputOffset = EntryOffset + InitialLength + 4;
1897       continue;
1898     }
1899 
1900     // This is an FDE, and we have a mapping.
1901     // Have we already emitted a corresponding CIE?
1902     StringRef CIEData = LocalCIES[CIEId];
1903     if (CIEData.empty())
1904       return reportWarning("Inconsistent debug_frame content. Dropping.", File);
1905 
1906     // Look if we already emitted a CIE that corresponds to the
1907     // referenced one (the CIE data is the key of that lookup).
1908     auto IteratorInserted = EmittedCIEs.insert(
1909         std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
1910     // If there is no CIE yet for this ID, emit it.
1911     if (IteratorInserted.second) {
1912       LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
1913       IteratorInserted.first->getValue() = LastCIEOffset;
1914       TheDwarfEmitter->emitCIE(CIEData);
1915     }
1916 
1917     // Emit the FDE with updated address and CIE pointer.
1918     // (4 + AddrSize) is the size of the CIEId + initial_location
1919     // fields that will get reconstructed by emitFDE().
1920     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
1921     TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
1922                              Loc + Range->second.Offset,
1923                              FrameData.substr(InputOffset, FDERemainingBytes));
1924     InputOffset += FDERemainingBytes;
1925   }
1926 }
1927 
1928 uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
1929                                                         CompileUnit &U,
1930                                                         const DWARFFile &File,
1931                                                         int ChildRecurseDepth) {
1932   const char *Name = nullptr;
1933   DWARFUnit *OrigUnit = &U.getOrigUnit();
1934   CompileUnit *CU = &U;
1935   Optional<DWARFFormValue> Ref;
1936 
1937   while (1) {
1938     if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
1939       Name = CurrentName;
1940 
1941     if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
1942         !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
1943       break;
1944 
1945     if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
1946       break;
1947 
1948     CompileUnit *RefCU;
1949     if (auto RefDIE =
1950             Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
1951       CU = RefCU;
1952       OrigUnit = &RefCU->getOrigUnit();
1953       DIE = RefDIE;
1954     }
1955   }
1956 
1957   unsigned Idx = OrigUnit->getDIEIndex(DIE);
1958   if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
1959     Name = "(anonymous namespace)";
1960 
1961   if (CU->getInfo(Idx).ParentIdx == 0 ||
1962       // FIXME: dsymutil-classic compatibility. Ignore modules.
1963       CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
1964           dwarf::DW_TAG_module)
1965     return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
1966 
1967   DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
1968   return djbHash(
1969       (Name ? Name : ""),
1970       djbHash((Name ? "::" : ""),
1971               hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
1972 }
1973 
1974 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
1975   auto DwoId = dwarf::toUnsigned(
1976       CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
1977   if (DwoId)
1978     return *DwoId;
1979   return 0;
1980 }
1981 
1982 static std::string remapPath(StringRef Path,
1983                              const objectPrefixMap &ObjectPrefixMap) {
1984   if (ObjectPrefixMap.empty())
1985     return Path.str();
1986 
1987   SmallString<256> p = Path;
1988   for (const auto &Entry : ObjectPrefixMap)
1989     if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
1990       break;
1991   return p.str().str();
1992 }
1993 
1994 bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit,
1995                                           const DWARFFile &File,
1996                                           OffsetsStringPool &StringPool,
1997                                           DeclContextTree &ODRContexts,
1998                                           uint64_t ModulesEndOffset,
1999                                           unsigned &UnitID, bool IsLittleEndian,
2000                                           unsigned Indent, bool Quiet) {
2001   std::string PCMfile = dwarf::toString(
2002       CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2003   if (PCMfile.empty())
2004     return false;
2005   if (Options.ObjectPrefixMap)
2006     PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap);
2007 
2008   // Clang module DWARF skeleton CUs abuse this for the path to the module.
2009   uint64_t DwoId = getDwoId(CUDie, Unit);
2010 
2011   std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2012   if (Name.empty()) {
2013     if (!Quiet)
2014       reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
2015     return true;
2016   }
2017 
2018   if (!Quiet && Options.Verbose) {
2019     outs().indent(Indent);
2020     outs() << "Found clang module reference " << PCMfile;
2021   }
2022 
2023   auto Cached = ClangModules.find(PCMfile);
2024   if (Cached != ClangModules.end()) {
2025     // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2026     // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2027     // ASTFileSignatures will change randomly when a module is rebuilt.
2028     if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2029       reportWarning(Twine("hash mismatch: this object file was built against a "
2030                           "different version of the module ") +
2031                         PCMfile,
2032                     File);
2033     if (!Quiet && Options.Verbose)
2034       outs() << " [cached].\n";
2035     return true;
2036   }
2037   if (!Quiet && Options.Verbose)
2038     outs() << " ...\n";
2039 
2040   // Cyclic dependencies are disallowed by Clang, but we still
2041   // shouldn't run into an infinite loop, so mark it as processed now.
2042   ClangModules.insert({PCMfile, DwoId});
2043 
2044   if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
2045                                 ODRContexts, ModulesEndOffset, UnitID,
2046                                 IsLittleEndian, Indent + 2, Quiet)) {
2047     consumeError(std::move(E));
2048     return false;
2049   }
2050   return true;
2051 }
2052 
2053 Error DWARFLinker::loadClangModule(
2054     DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
2055     const DWARFFile &File, OffsetsStringPool &StringPool,
2056     DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
2057     bool IsLittleEndian, unsigned Indent, bool Quiet) {
2058   /// Using a SmallString<0> because loadClangModule() is recursive.
2059   SmallString<0> Path(Options.PrependPath);
2060   if (sys::path::is_relative(Filename))
2061     resolveRelativeObjectPath(Path, CUDie);
2062   sys::path::append(Path, Filename);
2063   // Don't use the cached binary holder because we have no thread-safety
2064   // guarantee and the lifetime is limited.
2065 
2066   if (Options.ObjFileLoader == nullptr)
2067     return Error::success();
2068 
2069   auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
2070   if (!ErrOrObj)
2071     return Error::success();
2072 
2073   std::unique_ptr<CompileUnit> Unit;
2074 
2075   for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2076     updateDwarfVersion(CU->getVersion());
2077     // Recursively get all modules imported by this one.
2078     auto CUDie = CU->getUnitDIE(false);
2079     if (!CUDie)
2080       continue;
2081     if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts,
2082                                  ModulesEndOffset, UnitID, IsLittleEndian,
2083                                  Indent, Quiet)) {
2084       if (Unit) {
2085         std::string Err =
2086             (Filename +
2087              ": Clang modules are expected to have exactly 1 compile unit.\n")
2088                 .str();
2089         reportError(Err, File);
2090         return make_error<StringError>(Err, inconvertibleErrorCode());
2091       }
2092       // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2093       // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2094       // ASTFileSignatures will change randomly when a module is rebuilt.
2095       uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2096       if (PCMDwoId != DwoId) {
2097         if (!Quiet && Options.Verbose)
2098           reportWarning(
2099               Twine("hash mismatch: this object file was built against a "
2100                     "different version of the module ") +
2101                   Filename,
2102               File);
2103         // Update the cache entry with the DwoId of the module loaded from disk.
2104         ClangModules[Filename] = PCMDwoId;
2105       }
2106 
2107       // Add this module.
2108       Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2109                                            ModuleName);
2110       Unit->setHasInterestingContent();
2111       analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts,
2112                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2113                          [&](const Twine &Warning, const DWARFDie &DIE) {
2114                            reportWarning(Warning, File, &DIE);
2115                          });
2116       // Keep everything.
2117       Unit->markEverythingAsKept();
2118     }
2119   }
2120   assert(Unit && "CompileUnit is not set!");
2121   if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2122     return Error::success();
2123   if (!Quiet && Options.Verbose) {
2124     outs().indent(Indent);
2125     outs() << "cloning .debug_info from " << Filename << "\n";
2126   }
2127 
2128   UnitListTy CompileUnits;
2129   CompileUnits.push_back(std::move(Unit));
2130   assert(TheDwarfEmitter);
2131   DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
2132             Options.Update)
2133       .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
2134                             IsLittleEndian);
2135   return Error::success();
2136 }
2137 
2138 uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits(
2139     DWARFContext &DwarfContext, const DWARFFile &File,
2140     OffsetsStringPool &StringPool, bool IsLittleEndian) {
2141   uint64_t OutputDebugInfoSize =
2142       Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
2143   const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2144 
2145   for (auto &CurrentUnit : CompileUnits) {
2146     const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2147     const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2148     auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2149     CurrentUnit->setStartOffset(OutputDebugInfoSize);
2150     if (!InputDIE) {
2151       OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2152       continue;
2153     }
2154     if (CurrentUnit->getInfo(0).Keep) {
2155       // Clone the InputDIE into your Unit DIE in our compile unit since it
2156       // already has a DIE inside of it.
2157       CurrentUnit->createOutputDIE();
2158       cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
2159                UnitHeaderSize, 0, IsLittleEndian,
2160                CurrentUnit->getOutputUnitDIE());
2161     }
2162 
2163     OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2164 
2165     if (!Linker.Options.NoOutput) {
2166       assert(Emitter);
2167 
2168       if (LLVM_LIKELY(!Linker.Options.Update) ||
2169           Linker.needToTranslateStrings())
2170         Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
2171 
2172       Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2173 
2174       if (LLVM_UNLIKELY(Linker.Options.Update))
2175         continue;
2176 
2177       Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
2178       auto ProcessExpr = [&](StringRef Bytes,
2179                              SmallVectorImpl<uint8_t> &Buffer) {
2180         DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2181         DataExtractor Data(Bytes, IsLittleEndian,
2182                            OrigUnit.getAddressByteSize());
2183         cloneExpression(Data,
2184                         DWARFExpression(Data, OrigUnit.getAddressByteSize(),
2185                                         OrigUnit.getFormParams().Format),
2186                         File, *CurrentUnit, Buffer);
2187       };
2188       Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
2189     }
2190   }
2191 
2192   if (!Linker.Options.NoOutput) {
2193     assert(Emitter);
2194     // Emit all the compile unit's debug information.
2195     for (auto &CurrentUnit : CompileUnits) {
2196       if (LLVM_LIKELY(!Linker.Options.Update))
2197         Linker.generateUnitRanges(*CurrentUnit);
2198 
2199       CurrentUnit->fixupForwardReferences();
2200 
2201       if (!CurrentUnit->getOutputUnitDIE())
2202         continue;
2203 
2204       unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2205 
2206       assert(Emitter->getDebugInfoSectionSize() ==
2207              CurrentUnit->getStartOffset());
2208       Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
2209       Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
2210       assert(Emitter->getDebugInfoSectionSize() ==
2211              CurrentUnit->computeNextUnitOffset(DwarfVersion));
2212     }
2213   }
2214 
2215   return OutputDebugInfoSize - StartOutputDebugInfoSize;
2216 }
2217 
2218 void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
2219   if (Options.TheAccelTableKind != AccelTableKind::Default)
2220     return;
2221 
2222   auto &DwarfObj = Dwarf.getDWARFObj();
2223 
2224   if (!AtLeastOneDwarfAccelTable &&
2225       (!DwarfObj.getAppleNamesSection().Data.empty() ||
2226        !DwarfObj.getAppleTypesSection().Data.empty() ||
2227        !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2228        !DwarfObj.getAppleObjCSection().Data.empty())) {
2229     AtLeastOneAppleAccelTable = true;
2230   }
2231 
2232   if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
2233     AtLeastOneDwarfAccelTable = true;
2234   }
2235 }
2236 
2237 bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File,
2238                                          OffsetsStringPool &StringPool) {
2239 
2240   if (File.Warnings.empty())
2241     return false;
2242 
2243   DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2244   CUDie->setOffset(11);
2245   StringRef Producer;
2246   StringRef WarningHeader;
2247 
2248   switch (DwarfLinkerClientID) {
2249   case DwarfLinkerClient::Dsymutil:
2250     Producer = StringPool.internString("dsymutil");
2251     WarningHeader = "dsymutil_warning";
2252     break;
2253 
2254   default:
2255     Producer = StringPool.internString("dwarfopt");
2256     WarningHeader = "dwarfopt_warning";
2257     break;
2258   }
2259 
2260   StringRef FileName = StringPool.internString(File.FileName);
2261   CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2262                   DIEInteger(StringPool.getStringOffset(Producer)));
2263   DIEBlock *String = new (DIEAlloc) DIEBlock();
2264   DIEBlocks.push_back(String);
2265   for (auto &C : FileName)
2266     String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2267                      DIEInteger(C));
2268   String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2269                    DIEInteger(0));
2270 
2271   CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2272   for (const auto &Warning : File.Warnings) {
2273     DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2274     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2275                       DIEInteger(StringPool.getStringOffset(WarningHeader)));
2276     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2277                       DIEInteger(1));
2278     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2279                       DIEInteger(StringPool.getStringOffset(Warning)));
2280   }
2281   unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
2282                   File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
2283   DIEAbbrev Abbrev = CUDie->generateAbbrev();
2284   assignAbbrev(Abbrev);
2285   CUDie->setAbbrevNumber(Abbrev.getNumber());
2286   Size += getULEB128Size(Abbrev.getNumber());
2287   // Abbreviation ordering needed for classic compatibility.
2288   for (auto &Child : CUDie->children()) {
2289     Abbrev = Child.generateAbbrev();
2290     assignAbbrev(Abbrev);
2291     Child.setAbbrevNumber(Abbrev.getNumber());
2292     Size += getULEB128Size(Abbrev.getNumber());
2293   }
2294   CUDie->setSize(Size);
2295   TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
2296 
2297   return true;
2298 }
2299 
2300 void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
2301   if (!needToTranslateStrings())
2302     TheDwarfEmitter->emitSectionContents(
2303         Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
2304   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
2305                                        "debug_loc");
2306   TheDwarfEmitter->emitSectionContents(
2307       Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
2308   TheDwarfEmitter->emitSectionContents(
2309       Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
2310   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
2311                                        "debug_aranges");
2312 }
2313 
2314 void DWARFLinker::addObjectFile(DWARFFile &File) {
2315   ObjectContexts.emplace_back(LinkContext(File));
2316 
2317   if (ObjectContexts.back().File.Dwarf)
2318     updateAccelKind(*ObjectContexts.back().File.Dwarf);
2319 }
2320 
2321 bool DWARFLinker::link() {
2322   assert(Options.NoOutput || TheDwarfEmitter);
2323 
2324   // A unique ID that identifies each compile unit.
2325   unsigned UnitID = 0;
2326 
2327   // First populate the data structure we need for each iteration of the
2328   // parallel loop.
2329   unsigned NumObjects = ObjectContexts.size();
2330 
2331   // This Dwarf string pool which is used for emission. It must be used
2332   // serially as the order of calling getStringOffset matters for
2333   // reproducibility.
2334   OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
2335 
2336   // ODR Contexts for the optimize.
2337   DeclContextTree ODRContexts;
2338 
2339   // If we haven't decided on an accelerator table kind yet, we base ourselves
2340   // on the DWARF we have seen so far. At this point we haven't pulled in debug
2341   // information from modules yet, so it is technically possible that they
2342   // would affect the decision. However, as they're built with the same
2343   // compiler and flags, it is safe to assume that they will follow the
2344   // decision made here.
2345   if (Options.TheAccelTableKind == AccelTableKind::Default) {
2346     if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2347       Options.TheAccelTableKind = AccelTableKind::Dwarf;
2348     else
2349       Options.TheAccelTableKind = AccelTableKind::Apple;
2350   }
2351 
2352   for (LinkContext &OptContext : ObjectContexts) {
2353     if (Options.Verbose) {
2354       if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
2355         outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
2356       else
2357         outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
2358     }
2359 
2360     if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
2361       continue;
2362 
2363     if (!OptContext.File.Dwarf)
2364       continue;
2365     // Look for relocations that correspond to address map entries.
2366 
2367     // there was findvalidrelocations previously ... probably we need to gather
2368     // info here
2369     if (LLVM_LIKELY(!Options.Update) &&
2370         !OptContext.File.Addresses->hasValidRelocs()) {
2371       if (Options.Verbose)
2372         outs() << "No valid relocations found. Skipping.\n";
2373 
2374       // Set "Skip" flag as a signal to other loops that we should not
2375       // process this iteration.
2376       OptContext.Skip = true;
2377       continue;
2378     }
2379 
2380     // Setup access to the debug info.
2381     if (!OptContext.File.Dwarf)
2382       continue;
2383 
2384     // In a first phase, just read in the debug info and load all clang modules.
2385     OptContext.CompileUnits.reserve(
2386         OptContext.File.Dwarf->getNumCompileUnits());
2387 
2388     for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
2389       updateDwarfVersion(CU->getVersion());
2390       auto CUDie = CU->getUnitDIE(false);
2391       if (Options.Verbose) {
2392         outs() << "Input compilation unit:";
2393         DIDumpOptions DumpOpts;
2394         DumpOpts.ChildRecurseDepth = 0;
2395         DumpOpts.Verbose = Options.Verbose;
2396         CUDie.dump(outs(), 0, DumpOpts);
2397       }
2398       if (CUDie && !LLVM_UNLIKELY(Options.Update))
2399         registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
2400                                 ODRContexts, 0, UnitID,
2401                                 OptContext.File.Dwarf->isLittleEndian());
2402     }
2403   }
2404 
2405   // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2406   if (MaxDwarfVersion == 0)
2407     MaxDwarfVersion = 3;
2408 
2409   // At this point we know how much data we have emitted. We use this value to
2410   // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2411   // is already emitted, without being affected by canonical die offsets set
2412   // later. This prevents undeterminism when analyze and clone execute
2413   // concurrently, as clone set the canonical DIE offset and analyze reads it.
2414   const uint64_t ModulesEndOffset =
2415       Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
2416 
2417   // These variables manage the list of processed object files.
2418   // The mutex and condition variable are to ensure that this is thread safe.
2419   std::mutex ProcessedFilesMutex;
2420   std::condition_variable ProcessedFilesConditionVariable;
2421   BitVector ProcessedFiles(NumObjects, false);
2422 
2423   //  Analyzing the context info is particularly expensive so it is executed in
2424   //  parallel with emitting the previous compile unit.
2425   auto AnalyzeLambda = [&](size_t I) {
2426     auto &Context = ObjectContexts[I];
2427 
2428     if (Context.Skip || !Context.File.Dwarf)
2429       return;
2430 
2431     for (const auto &CU : Context.File.Dwarf->compile_units()) {
2432       updateDwarfVersion(CU->getVersion());
2433       // The !registerModuleReference() condition effectively skips
2434       // over fully resolved skeleton units. This second pass of
2435       // registerModuleReferences doesn't do any new work, but it
2436       // will collect top-level errors, which are suppressed. Module
2437       // warnings were already displayed in the first iteration.
2438       bool Quiet = true;
2439       auto CUDie = CU->getUnitDIE(false);
2440       if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
2441           !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
2442                                    ODRContexts, ModulesEndOffset, UnitID,
2443                                    Quiet)) {
2444         Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
2445             *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2446       }
2447     }
2448 
2449     // Now build the DIE parent links that we will use during the next phase.
2450     for (auto &CurrentUnit : Context.CompileUnits) {
2451       auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2452       if (!CUDie)
2453         continue;
2454       analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2455                          *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
2456                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2457                          [&](const Twine &Warning, const DWARFDie &DIE) {
2458                            reportWarning(Warning, Context.File, &DIE);
2459                          });
2460     }
2461   };
2462 
2463   // For each object file map how many bytes were emitted.
2464   StringMap<DebugInfoSize> SizeByObject;
2465 
2466   // And then the remaining work in serial again.
2467   // Note, although this loop runs in serial, it can run in parallel with
2468   // the analyzeContextInfo loop so long as we process files with indices >=
2469   // than those processed by analyzeContextInfo.
2470   auto CloneLambda = [&](size_t I) {
2471     auto &OptContext = ObjectContexts[I];
2472     if (OptContext.Skip || !OptContext.File.Dwarf)
2473       return;
2474 
2475     // Then mark all the DIEs that need to be present in the generated output
2476     // and collect some information about them.
2477     // Note that this loop can not be merged with the previous one because
2478     // cross-cu references require the ParentIdx to be setup for every CU in
2479     // the object file before calling this.
2480     if (LLVM_UNLIKELY(Options.Update)) {
2481       for (auto &CurrentUnit : OptContext.CompileUnits)
2482         CurrentUnit->markEverythingAsKept();
2483       copyInvariantDebugSection(*OptContext.File.Dwarf);
2484     } else {
2485       for (auto &CurrentUnit : OptContext.CompileUnits)
2486         lookForDIEsToKeep(*OptContext.File.Addresses,
2487                           OptContext.File.Addresses->getValidAddressRanges(),
2488                           OptContext.CompileUnits,
2489                           CurrentUnit->getOrigUnit().getUnitDIE(),
2490                           OptContext.File, *CurrentUnit, 0);
2491     }
2492 
2493     // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2494     // array again (in the same way findValidRelocsInDebugInfo() did). We
2495     // need to reset the NextValidReloc index to the beginning.
2496     if (OptContext.File.Addresses->hasValidRelocs() ||
2497         LLVM_UNLIKELY(Options.Update)) {
2498       SizeByObject[OptContext.File.FileName].Input =
2499           getDebugInfoSize(*OptContext.File.Dwarf);
2500       SizeByObject[OptContext.File.FileName].Output =
2501           DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
2502                     OptContext.CompileUnits, Options.Update)
2503               .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
2504                                     OffsetsStringPool,
2505                                     OptContext.File.Dwarf->isLittleEndian());
2506     }
2507     if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
2508         LLVM_LIKELY(!Options.Update))
2509       patchFrameInfoForObject(
2510           OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
2511           *OptContext.File.Dwarf,
2512           OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2513 
2514     // Clean-up before starting working on the next object.
2515     cleanupAuxiliarryData(OptContext);
2516   };
2517 
2518   auto EmitLambda = [&]() {
2519     // Emit everything that's global.
2520     if (!Options.NoOutput) {
2521       TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2522       TheDwarfEmitter->emitStrings(OffsetsStringPool);
2523       switch (Options.TheAccelTableKind) {
2524       case AccelTableKind::Apple:
2525         TheDwarfEmitter->emitAppleNames(AppleNames);
2526         TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
2527         TheDwarfEmitter->emitAppleTypes(AppleTypes);
2528         TheDwarfEmitter->emitAppleObjc(AppleObjc);
2529         break;
2530       case AccelTableKind::Dwarf:
2531         TheDwarfEmitter->emitDebugNames(DebugNames);
2532         break;
2533       case AccelTableKind::Pub:
2534         // Already emitted by emitPubAcceleratorEntriesForUnit.
2535         break;
2536       case AccelTableKind::Default:
2537         llvm_unreachable("Default should have already been resolved.");
2538         break;
2539       }
2540     }
2541   };
2542 
2543   auto AnalyzeAll = [&]() {
2544     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2545       AnalyzeLambda(I);
2546 
2547       std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2548       ProcessedFiles.set(I);
2549       ProcessedFilesConditionVariable.notify_one();
2550     }
2551   };
2552 
2553   auto CloneAll = [&]() {
2554     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2555       {
2556         std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2557         if (!ProcessedFiles[I]) {
2558           ProcessedFilesConditionVariable.wait(
2559               LockGuard, [&]() { return ProcessedFiles[I]; });
2560         }
2561       }
2562 
2563       CloneLambda(I);
2564     }
2565     EmitLambda();
2566   };
2567 
2568   // To limit memory usage in the single threaded case, analyze and clone are
2569   // run sequentially so the OptContext is freed after processing each object
2570   // in endDebugObject.
2571   if (Options.Threads == 1) {
2572     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2573       AnalyzeLambda(I);
2574       CloneLambda(I);
2575     }
2576     EmitLambda();
2577   } else {
2578     ThreadPool Pool(hardware_concurrency(2));
2579     Pool.async(AnalyzeAll);
2580     Pool.async(CloneAll);
2581     Pool.wait();
2582   }
2583 
2584   if (Options.Statistics) {
2585     // Create a vector sorted in descending order by output size.
2586     std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
2587     for (auto &E : SizeByObject)
2588       Sorted.emplace_back(E.first(), E.second);
2589     llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
2590       return LHS.second.Output > RHS.second.Output;
2591     });
2592 
2593     auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
2594       const float Difference = Output - Input;
2595       const float Sum = Input + Output;
2596       if (Sum == 0)
2597         return 0;
2598       return (Difference / (Sum / 2));
2599     };
2600 
2601     int64_t InputTotal = 0;
2602     int64_t OutputTotal = 0;
2603     const char *FormatStr = "{0,-45} {1,10}b  {2,10}b {3,8:P}\n";
2604 
2605     // Print header.
2606     outs() << ".debug_info section size (in bytes)\n";
2607     outs() << "----------------------------------------------------------------"
2608               "---------------\n";
2609     outs() << "Filename                                           Object       "
2610               "  dSYM   Change\n";
2611     outs() << "----------------------------------------------------------------"
2612               "---------------\n";
2613 
2614     // Print body.
2615     for (auto &E : Sorted) {
2616       InputTotal += E.second.Input;
2617       OutputTotal += E.second.Output;
2618       llvm::outs() << formatv(
2619           FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
2620           E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
2621     }
2622     // Print total and footer.
2623     outs() << "----------------------------------------------------------------"
2624               "---------------\n";
2625     llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
2626                             ComputePercentange(InputTotal, OutputTotal));
2627     outs() << "----------------------------------------------------------------"
2628               "---------------\n\n";
2629   }
2630 
2631   return true;
2632 }
2633 
2634 } // namespace llvm
2635