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