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   if (Optional<DWARFFormValue> Val = DIE.find(dwarf::DW_AT_name))
227     if (Optional<const char *> Name = Val->getAsCString()) {
228       auto &Entry = (*ParseableSwiftInterfaces)[*Name];
229       // The prepend path is applied later when copying.
230       DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
231       SmallString<128> ResolvedPath;
232       if (sys::path::is_relative(Path))
233         resolveRelativeObjectPath(ResolvedPath, CUDie);
234       sys::path::append(ResolvedPath, Path);
235       if (!Entry.empty() && Entry != ResolvedPath)
236         ReportWarning(
237             Twine("Conflicting parseable interfaces for Swift Module ") +
238                 *Name + ": " + Entry + " and " + Path,
239             DIE);
240       Entry = std::string(ResolvedPath.str());
241     }
242 }
243 
244 /// The distinct types of work performed by the work loop in
245 /// analyzeContextInfo.
246 enum class ContextWorklistItemType : uint8_t {
247   AnalyzeContextInfo,
248   UpdateChildPruning,
249   UpdatePruning,
250 };
251 
252 /// This class represents an item in the work list. The type defines what kind
253 /// of work needs to be performed when processing the current item. Everything
254 /// but the Type and Die fields are optional based on the type.
255 struct ContextWorklistItem {
256   DWARFDie Die;
257   unsigned ParentIdx;
258   union {
259     CompileUnit::DIEInfo *OtherInfo;
260     DeclContext *Context;
261   };
262   ContextWorklistItemType Type;
263   bool InImportedModule;
264 
265   ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
266                       CompileUnit::DIEInfo *OtherInfo = nullptr)
267       : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
268         InImportedModule(false) {}
269 
270   ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
271                       bool InImportedModule)
272       : Die(Die), ParentIdx(ParentIdx), Context(Context),
273         Type(ContextWorklistItemType::AnalyzeContextInfo),
274         InImportedModule(InImportedModule) {}
275 };
276 
277 static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
278                           uint64_t ModulesEndOffset) {
279   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
280 
281   // Prune this DIE if it is either a forward declaration inside a
282   // DW_TAG_module or a DW_TAG_module that contains nothing but
283   // forward declarations.
284   Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
285                 (isTypeTag(Die.getTag()) &&
286                  dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
287 
288   // Only prune forward declarations inside a DW_TAG_module for which a
289   // definition exists elsewhere.
290   if (ModulesEndOffset == 0)
291     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
292   else
293     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
294                   Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
295 
296   return Info.Prune;
297 }
298 
299 static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
300                                CompileUnit::DIEInfo &ChildInfo) {
301   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
302   Info.Prune &= ChildInfo.Prune;
303 }
304 
305 /// Recursive helper to build the global DeclContext information and
306 /// gather the child->parent relationships in the original compile unit.
307 ///
308 /// This function uses the same work list approach as lookForDIEsToKeep.
309 ///
310 /// \return true when this DIE and all of its children are only
311 /// forward declarations to types defined in external clang modules
312 /// (i.e., forward declarations that are children of a DW_TAG_module).
313 static bool analyzeContextInfo(
314     const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
315     DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
316     uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
317     std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
318     bool InImportedModule = false) {
319   // LIFO work list.
320   std::vector<ContextWorklistItem> Worklist;
321   Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
322 
323   while (!Worklist.empty()) {
324     ContextWorklistItem Current = Worklist.back();
325     Worklist.pop_back();
326 
327     switch (Current.Type) {
328     case ContextWorklistItemType::UpdatePruning:
329       updatePruning(Current.Die, CU, ModulesEndOffset);
330       continue;
331     case ContextWorklistItemType::UpdateChildPruning:
332       updateChildPruning(Current.Die, CU, *Current.OtherInfo);
333       continue;
334     case ContextWorklistItemType::AnalyzeContextInfo:
335       break;
336     }
337 
338     unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
339     CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
340 
341     // Clang imposes an ODR on modules(!) regardless of the language:
342     //  "The module-id should consist of only a single identifier,
343     //   which provides the name of the module being defined. Each
344     //   module shall have a single definition."
345     //
346     // This does not extend to the types inside the modules:
347     //  "[I]n C, this implies that if two structs are defined in
348     //   different submodules with the same name, those two types are
349     //   distinct types (but may be compatible types if their
350     //   definitions match)."
351     //
352     // We treat non-C++ modules like namespaces for this reason.
353     if (Current.Die.getTag() == dwarf::DW_TAG_module &&
354         Current.ParentIdx == 0 &&
355         dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
356             CU.getClangModuleName()) {
357       Current.InImportedModule = true;
358       analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
359                             ReportWarning);
360     }
361 
362     Info.ParentIdx = Current.ParentIdx;
363     bool InClangModule = CU.isClangModule() || Current.InImportedModule;
364     if (CU.hasODR() || InClangModule) {
365       if (Current.Context) {
366         auto PtrInvalidPair = Contexts.getChildDeclContext(
367             *Current.Context, Current.Die, CU, InClangModule);
368         Current.Context = PtrInvalidPair.getPointer();
369         Info.Ctxt =
370             PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
371         if (Info.Ctxt)
372           Info.Ctxt->setDefinedInClangModule(InClangModule);
373       } else
374         Info.Ctxt = Current.Context = nullptr;
375     }
376 
377     Info.Prune = Current.InImportedModule;
378     // Add children in reverse order to the worklist to effectively process
379     // them in order.
380     Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
381     for (auto Child : reverse(Current.Die.children())) {
382       CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
383       Worklist.emplace_back(
384           Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
385       Worklist.emplace_back(Child, Current.Context, Idx,
386                             Current.InImportedModule);
387     }
388   }
389 
390   return CU.getInfo(DIE).Prune;
391 }
392 
393 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
394   switch (Tag) {
395   default:
396     return false;
397   case dwarf::DW_TAG_class_type:
398   case dwarf::DW_TAG_common_block:
399   case dwarf::DW_TAG_lexical_block:
400   case dwarf::DW_TAG_structure_type:
401   case dwarf::DW_TAG_subprogram:
402   case dwarf::DW_TAG_subroutine_type:
403   case dwarf::DW_TAG_union_type:
404     return true;
405   }
406   llvm_unreachable("Invalid Tag");
407 }
408 
409 void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
410   Context.clear();
411 
412   for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
413     (*I)->~DIEBlock();
414   for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
415     (*I)->~DIELoc();
416 
417   DIEBlocks.clear();
418   DIELocs.clear();
419   DIEAlloc.Reset();
420 }
421 
422 /// Check if a variable describing DIE should be kept.
423 /// \returns updated TraversalFlags.
424 unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
425                                             const DWARFDie &DIE,
426                                             CompileUnit::DIEInfo &MyInfo,
427                                             unsigned Flags) {
428   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
429 
430   // Global variables with constant value can always be kept.
431   if (!(Flags & TF_InFunctionScope) &&
432       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
433     MyInfo.InDebugMap = true;
434     return Flags | TF_Keep;
435   }
436 
437   // See if there is a relocation to a valid debug map entry inside
438   // this variable's location. The order is important here. We want to
439   // always check if the variable has a valid relocation, so that the
440   // DIEInfo is filled. However, we don't want a static variable in a
441   // function to force us to keep the enclosing function.
442   if (!RelocMgr.hasLiveMemoryLocation(DIE, MyInfo) ||
443       (Flags & TF_InFunctionScope))
444     return Flags;
445 
446   if (Options.Verbose) {
447     outs() << "Keeping variable DIE:";
448     DIDumpOptions DumpOpts;
449     DumpOpts.ChildRecurseDepth = 0;
450     DumpOpts.Verbose = Options.Verbose;
451     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
452   }
453 
454   return Flags | TF_Keep;
455 }
456 
457 /// Check if a function describing DIE should be kept.
458 /// \returns updated TraversalFlags.
459 unsigned DWARFLinker::shouldKeepSubprogramDIE(
460     AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
461     const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
462     unsigned Flags) {
463   Flags |= TF_InFunctionScope;
464 
465   auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
466   if (!LowPc)
467     return Flags;
468 
469   assert(LowPc.hasValue() && "low_pc attribute is not an address.");
470   if (!RelocMgr.hasLiveAddressRange(DIE, MyInfo))
471     return Flags;
472 
473   if (Options.Verbose) {
474     outs() << "Keeping subprogram DIE:";
475     DIDumpOptions DumpOpts;
476     DumpOpts.ChildRecurseDepth = 0;
477     DumpOpts.Verbose = Options.Verbose;
478     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
479   }
480 
481   if (DIE.getTag() == dwarf::DW_TAG_label) {
482     if (Unit.hasLabelAt(*LowPc))
483       return Flags;
484 
485     DWARFUnit &OrigUnit = Unit.getOrigUnit();
486     // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
487     // that don't fall into the CU's aranges. This is wrong IMO. Debug info
488     // generation bugs aside, this is really wrong in the case of labels, where
489     // a label marking the end of a function will have a PC == CU's high_pc.
490     if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
491             .getValueOr(UINT64_MAX) <= LowPc)
492       return Flags;
493     Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
494     return Flags | TF_Keep;
495   }
496 
497   Flags |= TF_Keep;
498 
499   Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
500   if (!HighPc) {
501     reportWarning("Function without high_pc. Range will be discarded.\n", File,
502                   &DIE);
503     return Flags;
504   }
505 
506   // Replace the debug map range with a more accurate one.
507   Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
508   Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
509   return Flags;
510 }
511 
512 /// Check if a DIE should be kept.
513 /// \returns updated TraversalFlags.
514 unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
515                                     const DWARFDie &DIE, const DWARFFile &File,
516                                     CompileUnit &Unit,
517                                     CompileUnit::DIEInfo &MyInfo,
518                                     unsigned Flags) {
519   switch (DIE.getTag()) {
520   case dwarf::DW_TAG_constant:
521   case dwarf::DW_TAG_variable:
522     return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
523   case dwarf::DW_TAG_subprogram:
524   case dwarf::DW_TAG_label:
525     return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
526                                    Flags);
527   case dwarf::DW_TAG_base_type:
528     // DWARF Expressions may reference basic types, but scanning them
529     // is expensive. Basic types are tiny, so just keep all of them.
530   case dwarf::DW_TAG_imported_module:
531   case dwarf::DW_TAG_imported_declaration:
532   case dwarf::DW_TAG_imported_unit:
533     // We always want to keep these.
534     return Flags | TF_Keep;
535   default:
536     break;
537   }
538 
539   return Flags;
540 }
541 
542 /// Helper that updates the completeness of the current DIE based on the
543 /// completeness of one of its children. It depends on the incompleteness of
544 /// the children already being computed.
545 static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
546                                       CompileUnit::DIEInfo &ChildInfo) {
547   switch (Die.getTag()) {
548   case dwarf::DW_TAG_structure_type:
549   case dwarf::DW_TAG_class_type:
550     break;
551   default:
552     return;
553   }
554 
555   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
556 
557   if (ChildInfo.Incomplete || ChildInfo.Prune)
558     MyInfo.Incomplete = true;
559 }
560 
561 /// Helper that updates the completeness of the current DIE based on the
562 /// completeness of the DIEs it references. It depends on the incompleteness of
563 /// the referenced DIE already being computed.
564 static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
565                                     CompileUnit::DIEInfo &RefInfo) {
566   switch (Die.getTag()) {
567   case dwarf::DW_TAG_typedef:
568   case dwarf::DW_TAG_member:
569   case dwarf::DW_TAG_reference_type:
570   case dwarf::DW_TAG_ptr_to_member_type:
571   case dwarf::DW_TAG_pointer_type:
572     break;
573   default:
574     return;
575   }
576 
577   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
578 
579   if (MyInfo.Incomplete)
580     return;
581 
582   if (RefInfo.Incomplete)
583     MyInfo.Incomplete = true;
584 }
585 
586 /// Look at the children of the given DIE and decide whether they should be
587 /// kept.
588 void DWARFLinker::lookForChildDIEsToKeep(
589     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
590     SmallVectorImpl<WorklistItem> &Worklist) {
591   // The TF_ParentWalk flag tells us that we are currently walking up the
592   // parent chain of a required DIE, and we don't want to mark all the children
593   // of the parents as kept (consider for example a DW_TAG_namespace node in
594   // the parent chain). There are however a set of DIE types for which we want
595   // to ignore that directive and still walk their children.
596   if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
597     Flags &= ~DWARFLinker::TF_ParentWalk;
598 
599   // We're finished if this DIE has no children or we're walking the parent
600   // chain.
601   if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
602     return;
603 
604   // Add children in reverse order to the worklist to effectively process them
605   // in order.
606   for (auto Child : reverse(Die.children())) {
607     // Add a worklist item before every child to calculate incompleteness right
608     // after the current child is processed.
609     CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
610     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
611                           &ChildInfo);
612     Worklist.emplace_back(Child, CU, Flags);
613   }
614 }
615 
616 /// Look at DIEs referenced by the given DIE and decide whether they should be
617 /// kept. All DIEs referenced though attributes should be kept.
618 void DWARFLinker::lookForRefDIEsToKeep(
619     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
620     const UnitListTy &Units, const DWARFFile &File,
621     SmallVectorImpl<WorklistItem> &Worklist) {
622   bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
623                     ? (Flags & DWARFLinker::TF_ODR)
624                     : CU.hasODR();
625   DWARFUnit &Unit = CU.getOrigUnit();
626   DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
627   const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
628   uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
629 
630   SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
631   for (const auto &AttrSpec : Abbrev->attributes()) {
632     DWARFFormValue Val(AttrSpec.Form);
633     if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
634         AttrSpec.Attr == dwarf::DW_AT_sibling) {
635       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
636                                 Unit.getFormParams());
637       continue;
638     }
639 
640     Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
641     CompileUnit *ReferencedCU;
642     if (auto RefDie =
643             resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
644       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
645       bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
646                          Info.Ctxt->isDefinedInClangModule();
647       // If the referenced DIE has a DeclContext that has already been
648       // emitted, then do not keep the one in this CU. We'll link to
649       // the canonical DIE in cloneDieReferenceAttribute.
650       //
651       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
652       // be necessary and could be advantageously replaced by
653       // ReferencedCU->hasODR() && CU.hasODR().
654       //
655       // FIXME: compatibility with dsymutil-classic. There is no
656       // reason not to unique ref_addr references.
657       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) &&
658           Info.Ctxt &&
659           Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
660           Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
661         continue;
662 
663       // Keep a module forward declaration if there is no definition.
664       if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
665             Info.Ctxt->getCanonicalDIEOffset()))
666         Info.Prune = false;
667       ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
668     }
669   }
670 
671   unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
672 
673   // Add referenced DIEs in reverse order to the worklist to effectively
674   // process them in order.
675   for (auto &P : reverse(ReferencedDIEs)) {
676     // Add a worklist item before every child to calculate incompleteness right
677     // after the current child is processed.
678     CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
679     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
680                           &Info);
681     Worklist.emplace_back(P.first, P.second,
682                           DWARFLinker::TF_Keep |
683                               DWARFLinker::TF_DependencyWalk | ODRFlag);
684   }
685 }
686 
687 /// Look at the parent of the given DIE and decide whether they should be kept.
688 void DWARFLinker::lookForParentDIEsToKeep(
689     unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
690     SmallVectorImpl<WorklistItem> &Worklist) {
691   // Stop if we encounter an ancestor that's already marked as kept.
692   if (CU.getInfo(AncestorIdx).Keep)
693     return;
694 
695   DWARFUnit &Unit = CU.getOrigUnit();
696   DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
697   Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
698   Worklist.emplace_back(ParentDIE, CU, Flags);
699 }
700 
701 /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
702 /// information in \p CU's DIEInfo.
703 ///
704 /// This function is the entry point of the DIE selection algorithm. It is
705 /// expected to walk the DIE tree in file order and (though the mediation of
706 /// its helper) call hasValidRelocation() on each DIE that might be a 'root
707 /// DIE' (See DwarfLinker class comment).
708 ///
709 /// While walking the dependencies of root DIEs, this function is also called,
710 /// but during these dependency walks the file order is not respected. The
711 /// TF_DependencyWalk flag tells us which kind of traversal we are currently
712 /// doing.
713 ///
714 /// The recursive algorithm is implemented iteratively as a work list because
715 /// very deep recursion could exhaust the stack for large projects. The work
716 /// list acts as a scheduler for different types of work that need to be
717 /// performed.
718 ///
719 /// The recursive nature of the algorithm is simulated by running the "main"
720 /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
721 /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
722 /// fixing up a computed property (UpdateChildIncompleteness,
723 /// UpdateRefIncompleteness).
724 ///
725 /// The return value indicates whether the DIE is incomplete.
726 void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
727                                     RangesTy &Ranges, const UnitListTy &Units,
728                                     const DWARFDie &Die, const DWARFFile &File,
729                                     CompileUnit &Cu, unsigned Flags) {
730   // LIFO work list.
731   SmallVector<WorklistItem, 4> Worklist;
732   Worklist.emplace_back(Die, Cu, Flags);
733 
734   while (!Worklist.empty()) {
735     WorklistItem Current = Worklist.pop_back_val();
736 
737     // Look at the worklist type to decide what kind of work to perform.
738     switch (Current.Type) {
739     case WorklistItemType::UpdateChildIncompleteness:
740       updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
741       continue;
742     case WorklistItemType::UpdateRefIncompleteness:
743       updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
744       continue;
745     case WorklistItemType::LookForChildDIEsToKeep:
746       lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
747       continue;
748     case WorklistItemType::LookForRefDIEsToKeep:
749       lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
750                            Worklist);
751       continue;
752     case WorklistItemType::LookForParentDIEsToKeep:
753       lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
754                               Worklist);
755       continue;
756     case WorklistItemType::LookForDIEsToKeep:
757       break;
758     }
759 
760     unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
761     CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
762 
763     if (MyInfo.Prune)
764       continue;
765 
766     // If the Keep flag is set, we are marking a required DIE's dependencies.
767     // If our target is already marked as kept, we're all set.
768     bool AlreadyKept = MyInfo.Keep;
769     if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
770       continue;
771 
772     // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
773     // because it would screw up the relocation finding logic.
774     if (!(Current.Flags & TF_DependencyWalk))
775       Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
776                                     Current.CU, MyInfo, Current.Flags);
777 
778     // Finish by looking for child DIEs. Because of the LIFO worklist we need
779     // to schedule that work before any subsequent items are added to the
780     // worklist.
781     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
782                           WorklistItemType::LookForChildDIEsToKeep);
783 
784     if (AlreadyKept || !(Current.Flags & TF_Keep))
785       continue;
786 
787     // If it is a newly kept DIE mark it as well as all its dependencies as
788     // kept.
789     MyInfo.Keep = true;
790 
791     // We're looking for incomplete types.
792     MyInfo.Incomplete =
793         Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
794         Current.Die.getTag() != dwarf::DW_TAG_member &&
795         dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
796 
797     // After looking at the parent chain, look for referenced DIEs. Because of
798     // the LIFO worklist we need to schedule that work before any subsequent
799     // items are added to the worklist.
800     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
801                           WorklistItemType::LookForRefDIEsToKeep);
802 
803     bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
804                                                       : Current.CU.hasODR();
805     unsigned ODRFlag = UseOdr ? TF_ODR : 0;
806     unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
807 
808     // Now schedule the parent walk.
809     Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
810   }
811 }
812 
813 /// Assign an abbreviation number to \p Abbrev.
814 ///
815 /// Our DIEs get freed after every DebugMapObject has been processed,
816 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
817 /// the instances hold by the DIEs. When we encounter an abbreviation
818 /// that we don't know, we create a permanent copy of it.
819 void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
820   // Check the set for priors.
821   FoldingSetNodeID ID;
822   Abbrev.Profile(ID);
823   void *InsertToken;
824   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
825 
826   // If it's newly added.
827   if (InSet) {
828     // Assign existing abbreviation number.
829     Abbrev.setNumber(InSet->getNumber());
830   } else {
831     // Add to abbreviation list.
832     Abbreviations.push_back(
833         std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
834     for (const auto &Attr : Abbrev.getData())
835       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
836     AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
837     // Assign the unique abbreviation number.
838     Abbrev.setNumber(Abbreviations.size());
839     Abbreviations.back()->setNumber(Abbreviations.size());
840   }
841 }
842 
843 unsigned DWARFLinker::DIECloner::cloneStringAttribute(
844     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
845     const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
846   Optional<const char *> String = Val.getAsCString();
847   if (!String)
848     return 0;
849 
850   // Switch everything to out of line strings.
851   auto StringEntry = StringPool.getEntry(*String);
852 
853   // Update attributes info.
854   if (AttrSpec.Attr == dwarf::DW_AT_name)
855     Info.Name = StringEntry;
856   else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
857            AttrSpec.Attr == dwarf::DW_AT_linkage_name)
858     Info.MangledName = StringEntry;
859 
860   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
861                DIEInteger(StringEntry.getOffset()));
862 
863   return 4;
864 }
865 
866 unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
867     DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
868     unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
869     CompileUnit &Unit) {
870   const DWARFUnit &U = Unit.getOrigUnit();
871   uint64_t Ref = *Val.getAsReference();
872 
873   DIE *NewRefDie = nullptr;
874   CompileUnit *RefUnit = nullptr;
875   DeclContext *Ctxt = nullptr;
876 
877   DWARFDie RefDie =
878       Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
879 
880   // If the referenced DIE is not found,  drop the attribute.
881   if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
882     return 0;
883 
884   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
885 
886   // If we already have emitted an equivalent DeclContext, just point
887   // at it.
888   if (isODRAttribute(AttrSpec.Attr)) {
889     Ctxt = RefInfo.Ctxt;
890     if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
891       DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
892       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
893                    dwarf::DW_FORM_ref_addr, Attr);
894       return U.getRefAddrByteSize();
895     }
896   }
897 
898   if (!RefInfo.Clone) {
899     assert(Ref > InputDIE.getOffset());
900     // We haven't cloned this DIE yet. Just create an empty one and
901     // store it. It'll get really cloned when we process it.
902     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
903   }
904   NewRefDie = RefInfo.Clone;
905 
906   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
907       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
908     // We cannot currently rely on a DIEEntry to emit ref_addr
909     // references, because the implementation calls back to DwarfDebug
910     // to find the unit offset. (We don't have a DwarfDebug)
911     // FIXME: we should be able to design DIEEntry reliance on
912     // DwarfDebug away.
913     uint64_t Attr;
914     if (Ref < InputDIE.getOffset()) {
915       // We must have already cloned that DIE.
916       uint32_t NewRefOffset =
917           RefUnit->getStartOffset() + NewRefDie->getOffset();
918       Attr = NewRefOffset;
919       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
920                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
921     } else {
922       // A forward reference. Note and fixup later.
923       Attr = 0xBADDEF;
924       Unit.noteForwardReference(
925           NewRefDie, RefUnit, Ctxt,
926           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
927                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
928     }
929     return U.getRefAddrByteSize();
930   }
931 
932   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
933                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
934 
935   return AttrSize;
936 }
937 
938 void DWARFLinker::DIECloner::cloneExpression(
939     DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
940     CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
941   using Encoding = DWARFExpression::Operation::Encoding;
942 
943   uint64_t OpOffset = 0;
944   for (auto &Op : Expression) {
945     auto Description = Op.getDescription();
946     // DW_OP_const_type is variable-length and has 3
947     // operands. DWARFExpression thus far only supports 2.
948     auto Op0 = Description.Op[0];
949     auto Op1 = Description.Op[1];
950     if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
951         (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
952       Linker.reportWarning("Unsupported DW_OP encoding.", File);
953 
954     if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
955         (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
956       // This code assumes that the other non-typeref operand fits into 1 byte.
957       assert(OpOffset < Op.getEndOffset());
958       uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
959       assert(ULEBsize <= 16);
960 
961       // Copy over the operation.
962       OutputBuffer.push_back(Op.getCode());
963       uint64_t RefOffset;
964       if (Op1 == Encoding::SizeNA) {
965         RefOffset = Op.getRawOperand(0);
966       } else {
967         OutputBuffer.push_back(Op.getRawOperand(0));
968         RefOffset = Op.getRawOperand(1);
969       }
970       uint32_t Offset = 0;
971       // Look up the base type. For DW_OP_convert, the operand may be 0 to
972       // instead indicate the generic type. The same holds for
973       // DW_OP_reinterpret, which is currently not supported.
974       if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
975         auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
976         CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
977         if (DIE *Clone = Info.Clone)
978           Offset = Clone->getOffset();
979         else
980           Linker.reportWarning(
981               "base type ref doesn't point to DW_TAG_base_type.", File);
982       }
983       uint8_t ULEB[16];
984       unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
985       if (RealSize > ULEBsize) {
986         // Emit the generic type as a fallback.
987         RealSize = encodeULEB128(0, ULEB, ULEBsize);
988         Linker.reportWarning("base type ref doesn't fit.", File);
989       }
990       assert(RealSize == ULEBsize && "padding failed");
991       ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
992       OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
993     } else {
994       // Copy over everything else unmodified.
995       StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
996       OutputBuffer.append(Bytes.begin(), Bytes.end());
997     }
998     OpOffset = Op.getEndOffset();
999   }
1000 }
1001 
1002 unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1003     DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
1004     const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
1005   DIEValueList *Attr;
1006   DIEValue Value;
1007   DIELoc *Loc = nullptr;
1008   DIEBlock *Block = nullptr;
1009   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1010     Loc = new (DIEAlloc) DIELoc;
1011     Linker.DIELocs.push_back(Loc);
1012   } else {
1013     Block = new (DIEAlloc) DIEBlock;
1014     Linker.DIEBlocks.push_back(Block);
1015   }
1016   Attr = Loc ? static_cast<DIEValueList *>(Loc)
1017              : static_cast<DIEValueList *>(Block);
1018 
1019   if (Loc)
1020     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1021                      dwarf::Form(AttrSpec.Form), Loc);
1022   else
1023     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1024                      dwarf::Form(AttrSpec.Form), Block);
1025 
1026   // If the block is a DWARF Expression, clone it into the temporary
1027   // buffer using cloneExpression(), otherwise copy the data directly.
1028   SmallVector<uint8_t, 32> Buffer;
1029   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1030   if (DWARFAttribute::mayHaveLocationDescription(AttrSpec.Attr) &&
1031       (Val.isFormClass(DWARFFormValue::FC_Block) ||
1032        Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1033     DWARFUnit &OrigUnit = Unit.getOrigUnit();
1034     DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1035                        IsLittleEndian, OrigUnit.getAddressByteSize());
1036     DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1037                          OrigUnit.getFormParams().Format);
1038     cloneExpression(Data, Expr, File, Unit, Buffer);
1039     Bytes = Buffer;
1040   }
1041   for (auto Byte : Bytes)
1042     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1043                    dwarf::DW_FORM_data1, DIEInteger(Byte));
1044 
1045   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1046   // the DIE class, this "if" could be replaced by
1047   // Attr->setSize(Bytes.size()).
1048   if (Loc)
1049     Loc->setSize(Bytes.size());
1050   else
1051     Block->setSize(Bytes.size());
1052 
1053   Die.addValue(DIEAlloc, Value);
1054   return AttrSize;
1055 }
1056 
1057 unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1058     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1059     const CompileUnit &Unit, AttributesInfo &Info) {
1060   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1061     if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1062       Info.HasLowPc = true;
1063     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1064                  dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1065     return Unit.getOrigUnit().getAddressByteSize();
1066   }
1067 
1068   dwarf::Form Form = AttrSpec.Form;
1069   uint64_t Addr = 0;
1070   if (Form == dwarf::DW_FORM_addrx) {
1071     if (Optional<uint64_t> AddrOffsetSectionBase =
1072             Unit.getOrigUnit().getAddrOffsetSectionBase()) {
1073       uint64_t StartOffset = *AddrOffsetSectionBase + Val.getRawUValue();
1074       uint64_t EndOffset =
1075           StartOffset + Unit.getOrigUnit().getAddressByteSize();
1076       if (llvm::Expected<uint64_t> RelocAddr =
1077               ObjFile.Addresses->relocateIndexedAddr(StartOffset, EndOffset))
1078         Addr = *RelocAddr;
1079       else
1080         Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile);
1081     } else
1082       Linker.reportWarning("no base offset for address table", ObjFile);
1083 
1084     // If this is an indexed address emit the debug_info address.
1085     Form = dwarf::DW_FORM_addr;
1086   } else
1087     Addr = *Val.getAsAddress();
1088 
1089   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1090     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1091         Die.getTag() == dwarf::DW_TAG_lexical_block)
1092       // The low_pc of a block or inline subroutine might get
1093       // relocated because it happens to match the low_pc of the
1094       // enclosing subprogram. To prevent issues with that, always use
1095       // the low_pc from the input DIE if relocations have been applied.
1096       Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1097                   ? Info.OrigLowPc
1098                   : Addr) +
1099              Info.PCOffset;
1100     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1101       Addr = Unit.getLowPc();
1102       if (Addr == std::numeric_limits<uint64_t>::max())
1103         return 0;
1104     }
1105     Info.HasLowPc = true;
1106   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1107     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1108       if (uint64_t HighPc = Unit.getHighPc())
1109         Addr = HighPc;
1110       else
1111         return 0;
1112     } else
1113       // If we have a high_pc recorded for the input DIE, use
1114       // it. Otherwise (when no relocations where applied) just use the
1115       // one we just decoded.
1116       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1117   } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
1118     // Relocate a return PC address within a call site entry.
1119     if (Die.getTag() == dwarf::DW_TAG_call_site)
1120       Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
1121              Info.PCOffset;
1122   } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) {
1123     // Relocate the address of a branch instruction within a call site entry.
1124     if (Die.getTag() == dwarf::DW_TAG_call_site)
1125       Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset;
1126   }
1127 
1128   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1129                static_cast<dwarf::Form>(Form), DIEInteger(Addr));
1130   return Unit.getOrigUnit().getAddressByteSize();
1131 }
1132 
1133 unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1134     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1135     CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1136     unsigned AttrSize, AttributesInfo &Info) {
1137   uint64_t Value;
1138 
1139   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1140     if (auto OptionalValue = Val.getAsUnsignedConstant())
1141       Value = *OptionalValue;
1142     else if (auto OptionalValue = Val.getAsSignedConstant())
1143       Value = *OptionalValue;
1144     else if (auto OptionalValue = Val.getAsSectionOffset())
1145       Value = *OptionalValue;
1146     else {
1147       Linker.reportWarning(
1148           "Unsupported scalar attribute form. Dropping attribute.", File,
1149           &InputDIE);
1150       return 0;
1151     }
1152     if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1153       Info.IsDeclaration = true;
1154     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1155                  dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1156     return AttrSize;
1157   }
1158 
1159   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1160       Die.getTag() == dwarf::DW_TAG_compile_unit) {
1161     if (Unit.getLowPc() == -1ULL)
1162       return 0;
1163     // Dwarf >= 4 high_pc is an size, not an address.
1164     Value = Unit.getHighPc() - Unit.getLowPc();
1165   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1166     Value = *Val.getAsSectionOffset();
1167   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1168     Value = *Val.getAsSignedConstant();
1169   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1170     Value = *OptionalValue;
1171   else {
1172     Linker.reportWarning(
1173         "Unsupported scalar attribute form. Dropping attribute.", File,
1174         &InputDIE);
1175     return 0;
1176   }
1177   PatchLocation Patch =
1178       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1179                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1180   if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1181     Unit.noteRangeAttribute(Die, Patch);
1182     Info.HasRanges = true;
1183   }
1184 
1185   // A more generic way to check for location attributes would be
1186   // nice, but it's very unlikely that any other attribute needs a
1187   // location list.
1188   // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1189   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1190            AttrSpec.Attr == dwarf::DW_AT_frame_base) {
1191     Unit.noteLocationAttribute(Patch, Info.PCOffset);
1192   } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1193     Info.IsDeclaration = true;
1194 
1195   return AttrSize;
1196 }
1197 
1198 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1199 /// value \p Val, and add it to \p Die.
1200 /// \returns the size of the cloned attribute.
1201 unsigned DWARFLinker::DIECloner::cloneAttribute(
1202     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1203     CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1204     const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1205     bool IsLittleEndian) {
1206   const DWARFUnit &U = Unit.getOrigUnit();
1207 
1208   switch (AttrSpec.Form) {
1209   case dwarf::DW_FORM_strp:
1210   case dwarf::DW_FORM_string:
1211   case dwarf::DW_FORM_strx:
1212   case dwarf::DW_FORM_strx1:
1213   case dwarf::DW_FORM_strx2:
1214   case dwarf::DW_FORM_strx3:
1215   case dwarf::DW_FORM_strx4:
1216     return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1217   case dwarf::DW_FORM_ref_addr:
1218   case dwarf::DW_FORM_ref1:
1219   case dwarf::DW_FORM_ref2:
1220   case dwarf::DW_FORM_ref4:
1221   case dwarf::DW_FORM_ref8:
1222     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1223                                       File, Unit);
1224   case dwarf::DW_FORM_block:
1225   case dwarf::DW_FORM_block1:
1226   case dwarf::DW_FORM_block2:
1227   case dwarf::DW_FORM_block4:
1228   case dwarf::DW_FORM_exprloc:
1229     return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
1230                                IsLittleEndian);
1231   case dwarf::DW_FORM_addr:
1232   case dwarf::DW_FORM_addrx:
1233     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1234   case dwarf::DW_FORM_data1:
1235   case dwarf::DW_FORM_data2:
1236   case dwarf::DW_FORM_data4:
1237   case dwarf::DW_FORM_data8:
1238   case dwarf::DW_FORM_udata:
1239   case dwarf::DW_FORM_sdata:
1240   case dwarf::DW_FORM_sec_offset:
1241   case dwarf::DW_FORM_flag:
1242   case dwarf::DW_FORM_flag_present:
1243     return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1244                                 AttrSize, Info);
1245   default:
1246     Linker.reportWarning("Unsupported attribute form " +
1247                              dwarf::FormEncodingString(AttrSpec.Form) +
1248                              " in cloneAttribute. Dropping.",
1249                          File, &InputDIE);
1250   }
1251 
1252   return 0;
1253 }
1254 
1255 static bool isObjCSelector(StringRef Name) {
1256   return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1257          (Name[1] == '[');
1258 }
1259 
1260 void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1261                                                 const DIE *Die,
1262                                                 DwarfStringPoolEntryRef Name,
1263                                                 OffsetsStringPool &StringPool,
1264                                                 bool SkipPubSection) {
1265   assert(isObjCSelector(Name.getString()) && "not an objc selector");
1266   // Objective C method or class function.
1267   // "- [Class(Category) selector :withArg ...]"
1268   StringRef ClassNameStart(Name.getString().drop_front(2));
1269   size_t FirstSpace = ClassNameStart.find(' ');
1270   if (FirstSpace == StringRef::npos)
1271     return;
1272 
1273   StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1274   if (!SelectorStart.size())
1275     return;
1276 
1277   StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1278   Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1279 
1280   // Add an entry for the class name that points to this
1281   // method/class function.
1282   StringRef ClassName(ClassNameStart.data(), FirstSpace);
1283   Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1284 
1285   if (ClassName[ClassName.size() - 1] == ')') {
1286     size_t OpenParens = ClassName.find('(');
1287     if (OpenParens != StringRef::npos) {
1288       StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1289       Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1290                               SkipPubSection);
1291 
1292       std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1293       // FIXME: The missing space here may be a bug, but
1294       //        dsymutil-classic also does it this way.
1295       MethodNameNoCategory.append(std::string(SelectorStart));
1296       Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1297                               SkipPubSection);
1298     }
1299   }
1300 }
1301 
1302 static bool
1303 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1304                     uint16_t Tag, bool InDebugMap, bool SkipPC,
1305                     bool InFunctionScope) {
1306   switch (AttrSpec.Attr) {
1307   default:
1308     return false;
1309   case dwarf::DW_AT_low_pc:
1310   case dwarf::DW_AT_high_pc:
1311   case dwarf::DW_AT_ranges:
1312     return SkipPC;
1313   case dwarf::DW_AT_str_offsets_base:
1314     // FIXME: Use the string offset table with Dwarf 5.
1315     return true;
1316   case dwarf::DW_AT_location:
1317   case dwarf::DW_AT_frame_base:
1318     // FIXME: for some reason dsymutil-classic keeps the location attributes
1319     // when they are of block type (i.e. not location lists). This is totally
1320     // wrong for globals where we will keep a wrong address. It is mostly
1321     // harmless for locals, but there is no point in keeping these anyway when
1322     // the function wasn't linked.
1323     return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1324                        !InDebugMap)) &&
1325            !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1326   }
1327 }
1328 
1329 DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1330                                       const DWARFFile &File, CompileUnit &Unit,
1331                                       OffsetsStringPool &StringPool,
1332                                       int64_t PCOffset, uint32_t OutOffset,
1333                                       unsigned Flags, bool IsLittleEndian,
1334                                       DIE *Die) {
1335   DWARFUnit &U = Unit.getOrigUnit();
1336   unsigned Idx = U.getDIEIndex(InputDIE);
1337   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1338 
1339   // Should the DIE appear in the output?
1340   if (!Unit.getInfo(Idx).Keep)
1341     return nullptr;
1342 
1343   uint64_t Offset = InputDIE.getOffset();
1344   assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1345   if (!Die) {
1346     // The DIE might have been already created by a forward reference
1347     // (see cloneDieReferenceAttribute()).
1348     if (!Info.Clone)
1349       Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1350     Die = Info.Clone;
1351   }
1352 
1353   assert(Die->getTag() == InputDIE.getTag());
1354   Die->setOffset(OutOffset);
1355   if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
1356       Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
1357       Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
1358       !Info.Ctxt->getCanonicalDIEOffset()) {
1359     // We are about to emit a DIE that is the root of its own valid
1360     // DeclContext tree. Make the current offset the canonical offset
1361     // for this context.
1362     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1363   }
1364 
1365   // Extract and clone every attribute.
1366   DWARFDataExtractor Data = U.getDebugInfoExtractor();
1367   // Point to the next DIE (generally there is always at least a NULL
1368   // entry after the current one). If this is a lone
1369   // DW_TAG_compile_unit without any children, point to the next unit.
1370   uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1371                             ? U.getDIEAtIndex(Idx + 1).getOffset()
1372                             : U.getNextUnitOffset();
1373   AttributesInfo AttrInfo;
1374 
1375   // We could copy the data only if we need to apply a relocation to it. After
1376   // testing, it seems there is no performance downside to doing the copy
1377   // unconditionally, and it makes the code simpler.
1378   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1379   Data =
1380       DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1381 
1382   // Modify the copy with relocated addresses.
1383   if (ObjFile.Addresses->areRelocationsResolved() &&
1384       ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
1385                                           Data.isLittleEndian())) {
1386     // If we applied relocations, we store the value of high_pc that was
1387     // potentially stored in the input DIE. If high_pc is an address
1388     // (Dwarf version == 2), then it might have been relocated to a
1389     // totally unrelated value (because the end address in the object
1390     // file might be start address of another function which got moved
1391     // independently by the linker). The computation of the actual
1392     // high_pc value is done in cloneAddressAttribute().
1393     AttrInfo.OrigHighPc =
1394         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1395     // Also store the low_pc. It might get relocated in an
1396     // inline_subprogram that happens at the beginning of its
1397     // inlining function.
1398     AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1399                                           std::numeric_limits<uint64_t>::max());
1400     AttrInfo.OrigCallReturnPc =
1401         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
1402     AttrInfo.OrigCallPc =
1403         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0);
1404   }
1405 
1406   // Reset the Offset to 0 as we will be working on the local copy of
1407   // the data.
1408   Offset = 0;
1409 
1410   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1411   Offset += getULEB128Size(Abbrev->getCode());
1412 
1413   // We are entering a subprogram. Get and propagate the PCOffset.
1414   if (Die->getTag() == dwarf::DW_TAG_subprogram)
1415     PCOffset = Info.AddrAdjust;
1416   AttrInfo.PCOffset = PCOffset;
1417 
1418   if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1419     Flags |= TF_InFunctionScope;
1420     if (!Info.InDebugMap && LLVM_LIKELY(!Update))
1421       Flags |= TF_SkipPC;
1422   }
1423 
1424   bool Copied = false;
1425   for (const auto &AttrSpec : Abbrev->attributes()) {
1426     if (LLVM_LIKELY(!Update) &&
1427         shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1428                             Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1429       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1430                                 U.getFormParams());
1431       // FIXME: dsymutil-classic keeps the old abbreviation around
1432       // even if it's not used. We can remove this (and the copyAbbrev
1433       // helper) as soon as bit-for-bit compatibility is not a goal anymore.
1434       if (!Copied) {
1435         copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
1436         Copied = true;
1437       }
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::Default:
1797     llvm_unreachable("The default must be updated to a concrete value.");
1798     break;
1799   }
1800 }
1801 
1802 void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1803   // Add namespaces.
1804   for (const auto &Namespace : Unit.getNamespaces())
1805     AppleNamespaces.addName(Namespace.Name,
1806                             Namespace.Die->getOffset() + Unit.getStartOffset());
1807 
1808   /// Add names.
1809   TheDwarfEmitter->emitPubNamesForUnit(Unit);
1810   for (const auto &Pubname : Unit.getPubnames())
1811     AppleNames.addName(Pubname.Name,
1812                        Pubname.Die->getOffset() + Unit.getStartOffset());
1813 
1814   /// Add types.
1815   TheDwarfEmitter->emitPubTypesForUnit(Unit);
1816   for (const auto &Pubtype : Unit.getPubtypes())
1817     AppleTypes.addName(
1818         Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1819         Pubtype.Die->getTag(),
1820         Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1821                                         : 0,
1822         Pubtype.QualifiedNameHash);
1823 
1824   /// Add ObjC names.
1825   for (const auto &ObjC : Unit.getObjC())
1826     AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1827 }
1828 
1829 void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1830   for (const auto &Namespace : Unit.getNamespaces())
1831     DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1832                        Namespace.Die->getTag(), Unit.getUniqueID());
1833   for (const auto &Pubname : Unit.getPubnames())
1834     DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1835                        Pubname.Die->getTag(), Unit.getUniqueID());
1836   for (const auto &Pubtype : Unit.getPubtypes())
1837     DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
1838                        Pubtype.Die->getTag(), Unit.getUniqueID());
1839 }
1840 
1841 /// Read the frame info stored in the object, and emit the
1842 /// patched frame descriptions for the resulting file.
1843 ///
1844 /// This is actually pretty easy as the data of the CIEs and FDEs can
1845 /// be considered as black boxes and moved as is. The only thing to do
1846 /// is to patch the addresses in the headers.
1847 void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File,
1848                                           RangesTy &Ranges,
1849                                           DWARFContext &OrigDwarf,
1850                                           unsigned AddrSize) {
1851   StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
1852   if (FrameData.empty())
1853     return;
1854 
1855   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
1856   uint64_t InputOffset = 0;
1857 
1858   // Store the data of the CIEs defined in this object, keyed by their
1859   // offsets.
1860   DenseMap<uint64_t, StringRef> LocalCIES;
1861 
1862   while (Data.isValidOffset(InputOffset)) {
1863     uint64_t EntryOffset = InputOffset;
1864     uint32_t InitialLength = Data.getU32(&InputOffset);
1865     if (InitialLength == 0xFFFFFFFF)
1866       return reportWarning("Dwarf64 bits no supported", File);
1867 
1868     uint32_t CIEId = Data.getU32(&InputOffset);
1869     if (CIEId == 0xFFFFFFFF) {
1870       // This is a CIE, store it.
1871       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
1872       LocalCIES[EntryOffset] = CIEData;
1873       // The -4 is to account for the CIEId we just read.
1874       InputOffset += InitialLength - 4;
1875       continue;
1876     }
1877 
1878     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
1879 
1880     // Some compilers seem to emit frame info that doesn't start at
1881     // the function entry point, thus we can't just lookup the address
1882     // in the debug map. Use the AddressInfo's range map to see if the FDE
1883     // describes something that we can relocate.
1884     auto Range = Ranges.upper_bound(Loc);
1885     if (Range != Ranges.begin())
1886       --Range;
1887     if (Range == Ranges.end() || Range->first > Loc ||
1888         Range->second.HighPC <= Loc) {
1889       // The +4 is to account for the size of the InitialLength field itself.
1890       InputOffset = EntryOffset + InitialLength + 4;
1891       continue;
1892     }
1893 
1894     // This is an FDE, and we have a mapping.
1895     // Have we already emitted a corresponding CIE?
1896     StringRef CIEData = LocalCIES[CIEId];
1897     if (CIEData.empty())
1898       return reportWarning("Inconsistent debug_frame content. Dropping.", File);
1899 
1900     // Look if we already emitted a CIE that corresponds to the
1901     // referenced one (the CIE data is the key of that lookup).
1902     auto IteratorInserted = EmittedCIEs.insert(
1903         std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
1904     // If there is no CIE yet for this ID, emit it.
1905     if (IteratorInserted.second ||
1906         // FIXME: dsymutil-classic only caches the last used CIE for
1907         // reuse. Mimic that behavior for now. Just removing that
1908         // second half of the condition and the LastCIEOffset variable
1909         // makes the code DTRT.
1910         LastCIEOffset != IteratorInserted.first->getValue()) {
1911       LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
1912       IteratorInserted.first->getValue() = LastCIEOffset;
1913       TheDwarfEmitter->emitCIE(CIEData);
1914     }
1915 
1916     // Emit the FDE with updated address and CIE pointer.
1917     // (4 + AddrSize) is the size of the CIEId + initial_location
1918     // fields that will get reconstructed by emitFDE().
1919     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
1920     TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
1921                              Loc + Range->second.Offset,
1922                              FrameData.substr(InputOffset, FDERemainingBytes));
1923     InputOffset += FDERemainingBytes;
1924   }
1925 }
1926 
1927 void DWARFLinker::DIECloner::copyAbbrev(
1928     const DWARFAbbreviationDeclaration &Abbrev, bool HasODR) {
1929   DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
1930                  dwarf::Form(Abbrev.hasChildren()));
1931 
1932   for (const auto &Attr : Abbrev.attributes()) {
1933     uint16_t Form = Attr.Form;
1934     if (HasODR && isODRAttribute(Attr.Attr))
1935       Form = dwarf::DW_FORM_ref_addr;
1936     Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
1937   }
1938 
1939   Linker.assignAbbrev(Copy);
1940 }
1941 
1942 uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
1943                                                         CompileUnit &U,
1944                                                         const DWARFFile &File,
1945                                                         int ChildRecurseDepth) {
1946   const char *Name = nullptr;
1947   DWARFUnit *OrigUnit = &U.getOrigUnit();
1948   CompileUnit *CU = &U;
1949   Optional<DWARFFormValue> Ref;
1950 
1951   while (1) {
1952     if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
1953       Name = CurrentName;
1954 
1955     if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
1956         !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
1957       break;
1958 
1959     if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
1960       break;
1961 
1962     CompileUnit *RefCU;
1963     if (auto RefDIE =
1964             Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
1965       CU = RefCU;
1966       OrigUnit = &RefCU->getOrigUnit();
1967       DIE = RefDIE;
1968     }
1969   }
1970 
1971   unsigned Idx = OrigUnit->getDIEIndex(DIE);
1972   if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
1973     Name = "(anonymous namespace)";
1974 
1975   if (CU->getInfo(Idx).ParentIdx == 0 ||
1976       // FIXME: dsymutil-classic compatibility. Ignore modules.
1977       CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
1978           dwarf::DW_TAG_module)
1979     return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
1980 
1981   DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
1982   return djbHash(
1983       (Name ? Name : ""),
1984       djbHash((Name ? "::" : ""),
1985               hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
1986 }
1987 
1988 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
1989   auto DwoId = dwarf::toUnsigned(
1990       CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
1991   if (DwoId)
1992     return *DwoId;
1993   return 0;
1994 }
1995 
1996 static std::string remapPath(StringRef Path,
1997                              const objectPrefixMap &ObjectPrefixMap) {
1998   if (ObjectPrefixMap.empty())
1999     return Path.str();
2000 
2001   SmallString<256> p = Path;
2002   for (const auto &Entry : ObjectPrefixMap)
2003     if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
2004       break;
2005   return p.str().str();
2006 }
2007 
2008 bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit,
2009                                           const DWARFFile &File,
2010                                           OffsetsStringPool &StringPool,
2011                                           DeclContextTree &ODRContexts,
2012                                           uint64_t ModulesEndOffset,
2013                                           unsigned &UnitID, bool IsLittleEndian,
2014                                           unsigned Indent, bool Quiet) {
2015   std::string PCMfile = dwarf::toString(
2016       CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2017   if (PCMfile.empty())
2018     return false;
2019   if (Options.ObjectPrefixMap)
2020     PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap);
2021 
2022   // Clang module DWARF skeleton CUs abuse this for the path to the module.
2023   uint64_t DwoId = getDwoId(CUDie, Unit);
2024 
2025   std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2026   if (Name.empty()) {
2027     if (!Quiet)
2028       reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
2029     return true;
2030   }
2031 
2032   if (!Quiet && Options.Verbose) {
2033     outs().indent(Indent);
2034     outs() << "Found clang module reference " << PCMfile;
2035   }
2036 
2037   auto Cached = ClangModules.find(PCMfile);
2038   if (Cached != ClangModules.end()) {
2039     // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2040     // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2041     // ASTFileSignatures will change randomly when a module is rebuilt.
2042     if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2043       reportWarning(Twine("hash mismatch: this object file was built against a "
2044                           "different version of the module ") +
2045                         PCMfile,
2046                     File);
2047     if (!Quiet && Options.Verbose)
2048       outs() << " [cached].\n";
2049     return true;
2050   }
2051   if (!Quiet && Options.Verbose)
2052     outs() << " ...\n";
2053 
2054   // Cyclic dependencies are disallowed by Clang, but we still
2055   // shouldn't run into an infinite loop, so mark it as processed now.
2056   ClangModules.insert({PCMfile, DwoId});
2057 
2058   if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
2059                                 ODRContexts, ModulesEndOffset, UnitID,
2060                                 IsLittleEndian, Indent + 2, Quiet)) {
2061     consumeError(std::move(E));
2062     return false;
2063   }
2064   return true;
2065 }
2066 
2067 Error DWARFLinker::loadClangModule(
2068     DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
2069     const DWARFFile &File, OffsetsStringPool &StringPool,
2070     DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
2071     bool IsLittleEndian, unsigned Indent, bool Quiet) {
2072   /// Using a SmallString<0> because loadClangModule() is recursive.
2073   SmallString<0> Path(Options.PrependPath);
2074   if (sys::path::is_relative(Filename))
2075     resolveRelativeObjectPath(Path, CUDie);
2076   sys::path::append(Path, Filename);
2077   // Don't use the cached binary holder because we have no thread-safety
2078   // guarantee and the lifetime is limited.
2079 
2080   if (Options.ObjFileLoader == nullptr)
2081     return Error::success();
2082 
2083   auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
2084   if (!ErrOrObj)
2085     return Error::success();
2086 
2087   std::unique_ptr<CompileUnit> Unit;
2088 
2089   for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2090     updateDwarfVersion(CU->getVersion());
2091     // Recursively get all modules imported by this one.
2092     auto CUDie = CU->getUnitDIE(false);
2093     if (!CUDie)
2094       continue;
2095     if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts,
2096                                  ModulesEndOffset, UnitID, IsLittleEndian,
2097                                  Indent, Quiet)) {
2098       if (Unit) {
2099         std::string Err =
2100             (Filename +
2101              ": Clang modules are expected to have exactly 1 compile unit.\n")
2102                 .str();
2103         reportError(Err, File);
2104         return make_error<StringError>(Err, inconvertibleErrorCode());
2105       }
2106       // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2107       // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2108       // ASTFileSignatures will change randomly when a module is rebuilt.
2109       uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2110       if (PCMDwoId != DwoId) {
2111         if (!Quiet && Options.Verbose)
2112           reportWarning(
2113               Twine("hash mismatch: this object file was built against a "
2114                     "different version of the module ") +
2115                   Filename,
2116               File);
2117         // Update the cache entry with the DwoId of the module loaded from disk.
2118         ClangModules[Filename] = PCMDwoId;
2119       }
2120 
2121       // Add this module.
2122       Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2123                                            ModuleName);
2124       Unit->setHasInterestingContent();
2125       analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts,
2126                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2127                          [&](const Twine &Warning, const DWARFDie &DIE) {
2128                            reportWarning(Warning, File, &DIE);
2129                          });
2130       // Keep everything.
2131       Unit->markEverythingAsKept();
2132     }
2133   }
2134   assert(Unit && "CompileUnit is not set!");
2135   if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2136     return Error::success();
2137   if (!Quiet && Options.Verbose) {
2138     outs().indent(Indent);
2139     outs() << "cloning .debug_info from " << Filename << "\n";
2140   }
2141 
2142   UnitListTy CompileUnits;
2143   CompileUnits.push_back(std::move(Unit));
2144   assert(TheDwarfEmitter);
2145   DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
2146             Options.Update)
2147       .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
2148                             IsLittleEndian);
2149   return Error::success();
2150 }
2151 
2152 uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits(
2153     DWARFContext &DwarfContext, const DWARFFile &File,
2154     OffsetsStringPool &StringPool, bool IsLittleEndian) {
2155   uint64_t OutputDebugInfoSize =
2156       Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
2157   const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2158 
2159   for (auto &CurrentUnit : CompileUnits) {
2160     const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2161     const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2162     auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2163     CurrentUnit->setStartOffset(OutputDebugInfoSize);
2164     if (!InputDIE) {
2165       OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2166       continue;
2167     }
2168     if (CurrentUnit->getInfo(0).Keep) {
2169       // Clone the InputDIE into your Unit DIE in our compile unit since it
2170       // already has a DIE inside of it.
2171       CurrentUnit->createOutputDIE();
2172       cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
2173                UnitHeaderSize, 0, IsLittleEndian,
2174                CurrentUnit->getOutputUnitDIE());
2175     }
2176 
2177     OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2178 
2179     if (!Linker.Options.NoOutput) {
2180       assert(Emitter);
2181 
2182       if (LLVM_LIKELY(!Linker.Options.Update) ||
2183           Linker.needToTranslateStrings())
2184         Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
2185 
2186       Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2187 
2188       if (LLVM_UNLIKELY(Linker.Options.Update))
2189         continue;
2190 
2191       Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
2192       auto ProcessExpr = [&](StringRef Bytes,
2193                              SmallVectorImpl<uint8_t> &Buffer) {
2194         DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2195         DataExtractor Data(Bytes, IsLittleEndian,
2196                            OrigUnit.getAddressByteSize());
2197         cloneExpression(Data,
2198                         DWARFExpression(Data, OrigUnit.getAddressByteSize(),
2199                                         OrigUnit.getFormParams().Format),
2200                         File, *CurrentUnit, Buffer);
2201       };
2202       Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
2203     }
2204   }
2205 
2206   if (!Linker.Options.NoOutput) {
2207     assert(Emitter);
2208     // Emit all the compile unit's debug information.
2209     for (auto &CurrentUnit : CompileUnits) {
2210       if (LLVM_LIKELY(!Linker.Options.Update))
2211         Linker.generateUnitRanges(*CurrentUnit);
2212 
2213       CurrentUnit->fixupForwardReferences();
2214 
2215       if (!CurrentUnit->getOutputUnitDIE())
2216         continue;
2217 
2218       unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2219 
2220       assert(Emitter->getDebugInfoSectionSize() ==
2221              CurrentUnit->getStartOffset());
2222       Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
2223       Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
2224       assert(Emitter->getDebugInfoSectionSize() ==
2225              CurrentUnit->computeNextUnitOffset(DwarfVersion));
2226     }
2227   }
2228 
2229   return OutputDebugInfoSize - StartOutputDebugInfoSize;
2230 }
2231 
2232 void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
2233   if (Options.TheAccelTableKind != AccelTableKind::Default)
2234     return;
2235 
2236   auto &DwarfObj = Dwarf.getDWARFObj();
2237 
2238   if (!AtLeastOneDwarfAccelTable &&
2239       (!DwarfObj.getAppleNamesSection().Data.empty() ||
2240        !DwarfObj.getAppleTypesSection().Data.empty() ||
2241        !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2242        !DwarfObj.getAppleObjCSection().Data.empty())) {
2243     AtLeastOneAppleAccelTable = true;
2244   }
2245 
2246   if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
2247     AtLeastOneDwarfAccelTable = true;
2248   }
2249 }
2250 
2251 bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File,
2252                                          OffsetsStringPool &StringPool) {
2253 
2254   if (File.Warnings.empty())
2255     return false;
2256 
2257   DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2258   CUDie->setOffset(11);
2259   StringRef Producer;
2260   StringRef WarningHeader;
2261 
2262   switch (DwarfLinkerClientID) {
2263   case DwarfLinkerClient::Dsymutil:
2264     Producer = StringPool.internString("dsymutil");
2265     WarningHeader = "dsymutil_warning";
2266     break;
2267 
2268   default:
2269     Producer = StringPool.internString("dwarfopt");
2270     WarningHeader = "dwarfopt_warning";
2271     break;
2272   }
2273 
2274   StringRef FileName = StringPool.internString(File.FileName);
2275   CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2276                   DIEInteger(StringPool.getStringOffset(Producer)));
2277   DIEBlock *String = new (DIEAlloc) DIEBlock();
2278   DIEBlocks.push_back(String);
2279   for (auto &C : FileName)
2280     String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2281                      DIEInteger(C));
2282   String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2283                    DIEInteger(0));
2284 
2285   CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2286   for (const auto &Warning : File.Warnings) {
2287     DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2288     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2289                       DIEInteger(StringPool.getStringOffset(WarningHeader)));
2290     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2291                       DIEInteger(1));
2292     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2293                       DIEInteger(StringPool.getStringOffset(Warning)));
2294   }
2295   unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
2296                   File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
2297   DIEAbbrev Abbrev = CUDie->generateAbbrev();
2298   assignAbbrev(Abbrev);
2299   CUDie->setAbbrevNumber(Abbrev.getNumber());
2300   Size += getULEB128Size(Abbrev.getNumber());
2301   // Abbreviation ordering needed for classic compatibility.
2302   for (auto &Child : CUDie->children()) {
2303     Abbrev = Child.generateAbbrev();
2304     assignAbbrev(Abbrev);
2305     Child.setAbbrevNumber(Abbrev.getNumber());
2306     Size += getULEB128Size(Abbrev.getNumber());
2307   }
2308   CUDie->setSize(Size);
2309   TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
2310 
2311   return true;
2312 }
2313 
2314 void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
2315   if (!needToTranslateStrings())
2316     TheDwarfEmitter->emitSectionContents(
2317         Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
2318   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
2319                                        "debug_loc");
2320   TheDwarfEmitter->emitSectionContents(
2321       Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
2322   TheDwarfEmitter->emitSectionContents(
2323       Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
2324   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
2325                                        "debug_aranges");
2326 }
2327 
2328 void DWARFLinker::addObjectFile(DWARFFile &File) {
2329   ObjectContexts.emplace_back(LinkContext(File));
2330 
2331   if (ObjectContexts.back().File.Dwarf)
2332     updateAccelKind(*ObjectContexts.back().File.Dwarf);
2333 }
2334 
2335 bool DWARFLinker::link() {
2336   assert(Options.NoOutput || TheDwarfEmitter);
2337 
2338   // A unique ID that identifies each compile unit.
2339   unsigned UnitID = 0;
2340 
2341   // First populate the data structure we need for each iteration of the
2342   // parallel loop.
2343   unsigned NumObjects = ObjectContexts.size();
2344 
2345   // This Dwarf string pool which is used for emission. It must be used
2346   // serially as the order of calling getStringOffset matters for
2347   // reproducibility.
2348   OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
2349 
2350   // ODR Contexts for the optimize.
2351   DeclContextTree ODRContexts;
2352 
2353   // If we haven't decided on an accelerator table kind yet, we base ourselves
2354   // on the DWARF we have seen so far. At this point we haven't pulled in debug
2355   // information from modules yet, so it is technically possible that they
2356   // would affect the decision. However, as they're built with the same
2357   // compiler and flags, it is safe to assume that they will follow the
2358   // decision made here.
2359   if (Options.TheAccelTableKind == AccelTableKind::Default) {
2360     if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2361       Options.TheAccelTableKind = AccelTableKind::Dwarf;
2362     else
2363       Options.TheAccelTableKind = AccelTableKind::Apple;
2364   }
2365 
2366   for (LinkContext &OptContext : ObjectContexts) {
2367     if (Options.Verbose) {
2368       if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
2369         outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
2370       else
2371         outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
2372     }
2373 
2374     if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
2375       continue;
2376 
2377     if (!OptContext.File.Dwarf)
2378       continue;
2379     // Look for relocations that correspond to address map entries.
2380 
2381     // there was findvalidrelocations previously ... probably we need to gather
2382     // info here
2383     if (LLVM_LIKELY(!Options.Update) &&
2384         !OptContext.File.Addresses->hasValidRelocs()) {
2385       if (Options.Verbose)
2386         outs() << "No valid relocations found. Skipping.\n";
2387 
2388       // Set "Skip" flag as a signal to other loops that we should not
2389       // process this iteration.
2390       OptContext.Skip = true;
2391       continue;
2392     }
2393 
2394     // Setup access to the debug info.
2395     if (!OptContext.File.Dwarf)
2396       continue;
2397 
2398     // In a first phase, just read in the debug info and load all clang modules.
2399     OptContext.CompileUnits.reserve(
2400         OptContext.File.Dwarf->getNumCompileUnits());
2401 
2402     for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
2403       updateDwarfVersion(CU->getVersion());
2404       auto CUDie = CU->getUnitDIE(false);
2405       if (Options.Verbose) {
2406         outs() << "Input compilation unit:";
2407         DIDumpOptions DumpOpts;
2408         DumpOpts.ChildRecurseDepth = 0;
2409         DumpOpts.Verbose = Options.Verbose;
2410         CUDie.dump(outs(), 0, DumpOpts);
2411       }
2412       if (CUDie && !LLVM_UNLIKELY(Options.Update))
2413         registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
2414                                 ODRContexts, 0, UnitID,
2415                                 OptContext.File.Dwarf->isLittleEndian());
2416     }
2417   }
2418 
2419   // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2420   if (MaxDwarfVersion == 0)
2421     MaxDwarfVersion = 3;
2422 
2423   // At this point we know how much data we have emitted. We use this value to
2424   // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2425   // is already emitted, without being affected by canonical die offsets set
2426   // later. This prevents undeterminism when analyze and clone execute
2427   // concurrently, as clone set the canonical DIE offset and analyze reads it.
2428   const uint64_t ModulesEndOffset =
2429       Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
2430 
2431   // These variables manage the list of processed object files.
2432   // The mutex and condition variable are to ensure that this is thread safe.
2433   std::mutex ProcessedFilesMutex;
2434   std::condition_variable ProcessedFilesConditionVariable;
2435   BitVector ProcessedFiles(NumObjects, false);
2436 
2437   //  Analyzing the context info is particularly expensive so it is executed in
2438   //  parallel with emitting the previous compile unit.
2439   auto AnalyzeLambda = [&](size_t I) {
2440     auto &Context = ObjectContexts[I];
2441 
2442     if (Context.Skip || !Context.File.Dwarf)
2443       return;
2444 
2445     for (const auto &CU : Context.File.Dwarf->compile_units()) {
2446       updateDwarfVersion(CU->getVersion());
2447       // The !registerModuleReference() condition effectively skips
2448       // over fully resolved skeleton units. This second pass of
2449       // registerModuleReferences doesn't do any new work, but it
2450       // will collect top-level errors, which are suppressed. Module
2451       // warnings were already displayed in the first iteration.
2452       bool Quiet = true;
2453       auto CUDie = CU->getUnitDIE(false);
2454       if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
2455           !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
2456                                    ODRContexts, ModulesEndOffset, UnitID,
2457                                    Quiet)) {
2458         Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
2459             *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2460       }
2461     }
2462 
2463     // Now build the DIE parent links that we will use during the next phase.
2464     for (auto &CurrentUnit : Context.CompileUnits) {
2465       auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2466       if (!CUDie)
2467         continue;
2468       analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2469                          *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
2470                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2471                          [&](const Twine &Warning, const DWARFDie &DIE) {
2472                            reportWarning(Warning, Context.File, &DIE);
2473                          });
2474     }
2475   };
2476 
2477   // For each object file map how many bytes were emitted.
2478   StringMap<DebugInfoSize> SizeByObject;
2479 
2480   // And then the remaining work in serial again.
2481   // Note, although this loop runs in serial, it can run in parallel with
2482   // the analyzeContextInfo loop so long as we process files with indices >=
2483   // than those processed by analyzeContextInfo.
2484   auto CloneLambda = [&](size_t I) {
2485     auto &OptContext = ObjectContexts[I];
2486     if (OptContext.Skip || !OptContext.File.Dwarf)
2487       return;
2488 
2489     // Then mark all the DIEs that need to be present in the generated output
2490     // and collect some information about them.
2491     // Note that this loop can not be merged with the previous one because
2492     // cross-cu references require the ParentIdx to be setup for every CU in
2493     // the object file before calling this.
2494     if (LLVM_UNLIKELY(Options.Update)) {
2495       for (auto &CurrentUnit : OptContext.CompileUnits)
2496         CurrentUnit->markEverythingAsKept();
2497       copyInvariantDebugSection(*OptContext.File.Dwarf);
2498     } else {
2499       for (auto &CurrentUnit : OptContext.CompileUnits)
2500         lookForDIEsToKeep(*OptContext.File.Addresses,
2501                           OptContext.File.Addresses->getValidAddressRanges(),
2502                           OptContext.CompileUnits,
2503                           CurrentUnit->getOrigUnit().getUnitDIE(),
2504                           OptContext.File, *CurrentUnit, 0);
2505     }
2506 
2507     // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2508     // array again (in the same way findValidRelocsInDebugInfo() did). We
2509     // need to reset the NextValidReloc index to the beginning.
2510     if (OptContext.File.Addresses->hasValidRelocs() ||
2511         LLVM_UNLIKELY(Options.Update)) {
2512       SizeByObject[OptContext.File.FileName].Input =
2513           getDebugInfoSize(*OptContext.File.Dwarf);
2514       SizeByObject[OptContext.File.FileName].Output =
2515           DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
2516                     OptContext.CompileUnits, Options.Update)
2517               .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
2518                                     OffsetsStringPool,
2519                                     OptContext.File.Dwarf->isLittleEndian());
2520     }
2521     if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
2522         LLVM_LIKELY(!Options.Update))
2523       patchFrameInfoForObject(
2524           OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
2525           *OptContext.File.Dwarf,
2526           OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2527 
2528     // Clean-up before starting working on the next object.
2529     cleanupAuxiliarryData(OptContext);
2530   };
2531 
2532   auto EmitLambda = [&]() {
2533     // Emit everything that's global.
2534     if (!Options.NoOutput) {
2535       TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2536       TheDwarfEmitter->emitStrings(OffsetsStringPool);
2537       switch (Options.TheAccelTableKind) {
2538       case AccelTableKind::Apple:
2539         TheDwarfEmitter->emitAppleNames(AppleNames);
2540         TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
2541         TheDwarfEmitter->emitAppleTypes(AppleTypes);
2542         TheDwarfEmitter->emitAppleObjc(AppleObjc);
2543         break;
2544       case AccelTableKind::Dwarf:
2545         TheDwarfEmitter->emitDebugNames(DebugNames);
2546         break;
2547       case AccelTableKind::Default:
2548         llvm_unreachable("Default should have already been resolved.");
2549         break;
2550       }
2551     }
2552   };
2553 
2554   auto AnalyzeAll = [&]() {
2555     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2556       AnalyzeLambda(I);
2557 
2558       std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2559       ProcessedFiles.set(I);
2560       ProcessedFilesConditionVariable.notify_one();
2561     }
2562   };
2563 
2564   auto CloneAll = [&]() {
2565     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2566       {
2567         std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2568         if (!ProcessedFiles[I]) {
2569           ProcessedFilesConditionVariable.wait(
2570               LockGuard, [&]() { return ProcessedFiles[I]; });
2571         }
2572       }
2573 
2574       CloneLambda(I);
2575     }
2576     EmitLambda();
2577   };
2578 
2579   // To limit memory usage in the single threaded case, analyze and clone are
2580   // run sequentially so the OptContext is freed after processing each object
2581   // in endDebugObject.
2582   if (Options.Threads == 1) {
2583     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2584       AnalyzeLambda(I);
2585       CloneLambda(I);
2586     }
2587     EmitLambda();
2588   } else {
2589     ThreadPool Pool(hardware_concurrency(2));
2590     Pool.async(AnalyzeAll);
2591     Pool.async(CloneAll);
2592     Pool.wait();
2593   }
2594 
2595   if (Options.Statistics) {
2596     // Create a vector sorted in descending order by output size.
2597     std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
2598     for (auto &E : SizeByObject)
2599       Sorted.emplace_back(E.first(), E.second);
2600     llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
2601       return LHS.second.Output > RHS.second.Output;
2602     });
2603 
2604     auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
2605       const float Difference = Output - Input;
2606       const float Sum = Input + Output;
2607       if (Sum == 0)
2608         return 0;
2609       return (Difference / (Sum / 2));
2610     };
2611 
2612     int64_t InputTotal = 0;
2613     int64_t OutputTotal = 0;
2614     const char *FormatStr = "{0,-45} {1,10}b  {2,10}b {3,8:P}\n";
2615 
2616     // Print header.
2617     outs() << ".debug_info section size (in bytes)\n";
2618     outs() << "----------------------------------------------------------------"
2619               "---------------\n";
2620     outs() << "Filename                                           Object       "
2621               "  dSYM   Change\n";
2622     outs() << "----------------------------------------------------------------"
2623               "---------------\n";
2624 
2625     // Print body.
2626     for (auto &E : Sorted) {
2627       InputTotal += E.second.Input;
2628       OutputTotal += E.second.Output;
2629       llvm::outs() << formatv(
2630           FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
2631           E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
2632     }
2633     // Print total and footer.
2634     outs() << "----------------------------------------------------------------"
2635               "---------------\n";
2636     llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
2637                             ComputePercentange(InputTotal, OutputTotal));
2638     outs() << "----------------------------------------------------------------"
2639               "---------------\n\n";
2640   }
2641 
2642   return true;
2643 }
2644 
2645 } // namespace llvm
2646