[yaml2elf] - Refactoring followup for D62809
[llvm-complete.git] / tools / dsymutil / DwarfLinker.cpp
blobbe8bcc648ad41f7d76d7bfc6d4c62d44de561e03
1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
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 //===----------------------------------------------------------------------===//
9 #include "DwarfLinker.h"
10 #include "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "DeclContext.h"
13 #include "DwarfStreamer.h"
14 #include "MachOUtils.h"
15 #include "NonRelocatableStringpool.h"
16 #include "dsymutil.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/Hashing.h"
24 #include "llvm/ADT/IntervalMap.h"
25 #include "llvm/ADT/None.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/PointerIntPair.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/BinaryFormat/Dwarf.h"
35 #include "llvm/BinaryFormat/MachO.h"
36 #include "llvm/CodeGen/AccelTable.h"
37 #include "llvm/CodeGen/AsmPrinter.h"
38 #include "llvm/CodeGen/DIE.h"
39 #include "llvm/Config/config.h"
40 #include "llvm/DebugInfo/DIContext.h"
41 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
42 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
43 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
44 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
45 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
46 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
47 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
48 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
49 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
50 #include "llvm/MC/MCAsmBackend.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCCodeEmitter.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCInstrInfo.h"
56 #include "llvm/MC/MCObjectFileInfo.h"
57 #include "llvm/MC/MCObjectWriter.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/MC/MCSection.h"
60 #include "llvm/MC/MCStreamer.h"
61 #include "llvm/MC/MCSubtargetInfo.h"
62 #include "llvm/MC/MCTargetOptions.h"
63 #include "llvm/Object/MachO.h"
64 #include "llvm/Object/ObjectFile.h"
65 #include "llvm/Object/SymbolicFile.h"
66 #include "llvm/Support/Allocator.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/DJB.h"
70 #include "llvm/Support/DataExtractor.h"
71 #include "llvm/Support/Error.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/ErrorOr.h"
74 #include "llvm/Support/FileSystem.h"
75 #include "llvm/Support/Format.h"
76 #include "llvm/Support/LEB128.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/MemoryBuffer.h"
79 #include "llvm/Support/Path.h"
80 #include "llvm/Support/TargetRegistry.h"
81 #include "llvm/Support/ThreadPool.h"
82 #include "llvm/Support/ToolOutputFile.h"
83 #include "llvm/Support/WithColor.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include "llvm/Target/TargetOptions.h"
87 #include <algorithm>
88 #include <cassert>
89 #include <cinttypes>
90 #include <climits>
91 #include <cstdint>
92 #include <cstdlib>
93 #include <cstring>
94 #include <limits>
95 #include <map>
96 #include <memory>
97 #include <string>
98 #include <system_error>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
103 namespace llvm {
104 namespace dsymutil {
106 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
107 /// CompileUnit object instead.
108 static CompileUnit *getUnitForOffset(const UnitListTy &Units, unsigned Offset) {
109 auto CU = std::upper_bound(
110 Units.begin(), Units.end(), Offset,
111 [](uint32_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
112 return LHS < RHS->getOrigUnit().getNextUnitOffset();
114 return CU != Units.end() ? CU->get() : nullptr;
117 /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
118 /// The resulting DIE might be in another CompileUnit which is stored into \p
119 /// ReferencedCU. \returns null if resolving fails for any reason.
120 static DWARFDie resolveDIEReference(const DwarfLinker &Linker,
121 const DebugMapObject &DMO,
122 const UnitListTy &Units,
123 const DWARFFormValue &RefValue,
124 const DWARFDie &DIE, CompileUnit *&RefCU) {
125 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
126 uint64_t RefOffset = *RefValue.getAsReference();
127 if ((RefCU = getUnitForOffset(Units, RefOffset)))
128 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
129 // In a file with broken references, an attribute might point to a NULL
130 // DIE.
131 if (!RefDie.isNULL())
132 return RefDie;
135 Linker.reportWarning("could not find referenced DIE", DMO, &DIE);
136 return DWARFDie();
139 /// \returns whether the passed \a Attr type might contain a DIE reference
140 /// suitable for ODR uniquing.
141 static bool isODRAttribute(uint16_t Attr) {
142 switch (Attr) {
143 default:
144 return false;
145 case dwarf::DW_AT_type:
146 case dwarf::DW_AT_containing_type:
147 case dwarf::DW_AT_specification:
148 case dwarf::DW_AT_abstract_origin:
149 case dwarf::DW_AT_import:
150 return true;
152 llvm_unreachable("Improper attribute.");
155 static bool isTypeTag(uint16_t Tag) {
156 switch (Tag) {
157 case dwarf::DW_TAG_array_type:
158 case dwarf::DW_TAG_class_type:
159 case dwarf::DW_TAG_enumeration_type:
160 case dwarf::DW_TAG_pointer_type:
161 case dwarf::DW_TAG_reference_type:
162 case dwarf::DW_TAG_string_type:
163 case dwarf::DW_TAG_structure_type:
164 case dwarf::DW_TAG_subroutine_type:
165 case dwarf::DW_TAG_typedef:
166 case dwarf::DW_TAG_union_type:
167 case dwarf::DW_TAG_ptr_to_member_type:
168 case dwarf::DW_TAG_set_type:
169 case dwarf::DW_TAG_subrange_type:
170 case dwarf::DW_TAG_base_type:
171 case dwarf::DW_TAG_const_type:
172 case dwarf::DW_TAG_constant:
173 case dwarf::DW_TAG_file_type:
174 case dwarf::DW_TAG_namelist:
175 case dwarf::DW_TAG_packed_type:
176 case dwarf::DW_TAG_volatile_type:
177 case dwarf::DW_TAG_restrict_type:
178 case dwarf::DW_TAG_atomic_type:
179 case dwarf::DW_TAG_interface_type:
180 case dwarf::DW_TAG_unspecified_type:
181 case dwarf::DW_TAG_shared_type:
182 return true;
183 default:
184 break;
186 return false;
189 bool DwarfLinker::DIECloner::getDIENames(const DWARFDie &Die,
190 AttributesInfo &Info,
191 OffsetsStringPool &StringPool,
192 bool StripTemplate) {
193 // This function will be called on DIEs having low_pcs and
194 // ranges. As getting the name might be more expansive, filter out
195 // blocks directly.
196 if (Die.getTag() == dwarf::DW_TAG_lexical_block)
197 return false;
199 // FIXME: a bit wasteful as the first getName might return the
200 // short name.
201 if (!Info.MangledName)
202 if (const char *MangledName = Die.getName(DINameKind::LinkageName))
203 Info.MangledName = StringPool.getEntry(MangledName);
205 if (!Info.Name)
206 if (const char *Name = Die.getName(DINameKind::ShortName))
207 Info.Name = StringPool.getEntry(Name);
209 if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
210 // FIXME: dsymutil compatibility. This is wrong for operator<
211 auto Split = Info.Name.getString().split('<');
212 if (!Split.second.empty())
213 Info.NameWithoutTemplate = StringPool.getEntry(Split.first);
216 return Info.Name || Info.MangledName;
219 /// Report a warning to the user, optionally including information about a
220 /// specific \p DIE related to the warning.
221 void DwarfLinker::reportWarning(const Twine &Warning, const DebugMapObject &DMO,
222 const DWARFDie *DIE) const {
223 StringRef Context = DMO.getObjectFilename();
224 warn(Warning, Context);
226 if (!Options.Verbose || !DIE)
227 return;
229 DIDumpOptions DumpOpts;
230 DumpOpts.ChildRecurseDepth = 0;
231 DumpOpts.Verbose = Options.Verbose;
233 WithColor::note() << " in DIE:\n";
234 DIE->dump(errs(), 6 /* Indent */, DumpOpts);
237 bool DwarfLinker::createStreamer(const Triple &TheTriple,
238 raw_fd_ostream &OutFile) {
239 if (Options.NoOutput)
240 return true;
242 Streamer = llvm::make_unique<DwarfStreamer>(OutFile, Options);
243 return Streamer->init(TheTriple);
246 /// Resolve the relative path to a build artifact referenced by DWARF by
247 /// applying DW_AT_comp_dir.
248 static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
249 sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
252 /// Collect references to parseable Swift interfaces in imported
253 /// DW_TAG_module blocks.
254 static void analyzeImportedModule(
255 const DWARFDie &DIE, CompileUnit &CU,
256 std::map<std::string, std::string> &ParseableSwiftInterfaces,
257 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
258 if (CU.getLanguage() != dwarf::DW_LANG_Swift)
259 return;
261 StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
262 if (!Path.endswith(".swiftinterface"))
263 return;
264 if (Optional<DWARFFormValue> Val = DIE.find(dwarf::DW_AT_name))
265 if (Optional<const char *> Name = Val->getAsCString()) {
266 auto &Entry = ParseableSwiftInterfaces[*Name];
267 // The prepend path is applied later when copying.
268 DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
269 SmallString<128> ResolvedPath;
270 if (sys::path::is_relative(Path))
271 resolveRelativeObjectPath(ResolvedPath, CUDie);
272 sys::path::append(ResolvedPath, Path);
273 if (!Entry.empty() && Entry != ResolvedPath)
274 ReportWarning(
275 Twine("Conflicting parseable interfaces for Swift Module ") +
276 *Name + ": " + Entry + " and " + Path,
277 DIE);
278 Entry = ResolvedPath.str();
282 /// Recursive helper to build the global DeclContext information and
283 /// gather the child->parent relationships in the original compile unit.
285 /// \return true when this DIE and all of its children are only
286 /// forward declarations to types defined in external clang modules
287 /// (i.e., forward declarations that are children of a DW_TAG_module).
288 static bool analyzeContextInfo(
289 const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
290 DeclContext *CurrentDeclContext, UniquingStringPool &StringPool,
291 DeclContextTree &Contexts, uint64_t ModulesEndOffset,
292 std::map<std::string, std::string> &ParseableSwiftInterfaces,
293 std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
294 bool InImportedModule = false) {
295 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
296 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
298 // Clang imposes an ODR on modules(!) regardless of the language:
299 // "The module-id should consist of only a single identifier,
300 // which provides the name of the module being defined. Each
301 // module shall have a single definition."
303 // This does not extend to the types inside the modules:
304 // "[I]n C, this implies that if two structs are defined in
305 // different submodules with the same name, those two types are
306 // distinct types (but may be compatible types if their
307 // definitions match)."
309 // We treat non-C++ modules like namespaces for this reason.
310 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
311 dwarf::toString(DIE.find(dwarf::DW_AT_name), "") !=
312 CU.getClangModuleName()) {
313 InImportedModule = true;
314 analyzeImportedModule(DIE, CU, ParseableSwiftInterfaces, ReportWarning);
317 Info.ParentIdx = ParentIdx;
318 bool InClangModule = CU.isClangModule() || InImportedModule;
319 if (CU.hasODR() || InClangModule) {
320 if (CurrentDeclContext) {
321 auto PtrInvalidPair = Contexts.getChildDeclContext(
322 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
323 CurrentDeclContext = PtrInvalidPair.getPointer();
324 Info.Ctxt =
325 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
326 if (Info.Ctxt)
327 Info.Ctxt->setDefinedInClangModule(InClangModule);
328 } else
329 Info.Ctxt = CurrentDeclContext = nullptr;
332 Info.Prune = InImportedModule;
333 if (DIE.hasChildren())
334 for (auto Child : DIE.children())
335 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
336 StringPool, Contexts, ModulesEndOffset,
337 ParseableSwiftInterfaces, ReportWarning,
338 InImportedModule);
340 // Prune this DIE if it is either a forward declaration inside a
341 // DW_TAG_module or a DW_TAG_module that contains nothing but
342 // forward declarations.
343 Info.Prune &= (DIE.getTag() == dwarf::DW_TAG_module) ||
344 (isTypeTag(DIE.getTag()) &&
345 dwarf::toUnsigned(DIE.find(dwarf::DW_AT_declaration), 0));
347 // Only prune forward declarations inside a DW_TAG_module for which a
348 // definition exists elsewhere.
349 if (ModulesEndOffset == 0)
350 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
351 else
352 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
353 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
355 return Info.Prune;
356 } // namespace dsymutil
358 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
359 switch (Tag) {
360 default:
361 return false;
362 case dwarf::DW_TAG_subprogram:
363 case dwarf::DW_TAG_lexical_block:
364 case dwarf::DW_TAG_subroutine_type:
365 case dwarf::DW_TAG_structure_type:
366 case dwarf::DW_TAG_class_type:
367 case dwarf::DW_TAG_union_type:
368 return true;
370 llvm_unreachable("Invalid Tag");
373 void DwarfLinker::startDebugObject(LinkContext &Context) {
374 // Iterate over the debug map entries and put all the ones that are
375 // functions (because they have a size) into the Ranges map. This map is
376 // very similar to the FunctionRanges that are stored in each unit, with 2
377 // notable differences:
379 // 1. Obviously this one is global, while the other ones are per-unit.
381 // 2. This one contains not only the functions described in the DIE
382 // tree, but also the ones that are only in the debug map.
384 // The latter information is required to reproduce dsymutil's logic while
385 // linking line tables. The cases where this information matters look like
386 // bugs that need to be investigated, but for now we need to reproduce
387 // dsymutil's behavior.
388 // FIXME: Once we understood exactly if that information is needed,
389 // maybe totally remove this (or try to use it to do a real
390 // -gline-tables-only on Darwin.
391 for (const auto &Entry : Context.DMO.symbols()) {
392 const auto &Mapping = Entry.getValue();
393 if (Mapping.Size && Mapping.ObjectAddress)
394 Context.Ranges[*Mapping.ObjectAddress] = DebugMapObjectRange(
395 *Mapping.ObjectAddress + Mapping.Size,
396 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
400 void DwarfLinker::endDebugObject(LinkContext &Context) {
401 Context.Clear();
403 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
404 (*I)->~DIEBlock();
405 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
406 (*I)->~DIELoc();
408 DIEBlocks.clear();
409 DIELocs.clear();
410 DIEAlloc.Reset();
413 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
414 switch (Arch) {
415 case Triple::x86:
416 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
417 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
418 case Triple::x86_64:
419 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
420 case Triple::arm:
421 case Triple::thumb:
422 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
423 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
424 RelocType == MachO::ARM_RELOC_HALF ||
425 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
426 case Triple::aarch64:
427 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
428 default:
429 return false;
433 /// Iterate over the relocations of the given \p Section and
434 /// store the ones that correspond to debug map entries into the
435 /// ValidRelocs array.
436 void DwarfLinker::RelocationManager::findValidRelocsMachO(
437 const object::SectionRef &Section, const object::MachOObjectFile &Obj,
438 const DebugMapObject &DMO) {
439 Expected<StringRef> ContentsOrErr = Section.getContents();
440 if (!ContentsOrErr) {
441 consumeError(ContentsOrErr.takeError());
442 Linker.reportWarning("error reading section", DMO);
443 return;
445 DataExtractor Data(*ContentsOrErr, Obj.isLittleEndian(), 0);
446 bool SkipNext = false;
448 for (const object::RelocationRef &Reloc : Section.relocations()) {
449 if (SkipNext) {
450 SkipNext = false;
451 continue;
454 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
455 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
457 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
458 Obj.getArch())) {
459 SkipNext = true;
460 Linker.reportWarning("unsupported relocation in debug_info section.",
461 DMO);
462 continue;
465 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
466 uint64_t Offset64 = Reloc.getOffset();
467 if ((RelocSize != 4 && RelocSize != 8)) {
468 Linker.reportWarning("unsupported relocation in debug_info section.",
469 DMO);
470 continue;
472 uint32_t Offset = Offset64;
473 // Mach-o uses REL relocations, the addend is at the relocation offset.
474 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
475 uint64_t SymAddress;
476 int64_t SymOffset;
478 if (Obj.isRelocationScattered(MachOReloc)) {
479 // The address of the base symbol for scattered relocations is
480 // stored in the reloc itself. The actual addend will store the
481 // base address plus the offset.
482 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
483 SymOffset = int64_t(Addend) - SymAddress;
484 } else {
485 SymAddress = Addend;
486 SymOffset = 0;
489 auto Sym = Reloc.getSymbol();
490 if (Sym != Obj.symbol_end()) {
491 Expected<StringRef> SymbolName = Sym->getName();
492 if (!SymbolName) {
493 consumeError(SymbolName.takeError());
494 Linker.reportWarning("error getting relocation symbol name.", DMO);
495 continue;
497 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
498 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
499 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
500 // Do not store the addend. The addend was the address of the symbol in
501 // the object file, the address in the binary that is stored in the debug
502 // map doesn't need to be offset.
503 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
508 /// Dispatch the valid relocation finding logic to the
509 /// appropriate handler depending on the object file format.
510 bool DwarfLinker::RelocationManager::findValidRelocs(
511 const object::SectionRef &Section, const object::ObjectFile &Obj,
512 const DebugMapObject &DMO) {
513 // Dispatch to the right handler depending on the file type.
514 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
515 findValidRelocsMachO(Section, *MachOObj, DMO);
516 else
517 Linker.reportWarning(
518 Twine("unsupported object file type: ") + Obj.getFileName(), DMO);
520 if (ValidRelocs.empty())
521 return false;
523 // Sort the relocations by offset. We will walk the DIEs linearly in
524 // the file, this allows us to just keep an index in the relocation
525 // array that we advance during our walk, rather than resorting to
526 // some associative container. See DwarfLinker::NextValidReloc.
527 llvm::sort(ValidRelocs);
528 return true;
531 /// Look for relocations in the debug_info section that match
532 /// entries in the debug map. These relocations will drive the Dwarf
533 /// link by indicating which DIEs refer to symbols present in the
534 /// linked binary.
535 /// \returns whether there are any valid relocations in the debug info.
536 bool DwarfLinker::RelocationManager::findValidRelocsInDebugInfo(
537 const object::ObjectFile &Obj, const DebugMapObject &DMO) {
538 // Find the debug_info section.
539 for (const object::SectionRef &Section : Obj.sections()) {
540 StringRef SectionName;
541 Section.getName(SectionName);
542 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
543 if (SectionName != "debug_info")
544 continue;
545 return findValidRelocs(Section, Obj, DMO);
547 return false;
550 /// Checks that there is a relocation against an actual debug
551 /// map entry between \p StartOffset and \p NextOffset.
553 /// This function must be called with offsets in strictly ascending
554 /// order because it never looks back at relocations it already 'went past'.
555 /// \returns true and sets Info.InDebugMap if it is the case.
556 bool DwarfLinker::RelocationManager::hasValidRelocation(
557 uint32_t StartOffset, uint32_t EndOffset, CompileUnit::DIEInfo &Info) {
558 assert(NextValidReloc == 0 ||
559 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
560 if (NextValidReloc >= ValidRelocs.size())
561 return false;
563 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
565 // We might need to skip some relocs that we didn't consider. For
566 // example the high_pc of a discarded DIE might contain a reloc that
567 // is in the list because it actually corresponds to the start of a
568 // function that is in the debug map.
569 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
570 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
572 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
573 return false;
575 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
576 const auto &Mapping = ValidReloc.Mapping->getValue();
577 uint64_t ObjectAddress = Mapping.ObjectAddress
578 ? uint64_t(*Mapping.ObjectAddress)
579 : std::numeric_limits<uint64_t>::max();
580 if (Linker.Options.Verbose)
581 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
582 << " "
583 << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
584 uint64_t(Mapping.BinaryAddress));
586 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
587 if (Mapping.ObjectAddress)
588 Info.AddrAdjust -= ObjectAddress;
589 Info.InDebugMap = true;
590 return true;
593 /// Get the starting and ending (exclusive) offset for the
594 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
595 /// supposed to point to the position of the first attribute described
596 /// by \p Abbrev.
597 /// \return [StartOffset, EndOffset) as a pair.
598 static std::pair<uint32_t, uint32_t>
599 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
600 unsigned Offset, const DWARFUnit &Unit) {
601 DataExtractor Data = Unit.getDebugInfoExtractor();
603 for (unsigned i = 0; i < Idx; ++i)
604 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset,
605 Unit.getFormParams());
607 uint32_t End = Offset;
608 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End,
609 Unit.getFormParams());
611 return std::make_pair(Offset, End);
614 /// Check if a variable describing DIE should be kept.
615 /// \returns updated TraversalFlags.
616 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
617 const DWARFDie &DIE,
618 CompileUnit &Unit,
619 CompileUnit::DIEInfo &MyInfo,
620 unsigned Flags) {
621 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
623 // Global variables with constant value can always be kept.
624 if (!(Flags & TF_InFunctionScope) &&
625 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
626 MyInfo.InDebugMap = true;
627 return Flags | TF_Keep;
630 Optional<uint32_t> LocationIdx =
631 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
632 if (!LocationIdx)
633 return Flags;
635 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
636 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
637 uint32_t LocationOffset, LocationEndOffset;
638 std::tie(LocationOffset, LocationEndOffset) =
639 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
641 // See if there is a relocation to a valid debug map entry inside
642 // this variable's location. The order is important here. We want to
643 // always check in the variable has a valid relocation, so that the
644 // DIEInfo is filled. However, we don't want a static variable in a
645 // function to force us to keep the enclosing function.
646 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
647 (Flags & TF_InFunctionScope))
648 return Flags;
650 if (Options.Verbose) {
651 DIDumpOptions DumpOpts;
652 DumpOpts.ChildRecurseDepth = 0;
653 DumpOpts.Verbose = Options.Verbose;
654 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
657 return Flags | TF_Keep;
660 /// Check if a function describing DIE should be kept.
661 /// \returns updated TraversalFlags.
662 unsigned DwarfLinker::shouldKeepSubprogramDIE(
663 RelocationManager &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
664 const DebugMapObject &DMO, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
665 unsigned Flags) {
666 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
668 Flags |= TF_InFunctionScope;
670 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
671 if (!LowPcIdx)
672 return Flags;
674 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
675 DWARFUnit &OrigUnit = Unit.getOrigUnit();
676 uint32_t LowPcOffset, LowPcEndOffset;
677 std::tie(LowPcOffset, LowPcEndOffset) =
678 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
680 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
681 assert(LowPc.hasValue() && "low_pc attribute is not an address.");
682 if (!LowPc ||
683 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
684 return Flags;
686 if (Options.Verbose) {
687 DIDumpOptions DumpOpts;
688 DumpOpts.ChildRecurseDepth = 0;
689 DumpOpts.Verbose = Options.Verbose;
690 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
693 if (DIE.getTag() == dwarf::DW_TAG_label) {
694 if (Unit.hasLabelAt(*LowPc))
695 return Flags;
696 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
697 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
698 // generation bugs aside, this is really wrong in the case of labels, where
699 // a label marking the end of a function will have a PC == CU's high_pc.
700 if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
701 .getValueOr(UINT64_MAX) <= LowPc)
702 return Flags;
703 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
704 return Flags | TF_Keep;
707 Flags |= TF_Keep;
709 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
710 if (!HighPc) {
711 reportWarning("Function without high_pc. Range will be discarded.\n", DMO,
712 &DIE);
713 return Flags;
716 // Replace the debug map range with a more accurate one.
717 Ranges[*LowPc] = DebugMapObjectRange(*HighPc, MyInfo.AddrAdjust);
718 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
719 return Flags;
722 /// Check if a DIE should be kept.
723 /// \returns updated TraversalFlags.
724 unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
725 RangesTy &Ranges, const DWARFDie &DIE,
726 const DebugMapObject &DMO,
727 CompileUnit &Unit,
728 CompileUnit::DIEInfo &MyInfo,
729 unsigned Flags) {
730 switch (DIE.getTag()) {
731 case dwarf::DW_TAG_constant:
732 case dwarf::DW_TAG_variable:
733 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
734 case dwarf::DW_TAG_subprogram:
735 case dwarf::DW_TAG_label:
736 return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, DMO, Unit, MyInfo,
737 Flags);
738 case dwarf::DW_TAG_base_type:
739 // DWARF Expressions may reference basic types, but scanning them
740 // is expensive. Basic types are tiny, so just keep all of them.
741 case dwarf::DW_TAG_imported_module:
742 case dwarf::DW_TAG_imported_declaration:
743 case dwarf::DW_TAG_imported_unit:
744 // We always want to keep these.
745 return Flags | TF_Keep;
746 default:
747 break;
750 return Flags;
753 /// Mark the passed DIE as well as all the ones it depends on
754 /// as kept.
756 /// This function is called by lookForDIEsToKeep on DIEs that are
757 /// newly discovered to be needed in the link. It recursively calls
758 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
759 /// TraversalFlags to inform it that it's not doing the primary DIE
760 /// tree walk.
761 void DwarfLinker::keepDIEAndDependencies(
762 RelocationManager &RelocMgr, RangesTy &Ranges, const UnitListTy &Units,
763 const DWARFDie &Die, CompileUnit::DIEInfo &MyInfo,
764 const DebugMapObject &DMO, CompileUnit &CU, bool UseODR) {
765 DWARFUnit &Unit = CU.getOrigUnit();
766 MyInfo.Keep = true;
768 // We're looking for incomplete types.
769 MyInfo.Incomplete = Die.getTag() != dwarf::DW_TAG_subprogram &&
770 Die.getTag() != dwarf::DW_TAG_member &&
771 dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0);
773 // First mark all the parent chain as kept.
774 unsigned AncestorIdx = MyInfo.ParentIdx;
775 while (!CU.getInfo(AncestorIdx).Keep) {
776 unsigned ODRFlag = UseODR ? TF_ODR : 0;
777 lookForDIEsToKeep(RelocMgr, Ranges, Units, Unit.getDIEAtIndex(AncestorIdx),
778 DMO, CU,
779 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
780 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
783 // Then we need to mark all the DIEs referenced by this DIE's
784 // attributes as kept.
785 DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
786 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
787 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
789 // Mark all DIEs referenced through attributes as kept.
790 for (const auto &AttrSpec : Abbrev->attributes()) {
791 DWARFFormValue Val(AttrSpec.Form);
792 if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
793 AttrSpec.Attr == dwarf::DW_AT_sibling) {
794 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
795 Unit.getFormParams());
796 continue;
799 Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
800 CompileUnit *ReferencedCU;
801 if (auto RefDie =
802 resolveDIEReference(*this, DMO, Units, Val, Die, ReferencedCU)) {
803 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDie);
804 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
805 bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
806 Info.Ctxt->isDefinedInClangModule();
807 // If the referenced DIE has a DeclContext that has already been
808 // emitted, then do not keep the one in this CU. We'll link to
809 // the canonical DIE in cloneDieReferenceAttribute.
810 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
811 // be necessary and could be advantageously replaced by
812 // ReferencedCU->hasODR() && CU.hasODR().
813 // FIXME: compatibility with dsymutil-classic. There is no
814 // reason not to unique ref_addr references.
815 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseODR || IsModuleRef) &&
816 Info.Ctxt &&
817 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
818 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
819 continue;
821 // Keep a module forward declaration if there is no definition.
822 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
823 Info.Ctxt->getCanonicalDIEOffset()))
824 Info.Prune = false;
826 unsigned ODRFlag = UseODR ? TF_ODR : 0;
827 lookForDIEsToKeep(RelocMgr, Ranges, Units, RefDie, DMO, *ReferencedCU,
828 TF_Keep | TF_DependencyWalk | ODRFlag);
830 // The incomplete property is propagated if the current DIE is complete
831 // but references an incomplete DIE.
832 if (Info.Incomplete && !MyInfo.Incomplete &&
833 (Die.getTag() == dwarf::DW_TAG_typedef ||
834 Die.getTag() == dwarf::DW_TAG_member ||
835 Die.getTag() == dwarf::DW_TAG_reference_type ||
836 Die.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
837 Die.getTag() == dwarf::DW_TAG_pointer_type))
838 MyInfo.Incomplete = true;
843 namespace {
844 /// This class represents an item in the work list. In addition to it's obvious
845 /// purpose of representing the state associated with a particular run of the
846 /// work loop, it also serves as a marker to indicate that we should run the
847 /// "continuation" code.
849 /// Originally, the latter was lambda which allowed arbitrary code to be run.
850 /// Because we always need to run the exact same code, it made more sense to
851 /// use a boolean and repurpose the already existing DIE field.
852 struct WorklistItem {
853 DWARFDie Die;
854 unsigned Flags;
855 bool IsContinuation;
856 CompileUnit::DIEInfo *ChildInfo = nullptr;
858 /// Construct a classic worklist item.
859 WorklistItem(DWARFDie Die, unsigned Flags)
860 : Die(Die), Flags(Flags), IsContinuation(false){};
862 /// Creates a continuation marker.
863 WorklistItem(DWARFDie Die) : Die(Die), IsContinuation(true){};
865 } // namespace
867 // Helper that updates the completeness of the current DIE. It depends on the
868 // fact that the incompletness of its children is already computed.
869 static void updateIncompleteness(const DWARFDie &Die,
870 CompileUnit::DIEInfo &ChildInfo,
871 CompileUnit &CU) {
872 // Only propagate incomplete members.
873 if (Die.getTag() != dwarf::DW_TAG_structure_type &&
874 Die.getTag() != dwarf::DW_TAG_class_type)
875 return;
877 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
878 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
880 if (MyInfo.Incomplete)
881 return;
883 if (ChildInfo.Incomplete || ChildInfo.Prune)
884 MyInfo.Incomplete = true;
887 /// Recursively walk the \p DIE tree and look for DIEs to
888 /// keep. Store that information in \p CU's DIEInfo.
890 /// This function is the entry point of the DIE selection
891 /// algorithm. It is expected to walk the DIE tree in file order and
892 /// (though the mediation of its helper) call hasValidRelocation() on
893 /// each DIE that might be a 'root DIE' (See DwarfLinker class
894 /// comment).
895 /// While walking the dependencies of root DIEs, this function is
896 /// also called, but during these dependency walks the file order is
897 /// not respected. The TF_DependencyWalk flag tells us which kind of
898 /// traversal we are currently doing.
900 /// The return value indicates whether the DIE is incomplete.
901 void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
902 RangesTy &Ranges, const UnitListTy &Units,
903 const DWARFDie &Die,
904 const DebugMapObject &DMO, CompileUnit &CU,
905 unsigned Flags) {
906 // LIFO work list.
907 SmallVector<WorklistItem, 4> Worklist;
908 Worklist.emplace_back(Die, Flags);
910 while (!Worklist.empty()) {
911 WorklistItem Current = Worklist.back();
912 Worklist.pop_back();
914 if (Current.IsContinuation) {
915 updateIncompleteness(Current.Die, *Current.ChildInfo, CU);
916 continue;
919 unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
920 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
922 // At this point we are guaranteed to have a continuation marker before us
923 // in the worklist, except for the last DIE.
924 if (!Worklist.empty())
925 Worklist.back().ChildInfo = &MyInfo;
927 if (MyInfo.Prune)
928 continue;
930 // If the Keep flag is set, we are marking a required DIE's dependencies.
931 // If our target is already marked as kept, we're all set.
932 bool AlreadyKept = MyInfo.Keep;
933 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
934 continue;
936 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
937 // because it would screw up the relocation finding logic.
938 if (!(Current.Flags & TF_DependencyWalk))
939 Current.Flags = shouldKeepDIE(RelocMgr, Ranges, Current.Die, DMO, CU,
940 MyInfo, Current.Flags);
942 // If it is a newly kept DIE mark it as well as all its dependencies as
943 // kept.
944 if (!AlreadyKept && (Current.Flags & TF_Keep)) {
945 bool UseOdr = (Current.Flags & TF_DependencyWalk)
946 ? (Current.Flags & TF_ODR)
947 : CU.hasODR();
948 keepDIEAndDependencies(RelocMgr, Ranges, Units, Current.Die, MyInfo, DMO,
949 CU, UseOdr);
952 // The TF_ParentWalk flag tells us that we are currently walking up
953 // the parent chain of a required DIE, and we don't want to mark all
954 // the children of the parents as kept (consider for example a
955 // DW_TAG_namespace node in the parent chain). There are however a
956 // set of DIE types for which we want to ignore that directive and still
957 // walk their children.
958 if (dieNeedsChildrenToBeMeaningful(Current.Die.getTag()))
959 Current.Flags &= ~TF_ParentWalk;
961 if (!Current.Die.hasChildren() || (Current.Flags & TF_ParentWalk))
962 continue;
964 // Add children in reverse order to the worklist to effectively process
965 // them in order.
966 for (auto Child : reverse(Current.Die.children())) {
967 // Add continuation marker before every child to calculate incompleteness
968 // after the last child is processed. We can't store this information in
969 // the same item because we might have to process other continuations
970 // first.
971 Worklist.emplace_back(Current.Die);
972 Worklist.emplace_back(Child, Current.Flags);
977 /// Assign an abbreviation number to \p Abbrev.
979 /// Our DIEs get freed after every DebugMapObject has been processed,
980 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
981 /// the instances hold by the DIEs. When we encounter an abbreviation
982 /// that we don't know, we create a permanent copy of it.
983 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
984 // Check the set for priors.
985 FoldingSetNodeID ID;
986 Abbrev.Profile(ID);
987 void *InsertToken;
988 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
990 // If it's newly added.
991 if (InSet) {
992 // Assign existing abbreviation number.
993 Abbrev.setNumber(InSet->getNumber());
994 } else {
995 // Add to abbreviation list.
996 Abbreviations.push_back(
997 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
998 for (const auto &Attr : Abbrev.getData())
999 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1000 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
1001 // Assign the unique abbreviation number.
1002 Abbrev.setNumber(Abbreviations.size());
1003 Abbreviations.back()->setNumber(Abbreviations.size());
1007 unsigned DwarfLinker::DIECloner::cloneStringAttribute(
1008 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1009 const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
1010 // Switch everything to out of line strings.
1011 const char *String = *Val.getAsCString();
1012 auto StringEntry = StringPool.getEntry(String);
1014 // Update attributes info.
1015 if (AttrSpec.Attr == dwarf::DW_AT_name)
1016 Info.Name = StringEntry;
1017 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
1018 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
1019 Info.MangledName = StringEntry;
1021 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1022 DIEInteger(StringEntry.getOffset()));
1024 return 4;
1027 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
1028 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1029 unsigned AttrSize, const DWARFFormValue &Val, const DebugMapObject &DMO,
1030 CompileUnit &Unit) {
1031 const DWARFUnit &U = Unit.getOrigUnit();
1032 uint32_t Ref = *Val.getAsReference();
1033 DIE *NewRefDie = nullptr;
1034 CompileUnit *RefUnit = nullptr;
1035 DeclContext *Ctxt = nullptr;
1037 DWARFDie RefDie =
1038 resolveDIEReference(Linker, DMO, CompileUnits, Val, InputDIE, RefUnit);
1040 // If the referenced DIE is not found, drop the attribute.
1041 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
1042 return 0;
1044 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1045 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1047 // If we already have emitted an equivalent DeclContext, just point
1048 // at it.
1049 if (isODRAttribute(AttrSpec.Attr)) {
1050 Ctxt = RefInfo.Ctxt;
1051 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
1052 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
1053 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1054 dwarf::DW_FORM_ref_addr, Attr);
1055 return U.getRefAddrByteSize();
1059 if (!RefInfo.Clone) {
1060 assert(Ref > InputDIE.getOffset());
1061 // We haven't cloned this DIE yet. Just create an empty one and
1062 // store it. It'll get really cloned when we process it.
1063 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
1065 NewRefDie = RefInfo.Clone;
1067 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
1068 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
1069 // We cannot currently rely on a DIEEntry to emit ref_addr
1070 // references, because the implementation calls back to DwarfDebug
1071 // to find the unit offset. (We don't have a DwarfDebug)
1072 // FIXME: we should be able to design DIEEntry reliance on
1073 // DwarfDebug away.
1074 uint64_t Attr;
1075 if (Ref < InputDIE.getOffset()) {
1076 // We must have already cloned that DIE.
1077 uint32_t NewRefOffset =
1078 RefUnit->getStartOffset() + NewRefDie->getOffset();
1079 Attr = NewRefOffset;
1080 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1081 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
1082 } else {
1083 // A forward reference. Note and fixup later.
1084 Attr = 0xBADDEF;
1085 Unit.noteForwardReference(
1086 NewRefDie, RefUnit, Ctxt,
1087 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1088 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
1090 return U.getRefAddrByteSize();
1093 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1094 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1095 return AttrSize;
1098 void DwarfLinker::DIECloner::cloneExpression(
1099 DataExtractor &Data, DWARFExpression Expression, const DebugMapObject &DMO,
1100 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
1101 using Encoding = DWARFExpression::Operation::Encoding;
1103 uint32_t OpOffset = 0;
1104 for (auto &Op : Expression) {
1105 auto Description = Op.getDescription();
1106 // DW_OP_const_type is variable-length and has 3
1107 // operands. DWARFExpression thus far only supports 2.
1108 auto Op0 = Description.Op[0];
1109 auto Op1 = Description.Op[1];
1110 if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
1111 (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
1112 Linker.reportWarning("Unsupported DW_OP encoding.", DMO);
1114 if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
1115 (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
1116 // This code assumes that the other non-typeref operand fits into 1 byte.
1117 assert(OpOffset < Op.getEndOffset());
1118 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
1119 assert(ULEBsize <= 16);
1121 // Copy over the operation.
1122 OutputBuffer.push_back(Op.getCode());
1123 uint64_t RefOffset;
1124 if (Op1 == Encoding::SizeNA) {
1125 RefOffset = Op.getRawOperand(0);
1126 } else {
1127 OutputBuffer.push_back(Op.getRawOperand(0));
1128 RefOffset = Op.getRawOperand(1);
1130 auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
1131 uint32_t RefIdx = Unit.getOrigUnit().getDIEIndex(RefDie);
1132 CompileUnit::DIEInfo &Info = Unit.getInfo(RefIdx);
1133 uint32_t Offset = 0;
1134 if (DIE *Clone = Info.Clone)
1135 Offset = Clone->getOffset();
1136 else
1137 Linker.reportWarning("base type ref doesn't point to DW_TAG_base_type.",
1138 DMO);
1139 uint8_t ULEB[16];
1140 unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1141 if (RealSize > ULEBsize) {
1142 // Emit the generic type as a fallback.
1143 RealSize = encodeULEB128(0, ULEB, ULEBsize);
1144 Linker.reportWarning("base type ref doesn't fit.", DMO);
1146 assert(RealSize == ULEBsize && "padding failed");
1147 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1148 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1149 } else {
1150 // Copy over everything else unmodified.
1151 StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
1152 OutputBuffer.append(Bytes.begin(), Bytes.end());
1154 OpOffset = Op.getEndOffset();
1158 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(
1159 DIE &Die, const DebugMapObject &DMO, CompileUnit &Unit,
1160 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1161 bool IsLittleEndian) {
1162 DIEValueList *Attr;
1163 DIEValue Value;
1164 DIELoc *Loc = nullptr;
1165 DIEBlock *Block = nullptr;
1166 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1167 Loc = new (DIEAlloc) DIELoc;
1168 Linker.DIELocs.push_back(Loc);
1169 } else {
1170 Block = new (DIEAlloc) DIEBlock;
1171 Linker.DIEBlocks.push_back(Block);
1173 Attr = Loc ? static_cast<DIEValueList *>(Loc)
1174 : static_cast<DIEValueList *>(Block);
1176 if (Loc)
1177 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1178 dwarf::Form(AttrSpec.Form), Loc);
1179 else
1180 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1181 dwarf::Form(AttrSpec.Form), Block);
1183 // If the block is a DWARF Expression, clone it into the temporary
1184 // buffer using cloneExpression(), otherwise copy the data directly.
1185 SmallVector<uint8_t, 32> Buffer;
1186 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1187 if (DWARFAttribute::mayHaveLocationDescription(AttrSpec.Attr) &&
1188 (Val.isFormClass(DWARFFormValue::FC_Block) ||
1189 Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1190 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1191 DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1192 IsLittleEndian, OrigUnit.getAddressByteSize());
1193 DWARFExpression Expr(Data, OrigUnit.getVersion(),
1194 OrigUnit.getAddressByteSize());
1195 cloneExpression(Data, Expr, DMO, Unit, Buffer);
1196 Bytes = Buffer;
1198 for (auto Byte : Bytes)
1199 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1200 dwarf::DW_FORM_data1, DIEInteger(Byte));
1202 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1203 // the DIE class, this if could be replaced by
1204 // Attr->setSize(Bytes.size()).
1205 if (Linker.Streamer) {
1206 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
1207 if (Loc)
1208 Loc->ComputeSize(AsmPrinter);
1209 else
1210 Block->ComputeSize(AsmPrinter);
1212 Die.addValue(DIEAlloc, Value);
1213 return AttrSize;
1216 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
1217 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1218 const CompileUnit &Unit, AttributesInfo &Info) {
1219 uint64_t Addr = *Val.getAsAddress();
1221 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1222 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1223 Info.HasLowPc = true;
1224 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1225 dwarf::Form(AttrSpec.Form), DIEInteger(Addr));
1226 return Unit.getOrigUnit().getAddressByteSize();
1229 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1230 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1231 Die.getTag() == dwarf::DW_TAG_lexical_block)
1232 // The low_pc of a block or inline subroutine might get
1233 // relocated because it happens to match the low_pc of the
1234 // enclosing subprogram. To prevent issues with that, always use
1235 // the low_pc from the input DIE if relocations have been applied.
1236 Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1237 ? Info.OrigLowPc
1238 : Addr) +
1239 Info.PCOffset;
1240 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1241 Addr = Unit.getLowPc();
1242 if (Addr == std::numeric_limits<uint64_t>::max())
1243 return 0;
1245 Info.HasLowPc = true;
1246 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1247 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1248 if (uint64_t HighPc = Unit.getHighPc())
1249 Addr = HighPc;
1250 else
1251 return 0;
1252 } else
1253 // If we have a high_pc recorded for the input DIE, use
1254 // it. Otherwise (when no relocations where applied) just use the
1255 // one we just decoded.
1256 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1259 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1260 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
1261 return Unit.getOrigUnit().getAddressByteSize();
1264 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
1265 DIE &Die, const DWARFDie &InputDIE, const DebugMapObject &DMO,
1266 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1267 unsigned AttrSize, AttributesInfo &Info) {
1268 uint64_t Value;
1270 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1271 if (auto OptionalValue = Val.getAsUnsignedConstant())
1272 Value = *OptionalValue;
1273 else if (auto OptionalValue = Val.getAsSignedConstant())
1274 Value = *OptionalValue;
1275 else if (auto OptionalValue = Val.getAsSectionOffset())
1276 Value = *OptionalValue;
1277 else {
1278 Linker.reportWarning(
1279 "Unsupported scalar attribute form. Dropping attribute.", DMO,
1280 &InputDIE);
1281 return 0;
1283 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1284 Info.IsDeclaration = true;
1285 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1286 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1287 return AttrSize;
1290 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1291 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1292 if (Unit.getLowPc() == -1ULL)
1293 return 0;
1294 // Dwarf >= 4 high_pc is an size, not an address.
1295 Value = Unit.getHighPc() - Unit.getLowPc();
1296 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1297 Value = *Val.getAsSectionOffset();
1298 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1299 Value = *Val.getAsSignedConstant();
1300 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1301 Value = *OptionalValue;
1302 else {
1303 Linker.reportWarning(
1304 "Unsupported scalar attribute form. Dropping attribute.", DMO,
1305 &InputDIE);
1306 return 0;
1308 PatchLocation Patch =
1309 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1310 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1311 if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1312 Unit.noteRangeAttribute(Die, Patch);
1313 Info.HasRanges = true;
1316 // A more generic way to check for location attributes would be
1317 // nice, but it's very unlikely that any other attribute needs a
1318 // location list.
1319 // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1320 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1321 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1322 Unit.noteLocationAttribute(Patch, Info.PCOffset);
1323 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1324 Info.IsDeclaration = true;
1326 return AttrSize;
1329 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1330 /// value \p Val, and add it to \p Die.
1331 /// \returns the size of the cloned attribute.
1332 unsigned DwarfLinker::DIECloner::cloneAttribute(
1333 DIE &Die, const DWARFDie &InputDIE, const DebugMapObject &DMO,
1334 CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1335 const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1336 bool IsLittleEndian) {
1337 const DWARFUnit &U = Unit.getOrigUnit();
1339 switch (AttrSpec.Form) {
1340 case dwarf::DW_FORM_strp:
1341 case dwarf::DW_FORM_string:
1342 return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1343 case dwarf::DW_FORM_ref_addr:
1344 case dwarf::DW_FORM_ref1:
1345 case dwarf::DW_FORM_ref2:
1346 case dwarf::DW_FORM_ref4:
1347 case dwarf::DW_FORM_ref8:
1348 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1349 DMO, Unit);
1350 case dwarf::DW_FORM_block:
1351 case dwarf::DW_FORM_block1:
1352 case dwarf::DW_FORM_block2:
1353 case dwarf::DW_FORM_block4:
1354 case dwarf::DW_FORM_exprloc:
1355 return cloneBlockAttribute(Die, DMO, Unit, AttrSpec, Val, AttrSize,
1356 IsLittleEndian);
1357 case dwarf::DW_FORM_addr:
1358 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1359 case dwarf::DW_FORM_data1:
1360 case dwarf::DW_FORM_data2:
1361 case dwarf::DW_FORM_data4:
1362 case dwarf::DW_FORM_data8:
1363 case dwarf::DW_FORM_udata:
1364 case dwarf::DW_FORM_sdata:
1365 case dwarf::DW_FORM_sec_offset:
1366 case dwarf::DW_FORM_flag:
1367 case dwarf::DW_FORM_flag_present:
1368 return cloneScalarAttribute(Die, InputDIE, DMO, Unit, AttrSpec, Val,
1369 AttrSize, Info);
1370 default:
1371 Linker.reportWarning(
1372 "Unsupported attribute form in cloneAttribute. Dropping.", DMO,
1373 &InputDIE);
1376 return 0;
1379 /// Apply the valid relocations found by findValidRelocs() to
1380 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1381 /// in the debug_info section.
1383 /// Like for findValidRelocs(), this function must be called with
1384 /// monotonic \p BaseOffset values.
1386 /// \returns whether any reloc has been applied.
1387 bool DwarfLinker::RelocationManager::applyValidRelocs(
1388 MutableArrayRef<char> Data, uint32_t BaseOffset, bool IsLittleEndian) {
1389 assert((NextValidReloc == 0 ||
1390 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1391 "BaseOffset should only be increasing.");
1392 if (NextValidReloc >= ValidRelocs.size())
1393 return false;
1395 // Skip relocs that haven't been applied.
1396 while (NextValidReloc < ValidRelocs.size() &&
1397 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1398 ++NextValidReloc;
1400 bool Applied = false;
1401 uint64_t EndOffset = BaseOffset + Data.size();
1402 while (NextValidReloc < ValidRelocs.size() &&
1403 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1404 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1405 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1406 assert(ValidReloc.Offset - BaseOffset < Data.size());
1407 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1408 char Buf[8];
1409 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1410 Value += ValidReloc.Addend;
1411 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1412 unsigned Index = IsLittleEndian ? i : (ValidReloc.Size - i - 1);
1413 Buf[i] = uint8_t(Value >> (Index * 8));
1415 assert(ValidReloc.Size <= sizeof(Buf));
1416 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1417 Applied = true;
1420 return Applied;
1423 static bool isObjCSelector(StringRef Name) {
1424 return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1425 (Name[1] == '[');
1428 void DwarfLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1429 const DIE *Die,
1430 DwarfStringPoolEntryRef Name,
1431 OffsetsStringPool &StringPool,
1432 bool SkipPubSection) {
1433 assert(isObjCSelector(Name.getString()) && "not an objc selector");
1434 // Objective C method or class function.
1435 // "- [Class(Category) selector :withArg ...]"
1436 StringRef ClassNameStart(Name.getString().drop_front(2));
1437 size_t FirstSpace = ClassNameStart.find(' ');
1438 if (FirstSpace == StringRef::npos)
1439 return;
1441 StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1442 if (!SelectorStart.size())
1443 return;
1445 StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1446 Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1448 // Add an entry for the class name that points to this
1449 // method/class function.
1450 StringRef ClassName(ClassNameStart.data(), FirstSpace);
1451 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1453 if (ClassName[ClassName.size() - 1] == ')') {
1454 size_t OpenParens = ClassName.find('(');
1455 if (OpenParens != StringRef::npos) {
1456 StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1457 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1458 SkipPubSection);
1460 std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1461 // FIXME: The missing space here may be a bug, but
1462 // dsymutil-classic also does it this way.
1463 MethodNameNoCategory.append(SelectorStart);
1464 Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1465 SkipPubSection);
1470 static bool
1471 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1472 uint16_t Tag, bool InDebugMap, bool SkipPC,
1473 bool InFunctionScope) {
1474 switch (AttrSpec.Attr) {
1475 default:
1476 return false;
1477 case dwarf::DW_AT_low_pc:
1478 case dwarf::DW_AT_high_pc:
1479 case dwarf::DW_AT_ranges:
1480 return SkipPC;
1481 case dwarf::DW_AT_location:
1482 case dwarf::DW_AT_frame_base:
1483 // FIXME: for some reason dsymutil-classic keeps the location attributes
1484 // when they are of block type (i.e. not location lists). This is totally
1485 // wrong for globals where we will keep a wrong address. It is mostly
1486 // harmless for locals, but there is no point in keeping these anyway when
1487 // the function wasn't linked.
1488 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1489 !InDebugMap)) &&
1490 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1494 DIE *DwarfLinker::DIECloner::cloneDIE(
1495 const DWARFDie &InputDIE, const DebugMapObject &DMO, CompileUnit &Unit,
1496 OffsetsStringPool &StringPool, int64_t PCOffset, uint32_t OutOffset,
1497 unsigned Flags, bool IsLittleEndian, DIE *Die) {
1498 DWARFUnit &U = Unit.getOrigUnit();
1499 unsigned Idx = U.getDIEIndex(InputDIE);
1500 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1502 // Should the DIE appear in the output?
1503 if (!Unit.getInfo(Idx).Keep)
1504 return nullptr;
1506 uint32_t Offset = InputDIE.getOffset();
1507 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1508 if (!Die) {
1509 // The DIE might have been already created by a forward reference
1510 // (see cloneDieReferenceAttribute()).
1511 if (!Info.Clone)
1512 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1513 Die = Info.Clone;
1516 assert(Die->getTag() == InputDIE.getTag());
1517 Die->setOffset(OutOffset);
1518 if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
1519 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
1520 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
1521 !Info.Ctxt->getCanonicalDIEOffset()) {
1522 // We are about to emit a DIE that is the root of its own valid
1523 // DeclContext tree. Make the current offset the canonical offset
1524 // for this context.
1525 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1528 // Extract and clone every attribute.
1529 DWARFDataExtractor Data = U.getDebugInfoExtractor();
1530 // Point to the next DIE (generally there is always at least a NULL
1531 // entry after the current one). If this is a lone
1532 // DW_TAG_compile_unit without any children, point to the next unit.
1533 uint32_t NextOffset = (Idx + 1 < U.getNumDIEs())
1534 ? U.getDIEAtIndex(Idx + 1).getOffset()
1535 : U.getNextUnitOffset();
1536 AttributesInfo AttrInfo;
1538 // We could copy the data only if we need to apply a relocation to it. After
1539 // testing, it seems there is no performance downside to doing the copy
1540 // unconditionally, and it makes the code simpler.
1541 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1542 Data =
1543 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1544 // Modify the copy with relocated addresses.
1545 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1546 // If we applied relocations, we store the value of high_pc that was
1547 // potentially stored in the input DIE. If high_pc is an address
1548 // (Dwarf version == 2), then it might have been relocated to a
1549 // totally unrelated value (because the end address in the object
1550 // file might be start address of another function which got moved
1551 // independently by the linker). The computation of the actual
1552 // high_pc value is done in cloneAddressAttribute().
1553 AttrInfo.OrigHighPc =
1554 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1555 // Also store the low_pc. It might get relocated in an
1556 // inline_subprogram that happens at the beginning of its
1557 // inlining function.
1558 AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1559 std::numeric_limits<uint64_t>::max());
1562 // Reset the Offset to 0 as we will be working on the local copy of
1563 // the data.
1564 Offset = 0;
1566 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1567 Offset += getULEB128Size(Abbrev->getCode());
1569 // We are entering a subprogram. Get and propagate the PCOffset.
1570 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1571 PCOffset = Info.AddrAdjust;
1572 AttrInfo.PCOffset = PCOffset;
1574 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1575 Flags |= TF_InFunctionScope;
1576 if (!Info.InDebugMap && LLVM_LIKELY(!Options.Update))
1577 Flags |= TF_SkipPC;
1580 bool Copied = false;
1581 for (const auto &AttrSpec : Abbrev->attributes()) {
1582 if (LLVM_LIKELY(!Options.Update) &&
1583 shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1584 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1585 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1586 U.getFormParams());
1587 // FIXME: dsymutil-classic keeps the old abbreviation around
1588 // even if it's not used. We can remove this (and the copyAbbrev
1589 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
1590 if (!Copied) {
1591 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
1592 Copied = true;
1594 continue;
1597 DWARFFormValue Val(AttrSpec.Form);
1598 uint32_t AttrSize = Offset;
1599 Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1600 AttrSize = Offset - AttrSize;
1602 OutOffset += cloneAttribute(*Die, InputDIE, DMO, Unit, StringPool, Val,
1603 AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
1606 // Look for accelerator entries.
1607 uint16_t Tag = InputDIE.getTag();
1608 // FIXME: This is slightly wrong. An inline_subroutine without a
1609 // low_pc, but with AT_ranges might be interesting to get into the
1610 // accelerator tables too. For now stick with dsymutil's behavior.
1611 if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1612 Tag != dwarf::DW_TAG_compile_unit &&
1613 getDIENames(InputDIE, AttrInfo, StringPool,
1614 Tag != dwarf::DW_TAG_inlined_subroutine)) {
1615 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1616 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1617 Tag == dwarf::DW_TAG_inlined_subroutine);
1618 if (AttrInfo.Name) {
1619 if (AttrInfo.NameWithoutTemplate)
1620 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1621 /* SkipPubSection */ true);
1622 Unit.addNameAccelerator(Die, AttrInfo.Name,
1623 Tag == dwarf::DW_TAG_inlined_subroutine);
1625 if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
1626 addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
1627 /* SkipPubSection =*/true);
1629 } else if (Tag == dwarf::DW_TAG_namespace) {
1630 if (!AttrInfo.Name)
1631 AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
1632 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1633 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
1634 getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
1635 AttrInfo.Name.getString()[0]) {
1636 uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, DMO);
1637 uint64_t RuntimeLang =
1638 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1639 .getValueOr(0);
1640 bool ObjCClassIsImplementation =
1641 (RuntimeLang == dwarf::DW_LANG_ObjC ||
1642 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1643 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1644 .getValueOr(0);
1645 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1646 Hash);
1649 // Determine whether there are any children that we want to keep.
1650 bool HasChildren = false;
1651 for (auto Child : InputDIE.children()) {
1652 unsigned Idx = U.getDIEIndex(Child);
1653 if (Unit.getInfo(Idx).Keep) {
1654 HasChildren = true;
1655 break;
1659 DIEAbbrev NewAbbrev = Die->generateAbbrev();
1660 if (HasChildren)
1661 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1662 // Assign a permanent abbrev number
1663 Linker.AssignAbbrev(NewAbbrev);
1664 Die->setAbbrevNumber(NewAbbrev.getNumber());
1666 // Add the size of the abbreviation number to the output offset.
1667 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1669 if (!HasChildren) {
1670 // Update our size.
1671 Die->setSize(OutOffset - Die->getOffset());
1672 return Die;
1675 // Recursively clone children.
1676 for (auto Child : InputDIE.children()) {
1677 if (DIE *Clone = cloneDIE(Child, DMO, Unit, StringPool, PCOffset, OutOffset,
1678 Flags, IsLittleEndian)) {
1679 Die->addChild(Clone);
1680 OutOffset = Clone->getOffset() + Clone->getSize();
1684 // Account for the end of children marker.
1685 OutOffset += sizeof(int8_t);
1686 // Update our size.
1687 Die->setSize(OutOffset - Die->getOffset());
1688 return Die;
1691 /// Patch the input object file relevant debug_ranges entries
1692 /// and emit them in the output file. Update the relevant attributes
1693 /// to point at the new entries.
1694 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1695 DWARFContext &OrigDwarf,
1696 const DebugMapObject &DMO) const {
1697 DWARFDebugRangeList RangeList;
1698 const auto &FunctionRanges = Unit.getFunctionRanges();
1699 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1700 DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
1701 OrigDwarf.getDWARFObj().getRangeSection(),
1702 OrigDwarf.isLittleEndian(), AddressSize);
1703 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1704 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1705 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
1706 uint64_t OrigLowPc =
1707 dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
1708 // Ranges addresses are based on the unit's low_pc. Compute the
1709 // offset we need to apply to adapt to the new unit's low_pc.
1710 int64_t UnitPcOffset = 0;
1711 if (OrigLowPc != -1ULL)
1712 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1714 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1715 uint32_t Offset = RangeAttribute.get();
1716 RangeAttribute.set(Streamer->getRangesSectionSize());
1717 if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
1718 llvm::consumeError(std::move(E));
1719 reportWarning("invalid range list ignored.", DMO);
1720 RangeList.clear();
1722 const auto &Entries = RangeList.getEntries();
1723 if (!Entries.empty()) {
1724 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1726 if (CurrRange == InvalidRange ||
1727 First.StartAddress + OrigLowPc < CurrRange.start() ||
1728 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
1729 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1730 if (CurrRange == InvalidRange ||
1731 CurrRange.start() > First.StartAddress + OrigLowPc) {
1732 reportWarning("no mapping for range.", DMO);
1733 continue;
1738 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
1739 AddressSize);
1743 /// Generate the debug_aranges entries for \p Unit and if the
1744 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1745 /// contribution for this attribute.
1746 /// FIXME: this could actually be done right in patchRangesForUnit,
1747 /// but for the sake of initial bit-for-bit compatibility with legacy
1748 /// dsymutil, we have to do it in a delayed pass.
1749 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
1750 auto Attr = Unit.getUnitRangesAttribute();
1751 if (Attr)
1752 Attr->set(Streamer->getRangesSectionSize());
1753 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
1756 /// Insert the new line info sequence \p Seq into the current
1757 /// set of already linked line info \p Rows.
1758 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1759 std::vector<DWARFDebugLine::Row> &Rows) {
1760 if (Seq.empty())
1761 return;
1763 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1764 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
1765 Seq.clear();
1766 return;
1769 auto InsertPoint = std::lower_bound(
1770 Rows.begin(), Rows.end(), Seq.front(),
1771 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
1772 return LHS.Address < RHS.Address;
1775 // FIXME: this only removes the unneeded end_sequence if the
1776 // sequences have been inserted in order. Using a global sort like
1777 // described in patchLineTableForUnit() and delaying the end_sequene
1778 // elimination to emitLineTableForUnit() we can get rid of all of them.
1779 if (InsertPoint != Rows.end() &&
1780 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
1781 *InsertPoint = Seq.front();
1782 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1783 } else {
1784 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1787 Seq.clear();
1790 static void patchStmtList(DIE &Die, DIEInteger Offset) {
1791 for (auto &V : Die.values())
1792 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1793 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
1794 return;
1797 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1800 /// Extract the line table for \p Unit from \p OrigDwarf, and
1801 /// recreate a relocated version of these for the address ranges that
1802 /// are present in the binary.
1803 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
1804 DWARFContext &OrigDwarf,
1805 RangesTy &Ranges,
1806 const DebugMapObject &DMO) {
1807 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
1808 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1809 if (!StmtList)
1810 return;
1812 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1813 if (auto *OutputDIE = Unit.getOutputUnitDIE())
1814 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
1816 // Parse the original line info for the unit.
1817 DWARFDebugLine::LineTable LineTable;
1818 uint32_t StmtOffset = *StmtList;
1819 DWARFDataExtractor LineExtractor(
1820 OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
1821 OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
1822 if (Options.Translator)
1823 return Streamer->translateLineTable(LineExtractor, StmtOffset);
1825 Error Err = LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
1826 &Unit.getOrigUnit(), DWARFContext::dumpWarning);
1827 DWARFContext::dumpWarning(std::move(Err));
1829 // This vector is the output line table.
1830 std::vector<DWARFDebugLine::Row> NewRows;
1831 NewRows.reserve(LineTable.Rows.size());
1833 // Current sequence of rows being extracted, before being inserted
1834 // in NewRows.
1835 std::vector<DWARFDebugLine::Row> Seq;
1836 const auto &FunctionRanges = Unit.getFunctionRanges();
1837 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1839 // FIXME: This logic is meant to generate exactly the same output as
1840 // Darwin's classic dsymutil. There is a nicer way to implement this
1841 // by simply putting all the relocated line info in NewRows and simply
1842 // sorting NewRows before passing it to emitLineTableForUnit. This
1843 // should be correct as sequences for a function should stay
1844 // together in the sorted output. There are a few corner cases that
1845 // look suspicious though, and that required to implement the logic
1846 // this way. Revisit that once initial validation is finished.
1848 // Iterate over the object file line info and extract the sequences
1849 // that correspond to linked functions.
1850 for (auto &Row : LineTable.Rows) {
1851 // Check whether we stepped out of the range. The range is
1852 // half-open, but consider accept the end address of the range if
1853 // it is marked as end_sequence in the input (because in that
1854 // case, the relocation offset is accurate and that entry won't
1855 // serve as the start of another function).
1856 if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
1857 Row.Address.Address > CurrRange.stop() ||
1858 (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
1859 // We just stepped out of a known range. Insert a end_sequence
1860 // corresponding to the end of the range.
1861 uint64_t StopAddress = CurrRange != InvalidRange
1862 ? CurrRange.stop() + CurrRange.value()
1863 : -1ULL;
1864 CurrRange = FunctionRanges.find(Row.Address.Address);
1865 bool CurrRangeValid =
1866 CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
1867 if (!CurrRangeValid) {
1868 CurrRange = InvalidRange;
1869 if (StopAddress != -1ULL) {
1870 // Try harder by looking in the DebugMapObject function
1871 // ranges map. There are corner cases where this finds a
1872 // valid entry. It's unclear if this is right or wrong, but
1873 // for now do as dsymutil.
1874 // FIXME: Understand exactly what cases this addresses and
1875 // potentially remove it along with the Ranges map.
1876 auto Range = Ranges.lower_bound(Row.Address.Address);
1877 if (Range != Ranges.begin() && Range != Ranges.end())
1878 --Range;
1880 if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
1881 Range->second.HighPC >= Row.Address.Address) {
1882 StopAddress = Row.Address.Address + Range->second.Offset;
1886 if (StopAddress != -1ULL && !Seq.empty()) {
1887 // Insert end sequence row with the computed end address, but
1888 // the same line as the previous one.
1889 auto NextLine = Seq.back();
1890 NextLine.Address.Address = StopAddress;
1891 NextLine.EndSequence = 1;
1892 NextLine.PrologueEnd = 0;
1893 NextLine.BasicBlock = 0;
1894 NextLine.EpilogueBegin = 0;
1895 Seq.push_back(NextLine);
1896 insertLineSequence(Seq, NewRows);
1899 if (!CurrRangeValid)
1900 continue;
1903 // Ignore empty sequences.
1904 if (Row.EndSequence && Seq.empty())
1905 continue;
1907 // Relocate row address and add it to the current sequence.
1908 Row.Address.Address += CurrRange.value();
1909 Seq.emplace_back(Row);
1911 if (Row.EndSequence)
1912 insertLineSequence(Seq, NewRows);
1915 // Finished extracting, now emit the line tables.
1916 // FIXME: LLVM hard-codes its prologue values. We just copy the
1917 // prologue over and that works because we act as both producer and
1918 // consumer. It would be nicer to have a real configurable line
1919 // table emitter.
1920 if (LineTable.Prologue.getVersion() < 2 ||
1921 LineTable.Prologue.getVersion() > 5 ||
1922 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
1923 LineTable.Prologue.OpcodeBase > 13)
1924 reportWarning("line table parameters mismatch. Cannot emit.", DMO);
1925 else {
1926 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
1927 // DWARF v5 has an extra 2 bytes of information before the header_length
1928 // field.
1929 if (LineTable.Prologue.getVersion() == 5)
1930 PrologueEnd += 2;
1931 StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
1932 MCDwarfLineTableParams Params;
1933 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1934 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1935 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1936 Streamer->emitLineTableForUnit(Params,
1937 LineData.slice(*StmtList + 4, PrologueEnd),
1938 LineTable.Prologue.MinInstLength, NewRows,
1939 Unit.getOrigUnit().getAddressByteSize());
1943 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
1944 switch (Options.TheAccelTableKind) {
1945 case AccelTableKind::Apple:
1946 emitAppleAcceleratorEntriesForUnit(Unit);
1947 break;
1948 case AccelTableKind::Dwarf:
1949 emitDwarfAcceleratorEntriesForUnit(Unit);
1950 break;
1951 case AccelTableKind::Default:
1952 llvm_unreachable("The default must be updated to a concrete value.");
1953 break;
1957 void DwarfLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1958 // Add namespaces.
1959 for (const auto &Namespace : Unit.getNamespaces())
1960 AppleNamespaces.addName(Namespace.Name,
1961 Namespace.Die->getOffset() + Unit.getStartOffset());
1963 /// Add names.
1964 if (!Options.Minimize)
1965 Streamer->emitPubNamesForUnit(Unit);
1966 for (const auto &Pubname : Unit.getPubnames())
1967 AppleNames.addName(Pubname.Name,
1968 Pubname.Die->getOffset() + Unit.getStartOffset());
1970 /// Add types.
1971 if (!Options.Minimize)
1972 Streamer->emitPubTypesForUnit(Unit);
1973 for (const auto &Pubtype : Unit.getPubtypes())
1974 AppleTypes.addName(
1975 Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1976 Pubtype.Die->getTag(),
1977 Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1978 : 0,
1979 Pubtype.QualifiedNameHash);
1981 /// Add ObjC names.
1982 for (const auto &ObjC : Unit.getObjC())
1983 AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1986 void DwarfLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1987 for (const auto &Namespace : Unit.getNamespaces())
1988 DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1989 Namespace.Die->getTag(), Unit.getUniqueID());
1990 for (const auto &Pubname : Unit.getPubnames())
1991 DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1992 Pubname.Die->getTag(), Unit.getUniqueID());
1993 for (const auto &Pubtype : Unit.getPubtypes())
1994 DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
1995 Pubtype.Die->getTag(), Unit.getUniqueID());
1998 /// Read the frame info stored in the object, and emit the
1999 /// patched frame descriptions for the linked binary.
2001 /// This is actually pretty easy as the data of the CIEs and FDEs can
2002 /// be considered as black boxes and moved as is. The only thing to do
2003 /// is to patch the addresses in the headers.
2004 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2005 RangesTy &Ranges,
2006 DWARFContext &OrigDwarf,
2007 unsigned AddrSize) {
2008 StringRef FrameData = OrigDwarf.getDWARFObj().getDebugFrameSection();
2009 if (FrameData.empty())
2010 return;
2012 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2013 uint32_t InputOffset = 0;
2015 // Store the data of the CIEs defined in this object, keyed by their
2016 // offsets.
2017 DenseMap<uint32_t, StringRef> LocalCIES;
2019 while (Data.isValidOffset(InputOffset)) {
2020 uint32_t EntryOffset = InputOffset;
2021 uint32_t InitialLength = Data.getU32(&InputOffset);
2022 if (InitialLength == 0xFFFFFFFF)
2023 return reportWarning("Dwarf64 bits no supported", DMO);
2025 uint32_t CIEId = Data.getU32(&InputOffset);
2026 if (CIEId == 0xFFFFFFFF) {
2027 // This is a CIE, store it.
2028 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2029 LocalCIES[EntryOffset] = CIEData;
2030 // The -4 is to account for the CIEId we just read.
2031 InputOffset += InitialLength - 4;
2032 continue;
2035 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2037 // Some compilers seem to emit frame info that doesn't start at
2038 // the function entry point, thus we can't just lookup the address
2039 // in the debug map. Use the linker's range map to see if the FDE
2040 // describes something that we can relocate.
2041 auto Range = Ranges.upper_bound(Loc);
2042 if (Range != Ranges.begin())
2043 --Range;
2044 if (Range == Ranges.end() || Range->first > Loc ||
2045 Range->second.HighPC <= Loc) {
2046 // The +4 is to account for the size of the InitialLength field itself.
2047 InputOffset = EntryOffset + InitialLength + 4;
2048 continue;
2051 // This is an FDE, and we have a mapping.
2052 // Have we already emitted a corresponding CIE?
2053 StringRef CIEData = LocalCIES[CIEId];
2054 if (CIEData.empty())
2055 return reportWarning("Inconsistent debug_frame content. Dropping.", DMO);
2057 // Look if we already emitted a CIE that corresponds to the
2058 // referenced one (the CIE data is the key of that lookup).
2059 auto IteratorInserted = EmittedCIEs.insert(
2060 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2061 // If there is no CIE yet for this ID, emit it.
2062 if (IteratorInserted.second ||
2063 // FIXME: dsymutil-classic only caches the last used CIE for
2064 // reuse. Mimic that behavior for now. Just removing that
2065 // second half of the condition and the LastCIEOffset variable
2066 // makes the code DTRT.
2067 LastCIEOffset != IteratorInserted.first->getValue()) {
2068 LastCIEOffset = Streamer->getFrameSectionSize();
2069 IteratorInserted.first->getValue() = LastCIEOffset;
2070 Streamer->emitCIE(CIEData);
2073 // Emit the FDE with updated address and CIE pointer.
2074 // (4 + AddrSize) is the size of the CIEId + initial_location
2075 // fields that will get reconstructed by emitFDE().
2076 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2077 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2078 Loc + Range->second.Offset,
2079 FrameData.substr(InputOffset, FDERemainingBytes));
2080 InputOffset += FDERemainingBytes;
2084 void DwarfLinker::DIECloner::copyAbbrev(
2085 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
2086 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
2087 dwarf::Form(Abbrev.hasChildren()));
2089 for (const auto &Attr : Abbrev.attributes()) {
2090 uint16_t Form = Attr.Form;
2091 if (hasODR && isODRAttribute(Attr.Attr))
2092 Form = dwarf::DW_FORM_ref_addr;
2093 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
2096 Linker.AssignAbbrev(Copy);
2099 uint32_t
2100 DwarfLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE, CompileUnit &U,
2101 const DebugMapObject &DMO,
2102 int ChildRecurseDepth) {
2103 const char *Name = nullptr;
2104 DWARFUnit *OrigUnit = &U.getOrigUnit();
2105 CompileUnit *CU = &U;
2106 Optional<DWARFFormValue> Ref;
2108 while (1) {
2109 if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
2110 Name = CurrentName;
2112 if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
2113 !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
2114 break;
2116 if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
2117 break;
2119 CompileUnit *RefCU;
2120 if (auto RefDIE =
2121 resolveDIEReference(Linker, DMO, CompileUnits, *Ref, DIE, RefCU)) {
2122 CU = RefCU;
2123 OrigUnit = &RefCU->getOrigUnit();
2124 DIE = RefDIE;
2128 unsigned Idx = OrigUnit->getDIEIndex(DIE);
2129 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
2130 Name = "(anonymous namespace)";
2132 if (CU->getInfo(Idx).ParentIdx == 0 ||
2133 // FIXME: dsymutil-classic compatibility. Ignore modules.
2134 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
2135 dwarf::DW_TAG_module)
2136 return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
2138 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
2139 return djbHash(
2140 (Name ? Name : ""),
2141 djbHash((Name ? "::" : ""),
2142 hashFullyQualifiedName(Die, *CU, DMO, ++ChildRecurseDepth)));
2145 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
2146 auto DwoId = dwarf::toUnsigned(
2147 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2148 if (DwoId)
2149 return *DwoId;
2150 return 0;
2153 bool DwarfLinker::registerModuleReference(
2154 DWARFDie CUDie, const DWARFUnit &Unit, DebugMap &ModuleMap,
2155 const DebugMapObject &DMO, RangesTy &Ranges, OffsetsStringPool &StringPool,
2156 UniquingStringPool &UniquingStringPool, DeclContextTree &ODRContexts,
2157 uint64_t ModulesEndOffset, unsigned &UnitID, bool IsLittleEndian,
2158 unsigned Indent, bool Quiet) {
2159 std::string PCMfile = dwarf::toString(
2160 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2161 if (PCMfile.empty())
2162 return false;
2164 // Clang module DWARF skeleton CUs abuse this for the path to the module.
2165 uint64_t DwoId = getDwoId(CUDie, Unit);
2167 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2168 if (Name.empty()) {
2169 if (!Quiet)
2170 reportWarning("Anonymous module skeleton CU for " + PCMfile, DMO);
2171 return true;
2174 if (!Quiet && Options.Verbose) {
2175 outs().indent(Indent);
2176 outs() << "Found clang module reference " << PCMfile;
2179 auto Cached = ClangModules.find(PCMfile);
2180 if (Cached != ClangModules.end()) {
2181 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2182 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2183 // ASTFileSignatures will change randomly when a module is rebuilt.
2184 if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2185 reportWarning(Twine("hash mismatch: this object file was built against a "
2186 "different version of the module ") +
2187 PCMfile,
2188 DMO);
2189 if (!Quiet && Options.Verbose)
2190 outs() << " [cached].\n";
2191 return true;
2193 if (!Quiet && Options.Verbose)
2194 outs() << " ...\n";
2196 // Cyclic dependencies are disallowed by Clang, but we still
2197 // shouldn't run into an infinite loop, so mark it as processed now.
2198 ClangModules.insert({PCMfile, DwoId});
2200 if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, ModuleMap, DMO,
2201 Ranges, StringPool, UniquingStringPool,
2202 ODRContexts, ModulesEndOffset, UnitID,
2203 IsLittleEndian, Indent + 2, Quiet)) {
2204 consumeError(std::move(E));
2205 return false;
2207 return true;
2210 ErrorOr<const object::ObjectFile &>
2211 DwarfLinker::loadObject(const DebugMapObject &Obj, const DebugMap &Map) {
2212 auto ObjectEntry =
2213 BinHolder.getObjectEntry(Obj.getObjectFilename(), Obj.getTimestamp());
2214 if (!ObjectEntry) {
2215 auto Err = ObjectEntry.takeError();
2216 reportWarning(
2217 Twine(Obj.getObjectFilename()) + ": " + toString(std::move(Err)), Obj);
2218 return errorToErrorCode(std::move(Err));
2221 auto Object = ObjectEntry->getObject(Map.getTriple());
2222 if (!Object) {
2223 auto Err = Object.takeError();
2224 reportWarning(
2225 Twine(Obj.getObjectFilename()) + ": " + toString(std::move(Err)), Obj);
2226 return errorToErrorCode(std::move(Err));
2229 return *Object;
2232 Error DwarfLinker::loadClangModule(
2233 DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
2234 DebugMap &ModuleMap, const DebugMapObject &DMO, RangesTy &Ranges,
2235 OffsetsStringPool &StringPool, UniquingStringPool &UniquingStringPool,
2236 DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
2237 bool IsLittleEndian, unsigned Indent, bool Quiet) {
2238 /// Using a SmallString<0> because loadClangModule() is recursive.
2239 SmallString<0> Path(Options.PrependPath);
2240 if (sys::path::is_relative(Filename))
2241 resolveRelativeObjectPath(Path, CUDie);
2242 sys::path::append(Path, Filename);
2243 // Don't use the cached binary holder because we have no thread-safety
2244 // guarantee and the lifetime is limited.
2245 auto &Obj = ModuleMap.addDebugMapObject(
2246 Path, sys::TimePoint<std::chrono::seconds>(), MachO::N_OSO);
2247 auto ErrOrObj = loadObject(Obj, ModuleMap);
2248 if (!ErrOrObj) {
2249 // Try and emit more helpful warnings by applying some heuristics.
2250 StringRef ObjFile = DMO.getObjectFilename();
2251 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
2252 bool isArchive = ObjFile.endswith(")");
2253 if (isClangModule) {
2254 StringRef ModuleCacheDir = sys::path::parent_path(Path);
2255 if (sys::fs::exists(ModuleCacheDir)) {
2256 // If the module's parent directory exists, we assume that the module
2257 // cache has expired and was pruned by clang. A more adventurous
2258 // dsymutil would invoke clang to rebuild the module now.
2259 if (!ModuleCacheHintDisplayed) {
2260 WithColor::note() << "The clang module cache may have expired since "
2261 "this object file was built. Rebuilding the "
2262 "object file will rebuild the module cache.\n";
2263 ModuleCacheHintDisplayed = true;
2265 } else if (isArchive) {
2266 // If the module cache directory doesn't exist at all and the object
2267 // file is inside a static library, we assume that the static library
2268 // was built on a different machine. We don't want to discourage module
2269 // debugging for convenience libraries within a project though.
2270 if (!ArchiveHintDisplayed) {
2271 WithColor::note()
2272 << "Linking a static library that was built with "
2273 "-gmodules, but the module cache was not found. "
2274 "Redistributable static libraries should never be "
2275 "built with module debugging enabled. The debug "
2276 "experience will be degraded due to incomplete "
2277 "debug information.\n";
2278 ArchiveHintDisplayed = true;
2282 return Error::success();
2285 std::unique_ptr<CompileUnit> Unit;
2287 // Setup access to the debug info.
2288 auto DwarfContext = DWARFContext::create(*ErrOrObj);
2289 RelocationManager RelocMgr(*this);
2291 for (const auto &CU : DwarfContext->compile_units()) {
2292 updateDwarfVersion(CU->getVersion());
2293 // Recursively get all modules imported by this one.
2294 auto CUDie = CU->getUnitDIE(false);
2295 if (!CUDie)
2296 continue;
2297 if (!registerModuleReference(CUDie, *CU, ModuleMap, DMO, Ranges, StringPool,
2298 UniquingStringPool, ODRContexts,
2299 ModulesEndOffset, UnitID, IsLittleEndian,
2300 Indent, Quiet)) {
2301 if (Unit) {
2302 std::string Err =
2303 (Filename +
2304 ": Clang modules are expected to have exactly 1 compile unit.\n")
2305 .str();
2306 error(Err);
2307 return make_error<StringError>(Err, inconvertibleErrorCode());
2309 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2310 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2311 // ASTFileSignatures will change randomly when a module is rebuilt.
2312 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2313 if (PCMDwoId != DwoId) {
2314 if (!Quiet && Options.Verbose)
2315 reportWarning(
2316 Twine("hash mismatch: this object file was built against a "
2317 "different version of the module ") +
2318 Filename,
2319 DMO);
2320 // Update the cache entry with the DwoId of the module loaded from disk.
2321 ClangModules[Filename] = PCMDwoId;
2324 // Add this module.
2325 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2326 ModuleName);
2327 Unit->setHasInterestingContent();
2328 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(),
2329 UniquingStringPool, ODRContexts, ModulesEndOffset,
2330 ParseableSwiftInterfaces,
2331 [&](const Twine &Warning, const DWARFDie &DIE) {
2332 reportWarning(Warning, DMO, &DIE);
2334 // Keep everything.
2335 Unit->markEverythingAsKept();
2338 if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2339 return Error::success();
2340 if (!Quiet && Options.Verbose) {
2341 outs().indent(Indent);
2342 outs() << "cloning .debug_info from " << Filename << "\n";
2345 UnitListTy CompileUnits;
2346 CompileUnits.push_back(std::move(Unit));
2347 DIECloner(*this, RelocMgr, DIEAlloc, CompileUnits, Options)
2348 .cloneAllCompileUnits(*DwarfContext, DMO, Ranges, StringPool,
2349 IsLittleEndian);
2350 return Error::success();
2353 void DwarfLinker::DIECloner::cloneAllCompileUnits(
2354 DWARFContext &DwarfContext, const DebugMapObject &DMO, RangesTy &Ranges,
2355 OffsetsStringPool &StringPool, bool IsLittleEndian) {
2356 if (!Linker.Streamer)
2357 return;
2359 for (auto &CurrentUnit : CompileUnits) {
2360 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2361 CurrentUnit->setStartOffset(Linker.OutputDebugInfoSize);
2362 if (!InputDIE) {
2363 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
2364 continue;
2366 if (CurrentUnit->getInfo(0).Keep) {
2367 // Clone the InputDIE into your Unit DIE in our compile unit since it
2368 // already has a DIE inside of it.
2369 CurrentUnit->createOutputDIE();
2370 cloneDIE(InputDIE, DMO, *CurrentUnit, StringPool, 0 /* PC offset */,
2371 11 /* Unit Header size */, 0, IsLittleEndian,
2372 CurrentUnit->getOutputUnitDIE());
2375 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
2377 if (Linker.Options.NoOutput)
2378 continue;
2380 // FIXME: for compatibility with the classic dsymutil, we emit
2381 // an empty line table for the unit, even if the unit doesn't
2382 // actually exist in the DIE tree.
2383 if (LLVM_LIKELY(!Linker.Options.Update) || Linker.Options.Translator)
2384 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, Ranges, DMO);
2386 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2388 if (LLVM_UNLIKELY(Linker.Options.Update))
2389 continue;
2391 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, DMO);
2392 auto ProcessExpr = [&](StringRef Bytes, SmallVectorImpl<uint8_t> &Buffer) {
2393 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2394 DataExtractor Data(Bytes, IsLittleEndian, OrigUnit.getAddressByteSize());
2395 cloneExpression(Data,
2396 DWARFExpression(Data, OrigUnit.getVersion(),
2397 OrigUnit.getAddressByteSize()),
2398 DMO, *CurrentUnit, Buffer);
2400 Linker.Streamer->emitLocationsForUnit(*CurrentUnit, DwarfContext,
2401 ProcessExpr);
2404 if (Linker.Options.NoOutput)
2405 return;
2407 // Emit all the compile unit's debug information.
2408 for (auto &CurrentUnit : CompileUnits) {
2409 if (LLVM_LIKELY(!Linker.Options.Update))
2410 Linker.generateUnitRanges(*CurrentUnit);
2412 CurrentUnit->fixupForwardReferences();
2414 if (!CurrentUnit->getOutputUnitDIE())
2415 continue;
2417 Linker.Streamer->emitCompileUnitHeader(*CurrentUnit);
2418 Linker.Streamer->emitDIE(*CurrentUnit->getOutputUnitDIE());
2422 void DwarfLinker::updateAccelKind(DWARFContext &Dwarf) {
2423 if (Options.TheAccelTableKind != AccelTableKind::Default)
2424 return;
2426 auto &DwarfObj = Dwarf.getDWARFObj();
2428 if (!AtLeastOneDwarfAccelTable &&
2429 (!DwarfObj.getAppleNamesSection().Data.empty() ||
2430 !DwarfObj.getAppleTypesSection().Data.empty() ||
2431 !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2432 !DwarfObj.getAppleObjCSection().Data.empty())) {
2433 AtLeastOneAppleAccelTable = true;
2436 if (!AtLeastOneDwarfAccelTable &&
2437 !DwarfObj.getDebugNamesSection().Data.empty()) {
2438 AtLeastOneDwarfAccelTable = true;
2442 bool DwarfLinker::emitPaperTrailWarnings(const DebugMapObject &DMO,
2443 const DebugMap &Map,
2444 OffsetsStringPool &StringPool) {
2445 if (DMO.getWarnings().empty() || !DMO.empty())
2446 return false;
2448 Streamer->switchToDebugInfoSection(/* Version */ 2);
2449 DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2450 CUDie->setOffset(11);
2451 StringRef Producer = StringPool.internString("dsymutil");
2452 StringRef File = StringPool.internString(DMO.getObjectFilename());
2453 CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2454 DIEInteger(StringPool.getStringOffset(Producer)));
2455 DIEBlock *String = new (DIEAlloc) DIEBlock();
2456 DIEBlocks.push_back(String);
2457 for (auto &C : File)
2458 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2459 DIEInteger(C));
2460 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2461 DIEInteger(0));
2463 CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2464 for (const auto &Warning : DMO.getWarnings()) {
2465 DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2466 ConstDie.addValue(
2467 DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2468 DIEInteger(StringPool.getStringOffset("dsymutil_warning")));
2469 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2470 DIEInteger(1));
2471 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2472 DIEInteger(StringPool.getStringOffset(Warning)));
2474 unsigned Size = 4 /* FORM_strp */ + File.size() + 1 +
2475 DMO.getWarnings().size() * (4 + 1 + 4) +
2476 1 /* End of children */;
2477 DIEAbbrev Abbrev = CUDie->generateAbbrev();
2478 AssignAbbrev(Abbrev);
2479 CUDie->setAbbrevNumber(Abbrev.getNumber());
2480 Size += getULEB128Size(Abbrev.getNumber());
2481 // Abbreviation ordering needed for classic compatibility.
2482 for (auto &Child : CUDie->children()) {
2483 Abbrev = Child.generateAbbrev();
2484 AssignAbbrev(Abbrev);
2485 Child.setAbbrevNumber(Abbrev.getNumber());
2486 Size += getULEB128Size(Abbrev.getNumber());
2488 CUDie->setSize(Size);
2489 auto &Asm = Streamer->getAsmPrinter();
2490 Asm.emitInt32(11 + CUDie->getSize() - 4);
2491 Asm.emitInt16(2);
2492 Asm.emitInt32(0);
2493 Asm.emitInt8(Map.getTriple().isArch64Bit() ? 8 : 4);
2494 Streamer->emitDIE(*CUDie);
2495 OutputDebugInfoSize += 11 /* Header */ + Size;
2497 return true;
2500 static Error copySwiftInterfaces(
2501 const std::map<std::string, std::string> &ParseableSwiftInterfaces,
2502 StringRef Architecture, const LinkOptions &Options) {
2503 std::error_code EC;
2504 SmallString<128> InputPath;
2505 SmallString<128> Path;
2506 sys::path::append(Path, *Options.ResourceDir, "Swift", Architecture);
2507 if ((EC = sys::fs::create_directories(Path.str(), true,
2508 sys::fs::perms::all_all)))
2509 return make_error<StringError>(
2510 "cannot create directory: " + toString(errorCodeToError(EC)), EC);
2511 unsigned BaseLength = Path.size();
2513 for (auto &I : ParseableSwiftInterfaces) {
2514 StringRef ModuleName = I.first;
2515 StringRef InterfaceFile = I.second;
2516 if (!Options.PrependPath.empty()) {
2517 InputPath.clear();
2518 sys::path::append(InputPath, Options.PrependPath, InterfaceFile);
2519 InterfaceFile = InputPath;
2521 sys::path::append(Path, ModuleName);
2522 Path.append(".swiftinterface");
2523 if (Options.Verbose)
2524 outs() << "copy parseable Swift interface " << InterfaceFile << " -> "
2525 << Path.str() << '\n';
2527 // copy_file attempts an APFS clone first, so this should be cheap.
2528 if ((EC = sys::fs::copy_file(InterfaceFile, Path.str())))
2529 warn(Twine("cannot copy parseable Swift interface ") +
2530 InterfaceFile + ": " +
2531 toString(errorCodeToError(EC)));
2532 Path.resize(BaseLength);
2534 return Error::success();
2537 bool DwarfLinker::link(const DebugMap &Map) {
2538 if (!createStreamer(Map.getTriple(), OutFile))
2539 return false;
2541 // Size of the DIEs (and headers) generated for the linked output.
2542 OutputDebugInfoSize = 0;
2543 // A unique ID that identifies each compile unit.
2544 unsigned UnitID = 0;
2545 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
2547 // First populate the data structure we need for each iteration of the
2548 // parallel loop.
2549 unsigned NumObjects = Map.getNumberOfObjects();
2550 std::vector<LinkContext> ObjectContexts;
2551 ObjectContexts.reserve(NumObjects);
2552 for (const auto &Obj : Map.objects()) {
2553 ObjectContexts.emplace_back(Map, *this, *Obj.get());
2554 LinkContext &LC = ObjectContexts.back();
2555 if (LC.ObjectFile)
2556 updateAccelKind(*LC.DwarfContext);
2559 // This Dwarf string pool which is only used for uniquing. This one should
2560 // never be used for offsets as its not thread-safe or predictable.
2561 UniquingStringPool UniquingStringPool;
2563 // This Dwarf string pool which is used for emission. It must be used
2564 // serially as the order of calling getStringOffset matters for
2565 // reproducibility.
2566 OffsetsStringPool OffsetsStringPool(Options.Translator);
2568 // ODR Contexts for the link.
2569 DeclContextTree ODRContexts;
2571 // If we haven't decided on an accelerator table kind yet, we base ourselves
2572 // on the DWARF we have seen so far. At this point we haven't pulled in debug
2573 // information from modules yet, so it is technically possible that they
2574 // would affect the decision. However, as they're built with the same
2575 // compiler and flags, it is safe to assume that they will follow the
2576 // decision made here.
2577 if (Options.TheAccelTableKind == AccelTableKind::Default) {
2578 if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2579 Options.TheAccelTableKind = AccelTableKind::Dwarf;
2580 else
2581 Options.TheAccelTableKind = AccelTableKind::Apple;
2584 for (LinkContext &LinkContext : ObjectContexts) {
2585 if (Options.Verbose)
2586 outs() << "DEBUG MAP OBJECT: " << LinkContext.DMO.getObjectFilename()
2587 << "\n";
2589 // N_AST objects (swiftmodule files) should get dumped directly into the
2590 // appropriate DWARF section.
2591 if (LinkContext.DMO.getType() == MachO::N_AST) {
2592 StringRef File = LinkContext.DMO.getObjectFilename();
2593 auto ErrorOrMem = MemoryBuffer::getFile(File);
2594 if (!ErrorOrMem) {
2595 warn("Could not open '" + File + "'\n");
2596 continue;
2598 sys::fs::file_status Stat;
2599 if (auto Err = sys::fs::status(File, Stat)) {
2600 warn(Err.message());
2601 continue;
2603 if (!Options.NoTimestamp) {
2604 // The modification can have sub-second precision so we need to cast
2605 // away the extra precision that's not present in the debug map.
2606 auto ModificationTime =
2607 std::chrono::time_point_cast<std::chrono::seconds>(
2608 Stat.getLastModificationTime());
2609 if (ModificationTime != LinkContext.DMO.getTimestamp()) {
2610 // Not using the helper here as we can easily stream TimePoint<>.
2611 WithColor::warning()
2612 << "Timestamp mismatch for " << File << ": "
2613 << Stat.getLastModificationTime() << " and "
2614 << sys::TimePoint<>(LinkContext.DMO.getTimestamp()) << "\n";
2615 continue;
2619 // Copy the module into the .swift_ast section.
2620 if (!Options.NoOutput)
2621 Streamer->emitSwiftAST((*ErrorOrMem)->getBuffer());
2622 continue;
2625 if (emitPaperTrailWarnings(LinkContext.DMO, Map, OffsetsStringPool))
2626 continue;
2628 if (!LinkContext.ObjectFile)
2629 continue;
2631 // Look for relocations that correspond to debug map entries.
2633 if (LLVM_LIKELY(!Options.Update) &&
2634 !LinkContext.RelocMgr.findValidRelocsInDebugInfo(
2635 *LinkContext.ObjectFile, LinkContext.DMO)) {
2636 if (Options.Verbose)
2637 outs() << "No valid relocations found. Skipping.\n";
2639 // Clear this ObjFile entry as a signal to other loops that we should not
2640 // process this iteration.
2641 LinkContext.ObjectFile = nullptr;
2642 continue;
2645 // Setup access to the debug info.
2646 if (!LinkContext.DwarfContext)
2647 continue;
2649 startDebugObject(LinkContext);
2651 // In a first phase, just read in the debug info and load all clang modules.
2652 LinkContext.CompileUnits.reserve(
2653 LinkContext.DwarfContext->getNumCompileUnits());
2655 for (const auto &CU : LinkContext.DwarfContext->compile_units()) {
2656 updateDwarfVersion(CU->getVersion());
2657 auto CUDie = CU->getUnitDIE(false);
2658 if (Options.Verbose) {
2659 outs() << "Input compilation unit:";
2660 DIDumpOptions DumpOpts;
2661 DumpOpts.ChildRecurseDepth = 0;
2662 DumpOpts.Verbose = Options.Verbose;
2663 CUDie.dump(outs(), 0, DumpOpts);
2665 if (CUDie && !LLVM_UNLIKELY(Options.Update))
2666 registerModuleReference(CUDie, *CU, ModuleMap, LinkContext.DMO,
2667 LinkContext.Ranges, OffsetsStringPool,
2668 UniquingStringPool, ODRContexts, 0, UnitID,
2669 LinkContext.DwarfContext->isLittleEndian());
2673 // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2674 if (MaxDwarfVersion == 0)
2675 MaxDwarfVersion = 3;
2677 // At this point we know how much data we have emitted. We use this value to
2678 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2679 // is already emitted, without being affected by canonical die offsets set
2680 // later. This prevents undeterminism when analyze and clone execute
2681 // concurrently, as clone set the canonical DIE offset and analyze reads it.
2682 const uint64_t ModulesEndOffset = OutputDebugInfoSize;
2684 // These variables manage the list of processed object files.
2685 // The mutex and condition variable are to ensure that this is thread safe.
2686 std::mutex ProcessedFilesMutex;
2687 std::condition_variable ProcessedFilesConditionVariable;
2688 BitVector ProcessedFiles(NumObjects, false);
2690 // Analyzing the context info is particularly expensive so it is executed in
2691 // parallel with emitting the previous compile unit.
2692 auto AnalyzeLambda = [&](size_t i) {
2693 auto &LinkContext = ObjectContexts[i];
2695 if (!LinkContext.ObjectFile || !LinkContext.DwarfContext)
2696 return;
2698 for (const auto &CU : LinkContext.DwarfContext->compile_units()) {
2699 updateDwarfVersion(CU->getVersion());
2700 // The !registerModuleReference() condition effectively skips
2701 // over fully resolved skeleton units. This second pass of
2702 // registerModuleReferences doesn't do any new work, but it
2703 // will collect top-level errors, which are suppressed. Module
2704 // warnings were already displayed in the first iteration.
2705 bool Quiet = true;
2706 auto CUDie = CU->getUnitDIE(false);
2707 if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
2708 !registerModuleReference(CUDie, *CU, ModuleMap, LinkContext.DMO,
2709 LinkContext.Ranges, OffsetsStringPool,
2710 UniquingStringPool, ODRContexts,
2711 ModulesEndOffset, UnitID, Quiet)) {
2712 LinkContext.CompileUnits.push_back(llvm::make_unique<CompileUnit>(
2713 *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2717 // Now build the DIE parent links that we will use during the next phase.
2718 for (auto &CurrentUnit : LinkContext.CompileUnits) {
2719 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2720 if (!CUDie)
2721 continue;
2722 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2723 *CurrentUnit, &ODRContexts.getRoot(),
2724 UniquingStringPool, ODRContexts, ModulesEndOffset,
2725 ParseableSwiftInterfaces,
2726 [&](const Twine &Warning, const DWARFDie &DIE) {
2727 reportWarning(Warning, LinkContext.DMO, &DIE);
2732 // And then the remaining work in serial again.
2733 // Note, although this loop runs in serial, it can run in parallel with
2734 // the analyzeContextInfo loop so long as we process files with indices >=
2735 // than those processed by analyzeContextInfo.
2736 auto CloneLambda = [&](size_t i) {
2737 auto &LinkContext = ObjectContexts[i];
2738 if (!LinkContext.ObjectFile)
2739 return;
2741 // Then mark all the DIEs that need to be present in the linked output
2742 // and collect some information about them.
2743 // Note that this loop can not be merged with the previous one because
2744 // cross-cu references require the ParentIdx to be setup for every CU in
2745 // the object file before calling this.
2746 if (LLVM_UNLIKELY(Options.Update)) {
2747 for (auto &CurrentUnit : LinkContext.CompileUnits)
2748 CurrentUnit->markEverythingAsKept();
2749 Streamer->copyInvariantDebugSection(*LinkContext.ObjectFile);
2750 } else {
2751 for (auto &CurrentUnit : LinkContext.CompileUnits)
2752 lookForDIEsToKeep(LinkContext.RelocMgr, LinkContext.Ranges,
2753 LinkContext.CompileUnits,
2754 CurrentUnit->getOrigUnit().getUnitDIE(),
2755 LinkContext.DMO, *CurrentUnit, 0);
2758 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2759 // array again (in the same way findValidRelocsInDebugInfo() did). We
2760 // need to reset the NextValidReloc index to the beginning.
2761 LinkContext.RelocMgr.resetValidRelocs();
2762 if (LinkContext.RelocMgr.hasValidRelocs() || LLVM_UNLIKELY(Options.Update))
2763 DIECloner(*this, LinkContext.RelocMgr, DIEAlloc, LinkContext.CompileUnits,
2764 Options)
2765 .cloneAllCompileUnits(*LinkContext.DwarfContext, LinkContext.DMO,
2766 LinkContext.Ranges, OffsetsStringPool,
2767 LinkContext.DwarfContext->isLittleEndian());
2768 if (!Options.NoOutput && !LinkContext.CompileUnits.empty() &&
2769 LLVM_LIKELY(!Options.Update))
2770 patchFrameInfoForObject(
2771 LinkContext.DMO, LinkContext.Ranges, *LinkContext.DwarfContext,
2772 LinkContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2774 // Clean-up before starting working on the next object.
2775 endDebugObject(LinkContext);
2778 auto EmitLambda = [&]() {
2779 // Emit everything that's global.
2780 if (!Options.NoOutput) {
2781 Streamer->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2782 Streamer->emitStrings(OffsetsStringPool);
2783 switch (Options.TheAccelTableKind) {
2784 case AccelTableKind::Apple:
2785 Streamer->emitAppleNames(AppleNames);
2786 Streamer->emitAppleNamespaces(AppleNamespaces);
2787 Streamer->emitAppleTypes(AppleTypes);
2788 Streamer->emitAppleObjc(AppleObjc);
2789 break;
2790 case AccelTableKind::Dwarf:
2791 Streamer->emitDebugNames(DebugNames);
2792 break;
2793 case AccelTableKind::Default:
2794 llvm_unreachable("Default should have already been resolved.");
2795 break;
2800 auto AnalyzeAll = [&]() {
2801 for (unsigned i = 0, e = NumObjects; i != e; ++i) {
2802 AnalyzeLambda(i);
2804 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2805 ProcessedFiles.set(i);
2806 ProcessedFilesConditionVariable.notify_one();
2810 auto CloneAll = [&]() {
2811 for (unsigned i = 0, e = NumObjects; i != e; ++i) {
2813 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2814 if (!ProcessedFiles[i]) {
2815 ProcessedFilesConditionVariable.wait(
2816 LockGuard, [&]() { return ProcessedFiles[i]; });
2820 CloneLambda(i);
2822 EmitLambda();
2825 // To limit memory usage in the single threaded case, analyze and clone are
2826 // run sequentially so the LinkContext is freed after processing each object
2827 // in endDebugObject.
2828 if (Options.Threads == 1) {
2829 for (unsigned i = 0, e = NumObjects; i != e; ++i) {
2830 AnalyzeLambda(i);
2831 CloneLambda(i);
2833 EmitLambda();
2834 } else {
2835 ThreadPool pool(2);
2836 pool.async(AnalyzeAll);
2837 pool.async(CloneAll);
2838 pool.wait();
2841 if (Options.NoOutput)
2842 return true;
2844 if (Options.ResourceDir && !ParseableSwiftInterfaces.empty()) {
2845 StringRef ArchName = Triple::getArchTypeName(Map.getTriple().getArch());
2846 if (auto E =
2847 copySwiftInterfaces(ParseableSwiftInterfaces, ArchName, Options))
2848 return error(toString(std::move(E)));
2851 return Streamer->finish(Map, Options.Translator);
2852 } // namespace dsymutil
2854 bool linkDwarf(raw_fd_ostream &OutFile, BinaryHolder &BinHolder,
2855 const DebugMap &DM, const LinkOptions &Options) {
2856 DwarfLinker Linker(OutFile, BinHolder, Options);
2857 return Linker.link(DM);
2860 } // namespace dsymutil
2861 } // namespace llvm