LLVM 23.0.0git
DWARFLinker.cpp
Go to the documentation of this file.
1//=== DWARFLinker.cpp -----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/BitVector.h"
12#include "llvm/ADT/STLExtras.h"
30#include "llvm/MC/MCDwarf.h"
32#include "llvm/Support/Error.h"
36#include "llvm/Support/LEB128.h"
37#include "llvm/Support/Path.h"
39#include <vector>
40
41namespace llvm {
42
43using namespace dwarf_linker;
44using namespace dwarf_linker::classic;
45
46/// Hold the input and output of the debug info size in bytes.
51
52/// Compute the total size of the debug info.
54 uint64_t Size = 0;
55 for (auto &Unit : Dwarf.compile_units()) {
56 Size += Unit->getLength();
57 }
58 return Size;
59}
60
61/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
62/// CompileUnit object instead.
64 auto CU = llvm::upper_bound(
65 Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
66 return LHS < RHS->getOrigUnit().getNextUnitOffset();
67 });
68 return CU != Units.end() ? CU->get() : nullptr;
69}
70
71/// Resolve the DIE attribute reference that has been extracted in \p RefValue.
72/// The resulting DIE might be in another CompileUnit which is stored into \p
73/// ReferencedCU. \returns null if resolving fails for any reason.
74DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
75 const UnitListTy &Units,
76 const DWARFFormValue &RefValue,
77 const DWARFDie &DIE,
78 CompileUnit *&RefCU) {
79 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
80 uint64_t RefOffset;
81 if (std::optional<uint64_t> Off = RefValue.getAsRelativeReference()) {
82 RefOffset = RefValue.getUnit()->getOffset() + *Off;
83 } else if (Off = RefValue.getAsDebugInfoReference(); Off) {
84 RefOffset = *Off;
85 } else {
86 reportWarning("Unsupported reference type", File, &DIE);
87 return DWARFDie();
88 }
89 if ((RefCU = getUnitForOffset(Units, RefOffset)))
90 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
91 // In a file with broken references, an attribute might point to a NULL
92 // DIE.
93 if (!RefDie.isNULL())
94 return RefDie;
95 }
96
97 reportWarning("could not find referenced DIE", File, &DIE);
98 return DWARFDie();
99}
100
101/// \returns whether the passed \a Attr type might contain a DIE reference
102/// suitable for ODR uniquing.
103static bool isODRAttribute(uint16_t Attr) {
104 switch (Attr) {
105 default:
106 return false;
107 case dwarf::DW_AT_type:
108 case dwarf::DW_AT_containing_type:
109 case dwarf::DW_AT_specification:
110 case dwarf::DW_AT_abstract_origin:
111 case dwarf::DW_AT_import:
112 case dwarf::DW_AT_LLVM_alloc_type:
113 return true;
114 }
115 llvm_unreachable("Improper attribute.");
116}
117
118static bool isTypeTag(uint16_t Tag) {
119 switch (Tag) {
120 case dwarf::DW_TAG_array_type:
121 case dwarf::DW_TAG_class_type:
122 case dwarf::DW_TAG_enumeration_type:
123 case dwarf::DW_TAG_pointer_type:
124 case dwarf::DW_TAG_reference_type:
125 case dwarf::DW_TAG_string_type:
126 case dwarf::DW_TAG_structure_type:
127 case dwarf::DW_TAG_subroutine_type:
128 case dwarf::DW_TAG_template_alias:
129 case dwarf::DW_TAG_typedef:
130 case dwarf::DW_TAG_union_type:
131 case dwarf::DW_TAG_ptr_to_member_type:
132 case dwarf::DW_TAG_set_type:
133 case dwarf::DW_TAG_subrange_type:
134 case dwarf::DW_TAG_base_type:
135 case dwarf::DW_TAG_const_type:
136 case dwarf::DW_TAG_constant:
137 case dwarf::DW_TAG_file_type:
138 case dwarf::DW_TAG_namelist:
139 case dwarf::DW_TAG_packed_type:
140 case dwarf::DW_TAG_volatile_type:
141 case dwarf::DW_TAG_restrict_type:
142 case dwarf::DW_TAG_atomic_type:
143 case dwarf::DW_TAG_interface_type:
144 case dwarf::DW_TAG_unspecified_type:
145 case dwarf::DW_TAG_shared_type:
146 case dwarf::DW_TAG_immutable_type:
147 return true;
148 default:
149 break;
150 }
151 return false;
152}
153
154/// Recurse through the input DIE's canonical references until we find a
155/// DW_AT_name.
157DWARFLinker::DIECloner::getCanonicalDIEName(DWARFDie Die, const DWARFFile &File,
158 CompileUnit *Unit) {
159 if (!Die)
160 return {};
161
162 std::optional<DWARFFormValue> Ref;
163
164 auto GetDieName = [](const DWARFDie &D) -> llvm::StringRef {
165 auto NameForm = D.find(llvm::dwarf::DW_AT_name);
166 if (!NameForm)
167 return {};
168
169 auto NameOrErr = NameForm->getAsCString();
170 if (!NameOrErr) {
171 llvm::consumeError(NameOrErr.takeError());
172 return {};
173 }
174
175 return *NameOrErr;
176 };
177
178 llvm::StringRef Name = GetDieName(Die);
179 if (!Name.empty())
180 return Name;
181
182 while (true) {
183 if (!(Ref = Die.find(llvm::dwarf::DW_AT_specification)) &&
184 !(Ref = Die.find(llvm::dwarf::DW_AT_abstract_origin)))
185 break;
186
187 Die = Linker.resolveDIEReference(File, CompileUnits, *Ref, Die, Unit);
188 if (!Die)
189 break;
190
191 assert(Unit);
192
193 unsigned SpecIdx = Unit->getOrigUnit().getDIEIndex(Die);
194 CompileUnit::DIEInfo &SpecInfo = Unit->getInfo(SpecIdx);
195 if (SpecInfo.Ctxt && SpecInfo.Ctxt->hasCanonicalDIE()) {
196 if (!SpecInfo.Ctxt->getCanonicalName().empty()) {
197 Name = SpecInfo.Ctxt->getCanonicalName();
198 break;
199 }
200 }
201
202 Name = GetDieName(Die);
203 if (!Name.empty())
204 break;
205 }
206
207 return Name;
208}
209
210bool DWARFLinker::DIECloner::getDIENames(
211 const DWARFDie &Die, AttributesInfo &Info, OffsetsStringPool &StringPool,
212 const DWARFFile &File, CompileUnit &Unit, bool StripTemplate) {
213 // This function will be called on DIEs having low_pcs and
214 // ranges. As getting the name might be more expansive, filter out
215 // blocks directly.
216 if (Die.getTag() == dwarf::DW_TAG_lexical_block)
217 return false;
218
219 // The mangled name of an specification DIE will by virtue of the
220 // uniquing algorithm be the same as the one it got uniqued into.
221 // So just use the input DIE's linkage name.
222 if (!Info.MangledName)
223 if (const char *MangledName = Die.getLinkageName())
224 Info.MangledName = StringPool.getEntry(MangledName);
225
226 // For subprograms with linkage names, we unique on the linkage name,
227 // so DW_AT_name's may differ between the input and canonical DIEs.
228 // Use the name of the canonical DIE.
229 if (!Info.Name)
230 if (llvm::StringRef Name = getCanonicalDIEName(Die, File, &Unit);
231 !Name.empty())
232 Info.Name = StringPool.getEntry(Name);
233
234 if (!Info.MangledName)
235 Info.MangledName = Info.Name;
236
237 if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
238 StringRef Name = Info.Name.getString();
239 if (std::optional<StringRef> StrippedName = StripTemplateParameters(Name))
240 Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
241 }
242
243 return Info.Name || Info.MangledName;
244}
245
246/// Resolve the relative path to a build artifact referenced by DWARF by
247/// applying DW_AT_comp_dir.
249 sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
250}
251
252/// Collect references to parseable Swift interfaces in imported
253/// DW_TAG_module blocks.
255 const DWARFDie &DIE, CompileUnit &CU,
256 DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces,
257 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
258 if (CU.getLanguage() != dwarf::DW_LANG_Swift)
259 return;
260
261 if (!ParseableSwiftInterfaces)
262 return;
263
264 StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
265 if (!Path.ends_with(".swiftinterface"))
266 return;
267 // Don't track interfaces that are part of the SDK.
268 StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
269 if (SysRoot.empty())
270 SysRoot = CU.getSysRoot();
271 if (!SysRoot.empty() && Path.starts_with(SysRoot))
272 return;
273 // Don't track interfaces that are part of the toolchain.
274 // For example: Swift, _Concurrency, ...
275 StringRef DeveloperDir = guessDeveloperDir(SysRoot);
276 if (!DeveloperDir.empty() && Path.starts_with(DeveloperDir))
277 return;
278 if (isInToolchainDir(Path))
279 return;
280 std::optional<const char *> Name =
281 dwarf::toString(DIE.find(dwarf::DW_AT_name));
282 if (!Name)
283 return;
284 auto &Entry = (*ParseableSwiftInterfaces)[*Name];
285 // The prepend path is applied later when copying.
286 DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
287 SmallString<128> ResolvedPath;
288 if (sys::path::is_relative(Path))
289 resolveRelativeObjectPath(ResolvedPath, CUDie);
290 sys::path::append(ResolvedPath, Path);
291 if (!Entry.empty() && Entry != ResolvedPath)
292 ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
293 *Name + ": " + Entry + " and " + Path,
294 DIE);
295 Entry = std::string(ResolvedPath);
296}
297
298/// The distinct types of work performed by the work loop in
299/// analyzeContextInfo.
305
306/// This class represents an item in the work list. The type defines what kind
307/// of work needs to be performed when processing the current item. Everything
308/// but the Type and Die fields are optional based on the type.
330
331static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
332 uint64_t ModulesEndOffset) {
333 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
334
335 // Prune this DIE if it is either a forward declaration inside a
336 // DW_TAG_module or a DW_TAG_module that contains nothing but
337 // forward declarations.
338 Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
339 (isTypeTag(Die.getTag()) &&
340 dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
341
342 // Only prune forward declarations inside a DW_TAG_module for which a
343 // definition exists elsewhere.
344 if (ModulesEndOffset == 0)
345 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
346 else
347 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
348 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
349
350 return Info.Prune;
351}
352
353static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
354 CompileUnit::DIEInfo &ChildInfo) {
355 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
356 Info.Prune &= ChildInfo.Prune;
357}
358
359/// Recursive helper to build the global DeclContext information and
360/// gather the child->parent relationships in the original compile unit.
361///
362/// This function uses the same work list approach as lookForDIEsToKeep.
363///
364/// \return true when this DIE and all of its children are only
365/// forward declarations to types defined in external clang modules
366/// (i.e., forward declarations that are children of a DW_TAG_module).
368 const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
369 DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
370 uint64_t ModulesEndOffset,
371 DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces,
372 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
373 // LIFO work list.
374 std::vector<ContextWorklistItem> Worklist;
375 Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, false);
376
377 while (!Worklist.empty()) {
378 ContextWorklistItem Current = Worklist.back();
379 Worklist.pop_back();
380
381 switch (Current.Type) {
383 updatePruning(Current.Die, CU, ModulesEndOffset);
384 continue;
386 updateChildPruning(Current.Die, CU, *Current.OtherInfo);
387 continue;
389 break;
390 }
391
392 unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
393 CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
394
395 // Clang imposes an ODR on modules(!) regardless of the language:
396 // "The module-id should consist of only a single identifier,
397 // which provides the name of the module being defined. Each
398 // module shall have a single definition."
399 //
400 // This does not extend to the types inside the modules:
401 // "[I]n C, this implies that if two structs are defined in
402 // different submodules with the same name, those two types are
403 // distinct types (but may be compatible types if their
404 // definitions match)."
405 //
406 // We treat non-C++ modules like namespaces for this reason.
407 if (Current.Die.getTag() == dwarf::DW_TAG_module &&
408 Current.ParentIdx == 0 &&
409 dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
410 CU.getClangModuleName()) {
411 Current.InImportedModule = true;
412 analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
413 ReportWarning);
414 }
415
416 Info.ParentIdx = Current.ParentIdx;
417 Info.InModuleScope = CU.isClangModule() || Current.InImportedModule;
418 if (CU.hasODR() || Info.InModuleScope) {
419 if (Current.Context) {
420 auto PtrInvalidPair = Contexts.getChildDeclContext(
421 *Current.Context, Current.Die, CU, Info.InModuleScope);
422 Current.Context = PtrInvalidPair.getPointer();
423 Info.Ctxt =
424 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
425 if (Info.Ctxt)
426 Info.Ctxt->setDefinedInClangModule(Info.InModuleScope);
427 } else
428 Info.Ctxt = Current.Context = nullptr;
429 }
430
431 Info.Prune = Current.InImportedModule;
432 // Add children in reverse order to the worklist to effectively process
433 // them in order.
434 Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
435 for (auto Child : reverse(Current.Die.children())) {
436 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
437 Worklist.emplace_back(
439 Worklist.emplace_back(Child, Current.Context, Idx,
440 Current.InImportedModule);
441 }
442 }
443}
444
446 switch (Tag) {
447 default:
448 return false;
449 case dwarf::DW_TAG_class_type:
450 case dwarf::DW_TAG_common_block:
451 case dwarf::DW_TAG_lexical_block:
452 case dwarf::DW_TAG_structure_type:
453 case dwarf::DW_TAG_subprogram:
454 case dwarf::DW_TAG_subroutine_type:
455 case dwarf::DW_TAG_union_type:
456 return true;
457 }
458 llvm_unreachable("Invalid Tag");
459}
460
461void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
462 Context.clear();
463
464 for (DIEBlock *I : DIEBlocks)
465 I->~DIEBlock();
466 for (DIELoc *I : DIELocs)
467 I->~DIELoc();
468
469 DIEBlocks.clear();
470 DIELocs.clear();
471 DIEAlloc.Reset();
472}
473
475 CompileUnit &Unit, const DWARFDebugLine::LineTable &LT,
476 DenseMap<uint64_t, uint64_t> &SeqOffToOrigRow) {
477 // Collect this unit's DW_AT_LLVM_stmt_sequence attribute values
478 // (input offsets), sorted ascending and deduplicated, to drive the
479 // shared mapping builder.
480 auto StmtAttrs = Unit.getStmtSeqListAttributes();
481 SmallVector<uint64_t> SortedOffsets;
482 SortedOffsets.reserve(StmtAttrs.size());
483 for (const PatchLocation &P : StmtAttrs)
484 SortedOffsets.push_back(P.get());
485 llvm::sort(SortedOffsets);
486 SortedOffsets.erase(llvm::unique(SortedOffsets), SortedOffsets.end());
487
489 SeqOffToOrigRow);
490}
491
492std::pair<bool, std::optional<int64_t>>
493DWARFLinker::getVariableRelocAdjustment(AddressesMap &RelocMgr,
494 const DWARFDie &DIE) {
495 assert((DIE.getTag() == dwarf::DW_TAG_variable ||
496 DIE.getTag() == dwarf::DW_TAG_constant) &&
497 "Wrong type of input die");
498
499 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
500
501 // Check if DIE has DW_AT_location attribute.
502 DWARFUnit *U = DIE.getDwarfUnit();
503 std::optional<uint32_t> LocationIdx =
504 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
505 if (!LocationIdx)
506 return std::make_pair(false, std::nullopt);
507
508 // Get offset to the DW_AT_location attribute.
509 uint64_t AttrOffset =
510 Abbrev->getAttributeOffsetFromIndex(*LocationIdx, DIE.getOffset(), *U);
511
512 // Get value of the DW_AT_location attribute.
513 std::optional<DWARFFormValue> LocationValue =
514 Abbrev->getAttributeValueFromOffset(*LocationIdx, AttrOffset, *U);
515 if (!LocationValue)
516 return std::make_pair(false, std::nullopt);
517
518 // Check that DW_AT_location attribute is of 'exprloc' class.
519 // Handling value of location expressions for attributes of 'loclist'
520 // class is not implemented yet.
521 std::optional<ArrayRef<uint8_t>> Expr = LocationValue->getAsBlock();
522 if (!Expr)
523 return std::make_pair(false, std::nullopt);
524
525 // Parse 'exprloc' expression.
526 DataExtractor Data(*Expr, U->getContext().isLittleEndian());
527 DWARFExpression Expression(Data, U->getAddressByteSize(),
528 U->getFormParams().Format);
529
530 bool HasLocationAddress = false;
531 uint64_t CurExprOffset = 0;
532 for (DWARFExpression::iterator It = Expression.begin();
533 It != Expression.end(); ++It) {
534 DWARFExpression::iterator NextIt = It;
535 ++NextIt;
536
537 const DWARFExpression::Operation &Op = *It;
538 switch (Op.getCode()) {
539 case dwarf::DW_OP_const2u:
540 case dwarf::DW_OP_const4u:
541 case dwarf::DW_OP_const8u:
542 case dwarf::DW_OP_const2s:
543 case dwarf::DW_OP_const4s:
544 case dwarf::DW_OP_const8s:
545 if (NextIt == Expression.end() ||
546 !dwarf::isTlsAddressOp(NextIt->getCode()))
547 break;
548 [[fallthrough]];
549 case dwarf::DW_OP_addr: {
550 HasLocationAddress = true;
551 // Check relocation for the address.
552 if (std::optional<int64_t> RelocAdjustment =
553 RelocMgr.getExprOpAddressRelocAdjustment(
554 *U, Op, AttrOffset + CurExprOffset,
555 AttrOffset + Op.getEndOffset(), Options.Verbose))
556 return std::make_pair(HasLocationAddress, *RelocAdjustment);
557 } break;
558 case dwarf::DW_OP_constx:
559 case dwarf::DW_OP_addrx: {
560 HasLocationAddress = true;
561 if (std::optional<uint64_t> AddressOffset =
562 DIE.getDwarfUnit()->getIndexedAddressOffset(
563 Op.getRawOperand(0))) {
564 // Check relocation for the address.
565 if (std::optional<int64_t> RelocAdjustment =
566 RelocMgr.getExprOpAddressRelocAdjustment(
567 *U, Op, *AddressOffset,
568 *AddressOffset + DIE.getDwarfUnit()->getAddressByteSize(),
569 Options.Verbose))
570 return std::make_pair(HasLocationAddress, *RelocAdjustment);
571 }
572 } break;
573 default: {
574 // Nothing to do.
575 } break;
576 }
577 CurExprOffset = Op.getEndOffset();
578 }
579
580 return std::make_pair(HasLocationAddress, std::nullopt);
581}
582
583/// Check if a variable describing DIE should be kept.
584/// \returns updated TraversalFlags.
585unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
586 const DWARFDie &DIE,
587 CompileUnit::DIEInfo &MyInfo,
588 unsigned Flags) {
589 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
590
591 // Global variables with constant value can always be kept.
592 if (!(Flags & TF_InFunctionScope) &&
593 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
594 MyInfo.InDebugMap = true;
595 return Flags | TF_Keep;
596 }
597
598 // See if there is a relocation to a valid debug map entry inside this
599 // variable's location. The order is important here. We want to always check
600 // if the variable has a valid relocation, so that the DIEInfo is filled.
601 // However, we don't want a static variable in a function to force us to keep
602 // the enclosing function, unless requested explicitly.
603 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
604 getVariableRelocAdjustment(RelocMgr, DIE);
605
606 if (LocExprAddrAndRelocAdjustment.first)
607 MyInfo.HasLocationExpressionAddr = true;
608
609 if (!LocExprAddrAndRelocAdjustment.second)
610 return Flags;
611
612 MyInfo.AddrAdjust = *LocExprAddrAndRelocAdjustment.second;
613 MyInfo.InDebugMap = true;
614
615 if (((Flags & TF_InFunctionScope) &&
616 !LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
617 return Flags;
618
619 if (Options.Verbose) {
620 outs() << "Keeping variable DIE:";
621 DIDumpOptions DumpOpts;
622 DumpOpts.ChildRecurseDepth = 0;
623 DumpOpts.Verbose = Options.Verbose;
624 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
625 }
626
627 return Flags | TF_Keep;
628}
629
630/// Check if a function describing DIE should be kept.
631/// \returns updated TraversalFlags.
632unsigned DWARFLinker::shouldKeepSubprogramDIE(
633 AddressesMap &RelocMgr, const DWARFDie &DIE, const DWARFFile &File,
634 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
635 Flags |= TF_InFunctionScope;
636
637 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
638 if (!LowPc)
639 return Flags;
640
641 assert(LowPc && "low_pc attribute is not an address.");
642 std::optional<int64_t> RelocAdjustment =
643 RelocMgr.getSubprogramRelocAdjustment(DIE, Options.Verbose);
644 if (!RelocAdjustment)
645 return Flags;
646
647 MyInfo.AddrAdjust = *RelocAdjustment;
648 MyInfo.InDebugMap = true;
649
650 if (Options.Verbose) {
651 outs() << "Keeping subprogram DIE:";
652 DIDumpOptions DumpOpts;
653 DumpOpts.ChildRecurseDepth = 0;
654 DumpOpts.Verbose = Options.Verbose;
655 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
656 }
657
658 if (DIE.getTag() == dwarf::DW_TAG_label) {
659 if (Unit.hasLabelAt(*LowPc))
660 return Flags;
661
662 DWARFUnit &OrigUnit = Unit.getOrigUnit();
663 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
664 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
665 // generation bugs aside, this is really wrong in the case of labels, where
666 // a label marking the end of a function will have a PC == CU's high_pc.
667 if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
668 .value_or(UINT64_MAX) <= LowPc)
669 return Flags;
670 // For assembly language files, try to preserve DWARF info by using
671 // function ranges when available, falling back to labels otherwise.
672 if (Unit.getLanguage() == dwarf::DW_LANG_Mips_Assembler ||
673 Unit.getLanguage() == dwarf::DW_LANG_Assembly) {
674 if (auto Range = RelocMgr.getAssemblyRangeForAddress(*LowPc)) {
675 Unit.addFunctionRange(Range->LowPC, Range->HighPC, MyInfo.AddrAdjust);
676 } else {
677 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
678 }
679 } else {
680 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
681 }
682 return Flags | TF_Keep;
683 }
684
685 Flags |= TF_Keep;
686
687 std::optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
688 if (!HighPc) {
689 reportWarning("Function without high_pc. Range will be discarded.\n", File,
690 &DIE);
691 return Flags;
692 }
693 if (*LowPc > *HighPc) {
694 reportWarning("low_pc greater than high_pc. Range will be discarded.\n",
695 File, &DIE);
696 return Flags;
697 }
698
699 // Replace the debug map range with a more accurate one.
700 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
701 return Flags;
702}
703
704/// Check if a DIE should be kept.
705/// \returns updated TraversalFlags.
706unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, const DWARFDie &DIE,
707 const DWARFFile &File, CompileUnit &Unit,
708 CompileUnit::DIEInfo &MyInfo,
709 unsigned Flags) {
710 switch (DIE.getTag()) {
711 case dwarf::DW_TAG_constant:
712 case dwarf::DW_TAG_variable:
713 return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
714 case dwarf::DW_TAG_subprogram:
715 case dwarf::DW_TAG_label:
716 return shouldKeepSubprogramDIE(RelocMgr, DIE, File, Unit, MyInfo, Flags);
717 case dwarf::DW_TAG_base_type:
718 // DWARF Expressions may reference basic types, but scanning them
719 // is expensive. Basic types are tiny, so just keep all of them.
720 case dwarf::DW_TAG_imported_module:
721 case dwarf::DW_TAG_imported_declaration:
722 case dwarf::DW_TAG_imported_unit:
723 // We always want to keep these.
724 return Flags | TF_Keep;
725 default:
726 break;
727 }
728
729 return Flags;
730}
731
732/// Helper that updates the completeness of the current DIE based on the
733/// completeness of one of its children. It depends on the incompleteness of
734/// the children already being computed.
736 CompileUnit::DIEInfo &ChildInfo) {
737 switch (Die.getTag()) {
738 case dwarf::DW_TAG_structure_type:
739 case dwarf::DW_TAG_class_type:
740 case dwarf::DW_TAG_union_type:
741 break;
742 default:
743 return;
744 }
745
746 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
747
748 if (ChildInfo.Incomplete || ChildInfo.Prune)
749 MyInfo.Incomplete = true;
750}
751
752/// Helper that updates the completeness of the current DIE based on the
753/// completeness of the DIEs it references. It depends on the incompleteness of
754/// the referenced DIE already being computed.
756 CompileUnit::DIEInfo &RefInfo) {
757 switch (Die.getTag()) {
758 case dwarf::DW_TAG_typedef:
759 case dwarf::DW_TAG_member:
760 case dwarf::DW_TAG_reference_type:
761 case dwarf::DW_TAG_ptr_to_member_type:
762 case dwarf::DW_TAG_pointer_type:
763 break;
764 default:
765 return;
766 }
767
768 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
769
770 if (MyInfo.Incomplete)
771 return;
772
773 if (RefInfo.Incomplete)
774 MyInfo.Incomplete = true;
775}
776
777/// Look at the children of the given DIE and decide whether they should be
778/// kept.
779void DWARFLinker::lookForChildDIEsToKeep(
780 const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
781 SmallVectorImpl<WorklistItem> &Worklist) {
782 // The TF_ParentWalk flag tells us that we are currently walking up the
783 // parent chain of a required DIE, and we don't want to mark all the children
784 // of the parents as kept (consider for example a DW_TAG_namespace node in
785 // the parent chain). There are however a set of DIE types for which we want
786 // to ignore that directive and still walk their children.
787 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
788 Flags &= ~DWARFLinker::TF_ParentWalk;
789
790 // We're finished if this DIE has no children or we're walking the parent
791 // chain.
792 if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
793 return;
794
795 // Add children in reverse order to the worklist to effectively process them
796 // in order.
797 for (auto Child : reverse(Die.children())) {
798 // Add a worklist item before every child to calculate incompleteness right
799 // after the current child is processed.
800 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
801 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
802 &ChildInfo);
803 Worklist.emplace_back(Child, CU, Flags);
804 }
805}
806
808 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
809
810 if (!Info.Ctxt || (Die.getTag() == dwarf::DW_TAG_namespace))
811 return false;
812
813 if (!CU.hasODR() && !Info.InModuleScope)
814 return false;
815
816 return !Info.Incomplete && Info.Ctxt != CU.getInfo(Info.ParentIdx).Ctxt;
817}
818
819void DWARFLinker::markODRCanonicalDie(const DWARFDie &Die, CompileUnit &CU) {
820 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
821
822 Info.ODRMarkingDone = true;
823 if (Info.Keep && isODRCanonicalCandidate(Die, CU) &&
824 !Info.Ctxt->hasCanonicalDIE())
825 Info.Ctxt->setHasCanonicalDIE();
826}
827
828/// Look at DIEs referenced by the given DIE and decide whether they should be
829/// kept. All DIEs referenced though attributes should be kept.
830void DWARFLinker::lookForRefDIEsToKeep(
831 const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
832 const UnitListTy &Units, const DWARFFile &File,
833 SmallVectorImpl<WorklistItem> &Worklist) {
834 bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
835 ? (Flags & DWARFLinker::TF_ODR)
836 : CU.hasODR();
837 DWARFUnit &Unit = CU.getOrigUnit();
838 DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
839 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
840 uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
841
843 for (const auto &AttrSpec : Abbrev->attributes()) {
844 DWARFFormValue Val(AttrSpec.Form);
845 if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
846 AttrSpec.Attr == dwarf::DW_AT_sibling) {
847 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
848 Unit.getFormParams());
849 continue;
850 }
851
852 Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
853 CompileUnit *ReferencedCU;
854 if (auto RefDie =
855 resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
856 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
857 // If the referenced DIE has a DeclContext that has already been
858 // emitted, then do not keep the one in this CU. We'll link to
859 // the canonical DIE in cloneDieReferenceAttribute.
860 //
861 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
862 // be necessary and could be advantageously replaced by
863 // ReferencedCU->hasODR() && CU.hasODR().
864 //
865 // FIXME: compatibility with dsymutil-classic. There is no
866 // reason not to unique ref_addr references.
867 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr &&
868 isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
869 Info.Ctxt->hasCanonicalDIE())
870 continue;
871
872 // Keep a module forward declaration if there is no definition.
873 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
874 Info.Ctxt->hasCanonicalDIE()))
875 Info.Prune = false;
876 ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
877 }
878 }
879
880 unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
881
882 // Add referenced DIEs in reverse order to the worklist to effectively
883 // process them in order.
884 for (auto &P : reverse(ReferencedDIEs)) {
885 // Add a worklist item before every child to calculate incompleteness right
886 // after the current child is processed.
887 CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
888 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
889 &Info);
890 Worklist.emplace_back(P.first, P.second,
891 DWARFLinker::TF_Keep |
892 DWARFLinker::TF_DependencyWalk | ODRFlag);
893 }
894}
895
896/// Look at the parent of the given DIE and decide whether they should be kept.
897void DWARFLinker::lookForParentDIEsToKeep(
898 unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
899 SmallVectorImpl<WorklistItem> &Worklist) {
900 // Stop if we encounter an ancestor that's already marked as kept.
901 if (CU.getInfo(AncestorIdx).Keep)
902 return;
903
904 DWARFUnit &Unit = CU.getOrigUnit();
905 DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
906 Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
907 Worklist.emplace_back(ParentDIE, CU, Flags);
908}
909
910/// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
911/// information in \p CU's DIEInfo.
912///
913/// This function is the entry point of the DIE selection algorithm. It is
914/// expected to walk the DIE tree in file order and (though the mediation of
915/// its helper) call hasValidRelocation() on each DIE that might be a 'root
916/// DIE' (See DwarfLinker class comment).
917///
918/// While walking the dependencies of root DIEs, this function is also called,
919/// but during these dependency walks the file order is not respected. The
920/// TF_DependencyWalk flag tells us which kind of traversal we are currently
921/// doing.
922///
923/// The recursive algorithm is implemented iteratively as a work list because
924/// very deep recursion could exhaust the stack for large projects. The work
925/// list acts as a scheduler for different types of work that need to be
926/// performed.
927///
928/// The recursive nature of the algorithm is simulated by running the "main"
929/// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
930/// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
931/// fixing up a computed property (UpdateChildIncompleteness,
932/// UpdateRefIncompleteness).
933///
934/// The return value indicates whether the DIE is incomplete.
935void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
936 const UnitListTy &Units,
937 const DWARFDie &Die, const DWARFFile &File,
938 CompileUnit &Cu, unsigned Flags) {
939 // LIFO work list.
941 Worklist.emplace_back(Die, Cu, Flags);
942
943 while (!Worklist.empty()) {
944 WorklistItem Current = Worklist.pop_back_val();
945
946 // Look at the worklist type to decide what kind of work to perform.
947 switch (Current.Type) {
948 case WorklistItemType::UpdateChildIncompleteness:
949 updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
950 continue;
951 case WorklistItemType::UpdateRefIncompleteness:
952 updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
953 continue;
954 case WorklistItemType::LookForChildDIEsToKeep:
955 lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
956 continue;
957 case WorklistItemType::LookForRefDIEsToKeep:
958 lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
959 Worklist);
960 continue;
961 case WorklistItemType::LookForParentDIEsToKeep:
962 lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
963 Worklist);
964 continue;
965 case WorklistItemType::MarkODRCanonicalDie:
966 markODRCanonicalDie(Current.Die, Current.CU);
967 continue;
968 case WorklistItemType::LookForDIEsToKeep:
969 break;
970 }
971
972 unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
973 CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
974
975 if (MyInfo.Prune) {
976 // We're walking the dependencies of a module forward declaration that was
977 // kept because there is no definition.
978 if (Current.Flags & TF_DependencyWalk)
979 MyInfo.Prune = false;
980 else
981 continue;
982 }
983
984 // If the Keep flag is set, we are marking a required DIE's dependencies.
985 // If our target is already marked as kept, we're all set.
986 bool AlreadyKept = MyInfo.Keep;
987 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
988 continue;
989
990 if (!(Current.Flags & TF_DependencyWalk))
991 Current.Flags = shouldKeepDIE(AddressesMap, Current.Die, File, Current.CU,
992 MyInfo, Current.Flags);
993
994 // We need to mark context for the canonical die in the end of normal
995 // traversing(not TF_DependencyWalk) or after normal traversing if die
996 // was not marked as kept.
997 if (!(Current.Flags & TF_DependencyWalk) ||
998 (MyInfo.ODRMarkingDone && !MyInfo.Keep)) {
999 if (Current.CU.hasODR() || MyInfo.InModuleScope)
1000 Worklist.emplace_back(Current.Die, Current.CU,
1001 WorklistItemType::MarkODRCanonicalDie);
1002 }
1003
1004 // Finish by looking for child DIEs. Because of the LIFO worklist we need
1005 // to schedule that work before any subsequent items are added to the
1006 // worklist.
1007 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1008 WorklistItemType::LookForChildDIEsToKeep);
1009
1010 if (AlreadyKept || !(Current.Flags & TF_Keep))
1011 continue;
1012
1013 // If it is a newly kept DIE mark it as well as all its dependencies as
1014 // kept.
1015 MyInfo.Keep = true;
1016
1017 // We're looking for incomplete types.
1018 MyInfo.Incomplete =
1019 Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
1020 Current.Die.getTag() != dwarf::DW_TAG_member &&
1021 dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
1022
1023 // After looking at the parent chain, look for referenced DIEs. Because of
1024 // the LIFO worklist we need to schedule that work before any subsequent
1025 // items are added to the worklist.
1026 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1027 WorklistItemType::LookForRefDIEsToKeep);
1028
1029 bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
1030 : Current.CU.hasODR();
1031 unsigned ODRFlag = UseOdr ? TF_ODR : 0;
1032 unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
1033
1034 // Now schedule the parent walk.
1035 Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
1036 }
1037}
1038
1039#ifndef NDEBUG
1040/// A broken link in the keep chain. By recording both the parent and the child
1041/// we can show only broken links for DIEs with multiple children.
1047
1048/// Verify the keep chain by looking for DIEs that are kept but who's parent
1049/// isn't.
1051 std::vector<DWARFDie> Worklist;
1052 Worklist.push_back(CU.getOrigUnit().getUnitDIE());
1053
1054 // List of broken links.
1055 std::vector<BrokenLink> BrokenLinks;
1056
1057 while (!Worklist.empty()) {
1058 const DWARFDie Current = Worklist.back();
1059 Worklist.pop_back();
1060
1061 const bool CurrentDieIsKept = CU.getInfo(Current).Keep;
1062
1063 for (DWARFDie Child : reverse(Current.children())) {
1064 Worklist.push_back(Child);
1065
1066 const bool ChildDieIsKept = CU.getInfo(Child).Keep;
1067 if (!CurrentDieIsKept && ChildDieIsKept)
1068 BrokenLinks.emplace_back(Current, Child);
1069 }
1070 }
1071
1072 if (!BrokenLinks.empty()) {
1073 for (BrokenLink Link : BrokenLinks) {
1075 "Found invalid link in keep chain between {0:x} and {1:x}\n",
1076 Link.Parent.getOffset(), Link.Child.getOffset());
1077
1078 errs() << "Parent:";
1079 Link.Parent.dump(errs(), 0, {});
1080 CU.getInfo(Link.Parent).dump();
1081
1082 errs() << "Child:";
1083 Link.Child.dump(errs(), 2, {});
1084 CU.getInfo(Link.Child).dump();
1085 }
1086 report_fatal_error("invalid keep chain");
1087 }
1088}
1089#endif
1090
1091/// Assign an abbreviation number to \p Abbrev.
1092///
1093/// Our DIEs get freed after every DebugMapObject has been processed,
1094/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1095/// the instances hold by the DIEs. When we encounter an abbreviation
1096/// that we don't know, we create a permanent copy of it.
1097void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
1098 // Check the set for priors.
1099 FoldingSetNodeID ID;
1100 Abbrev.Profile(ID);
1101 void *InsertToken;
1102 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1103
1104 // If it's newly added.
1105 if (InSet) {
1106 // Assign existing abbreviation number.
1107 Abbrev.setNumber(InSet->getNumber());
1108 } else {
1109 // Add to abbreviation list.
1110 Abbreviations.push_back(
1111 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
1112 for (const auto &Attr : Abbrev.getData())
1113 Abbreviations.back()->AddAttribute(Attr);
1114 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
1115 // Assign the unique abbreviation number.
1116 Abbrev.setNumber(Abbreviations.size());
1117 Abbreviations.back()->setNumber(Abbreviations.size());
1118 }
1119}
1120
1121unsigned DWARFLinker::DIECloner::cloneStringAttribute(DIE &Die,
1122 AttributeSpec AttrSpec,
1123 const DWARFFormValue &Val,
1124 const DWARFUnit &U,
1125 AttributesInfo &Info) {
1126 std::optional<const char *> String = dwarf::toString(Val);
1127 if (!String)
1128 return 0;
1129 DwarfStringPoolEntryRef StringEntry;
1130 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
1131 StringEntry = DebugLineStrPool.getEntry(*String);
1132 } else {
1133 StringEntry = DebugStrPool.getEntry(*String);
1134
1135 if (AttrSpec.Attr == dwarf::DW_AT_APPLE_origin) {
1136 Info.HasAppleOrigin = true;
1137 if (std::optional<StringRef> FileName =
1138 ObjFile.Addresses->getLibraryInstallName()) {
1139 StringEntry = DebugStrPool.getEntry(*FileName);
1140 }
1141 }
1142
1143 // Update attributes info.
1144 if (AttrSpec.Attr == dwarf::DW_AT_name)
1145 Info.Name = StringEntry;
1146 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
1147 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
1148 Info.MangledName = StringEntry;
1149 if (U.getVersion() >= 5) {
1150 // Switch everything to DW_FORM_strx strings.
1151 auto StringOffsetIndex =
1152 StringOffsetPool.getValueIndex(StringEntry.getOffset());
1153 return Die
1154 .addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1155 dwarf::DW_FORM_strx, DIEInteger(StringOffsetIndex))
1156 ->sizeOf(U.getFormParams());
1157 }
1158 // Switch everything to out of line strings.
1159 AttrSpec.Form = dwarf::DW_FORM_strp;
1160 }
1161 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), AttrSpec.Form,
1162 DIEInteger(StringEntry.getOffset()));
1163 return 4;
1164}
1165
1166unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
1167 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1168 unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
1169 CompileUnit &Unit) {
1170 const DWARFUnit &U = Unit.getOrigUnit();
1171 uint64_t Ref;
1172 if (std::optional<uint64_t> Off = Val.getAsRelativeReference())
1173 Ref = Val.getUnit()->getOffset() + *Off;
1174 else if (Off = Val.getAsDebugInfoReference(); Off)
1175 Ref = *Off;
1176 else
1177 return 0;
1178
1179 DIE *NewRefDie = nullptr;
1180 CompileUnit *RefUnit = nullptr;
1181
1182 DWARFDie RefDie =
1183 Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
1184
1185 // If the referenced DIE is not found, drop the attribute.
1186 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
1187 return 0;
1188
1189 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
1190
1191 // If we already have emitted an equivalent DeclContext, just point
1192 // at it.
1193 if (isODRAttribute(AttrSpec.Attr) && RefInfo.Ctxt &&
1194 RefInfo.Ctxt->getCanonicalDIEOffset()) {
1195 assert(RefInfo.Ctxt->hasCanonicalDIE() &&
1196 "Offset to canonical die is set, but context is not marked");
1197 DIEInteger Attr(RefInfo.Ctxt->getCanonicalDIEOffset());
1198 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1199 dwarf::DW_FORM_ref_addr, Attr);
1200 return U.getRefAddrByteSize();
1201 }
1202
1203 if (!RefInfo.Clone) {
1204 // We haven't cloned this DIE yet. Just create an empty one and
1205 // store it. It'll get really cloned when we process it.
1206 RefInfo.UnclonedReference = true;
1207 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
1208 }
1209 NewRefDie = RefInfo.Clone;
1210
1211 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
1212 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
1213 if (Ref < InputDIE.getOffset() && !RefInfo.UnclonedReference) {
1214 // Backward reference: the target DIE is already cloned and
1215 // parented in a unit tree, so DIEEntry can resolve the
1216 // absolute offset at emission time.
1217 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1218 dwarf::DW_FORM_ref_addr, DIEEntry(*NewRefDie));
1219 } else {
1220 // Forward reference: the target DIE may be a placeholder that
1221 // never gets adopted into a unit tree (e.g. due to ODR
1222 // pruning), so DIEEntry cannot safely resolve it. Use a
1223 // placeholder integer and fix it up after all units are cloned.
1224 Unit.noteForwardReference(
1225 NewRefDie, RefUnit, RefInfo.Ctxt,
1226 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1227 dwarf::DW_FORM_ref_addr, DIEInteger(UINT64_MAX)));
1228 }
1229 return U.getRefAddrByteSize();
1230 }
1231
1232 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1233 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1234
1235 return AttrSize;
1236}
1237
1238void DWARFLinker::DIECloner::cloneExpression(
1239 DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
1240 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer,
1241 int64_t AddrRelocAdjustment, bool IsLittleEndian) {
1242 using Encoding = DWARFExpression::Operation::Encoding;
1243
1244 uint8_t OrigAddressByteSize = Unit.getOrigUnit().getAddressByteSize();
1245
1246 uint64_t OpOffset = 0;
1247 for (auto &Op : Expression) {
1248 auto Desc = Op.getDescription();
1249 // DW_OP_const_type is variable-length and has 3
1250 // operands. Thus far we only support 2.
1251 if ((Desc.Op.size() == 2 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1252 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1253 Desc.Op[0] != Encoding::Size1))
1254 Linker.reportWarning("Unsupported DW_OP encoding.", File);
1255
1256 if ((Desc.Op.size() == 1 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1257 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1258 Desc.Op[0] == Encoding::Size1)) {
1259 // This code assumes that the other non-typeref operand fits into 1 byte.
1260 assert(OpOffset < Op.getEndOffset());
1261 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
1262 assert(ULEBsize <= 16);
1263
1264 // Copy over the operation.
1265 assert(!Op.getSubCode() && "SubOps not yet supported");
1266 OutputBuffer.push_back(Op.getCode());
1267 uint64_t RefOffset;
1268 if (Desc.Op.size() == 1) {
1269 RefOffset = Op.getRawOperand(0);
1270 } else {
1271 OutputBuffer.push_back(Op.getRawOperand(0));
1272 RefOffset = Op.getRawOperand(1);
1273 }
1274 uint32_t Offset = 0;
1275 // Look up the base type. For DW_OP_convert, the operand may be 0 to
1276 // instead indicate the generic type. The same holds for
1277 // DW_OP_reinterpret, which is currently not supported.
1278 if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
1279 RefOffset += Unit.getOrigUnit().getOffset();
1280 auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
1281 CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
1282 if (DIE *Clone = Info.Clone)
1283 Offset = Clone->getOffset();
1284 else
1285 Linker.reportWarning(
1286 "base type ref doesn't point to DW_TAG_base_type.", File);
1287 }
1288 uint8_t ULEB[16];
1289 unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1290 if (RealSize > ULEBsize) {
1291 // Emit the generic type as a fallback.
1292 RealSize = encodeULEB128(0, ULEB, ULEBsize);
1293 Linker.reportWarning("base type ref doesn't fit.", File);
1294 }
1295 assert(RealSize == ULEBsize && "padding failed");
1296 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1297 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1298 } else if (!Linker.Options.Update && Op.getCode() == dwarf::DW_OP_addrx) {
1299 if (std::optional<object::SectionedAddress> SA =
1300 Unit.getOrigUnit().getAddrOffsetSectionItem(
1301 Op.getRawOperand(0))) {
1302 // DWARFLinker does not use addrx forms since it generates relocated
1303 // addresses. Replace DW_OP_addrx with DW_OP_addr here.
1304 // Argument of DW_OP_addrx should be relocated here as it is not
1305 // processed by applyValidRelocs.
1306 OutputBuffer.push_back(dwarf::DW_OP_addr);
1307 uint64_t LinkedAddress = SA->Address + AddrRelocAdjustment;
1308 if (IsLittleEndian != sys::IsLittleEndianHost)
1309 sys::swapByteOrder(LinkedAddress);
1310 ArrayRef<uint8_t> AddressBytes(
1311 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1312 OrigAddressByteSize);
1313 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1314 } else
1315 Linker.reportWarning("cannot read DW_OP_addrx operand.", File);
1316 } else if (!Linker.Options.Update && Op.getCode() == dwarf::DW_OP_constx) {
1317 if (std::optional<object::SectionedAddress> SA =
1318 Unit.getOrigUnit().getAddrOffsetSectionItem(
1319 Op.getRawOperand(0))) {
1320 // DWARFLinker does not use constx forms since it generates relocated
1321 // addresses. Replace DW_OP_constx with DW_OP_const[*]u here.
1322 // Argument of DW_OP_constx should be relocated here as it is not
1323 // processed by applyValidRelocs.
1324 std::optional<uint8_t> OutOperandKind;
1325 switch (OrigAddressByteSize) {
1326 case 4:
1327 OutOperandKind = dwarf::DW_OP_const4u;
1328 break;
1329 case 8:
1330 OutOperandKind = dwarf::DW_OP_const8u;
1331 break;
1332 default:
1333 Linker.reportWarning(
1334 formatv(("unsupported address size: {0}."), OrigAddressByteSize),
1335 File);
1336 break;
1337 }
1338
1339 if (OutOperandKind) {
1340 OutputBuffer.push_back(*OutOperandKind);
1341 uint64_t LinkedAddress = SA->Address + AddrRelocAdjustment;
1342 if (IsLittleEndian != sys::IsLittleEndianHost)
1343 sys::swapByteOrder(LinkedAddress);
1344 ArrayRef<uint8_t> AddressBytes(
1345 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1346 OrigAddressByteSize);
1347 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1348 }
1349 } else
1350 Linker.reportWarning("cannot read DW_OP_constx operand.", File);
1351 } else {
1352 // Copy over everything else unmodified.
1353 StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
1354 OutputBuffer.append(Bytes.begin(), Bytes.end());
1355 }
1356 OpOffset = Op.getEndOffset();
1357 }
1358}
1359
1360unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1361 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1362 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1363 bool IsLittleEndian) {
1364 DIEValueList *Attr;
1365 DIEValue Value;
1366 DIELoc *Loc = nullptr;
1367 DIEBlock *Block = nullptr;
1368 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1369 Loc = new (DIEAlloc) DIELoc;
1370 Linker.DIELocs.push_back(Loc);
1371 } else {
1372 Block = new (DIEAlloc) DIEBlock;
1373 Linker.DIEBlocks.push_back(Block);
1374 }
1375 Attr = Loc ? static_cast<DIEValueList *>(Loc)
1376 : static_cast<DIEValueList *>(Block);
1377
1378 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1379 // If the block is a DWARF Expression, clone it into the temporary
1380 // buffer using cloneExpression(), otherwise copy the data directly.
1381 SmallVector<uint8_t, 32> Buffer;
1382 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1383 if (DWARFAttribute::mayHaveLocationExpr(AttrSpec.Attr) &&
1384 (Val.isFormClass(DWARFFormValue::FC_Block) ||
1385 Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1386 DataExtractor Data(Bytes, IsLittleEndian);
1387 DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1388 OrigUnit.getFormParams().Format);
1389 cloneExpression(Data, Expr, File, Unit, Buffer,
1390 Unit.getInfo(InputDIE).AddrAdjust, IsLittleEndian);
1391 Bytes = Buffer;
1392 }
1393 for (auto Byte : Bytes)
1394 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1395 dwarf::DW_FORM_data1, DIEInteger(Byte));
1396
1397 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1398 // the DIE class, this "if" could be replaced by
1399 // Attr->setSize(Bytes.size()).
1400 if (Loc)
1401 Loc->setSize(Bytes.size());
1402 else
1403 Block->setSize(Bytes.size());
1404
1405 if (Loc)
1406 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1407 dwarf::Form(AttrSpec.Form), Loc);
1408 else {
1409 // The expression location data might be updated and exceed the original
1410 // size. Check whether the new data fits into the original form.
1411 if ((AttrSpec.Form == dwarf::DW_FORM_block1 &&
1412 (Bytes.size() > UINT8_MAX)) ||
1413 (AttrSpec.Form == dwarf::DW_FORM_block2 &&
1414 (Bytes.size() > UINT16_MAX)) ||
1415 (AttrSpec.Form == dwarf::DW_FORM_block4 && (Bytes.size() > UINT32_MAX)))
1416 AttrSpec.Form = dwarf::DW_FORM_block;
1417
1418 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1419 dwarf::Form(AttrSpec.Form), Block);
1420 }
1421
1422 return Die.addValue(DIEAlloc, Value)->sizeOf(OrigUnit.getFormParams());
1423}
1424
1425unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1426 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1427 unsigned AttrSize, const DWARFFormValue &Val, const CompileUnit &Unit,
1428 AttributesInfo &Info) {
1429 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1430 Info.HasLowPc = true;
1431
1432 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1433 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1434 dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1435 return AttrSize;
1436 }
1437
1438 // Cloned Die may have address attributes relocated to a
1439 // totally unrelated value. This can happen:
1440 // - If high_pc is an address (Dwarf version == 2), then it might have been
1441 // relocated to a totally unrelated value (because the end address in the
1442 // object file might be start address of another function which got moved
1443 // independently by the linker).
1444 // - If address relocated in an inline_subprogram that happens at the
1445 // beginning of its inlining function.
1446 // To avoid above cases and to not apply relocation twice (in
1447 // applyValidRelocs and here), read address attribute from InputDIE and apply
1448 // Info.PCOffset here.
1449
1450 std::optional<DWARFFormValue> AddrAttribute = InputDIE.find(AttrSpec.Attr);
1451 if (!AddrAttribute)
1452 llvm_unreachable("Cann't find attribute.");
1453
1454 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
1455 if (!Addr) {
1456 Linker.reportWarning("Cann't read address attribute value.", ObjFile);
1457 return 0;
1458 }
1459
1460 if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1461 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1462 if (std::optional<uint64_t> LowPC = Unit.getLowPc())
1463 Addr = *LowPC;
1464 else
1465 return 0;
1466 } else if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1467 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1468 if (uint64_t HighPc = Unit.getHighPc())
1469 Addr = HighPc;
1470 else
1471 return 0;
1472 } else {
1473 *Addr += Info.PCOffset;
1474 }
1475
1476 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
1477 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1478 AttrSpec.Form, DIEInteger(*Addr));
1479 return Unit.getOrigUnit().getAddressByteSize();
1480 }
1481
1482 auto AddrIndex = AddrPool.getValueIndex(*Addr);
1483
1484 return Die
1485 .addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1486 dwarf::Form::DW_FORM_addrx, DIEInteger(AddrIndex))
1487 ->sizeOf(Unit.getOrigUnit().getFormParams());
1488}
1489
1490unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1491 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1492 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1493 unsigned AttrSize, AttributesInfo &Info) {
1494 uint64_t Value;
1495
1496 // We don't emit any skeleton CUs with dsymutil. So avoid emitting
1497 // a redundant DW_AT_GNU_dwo_id on the non-skeleton CU.
1498 if (AttrSpec.Attr == dwarf::DW_AT_GNU_dwo_id ||
1499 AttrSpec.Attr == dwarf::DW_AT_dwo_id)
1500 return 0;
1501
1502 // Check for the offset to the macro table. If offset is incorrect then we
1503 // need to remove the attribute.
1504 if (AttrSpec.Attr == dwarf::DW_AT_macro_info) {
1505 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
1506 const llvm::DWARFDebugMacro *Macro = File.Dwarf->getDebugMacinfo();
1507 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
1508 return 0;
1509 }
1510 }
1511
1512 if (AttrSpec.Attr == dwarf::DW_AT_macros) {
1513 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
1514 const llvm::DWARFDebugMacro *Macro = File.Dwarf->getDebugMacro();
1515 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
1516 return 0;
1517 }
1518 }
1519
1520 if (AttrSpec.Attr == dwarf::DW_AT_str_offsets_base) {
1521 // DWARFLinker generates common .debug_str_offsets table used for all
1522 // compile units. The offset to the common .debug_str_offsets table is 8 on
1523 // DWARF32.
1524 Info.AttrStrOffsetBaseSeen = true;
1525 return Die
1526 .addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
1527 dwarf::DW_FORM_sec_offset, DIEInteger(8))
1528 ->sizeOf(Unit.getOrigUnit().getFormParams());
1529 }
1530
1531 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
1532 // If needed, we'll patch this sec_offset later with the correct offset.
1533 auto Patch = Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1534 dwarf::DW_FORM_sec_offset,
1535 DIEInteger(*Val.getAsSectionOffset()));
1536
1537 // Record this patch location so that it can be fixed up later.
1538 Unit.noteStmtSeqListAttribute(Patch);
1539
1540 return Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1541 }
1542
1543 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1544 if (auto OptionalValue = Val.getAsUnsignedConstant())
1545 Value = *OptionalValue;
1546 else if (auto OptionalValue = Val.getAsSignedConstant())
1547 Value = *OptionalValue;
1548 else if (auto OptionalValue = Val.getAsSectionOffset())
1549 Value = *OptionalValue;
1550 else {
1551 Linker.reportWarning(
1552 "Unsupported scalar attribute form. Dropping attribute.", File,
1553 &InputDIE);
1554 return 0;
1555 }
1556 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1557 Info.IsDeclaration = true;
1558
1559 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
1560 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1561 dwarf::Form(AttrSpec.Form), DIELocList(Value));
1562 else
1563 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1564 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1565 return AttrSize;
1566 }
1567
1568 [[maybe_unused]] dwarf::Form OriginalForm = AttrSpec.Form;
1569 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
1570 // DWARFLinker does not generate .debug_addr table. Thus we need to change
1571 // all "addrx" related forms to "addr" version. Change DW_FORM_rnglistx
1572 // to DW_FORM_sec_offset here.
1573 std::optional<uint64_t> Index = Val.getAsSectionOffset();
1574 if (!Index) {
1575 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1576 &InputDIE);
1577 return 0;
1578 }
1579 std::optional<uint64_t> Offset =
1580 Unit.getOrigUnit().getRnglistOffset(*Index);
1581 if (!Offset) {
1582 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1583 &InputDIE);
1584 return 0;
1585 }
1586
1587 Value = *Offset;
1588 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1589 AttrSize = Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1590 } else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
1591 // DWARFLinker does not generate .debug_addr table. Thus we need to change
1592 // all "addrx" related forms to "addr" version. Change DW_FORM_loclistx
1593 // to DW_FORM_sec_offset here.
1594 std::optional<uint64_t> Index = Val.getAsSectionOffset();
1595 if (!Index) {
1596 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1597 &InputDIE);
1598 return 0;
1599 }
1600 std::optional<uint64_t> Offset =
1601 Unit.getOrigUnit().getLoclistOffset(*Index);
1602 if (!Offset) {
1603 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1604 &InputDIE);
1605 return 0;
1606 }
1607
1608 Value = *Offset;
1609 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1610 AttrSize = Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1611 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1612 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1613 std::optional<uint64_t> LowPC = Unit.getLowPc();
1614 if (!LowPC)
1615 return 0;
1616 // Dwarf >= 4 high_pc is an size, not an address.
1617 Value = Unit.getHighPc() - *LowPC;
1618 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1619 Value = *Val.getAsSectionOffset();
1620 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1621 Value = *Val.getAsSignedConstant();
1622 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1623 Value = *OptionalValue;
1624 else {
1625 Linker.reportWarning(
1626 "Unsupported scalar attribute form. Dropping attribute.", File,
1627 &InputDIE);
1628 return 0;
1629 }
1630
1631 DIE::value_iterator Patch =
1632 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1633 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1634 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
1635 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
1636 Unit.noteRangeAttribute(Die, Patch);
1637 Info.HasRanges = true;
1638 } else if (DWARFAttribute::mayHaveLocationList(AttrSpec.Attr) &&
1639 dwarf::doesFormBelongToClass(AttrSpec.Form,
1641 Unit.getOrigUnit().getVersion())) {
1642
1643 CompileUnit::DIEInfo &LocationDieInfo = Unit.getInfo(InputDIE);
1644 Unit.noteLocationAttribute({Patch, LocationDieInfo.InDebugMap
1645 ? LocationDieInfo.AddrAdjust
1646 : Info.PCOffset});
1647 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1648 Info.IsDeclaration = true;
1649
1650 // check that all dwarf::DW_FORM_rnglistx are handled previously.
1651 assert((Info.HasRanges || (OriginalForm != dwarf::DW_FORM_rnglistx)) &&
1652 "Unhandled DW_FORM_rnglistx attribute");
1653
1654 return AttrSize;
1655}
1656
1657/// Clone \p InputDIE's attribute described by \p AttrSpec with
1658/// value \p Val, and add it to \p Die.
1659/// \returns the size of the cloned attribute.
1660unsigned DWARFLinker::DIECloner::cloneAttribute(
1661 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1662 CompileUnit &Unit, const DWARFFormValue &Val, const AttributeSpec AttrSpec,
1663 unsigned AttrSize, AttributesInfo &Info, bool IsLittleEndian) {
1664 const DWARFUnit &U = Unit.getOrigUnit();
1665
1666 switch (AttrSpec.Form) {
1667 case dwarf::DW_FORM_strp:
1668 case dwarf::DW_FORM_line_strp:
1669 case dwarf::DW_FORM_string:
1670 case dwarf::DW_FORM_strx:
1671 case dwarf::DW_FORM_strx1:
1672 case dwarf::DW_FORM_strx2:
1673 case dwarf::DW_FORM_strx3:
1674 case dwarf::DW_FORM_strx4:
1675 return cloneStringAttribute(Die, AttrSpec, Val, U, Info);
1676 case dwarf::DW_FORM_ref_addr:
1677 case dwarf::DW_FORM_ref1:
1678 case dwarf::DW_FORM_ref2:
1679 case dwarf::DW_FORM_ref4:
1680 case dwarf::DW_FORM_ref8:
1681 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1682 File, Unit);
1683 case dwarf::DW_FORM_block:
1684 case dwarf::DW_FORM_block1:
1685 case dwarf::DW_FORM_block2:
1686 case dwarf::DW_FORM_block4:
1687 case dwarf::DW_FORM_exprloc:
1688 return cloneBlockAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1689 IsLittleEndian);
1690 case dwarf::DW_FORM_addr:
1691 case dwarf::DW_FORM_addrx:
1692 case dwarf::DW_FORM_addrx1:
1693 case dwarf::DW_FORM_addrx2:
1694 case dwarf::DW_FORM_addrx3:
1695 case dwarf::DW_FORM_addrx4:
1696 return cloneAddressAttribute(Die, InputDIE, AttrSpec, AttrSize, Val, Unit,
1697 Info);
1698 case dwarf::DW_FORM_data1:
1699 case dwarf::DW_FORM_data2:
1700 case dwarf::DW_FORM_data4:
1701 case dwarf::DW_FORM_data8:
1702 case dwarf::DW_FORM_udata:
1703 case dwarf::DW_FORM_sdata:
1704 case dwarf::DW_FORM_sec_offset:
1705 case dwarf::DW_FORM_flag:
1706 case dwarf::DW_FORM_flag_present:
1707 case dwarf::DW_FORM_rnglistx:
1708 case dwarf::DW_FORM_loclistx:
1709 case dwarf::DW_FORM_implicit_const:
1710 return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1711 AttrSize, Info);
1712 default:
1713 Linker.reportWarning("Unsupported attribute form " +
1714 dwarf::FormEncodingString(AttrSpec.Form) +
1715 " in cloneAttribute. Dropping.",
1716 File, &InputDIE);
1717 }
1718
1719 return 0;
1720}
1721
1722void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1723 const DIE *Die,
1724 DwarfStringPoolEntryRef Name,
1725 OffsetsStringPool &StringPool,
1726 bool SkipPubSection) {
1727 std::optional<ObjCSelectorNames> Names =
1728 getObjCNamesIfSelector(Name.getString());
1729 if (!Names)
1730 return;
1731 Unit.addNameAccelerator(Die, StringPool.getEntry(Names->Selector),
1732 SkipPubSection);
1733 Unit.addObjCAccelerator(Die, StringPool.getEntry(Names->ClassName),
1734 SkipPubSection);
1735 if (Names->ClassNameNoCategory)
1736 Unit.addObjCAccelerator(
1737 Die, StringPool.getEntry(*Names->ClassNameNoCategory), SkipPubSection);
1738 if (Names->MethodNameNoCategory)
1739 Unit.addNameAccelerator(
1740 Die, StringPool.getEntry(*Names->MethodNameNoCategory), SkipPubSection);
1741}
1742
1743static bool
1746 bool SkipPC) {
1747 switch (AttrSpec.Attr) {
1748 default:
1749 return false;
1750 case dwarf::DW_AT_low_pc:
1751 case dwarf::DW_AT_high_pc:
1752 case dwarf::DW_AT_ranges:
1753 return !Update && SkipPC;
1754 case dwarf::DW_AT_rnglists_base:
1755 // In case !Update the .debug_addr table is not generated/preserved.
1756 // Thus instead of DW_FORM_rnglistx the DW_FORM_sec_offset is used.
1757 // Since DW_AT_rnglists_base is used for only DW_FORM_rnglistx the
1758 // DW_AT_rnglists_base is removed.
1759 return !Update;
1760 case dwarf::DW_AT_loclists_base:
1761 // In case !Update the .debug_addr table is not generated/preserved.
1762 // Thus instead of DW_FORM_loclistx the DW_FORM_sec_offset is used.
1763 // Since DW_AT_loclists_base is used for only DW_FORM_loclistx the
1764 // DW_AT_loclists_base is removed.
1765 return !Update;
1766 case dwarf::DW_AT_location:
1767 case dwarf::DW_AT_frame_base:
1768 return !Update && SkipPC;
1769 }
1770}
1771
1777
1778DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1779 const DWARFFile &File, CompileUnit &Unit,
1780 int64_t PCOffset, uint32_t OutOffset,
1781 unsigned Flags, bool IsLittleEndian,
1782 DIE *Die) {
1783 DWARFUnit &U = Unit.getOrigUnit();
1784 unsigned Idx = U.getDIEIndex(InputDIE);
1785 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1786
1787 // Should the DIE appear in the output?
1788 if (!Unit.getInfo(Idx).Keep)
1789 return nullptr;
1790
1791 uint64_t Offset = InputDIE.getOffset();
1792 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1793 if (!Die) {
1794 // The DIE might have been already created by a forward reference
1795 // (see cloneDieReferenceAttribute()).
1796 if (!Info.Clone)
1797 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1798 Die = Info.Clone;
1799 }
1800
1801 assert(Die->getTag() == InputDIE.getTag());
1802 Die->setOffset(OutOffset);
1803 if (isODRCanonicalCandidate(InputDIE, Unit) && Info.Ctxt &&
1804 (Info.Ctxt->getCanonicalDIEOffset() == 0)) {
1805 if (!Info.Ctxt->hasCanonicalDIE())
1806 Info.Ctxt->setHasCanonicalDIE();
1807 // We are about to emit a DIE that is the root of its own valid
1808 // DeclContext tree. Make the current offset the canonical offset
1809 // for this context.
1810 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1811 }
1812
1813 // Extract and clone every attribute.
1814 DWARFDataExtractor Data = U.getDebugInfoExtractor();
1815 // Point to the next DIE (generally there is always at least a NULL
1816 // entry after the current one). If this is a lone
1817 // DW_TAG_compile_unit without any children, point to the next unit.
1818 uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1819 ? U.getDIEAtIndex(Idx + 1).getOffset()
1820 : U.getNextUnitOffset();
1821 AttributesInfo AttrInfo;
1822
1823 // We could copy the data only if we need to apply a relocation to it. After
1824 // testing, it seems there is no performance downside to doing the copy
1825 // unconditionally, and it makes the code simpler.
1826 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1827 Data =
1828 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1829
1830 // Modify the copy with relocated addresses.
1831 ObjFile.Addresses->applyValidRelocs(DIECopy, Offset, Data.isLittleEndian());
1832
1833 // Reset the Offset to 0 as we will be working on the local copy of
1834 // the data.
1835 Offset = 0;
1836
1837 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1838 Offset += getULEB128Size(Abbrev->getCode());
1839
1840 // We are entering a subprogram. Get and propagate the PCOffset.
1841 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1842 PCOffset = Info.AddrAdjust;
1843 AttrInfo.PCOffset = PCOffset;
1844
1845 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1846 Flags |= TF_InFunctionScope;
1847 if (!Info.InDebugMap && LLVM_LIKELY(!Update))
1848 Flags |= TF_SkipPC;
1849 } else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1850 // Function-local globals could be in the debug map even when the function
1851 // is not, e.g., inlined functions.
1852 if ((Flags & TF_InFunctionScope) && Info.InDebugMap)
1853 Flags &= ~TF_SkipPC;
1854 // Location expressions referencing an address which is not in debug map
1855 // should be deleted.
1856 else if (!Info.InDebugMap && Info.HasLocationExpressionAddr &&
1857 LLVM_LIKELY(!Update))
1858 Flags |= TF_SkipPC;
1859 }
1860
1861 std::optional<StringRef> LibraryInstallName =
1862 ObjFile.Addresses->getLibraryInstallName();
1864 for (const auto &AttrSpec : Abbrev->attributes()) {
1865 if (shouldSkipAttribute(Update, AttrSpec, Flags & TF_SkipPC)) {
1866 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1867 U.getFormParams());
1868 continue;
1869 }
1870
1871 AttributeLinkedOffsetFixup CurAttrFixup;
1872 CurAttrFixup.InputAttrStartOffset = InputDIE.getOffset() + Offset;
1873 CurAttrFixup.LinkedOffsetFixupVal =
1874 Unit.getStartOffset() + OutOffset - CurAttrFixup.InputAttrStartOffset;
1875
1876 DWARFFormValue Val = AttrSpec.getFormValue();
1877 uint64_t AttrSize = Offset;
1878 Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1879 CurAttrFixup.InputAttrEndOffset = InputDIE.getOffset() + Offset;
1880 AttrSize = Offset - AttrSize;
1881
1882 uint64_t FinalAttrSize =
1883 cloneAttribute(*Die, InputDIE, File, Unit, Val, AttrSpec, AttrSize,
1884 AttrInfo, IsLittleEndian);
1885 if (FinalAttrSize != 0 && ObjFile.Addresses->needToSaveValidRelocs())
1886 AttributesFixups.push_back(CurAttrFixup);
1887
1888 OutOffset += FinalAttrSize;
1889 }
1890
1891 uint16_t Tag = InputDIE.getTag();
1892 // Add the DW_AT_APPLE_origin attribute to Compile Unit die if we have
1893 // an install name and the DWARF doesn't have the attribute yet.
1894 const bool NeedsAppleOrigin = (Tag == dwarf::DW_TAG_compile_unit) &&
1895 LibraryInstallName.has_value() &&
1896 !AttrInfo.HasAppleOrigin;
1897 if (NeedsAppleOrigin) {
1898 auto StringEntry = DebugStrPool.getEntry(LibraryInstallName.value());
1899 Die->addValue(DIEAlloc, dwarf::Attribute(dwarf::DW_AT_APPLE_origin),
1900 dwarf::DW_FORM_strp, DIEInteger(StringEntry.getOffset()));
1901 AttrInfo.Name = StringEntry;
1902 OutOffset += 4;
1903 }
1904
1905 // Look for accelerator entries.
1906 // FIXME: This is slightly wrong. An inline_subroutine without a
1907 // low_pc, but with AT_ranges might be interesting to get into the
1908 // accelerator tables too. For now stick with dsymutil's behavior.
1909 if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1910 Tag != dwarf::DW_TAG_compile_unit &&
1911 getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit,
1912 Tag != dwarf::DW_TAG_inlined_subroutine)) {
1913 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1914 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1915 Tag == dwarf::DW_TAG_inlined_subroutine);
1916 if (AttrInfo.Name) {
1917 if (AttrInfo.NameWithoutTemplate)
1918 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1919 /* SkipPubSection */ true);
1920 Unit.addNameAccelerator(Die, AttrInfo.Name,
1921 Tag == dwarf::DW_TAG_inlined_subroutine);
1922 }
1923 if (AttrInfo.Name)
1924 addObjCAccelerator(Unit, Die, AttrInfo.Name, DebugStrPool,
1925 /* SkipPubSection =*/true);
1926
1927 } else if (Tag == dwarf::DW_TAG_namespace) {
1928 if (!AttrInfo.Name)
1929 AttrInfo.Name = DebugStrPool.getEntry("(anonymous namespace)");
1930 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1931 } else if (Tag == dwarf::DW_TAG_imported_declaration && AttrInfo.Name) {
1932 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1933 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration) {
1934 bool Success = getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit);
1935 uint64_t RuntimeLang =
1936 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1937 .value_or(0);
1938 bool ObjCClassIsImplementation =
1939 (RuntimeLang == dwarf::DW_LANG_ObjC ||
1940 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1941 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1942 .value_or(0);
1943 if (Success && AttrInfo.Name && !AttrInfo.Name.getString().empty()) {
1944 uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
1945 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1946 Hash);
1947 }
1948
1949 // For Swift, mangled names are put into DW_AT_linkage_name.
1950 if (Success && AttrInfo.MangledName &&
1951 RuntimeLang == dwarf::DW_LANG_Swift &&
1952 !AttrInfo.MangledName.getString().empty() &&
1953 AttrInfo.MangledName != AttrInfo.Name) {
1954 auto Hash = djbHash(AttrInfo.MangledName.getString().data());
1955 Unit.addTypeAccelerator(Die, AttrInfo.MangledName,
1956 ObjCClassIsImplementation, Hash);
1957 }
1958 }
1959
1960 // Determine whether there are any children that we want to keep.
1961 bool HasChildren = false;
1962 for (auto Child : InputDIE.children()) {
1963 unsigned Idx = U.getDIEIndex(Child);
1964 if (Unit.getInfo(Idx).Keep) {
1965 HasChildren = true;
1966 break;
1967 }
1968 }
1969
1970 if (Unit.getOrigUnit().getVersion() >= 5 && !AttrInfo.AttrStrOffsetBaseSeen &&
1971 Die->getTag() == dwarf::DW_TAG_compile_unit) {
1972 // No DW_AT_str_offsets_base seen, add it to the DIE.
1973 Die->addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
1974 dwarf::DW_FORM_sec_offset, DIEInteger(8));
1975 OutOffset += 4;
1976 }
1977
1978 DIEAbbrev NewAbbrev = Die->generateAbbrev();
1979 if (HasChildren)
1981 // Assign a permanent abbrev number
1982 Linker.assignAbbrev(NewAbbrev);
1983 Die->setAbbrevNumber(NewAbbrev.getNumber());
1984
1985 uint64_t AbbrevNumberSize = getULEB128Size(Die->getAbbrevNumber());
1986
1987 // Add the size of the abbreviation number to the output offset.
1988 OutOffset += AbbrevNumberSize;
1989
1990 // Update fixups with the size of the abbreviation number
1991 for (AttributeLinkedOffsetFixup &F : AttributesFixups)
1992 F.LinkedOffsetFixupVal += AbbrevNumberSize;
1993
1994 for (AttributeLinkedOffsetFixup &F : AttributesFixups)
1995 ObjFile.Addresses->updateAndSaveValidRelocs(
1996 Unit.getOrigUnit().getVersion() >= 5, Unit.getOrigUnit().getOffset(),
1997 F.LinkedOffsetFixupVal, F.InputAttrStartOffset, F.InputAttrEndOffset);
1998
1999 if (!HasChildren) {
2000 // Update our size.
2001 Die->setSize(OutOffset - Die->getOffset());
2002 return Die;
2003 }
2004
2005 // Recursively clone children.
2006 for (auto Child : InputDIE.children()) {
2007 if (DIE *Clone = cloneDIE(Child, File, Unit, PCOffset, OutOffset, Flags,
2008 IsLittleEndian)) {
2009 Die->addChild(Clone);
2010 OutOffset = Clone->getOffset() + Clone->getSize();
2011 }
2012 }
2013
2014 // Account for the end of children marker.
2015 OutOffset += sizeof(int8_t);
2016 // Update our size.
2017 Die->setSize(OutOffset - Die->getOffset());
2018 return Die;
2019}
2020
2021/// Patch the input object file relevant debug_ranges or debug_rnglists
2022/// entries and emit them in the output file. Update the relevant attributes
2023/// to point at the new entries.
2024Error DWARFLinker::generateUnitRanges(CompileUnit &Unit, const DWARFFile &File,
2025 DebugDieValuePool &AddrPool) const {
2026 if (LLVM_UNLIKELY(Options.Update))
2027 return Error::success();
2028
2029 const auto &FunctionRanges = Unit.getFunctionRanges();
2030
2031 // Build set of linked address ranges for unit function ranges.
2032 AddressRanges LinkedFunctionRanges;
2033 for (const AddressRangeValuePair &Range : FunctionRanges)
2034 LinkedFunctionRanges.insert(
2035 {Range.Range.start() + Range.Value, Range.Range.end() + Range.Value});
2036
2037 // Emit LinkedFunctionRanges into .debug_aranges
2038 if (!LinkedFunctionRanges.empty())
2039 TheDwarfEmitter->emitDwarfDebugArangesTable(Unit, LinkedFunctionRanges);
2040
2041 RngListAttributesTy AllRngListAttributes = Unit.getRangesAttributes();
2042 std::optional<PatchLocation> UnitRngListAttribute =
2043 Unit.getUnitRangesAttribute();
2044
2045 if (!AllRngListAttributes.empty() || UnitRngListAttribute) {
2046 std::optional<AddressRangeValuePair> CachedRange;
2047 MCSymbol *EndLabel = TheDwarfEmitter->emitDwarfDebugRangeListHeader(Unit);
2048
2049 // Read original address ranges, apply relocation value, emit linked address
2050 // ranges.
2051 for (PatchLocation &AttributePatch : AllRngListAttributes) {
2052 // Get ranges from the source DWARF corresponding to the current
2053 // attribute.
2054 AddressRanges LinkedRanges;
2055 if (Expected<DWARFAddressRangesVector> OriginalRanges =
2056 Unit.getOrigUnit().findRnglistFromOffset(AttributePatch.get())) {
2057 // Apply relocation adjustment.
2058 for (const auto &Range : *OriginalRanges) {
2059 if (!CachedRange || !CachedRange->Range.contains(Range.LowPC))
2060 CachedRange = FunctionRanges.getRangeThatContains(Range.LowPC);
2061
2062 // All range entries should lie in the function range.
2063 if (!CachedRange) {
2064 reportWarning("inconsistent range data.", File);
2065 continue;
2066 }
2067
2068 // Store range for emiting.
2069 LinkedRanges.insert({Range.LowPC + CachedRange->Value,
2070 Range.HighPC + CachedRange->Value});
2071 }
2072 } else {
2073 llvm::consumeError(OriginalRanges.takeError());
2074 reportWarning("invalid range list ignored.", File);
2075 }
2076
2077 // Emit linked ranges.
2078 if (Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2079 Unit, LinkedRanges, AttributePatch, AddrPool))
2080 return E;
2081 }
2082
2083 // Emit ranges for Unit AT_ranges attribute.
2084 if (UnitRngListAttribute.has_value())
2085 if (Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2086 Unit, LinkedFunctionRanges, *UnitRngListAttribute, AddrPool))
2087 return E;
2088
2089 // Emit ranges footer.
2090 TheDwarfEmitter->emitDwarfDebugRangeListFooter(Unit, EndLabel);
2091 }
2092
2093 return Error::success();
2094}
2095
2096Error DWARFLinker::DIECloner::generateUnitLocations(
2097 CompileUnit &Unit, const DWARFFile &File,
2098 ExpressionHandlerRef ExprHandler) {
2099 if (LLVM_UNLIKELY(Linker.Options.Update))
2100 return Error::success();
2101
2102 const LocListAttributesTy &AllLocListAttributes =
2103 Unit.getLocationAttributes();
2104
2105 if (AllLocListAttributes.empty())
2106 return Error::success();
2107
2108 // Emit locations list table header.
2109 MCSymbol *EndLabel = Emitter->emitDwarfDebugLocListHeader(Unit);
2110
2111 for (auto &CurLocAttr : AllLocListAttributes) {
2112 // Get location expressions vector corresponding to the current attribute
2113 // from the source DWARF.
2114 Expected<DWARFLocationExpressionsVector> OriginalLocations =
2115 Unit.getOrigUnit().findLoclistFromOffset(CurLocAttr.get());
2116
2117 if (!OriginalLocations) {
2118 llvm::consumeError(OriginalLocations.takeError());
2119 Linker.reportWarning("Invalid location attribute ignored.", File);
2120 continue;
2121 }
2122
2123 DWARFLocationExpressionsVector LinkedLocationExpressions;
2124 for (DWARFLocationExpression &CurExpression : *OriginalLocations) {
2125 DWARFLocationExpression LinkedExpression;
2126
2127 if (CurExpression.Range) {
2128 // Relocate address range.
2129 LinkedExpression.Range = {
2130 CurExpression.Range->LowPC + CurLocAttr.RelocAdjustment,
2131 CurExpression.Range->HighPC + CurLocAttr.RelocAdjustment};
2132 }
2133
2134 // Clone expression.
2135 LinkedExpression.Expr.reserve(CurExpression.Expr.size());
2136 ExprHandler(CurExpression.Expr, LinkedExpression.Expr,
2137 CurLocAttr.RelocAdjustment);
2138
2139 LinkedLocationExpressions.push_back(LinkedExpression);
2140 }
2141
2142 // Emit locations list table fragment corresponding to the CurLocAttr.
2143 if (Error E = Emitter->emitDwarfDebugLocListFragment(
2144 Unit, LinkedLocationExpressions, CurLocAttr, AddrPool))
2145 return E;
2146 }
2147
2148 // Emit locations list table footer.
2149 Emitter->emitDwarfDebugLocListFooter(Unit, EndLabel);
2150
2151 return Error::success();
2152}
2153
2155 for (auto &V : Die.values())
2156 if (V.getAttribute() == dwarf::DW_AT_addr_base) {
2157 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2158 return;
2159 }
2160
2161 llvm_unreachable("Didn't find a DW_AT_addr_base in cloned DIE!");
2162}
2163
2164Error DWARFLinker::DIECloner::emitDebugAddrSection(
2165 CompileUnit &Unit, const uint16_t DwarfVersion) const {
2166
2167 if (LLVM_UNLIKELY(Linker.Options.Update))
2168 return Error::success();
2169
2170 if (DwarfVersion < 5)
2171 return Error::success();
2172
2173 if (AddrPool.getValues().empty())
2174 return Error::success();
2175
2176 MCSymbol *EndLabel = Emitter->emitDwarfDebugAddrsHeader(Unit);
2177 uint64_t AddrOffset = Emitter->getDebugAddrSectionSize();
2178 dwarf::FormParams FP = Unit.getOrigUnit().getFormParams();
2179 if (AddrOffset > FP.getDwarfMaxOffset())
2180 return createStringError(".debug_addr section offset 0x" +
2181 Twine::utohexstr(AddrOffset) + " exceeds the " +
2182 dwarf::FormatString(FP.Format) + " limit");
2183 patchAddrBase(*Unit.getOutputUnitDIE(), DIEInteger(AddrOffset));
2184 Emitter->emitDwarfDebugAddrs(AddrPool.getValues(),
2185 Unit.getOrigUnit().getAddressByteSize());
2186 Emitter->emitDwarfDebugAddrsFooter(Unit, EndLabel);
2187
2188 return Error::success();
2189}
2190
2191/// A helper struct to help keep track of the association between the input and
2192/// output rows during line table rewriting. This is used to patch
2193/// DW_AT_LLVM_stmt_sequence attributes, which reference a particular line table
2194/// row.
2200
2201/// Insert the new line info sequence \p Seq into the current
2202/// set of already linked line info \p Rows.
2203static void insertLineSequence(std::vector<TrackedRow> &Seq,
2204 std::vector<TrackedRow> &Rows) {
2205 if (Seq.empty())
2206 return;
2207
2208 // Mark the first row in Seq to indicate it is the start of a sequence
2209 // in the output line table.
2210 Seq.front().isStartSeqInOutput = true;
2211
2212 if (!Rows.empty() && Rows.back().Row.Address < Seq.front().Row.Address) {
2213 llvm::append_range(Rows, Seq);
2214 Seq.clear();
2215 return;
2216 }
2217
2218 object::SectionedAddress Front = Seq.front().Row.Address;
2220 Rows, [=](const TrackedRow &O) { return O.Row.Address < Front; });
2221
2222 // FIXME: this only removes the unneeded end_sequence if the
2223 // sequences have been inserted in order. Using a global sort like
2224 // described in generateLineTableForUnit() and delaying the end_sequence
2225 // elimination to emitLineTableForUnit() we can get rid of all of them.
2226 if (InsertPoint != Rows.end() && InsertPoint->Row.Address == Front &&
2227 InsertPoint->Row.EndSequence) {
2228 *InsertPoint = Seq.front();
2229 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2230 } else {
2231 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2232 }
2233
2234 Seq.clear();
2235}
2236
2238 for (auto &V : Die.values())
2239 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2240 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2241 return;
2242 }
2243
2244 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2245}
2246
2247void DWARFLinker::DIECloner::rememberUnitForMacroOffset(CompileUnit &Unit) {
2248 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2249 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
2250
2251 if (std::optional<uint64_t> MacroAttr =
2252 dwarf::toSectionOffset(OrigUnitDie.find(dwarf::DW_AT_macros))) {
2253 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2254 return;
2255 }
2256
2257 if (std::optional<uint64_t> MacroAttr =
2258 dwarf::toSectionOffset(OrigUnitDie.find(dwarf::DW_AT_macro_info))) {
2259 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2260 return;
2261 }
2262}
2263
2264Error DWARFLinker::DIECloner::generateLineTableForUnit(CompileUnit &Unit) {
2265 if (LLVM_UNLIKELY(Emitter == nullptr))
2266 return Error::success();
2267
2268 // Check whether DW_AT_stmt_list attribute is presented.
2269 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
2270 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
2271 if (!StmtList)
2272 return Error::success();
2273
2274 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2275 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2276 uint64_t StmtOffset = Emitter->getLineSectionSize();
2277 dwarf::FormParams FP = Unit.getOrigUnit().getFormParams();
2278 if (StmtOffset > FP.getDwarfMaxOffset())
2279 return createStringError(".debug_line section offset 0x" +
2280 Twine::utohexstr(StmtOffset) + " exceeds the " +
2281 dwarf::FormatString(FP.Format) + " limit");
2282 patchStmtList(*OutputDIE, DIEInteger(StmtOffset));
2283 }
2284
2285 if (const DWARFDebugLine::LineTable *LT =
2286 ObjFile.Dwarf->getLineTableForUnit(&Unit.getOrigUnit())) {
2287
2288 DWARFDebugLine::LineTable LineTable;
2289
2290 // Set Line Table header.
2291 LineTable.Prologue = LT->Prologue;
2292
2293 // Set Line Table Rows.
2294 if (Linker.Options.Update) {
2295 LineTable.Rows = LT->Rows;
2296 // If all the line table contains is a DW_LNE_end_sequence, clear the line
2297 // table rows, it will be inserted again in the DWARFStreamer.
2298 if (LineTable.Rows.size() == 1 && LineTable.Rows[0].EndSequence)
2299 LineTable.Rows.clear();
2300
2301 LineTable.Sequences = LT->Sequences;
2302
2303 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2304 DebugLineStrPool);
2305 } else {
2306 // Create TrackedRow objects for all input rows.
2307 std::vector<TrackedRow> InputRows;
2308 InputRows.reserve(LT->Rows.size());
2309 for (size_t i = 0; i < LT->Rows.size(); i++)
2310 InputRows.emplace_back(TrackedRow{LT->Rows[i], i, false});
2311
2312 // This vector is the output line table (still in TrackedRow form).
2313 std::vector<TrackedRow> OutputRows;
2314 OutputRows.reserve(InputRows.size());
2315
2316 // Current sequence of rows being extracted, before being inserted
2317 // in OutputRows.
2318 std::vector<TrackedRow> Seq;
2319 Seq.reserve(InputRows.size());
2320
2321 const auto &FunctionRanges = Unit.getFunctionRanges();
2322 std::optional<AddressRangeValuePair> CurrRange;
2323
2324 // FIXME: This logic is meant to generate exactly the same output as
2325 // Darwin's classic dsymutil. There is a nicer way to implement this
2326 // by simply putting all the relocated line info in OutputRows and simply
2327 // sorting OutputRows before passing it to emitLineTableForUnit. This
2328 // should be correct as sequences for a function should stay
2329 // together in the sorted output. There are a few corner cases that
2330 // look suspicious though, and that required to implement the logic
2331 // this way. Revisit that once initial validation is finished.
2332
2333 // Iterate over the object file line info and extract the sequences
2334 // that correspond to linked functions.
2335 for (size_t i = 0; i < InputRows.size(); i++) {
2336 TrackedRow TR = InputRows[i];
2337
2338 // Check whether we stepped out of the range. The range is
2339 // half-open, but consider accepting the end address of the range if
2340 // it is marked as end_sequence in the input (because in that
2341 // case, the relocation offset is accurate and that entry won't
2342 // serve as the start of another function).
2343 if (!CurrRange || !CurrRange->Range.contains(TR.Row.Address.Address)) {
2344 // We just stepped out of a known range. Insert an end_sequence
2345 // corresponding to the end of the range.
2346 uint64_t StopAddress =
2347 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
2348 CurrRange =
2349 FunctionRanges.getRangeThatContains(TR.Row.Address.Address);
2350 if (StopAddress != -1ULL && !Seq.empty()) {
2351 // Insert end sequence row with the computed end address, but
2352 // the same line as the previous one.
2353 auto NextLine = Seq.back();
2354 NextLine.Row.Address.Address = StopAddress;
2355 NextLine.Row.EndSequence = 1;
2356 NextLine.Row.PrologueEnd = 0;
2357 NextLine.Row.BasicBlock = 0;
2358 NextLine.Row.EpilogueBegin = 0;
2359 Seq.push_back(NextLine);
2360 insertLineSequence(Seq, OutputRows);
2361 }
2362
2363 if (!CurrRange)
2364 continue;
2365 }
2366
2367 // Ignore empty sequences.
2368 if (TR.Row.EndSequence && Seq.empty())
2369 continue;
2370
2371 // Relocate row address and add it to the current sequence.
2372 TR.Row.Address.Address += CurrRange->Value;
2373 Seq.push_back(TR);
2374
2375 if (TR.Row.EndSequence)
2376 insertLineSequence(Seq, OutputRows);
2377 }
2378
2379 // Recompute isStartSeqInOutput based on the final row ordering.
2380 // A row is a sequence start (will have DW_LNE_set_address emitted) iff:
2381 // 1. It's the first row, OR
2382 // 2. The previous row has EndSequence = 1
2383 // This is necessary because insertLineSequence may merge sequences when
2384 // an EndSequence row is replaced by the start of a new sequence, which
2385 // removes the EndSequence marker and invalidates the original flag.
2386 if (!OutputRows.empty()) {
2387 OutputRows[0].isStartSeqInOutput = true;
2388 for (size_t i = 1; i < OutputRows.size(); ++i)
2389 OutputRows[i].isStartSeqInOutput = OutputRows[i - 1].Row.EndSequence;
2390 }
2391
2392 // Materialize the tracked rows into final DWARFDebugLine::Row objects.
2393 LineTable.Rows.clear();
2394 LineTable.Rows.reserve(OutputRows.size());
2395 for (auto &TR : OutputRows)
2396 LineTable.Rows.push_back(TR.Row);
2397
2398 // Use OutputRowOffsets to store the offsets of each line table row in the
2399 // output .debug_line section.
2400 std::vector<uint64_t> OutputRowOffsets;
2401
2402 // The unit might not have any DW_AT_LLVM_stmt_sequence attributes, so use
2403 // hasStmtSeq to skip the patching logic.
2404 bool hasStmtSeq = Unit.getStmtSeqListAttributes().size() > 0;
2405 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2406 DebugLineStrPool,
2407 hasStmtSeq ? &OutputRowOffsets : nullptr);
2408
2409 if (hasStmtSeq) {
2410 assert(OutputRowOffsets.size() == OutputRows.size() &&
2411 "must have an offset for each row");
2412
2413 // Create a map of stmt sequence offsets to original row indices.
2414 DenseMap<uint64_t, uint64_t> SeqOffToOrigRow;
2415 // The DWARF parser's discovery of sequences can be incomplete. To
2416 // ensure all DW_AT_LLVM_stmt_sequence attributes can be patched, we
2417 // build a map from both the parser's results and a manual
2418 // reconstruction.
2419 if (!LT->Rows.empty())
2420 constructSeqOffsettoOrigRowMapping(Unit, *LT, SeqOffToOrigRow);
2421
2422 // Build two maps to handle stmt_sequence patching:
2423 // 1. OrigRowToOutputRow: maps original row indices to output row
2424 // indices (for all rows, not just sequence starts).
2425 // 2. OutputRowToSeqStart: maps each output row index to its sequence
2426 // start's output row index
2427 DenseMap<size_t, size_t> OrigRowToOutputRow;
2428 std::vector<size_t> OutputRowToSeqStart(OutputRows.size());
2429
2430 size_t CurrentSeqStart = 0;
2431 for (size_t i = 0; i < OutputRows.size(); ++i) {
2432 // Track the current sequence start.
2433 if (OutputRows[i].isStartSeqInOutput)
2434 CurrentSeqStart = i;
2435 OutputRowToSeqStart[i] = CurrentSeqStart;
2436
2437 // Map original row index to output row index.
2438 OrigRowToOutputRow[OutputRows[i].OriginalRowIndex] = i;
2439 }
2440
2441 // Patch DW_AT_LLVM_stmt_sequence attributes in the compile unit DIE
2442 // with the correct offset into the .debug_line section.
2443 for (const auto &StmtSeq : Unit.getStmtSeqListAttributes()) {
2444 uint64_t OrigStmtSeq = StmtSeq.get();
2445 // 1. Get the original row index from the stmt list offset.
2446 auto OrigRowIter = SeqOffToOrigRow.find(OrigStmtSeq);
2447 const uint64_t InvalidOffset =
2448 Unit.getOrigUnit().getFormParams().getDwarfMaxOffset();
2449 // Check whether we have an output sequence for the StmtSeq offset.
2450 // Some sequences are discarded by the DWARFLinker if they are invalid
2451 // (empty).
2452 if (OrigRowIter == SeqOffToOrigRow.end()) {
2453 StmtSeq.set(InvalidOffset);
2454 continue;
2455 }
2456 size_t OrigRowIndex = OrigRowIter->second;
2457
2458 // 2. Find the output row for this original row.
2459 auto OutputRowIter = OrigRowToOutputRow.find(OrigRowIndex);
2460 if (OutputRowIter == OrigRowToOutputRow.end()) {
2461 // Row was dropped during linking.
2462 StmtSeq.set(InvalidOffset);
2463 continue;
2464 }
2465 size_t OutputRowIdx = OutputRowIter->second;
2466
2467 // 3. Find the sequence start for this output row.
2468 // If the original row was a sequence start but got merged into
2469 // another sequence, this finds the correct sequence start.
2470 size_t SeqStartIdx = OutputRowToSeqStart[OutputRowIdx];
2471
2472 // 4. Get the offset of the sequence start in the output .debug_line
2473 // section. This offset points to the DW_LNE_set_address opcode.
2474 assert(SeqStartIdx < OutputRowOffsets.size() &&
2475 "Sequence start index out of bounds");
2476 uint64_t NewStmtSeqOffset = OutputRowOffsets[SeqStartIdx];
2477
2478 // 5. Patch the stmt_sequence attribute with the new offset.
2479 StmtSeq.set(NewStmtSeqOffset);
2480 }
2481 }
2482 }
2483
2484 } else
2485 Linker.reportWarning("Cann't load line table.", ObjFile);
2486
2487 return Error::success();
2488}
2489
2490void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2491 for (AccelTableKind AccelTableKind : Options.AccelTables) {
2492 switch (AccelTableKind) {
2493 case AccelTableKind::Apple: {
2494 // Add namespaces.
2495 for (const auto &Namespace : Unit.getNamespaces())
2496 AppleNamespaces.addName(Namespace.Name, Namespace.Die->getOffset() +
2497 Unit.getStartOffset());
2498 // Add names.
2499 for (const auto &Pubname : Unit.getPubnames())
2500 AppleNames.addName(Pubname.Name,
2501 Pubname.Die->getOffset() + Unit.getStartOffset());
2502 // Add types.
2503 for (const auto &Pubtype : Unit.getPubtypes())
2504 AppleTypes.addName(
2505 Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
2506 Pubtype.Die->getTag(),
2507 Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
2508 : 0,
2509 Pubtype.QualifiedNameHash);
2510 // Add ObjC names.
2511 for (const auto &ObjC : Unit.getObjC())
2512 AppleObjc.addName(ObjC.Name,
2513 ObjC.Die->getOffset() + Unit.getStartOffset());
2514 } break;
2515 case AccelTableKind::Pub: {
2516 TheDwarfEmitter->emitPubNamesForUnit(Unit);
2517 TheDwarfEmitter->emitPubTypesForUnit(Unit);
2518 } break;
2520 for (const auto &Namespace : Unit.getNamespaces())
2521 DebugNames.addName(
2522 Namespace.Name, Namespace.Die->getOffset(),
2524 Namespace.Die->getTag(), Unit.getUniqueID(),
2525 Unit.getTag() == dwarf::DW_TAG_type_unit);
2526 for (const auto &Pubname : Unit.getPubnames())
2527 DebugNames.addName(
2528 Pubname.Name, Pubname.Die->getOffset(),
2530 Pubname.Die->getTag(), Unit.getUniqueID(),
2531 Unit.getTag() == dwarf::DW_TAG_type_unit);
2532 for (const auto &Pubtype : Unit.getPubtypes())
2533 DebugNames.addName(
2534 Pubtype.Name, Pubtype.Die->getOffset(),
2536 Pubtype.Die->getTag(), Unit.getUniqueID(),
2537 Unit.getTag() == dwarf::DW_TAG_type_unit);
2538 } break;
2539 }
2540 }
2541}
2542
2543/// Read the frame info stored in the object, and emit the
2544/// patched frame descriptions for the resulting file.
2545///
2546/// This is actually pretty easy as the data of the CIEs and FDEs can
2547/// be considered as black boxes and moved as is. The only thing to do
2548/// is to patch the addresses in the headers.
2549void DWARFLinker::patchFrameInfoForObject(LinkContext &Context) {
2550 DWARFContext &OrigDwarf = *Context.File.Dwarf;
2551 unsigned SrcAddrSize = OrigDwarf.getDWARFObj().getAddressSize();
2552
2553 StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
2554 if (FrameData.empty())
2555 return;
2556
2557 RangesTy AllUnitsRanges;
2558 for (std::unique_ptr<CompileUnit> &Unit : Context.CompileUnits) {
2559 for (auto CurRange : Unit->getFunctionRanges())
2560 AllUnitsRanges.insert(CurRange.Range, CurRange.Value);
2561 }
2562
2563 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian());
2564 uint64_t InputOffset = 0;
2565
2566 // Store the data of the CIEs defined in this object, keyed by their
2567 // offsets.
2568 DenseMap<uint64_t, StringRef> LocalCIES;
2569
2570 while (Data.isValidOffset(InputOffset)) {
2571 uint64_t EntryOffset = InputOffset;
2572 uint32_t InitialLength = Data.getU32(&InputOffset);
2573 if (InitialLength == 0xFFFFFFFF)
2574 return reportWarning("Dwarf64 bits no supported", Context.File);
2575
2576 uint32_t CIEId = Data.getU32(&InputOffset);
2577 if (CIEId == 0xFFFFFFFF) {
2578 // This is a CIE, store it.
2579 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2580 LocalCIES[EntryOffset] = CIEData;
2581 // The -4 is to account for the CIEId we just read.
2582 InputOffset += InitialLength - 4;
2583 continue;
2584 }
2585
2586 uint64_t Loc = Data.getUnsigned(&InputOffset, SrcAddrSize);
2587
2588 // Some compilers seem to emit frame info that doesn't start at
2589 // the function entry point, thus we can't just lookup the address
2590 // in the debug map. Use the AddressInfo's range map to see if the FDE
2591 // describes something that we can relocate.
2592 std::optional<AddressRangeValuePair> Range =
2593 AllUnitsRanges.getRangeThatContains(Loc);
2594 if (!Range) {
2595 // The +4 is to account for the size of the InitialLength field itself.
2596 InputOffset = EntryOffset + InitialLength + 4;
2597 continue;
2598 }
2599
2600 // This is an FDE, and we have a mapping.
2601 // Have we already emitted a corresponding CIE?
2602 StringRef CIEData = LocalCIES[CIEId];
2603 if (CIEData.empty())
2604 return reportWarning("Inconsistent debug_frame content. Dropping.",
2605 Context.File);
2606
2607 // Look if we already emitted a CIE that corresponds to the
2608 // referenced one (the CIE data is the key of that lookup).
2609 auto IteratorInserted = EmittedCIEs.insert(
2610 std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
2611 // If there is no CIE yet for this ID, emit it.
2612 if (IteratorInserted.second) {
2613 LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
2614 IteratorInserted.first->getValue() = LastCIEOffset;
2615 TheDwarfEmitter->emitCIE(CIEData);
2616 }
2617
2618 // Emit the FDE with updated address and CIE pointer.
2619 // (4 + AddrSize) is the size of the CIEId + initial_location
2620 // fields that will get reconstructed by emitFDE().
2621 unsigned FDERemainingBytes = InitialLength - (4 + SrcAddrSize);
2622 TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), SrcAddrSize,
2623 Loc + Range->Value,
2624 FrameData.substr(InputOffset, FDERemainingBytes));
2625 InputOffset += FDERemainingBytes;
2626 }
2627}
2628
2629uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
2630 CompileUnit &U,
2631 const DWARFFile &File,
2632 int ChildRecurseDepth) {
2633 const char *Name = nullptr;
2634 DWARFUnit *OrigUnit = &U.getOrigUnit();
2635 CompileUnit *CU = &U;
2636 std::optional<DWARFFormValue> Ref;
2637
2638 while (true) {
2639 if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
2640 Name = CurrentName;
2641
2642 if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
2643 !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
2644 break;
2645
2646 if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
2647 break;
2648
2649 CompileUnit *RefCU;
2650 if (auto RefDIE =
2651 Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
2652 CU = RefCU;
2653 OrigUnit = &RefCU->getOrigUnit();
2654 DIE = RefDIE;
2655 }
2656 }
2657
2658 unsigned Idx = OrigUnit->getDIEIndex(DIE);
2659 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
2660 Name = "(anonymous namespace)";
2661
2662 if (CU->getInfo(Idx).ParentIdx == 0 ||
2663 // FIXME: dsymutil-classic compatibility. Ignore modules.
2664 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
2665 dwarf::DW_TAG_module)
2666 return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
2667
2668 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
2669 return djbHash(
2670 (Name ? Name : ""),
2671 djbHash((Name ? "::" : ""),
2672 hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
2673}
2674
2675static uint64_t getDwoId(const DWARFDie &CUDie) {
2676 auto DwoId = dwarf::toUnsigned(
2677 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2678 if (DwoId)
2679 return *DwoId;
2680 return 0;
2681}
2682
2683static std::string
2685 const DWARFLinkerBase::ObjectPrefixMapTy &ObjectPrefixMap) {
2686 if (ObjectPrefixMap.empty())
2687 return Path.str();
2688
2689 SmallString<256> p = Path;
2690 for (const auto &Entry : ObjectPrefixMap)
2691 if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
2692 break;
2693 return p.str().str();
2694}
2695
2696static std::string
2698 const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap) {
2699 std::string PCMFile = dwarf::toString(
2700 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2701
2702 if (PCMFile.empty())
2703 return PCMFile;
2704
2705 if (ObjectPrefixMap)
2706 PCMFile = remapPath(PCMFile, *ObjectPrefixMap);
2707
2708 return PCMFile;
2709}
2710
2711std::pair<bool, bool> DWARFLinker::isClangModuleRef(const DWARFDie &CUDie,
2712 std::string &PCMFile,
2713 LinkContext &Context,
2714 unsigned Indent,
2715 bool Quiet) {
2716 if (PCMFile.empty())
2717 return std::make_pair(false, false);
2718
2719 // Clang module DWARF skeleton CUs abuse this for the path to the module.
2720 uint64_t DwoId = getDwoId(CUDie);
2721
2722 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2723 if (Name.empty()) {
2724 if (!Quiet)
2725 reportWarning("Anonymous module skeleton CU for " + PCMFile,
2726 Context.File);
2727 return std::make_pair(true, true);
2728 }
2729
2730 if (!Quiet && Options.Verbose) {
2731 outs().indent(Indent);
2732 outs() << "Found clang module reference " << PCMFile;
2733 }
2734
2735 auto Cached = ClangModules.find(PCMFile);
2736 if (Cached != ClangModules.end()) {
2737 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2738 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2739 // ASTFileSignatures will change randomly when a module is rebuilt.
2740 if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2741 reportWarning(Twine("hash mismatch: this object file was built against a "
2742 "different version of the module ") +
2743 PCMFile,
2744 Context.File);
2745 if (!Quiet && Options.Verbose)
2746 outs() << " [cached].\n";
2747 return std::make_pair(true, true);
2748 }
2749
2750 return std::make_pair(true, false);
2751}
2752
2753bool DWARFLinker::registerModuleReference(const DWARFDie &CUDie,
2754 LinkContext &Context,
2755 ObjFileLoaderTy Loader,
2756 CompileUnitHandlerTy OnCUDieLoaded,
2757 unsigned Indent) {
2758 std::string PCMFile = getPCMFile(CUDie, Options.ObjectPrefixMap);
2759 std::pair<bool, bool> IsClangModuleRef =
2760 isClangModuleRef(CUDie, PCMFile, Context, Indent, false);
2761
2762 if (!IsClangModuleRef.first)
2763 return false;
2764
2765 if (IsClangModuleRef.second)
2766 return true;
2767
2768 if (Options.Verbose)
2769 outs() << " ...\n";
2770
2771 // Cyclic dependencies are disallowed by Clang, but we still
2772 // shouldn't run into an infinite loop, so mark it as processed now.
2773 ClangModules.insert({PCMFile, getDwoId(CUDie)});
2774
2775 if (Error E = loadClangModule(Loader, CUDie, PCMFile, Context, OnCUDieLoaded,
2776 Indent + 2)) {
2777 consumeError(std::move(E));
2778 return false;
2779 }
2780 return true;
2781}
2782
2783Error DWARFLinker::loadClangModule(
2784 ObjFileLoaderTy Loader, const DWARFDie &CUDie, const std::string &PCMFile,
2785 LinkContext &Context, CompileUnitHandlerTy OnCUDieLoaded, unsigned Indent) {
2786
2787 uint64_t DwoId = getDwoId(CUDie);
2788 std::string ModuleName = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2789
2790 /// Using a SmallString<0> because loadClangModule() is recursive.
2791 SmallString<0> Path(Options.PrependPath);
2792 if (sys::path::is_relative(PCMFile))
2793 resolveRelativeObjectPath(Path, CUDie);
2794 sys::path::append(Path, PCMFile);
2795 // Don't use the cached binary holder because we have no thread-safety
2796 // guarantee and the lifetime is limited.
2797
2798 if (Loader == nullptr) {
2799 reportError("Could not load clang module: loader is not specified.\n",
2800 Context.File);
2801 return Error::success();
2802 }
2803
2804 auto ErrOrObj = Loader(Context.File.FileName, Path);
2805 if (!ErrOrObj)
2806 return Error::success();
2807
2808 std::unique_ptr<CompileUnit> Unit;
2809 for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2810 OnCUDieLoaded(*CU);
2811 // Recursively get all modules imported by this one.
2812 auto ChildCUDie = CU->getUnitDIE();
2813 if (!ChildCUDie)
2814 continue;
2815 if (!registerModuleReference(ChildCUDie, Context, Loader, OnCUDieLoaded,
2816 Indent)) {
2817 if (Unit) {
2818 std::string Err =
2819 (PCMFile +
2820 ": Clang modules are expected to have exactly 1 compile unit.\n");
2821 reportError(Err, Context.File);
2823 }
2824 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2825 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2826 // ASTFileSignatures will change randomly when a module is rebuilt.
2827 uint64_t PCMDwoId = getDwoId(ChildCUDie);
2828 if (PCMDwoId != DwoId) {
2829 if (Options.Verbose)
2830 reportWarning(
2831 Twine("hash mismatch: this object file was built against a "
2832 "different version of the module ") +
2833 PCMFile,
2834 Context.File);
2835 // Update the cache entry with the DwoId of the module loaded from disk.
2836 ClangModules[PCMFile] = PCMDwoId;
2837 }
2838
2839 // Add this module.
2840 Unit = std::make_unique<CompileUnit>(*CU, UniqueUnitID++, !Options.NoODR,
2841 ModuleName);
2842 }
2843 }
2844
2845 if (Unit)
2846 Context.ModuleUnits.emplace_back(RefModuleUnit{*ErrOrObj, std::move(Unit)});
2847
2848 return Error::success();
2849}
2850
2851Expected<uint64_t> DWARFLinker::DIECloner::cloneAllCompileUnits(
2852 DWARFContext &DwarfContext, const DWARFFile &File, bool IsLittleEndian) {
2853 uint64_t OutputDebugInfoSize =
2854 (Emitter == nullptr) ? 0 : Emitter->getDebugInfoSectionSize();
2855 const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2856
2857 for (auto &CurrentUnit : CompileUnits) {
2858 const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2859 const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2860 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2861 CurrentUnit->setStartOffset(OutputDebugInfoSize);
2862 if (!InputDIE) {
2863 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2864 continue;
2865 }
2866 if (CurrentUnit->getInfo(0).Keep) {
2867 // Clone the InputDIE into your Unit DIE in our compile unit since it
2868 // already has a DIE inside of it.
2869 CurrentUnit->createOutputDIE();
2870 rememberUnitForMacroOffset(*CurrentUnit);
2871 cloneDIE(InputDIE, File, *CurrentUnit, 0 /* PC offset */, UnitHeaderSize,
2872 0, IsLittleEndian, CurrentUnit->getOutputUnitDIE());
2873 }
2874
2875 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2876
2877 if (Emitter != nullptr) {
2878
2879 if (Error E = generateLineTableForUnit(*CurrentUnit))
2880 return E;
2881
2882 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2883
2884 if (LLVM_UNLIKELY(Linker.Options.Update))
2885 continue;
2886
2887 if (Error E = Linker.generateUnitRanges(*CurrentUnit, File, AddrPool))
2888 return E;
2889
2890 auto ProcessExpr = [&](SmallVectorImpl<uint8_t> &SrcBytes,
2891 SmallVectorImpl<uint8_t> &OutBytes,
2892 int64_t RelocAdjustment) {
2893 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2894 DataExtractor Data(SrcBytes, IsLittleEndian);
2895 cloneExpression(Data,
2896 DWARFExpression(Data, OrigUnit.getAddressByteSize(),
2897 OrigUnit.getFormParams().Format),
2898 File, *CurrentUnit, OutBytes, RelocAdjustment,
2899 IsLittleEndian);
2900 };
2901 if (Error E = generateUnitLocations(*CurrentUnit, File, ProcessExpr))
2902 return E;
2903 if (Error E = emitDebugAddrSection(*CurrentUnit, DwarfVersion))
2904 return E;
2905 }
2906 AddrPool.clear();
2907 }
2908
2909 if (Emitter != nullptr) {
2910 assert(Emitter);
2911 // Emit macro tables.
2912 Emitter->emitMacroTables(File.Dwarf.get(), UnitMacroMap, DebugStrPool);
2913
2914 // Emit all the compile unit's debug information.
2915 for (auto &CurrentUnit : CompileUnits) {
2916 CurrentUnit->fixupForwardReferences();
2917
2918 if (!CurrentUnit->getOutputUnitDIE())
2919 continue;
2920
2921 unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2922
2923 assert(Emitter->getDebugInfoSectionSize() ==
2924 CurrentUnit->getStartOffset());
2925 Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
2926 Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
2927 assert(Emitter->getDebugInfoSectionSize() ==
2928 CurrentUnit->computeNextUnitOffset(DwarfVersion));
2929 }
2930 }
2931
2932 return OutputDebugInfoSize - StartOutputDebugInfoSize;
2933}
2934
2935void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
2936 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
2938 TheDwarfEmitter->emitSectionContents(
2939 Dwarf.getDWARFObj().getRangesSection().Data,
2941 TheDwarfEmitter->emitSectionContents(
2942 Dwarf.getDWARFObj().getFrameSection().Data, DebugSectionKind::DebugFrame);
2943 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
2945 TheDwarfEmitter->emitSectionContents(
2946 Dwarf.getDWARFObj().getAddrSection().Data, DebugSectionKind::DebugAddr);
2947 TheDwarfEmitter->emitSectionContents(
2948 Dwarf.getDWARFObj().getRnglistsSection().Data,
2950 TheDwarfEmitter->emitSectionContents(
2951 Dwarf.getDWARFObj().getLoclistsSection().Data,
2953}
2954
2956 CompileUnitHandlerTy OnCUDieLoaded) {
2957 ObjectContexts.emplace_back(LinkContext(File));
2958
2959 if (ObjectContexts.back().File.Dwarf) {
2960 for (const std::unique_ptr<DWARFUnit> &CU :
2961 ObjectContexts.back().File.Dwarf->compile_units()) {
2962 DWARFDie CUDie = CU->getUnitDIE();
2963
2964 if (!CUDie)
2965 continue;
2966
2967 OnCUDieLoaded(*CU);
2968
2969 if (!LLVM_UNLIKELY(Options.Update))
2970 registerModuleReference(CUDie, ObjectContexts.back(), Loader,
2971 OnCUDieLoaded);
2972 }
2973 }
2974}
2975
2977 assert((Options.TargetDWARFVersion != 0) &&
2978 "TargetDWARFVersion should be set");
2979
2980 // First populate the data structure we need for each iteration of the
2981 // parallel loop.
2982 unsigned NumObjects = ObjectContexts.size();
2983
2984 // This Dwarf string pool which is used for emission. It must be used
2985 // serially as the order of calling getStringOffset matters for
2986 // reproducibility.
2987 OffsetsStringPool DebugStrPool(true);
2988 OffsetsStringPool DebugLineStrPool(false);
2989 DebugDieValuePool StringOffsetPool;
2990
2991 // ODR Contexts for the optimize.
2992 DeclContextTree ODRContexts;
2993
2994 for (LinkContext &OptContext : ObjectContexts) {
2995 if (Options.Verbose)
2996 outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
2997
2998 if (!OptContext.File.Dwarf)
2999 continue;
3000
3001 if (Options.VerifyInputDWARF)
3002 verifyInput(OptContext.File);
3003
3004 // Look for relocations that correspond to address map entries.
3005
3006 // there was findvalidrelocations previously ... probably we need to gather
3007 // info here
3008 if (LLVM_LIKELY(!Options.Update) &&
3009 !OptContext.File.Addresses->hasValidRelocs()) {
3010 if (Options.Verbose)
3011 outs() << "No valid relocations found. Skipping.\n";
3012
3013 // Set "Skip" flag as a signal to other loops that we should not
3014 // process this iteration.
3015 OptContext.Skip = true;
3016 continue;
3017 }
3018
3019 // Setup access to the debug info.
3020 if (!OptContext.File.Dwarf)
3021 continue;
3022
3023 // Check whether type units are presented.
3024 if (!OptContext.File.Dwarf->types_section_units().empty()) {
3025 reportWarning("type units are not currently supported: file will "
3026 "be skipped",
3027 OptContext.File);
3028 OptContext.Skip = true;
3029 continue;
3030 }
3031
3032 // Clone all the clang modules with requires extracting the DIE units. We
3033 // don't need the full debug info until the Analyze phase.
3034 OptContext.CompileUnits.reserve(
3035 OptContext.File.Dwarf->getNumCompileUnits());
3036 for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
3037 auto CUDie = CU->getUnitDIE(/*ExtractUnitDIEOnly=*/true);
3038 if (Options.Verbose) {
3039 outs() << "Input compilation unit:";
3040 DIDumpOptions DumpOpts;
3041 DumpOpts.ChildRecurseDepth = 0;
3042 DumpOpts.Verbose = Options.Verbose;
3043 CUDie.dump(outs(), 0, DumpOpts);
3044 }
3045 }
3046
3047 for (auto &CU : OptContext.ModuleUnits) {
3048 if (Error Err = cloneModuleUnit(OptContext, CU, ODRContexts, DebugStrPool,
3049 DebugLineStrPool, StringOffsetPool))
3050 reportWarning(toString(std::move(Err)), CU.File);
3051 }
3052 }
3053
3054 // At this point we know how much data we have emitted. We use this value to
3055 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
3056 // is already emitted, without being affected by canonical die offsets set
3057 // later. This prevents undeterminism when analyze and clone execute
3058 // concurrently, as clone set the canonical DIE offset and analyze reads it.
3059 const uint64_t ModulesEndOffset =
3060 (TheDwarfEmitter == nullptr) ? 0
3061 : TheDwarfEmitter->getDebugInfoSectionSize();
3062
3063 // These variables manage the list of processed object files.
3064 // The mutex and condition variable are to ensure that this is thread safe.
3065 std::mutex ProcessedFilesMutex;
3066 std::condition_variable ProcessedFilesConditionVariable;
3067 BitVector ProcessedFiles(NumObjects, false);
3068
3069 // Analyzing the context info is particularly expensive so it is executed in
3070 // parallel with emitting the previous compile unit.
3071 auto AnalyzeLambda = [&](size_t I) {
3072 auto &Context = ObjectContexts[I];
3073
3074 if (Context.Skip || !Context.File.Dwarf)
3075 return;
3076
3077 for (const auto &CU : Context.File.Dwarf->compile_units()) {
3078 // Previously we only extracted the unit DIEs. We need the full debug info
3079 // now.
3080 auto CUDie = CU->getUnitDIE(/*ExtractUnitDIEOnly=*/false);
3081 std::string PCMFile = getPCMFile(CUDie, Options.ObjectPrefixMap);
3082
3083 if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
3084 !isClangModuleRef(CUDie, PCMFile, Context, 0, true).first) {
3085 Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
3086 *CU, UniqueUnitID++, !Options.NoODR && !Options.Update, ""));
3087 }
3088 }
3089
3090 // Now build the DIE parent links that we will use during the next phase.
3091 for (auto &CurrentUnit : Context.CompileUnits) {
3092 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
3093 if (!CUDie)
3094 continue;
3095 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
3096 *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
3097 ModulesEndOffset, Options.ParseableSwiftInterfaces,
3098 [&](const Twine &Warning, const DWARFDie &DIE) {
3099 reportWarning(Warning, Context.File, &DIE);
3100 });
3101 }
3102 };
3103
3104 // For each object file map how many bytes were emitted.
3105 StringMap<DebugInfoSize> SizeByObject;
3106
3107 // And then the remaining work in serial again.
3108 // Note, although this loop runs in serial, it can run in parallel with
3109 // the analyzeContextInfo loop so long as we process files with indices >=
3110 // than those processed by analyzeContextInfo.
3111 auto CloneLambda = [&](size_t I, llvm::Error &CE) {
3112 auto &OptContext = ObjectContexts[I];
3113 if (OptContext.Skip || !OptContext.File.Dwarf)
3114 return;
3115
3116 // Then mark all the DIEs that need to be present in the generated output
3117 // and collect some information about them.
3118 // Note that this loop can not be merged with the previous one because
3119 // cross-cu references require the ParentIdx to be setup for every CU in
3120 // the object file before calling this.
3121 if (LLVM_UNLIKELY(Options.Update)) {
3122 for (auto &CurrentUnit : OptContext.CompileUnits)
3123 CurrentUnit->markEverythingAsKept();
3124 copyInvariantDebugSection(*OptContext.File.Dwarf);
3125 } else {
3126 for (auto &CurrentUnit : OptContext.CompileUnits) {
3127 lookForDIEsToKeep(*OptContext.File.Addresses, OptContext.CompileUnits,
3128 CurrentUnit->getOrigUnit().getUnitDIE(),
3129 OptContext.File, *CurrentUnit, 0);
3130#ifndef NDEBUG
3131 verifyKeepChain(*CurrentUnit);
3132#endif
3133 }
3134 }
3135
3136 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
3137 // array again (in the same way findValidRelocsInDebugInfo() did). We
3138 // need to reset the NextValidReloc index to the beginning.
3139 if (OptContext.File.Addresses->hasValidRelocs() ||
3140 LLVM_UNLIKELY(Options.Update)) {
3141 SizeByObject[OptContext.File.FileName].Input =
3142 getDebugInfoSize(*OptContext.File.Dwarf);
3143 Expected<uint64_t> SizeOrErr =
3144 DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
3145 OptContext.CompileUnits, Options.Update, DebugStrPool,
3146 DebugLineStrPool, StringOffsetPool)
3147 .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
3148 OptContext.File.Dwarf->isLittleEndian());
3149 if (!SizeOrErr) {
3150 CE = SizeOrErr.takeError();
3151 return;
3152 }
3153 SizeByObject[OptContext.File.FileName].Output = *SizeOrErr;
3154 }
3155 if ((TheDwarfEmitter != nullptr) && !OptContext.CompileUnits.empty() &&
3156 LLVM_LIKELY(!Options.Update))
3157 patchFrameInfoForObject(OptContext);
3158
3159 // Clean-up before starting working on the next object.
3160 cleanupAuxiliarryData(OptContext);
3161 };
3162
3163 auto EmitLambda = [&]() {
3164 // Emit everything that's global.
3165 if (TheDwarfEmitter != nullptr) {
3166 TheDwarfEmitter->emitAbbrevs(Abbreviations, Options.TargetDWARFVersion);
3167 TheDwarfEmitter->emitStrings(DebugStrPool);
3168 TheDwarfEmitter->emitStringOffsets(StringOffsetPool.getValues(),
3169 Options.TargetDWARFVersion);
3170 TheDwarfEmitter->emitLineStrings(DebugLineStrPool);
3171 for (AccelTableKind TableKind : Options.AccelTables) {
3172 switch (TableKind) {
3174 TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
3175 TheDwarfEmitter->emitAppleNames(AppleNames);
3176 TheDwarfEmitter->emitAppleTypes(AppleTypes);
3177 TheDwarfEmitter->emitAppleObjc(AppleObjc);
3178 break;
3180 // Already emitted by emitAcceleratorEntriesForUnit.
3181 // Already emitted by emitAcceleratorEntriesForUnit.
3182 break;
3184 TheDwarfEmitter->emitDebugNames(DebugNames);
3185 break;
3186 }
3187 }
3188 }
3189 };
3190
3191 auto AnalyzeAll = [&]() {
3192 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
3193 AnalyzeLambda(I);
3194
3195 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3196 ProcessedFiles.set(I);
3197 ProcessedFilesConditionVariable.notify_one();
3198 }
3199 };
3200
3201 auto CloneAll = [&](llvm::Error &CE) {
3202 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
3203 {
3204 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3205 if (!ProcessedFiles[I]) {
3206 ProcessedFilesConditionVariable.wait(
3207 LockGuard, [&]() { return ProcessedFiles[I]; });
3208 }
3209 }
3210
3211 CloneLambda(I, CE);
3212 if (CE)
3213 return;
3214 }
3215 EmitLambda();
3216 };
3217
3218 Error CE = Error::success();
3219
3220 // To limit memory usage in the single threaded case, analyze and clone are
3221 // run sequentially so the OptContext is freed after processing each object
3222 // in endDebugObject.
3223 if (Options.Threads == 1) {
3224 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
3225 AnalyzeLambda(I);
3226 CloneLambda(I, CE);
3227 if (CE)
3228 break;
3229 }
3230 if (!CE)
3231 EmitLambda();
3232 } else {
3234 Pool.async(AnalyzeAll);
3235 Pool.async(CloneAll, std::reference_wrapper<Error>(CE));
3236 Pool.wait();
3237 }
3238
3239 if (CE)
3240 return CE;
3241
3242 if (Options.Statistics) {
3243 // Create a vector sorted in descending order by output size.
3244 std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
3245 for (auto &E : SizeByObject)
3246 Sorted.emplace_back(E.first(), E.second);
3247 llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
3248 return LHS.second.Output > RHS.second.Output;
3249 });
3250
3251 auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
3252 const float Difference = Output - Input;
3253 const float Sum = Input + Output;
3254 if (Sum == 0)
3255 return 0;
3256 return (Difference / (Sum / 2));
3257 };
3258
3259 int64_t InputTotal = 0;
3260 int64_t OutputTotal = 0;
3261 const char *FormatStr = "{0,-45} {1,10}b {2,10}b {3,8:P}\n";
3262
3263 // Print header.
3264 outs() << ".debug_info section size (in bytes)\n";
3265 outs() << "----------------------------------------------------------------"
3266 "---------------\n";
3267 outs() << "Filename Object "
3268 " dSYM Change\n";
3269 outs() << "----------------------------------------------------------------"
3270 "---------------\n";
3271
3272 // Print body.
3273 for (auto &E : Sorted) {
3274 InputTotal += E.second.Input;
3275 OutputTotal += E.second.Output;
3276 llvm::outs() << formatv(
3277 FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
3278 E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
3279 }
3280 // Print total and footer.
3281 outs() << "----------------------------------------------------------------"
3282 "---------------\n";
3283 llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
3284 ComputePercentange(InputTotal, OutputTotal));
3285 outs() << "----------------------------------------------------------------"
3286 "---------------\n\n";
3287 }
3288
3289 return Error::success();
3290}
3291
3292Error DWARFLinker::cloneModuleUnit(LinkContext &Context, RefModuleUnit &Unit,
3293 DeclContextTree &ODRContexts,
3294 OffsetsStringPool &DebugStrPool,
3295 OffsetsStringPool &DebugLineStrPool,
3296 DebugDieValuePool &StringOffsetPool,
3297 unsigned Indent) {
3298 assert(Unit.Unit.get() != nullptr);
3299
3300 if (!Unit.Unit->getOrigUnit().getUnitDIE().hasChildren())
3301 return Error::success();
3302
3303 if (Options.Verbose) {
3304 outs().indent(Indent);
3305 outs() << "cloning .debug_info from " << Unit.File.FileName << "\n";
3306 }
3307
3308 // Analyze context for the module.
3309 analyzeContextInfo(Unit.Unit->getOrigUnit().getUnitDIE(), 0, *(Unit.Unit),
3310 &ODRContexts.getRoot(), ODRContexts, 0,
3311 Options.ParseableSwiftInterfaces,
3312 [&](const Twine &Warning, const DWARFDie &DIE) {
3313 reportWarning(Warning, Context.File, &DIE);
3314 });
3315 // Keep everything.
3316 Unit.Unit->markEverythingAsKept();
3317
3318 // Clone unit.
3319 UnitListTy CompileUnits;
3320 CompileUnits.emplace_back(std::move(Unit.Unit));
3321 assert(TheDwarfEmitter);
3322 Expected<uint64_t> SizeOrErr =
3323 DIECloner(*this, TheDwarfEmitter, Unit.File, DIEAlloc, CompileUnits,
3324 Options.Update, DebugStrPool, DebugLineStrPool,
3325 StringOffsetPool)
3326 .cloneAllCompileUnits(*Unit.File.Dwarf, Unit.File,
3327 Unit.File.Dwarf->isLittleEndian());
3328 if (!SizeOrErr)
3329 return SizeOrErr.takeError();
3330 return Error::success();
3331}
3332
3333void DWARFLinker::verifyInput(const DWARFFile &File) {
3334 assert(File.Dwarf);
3335
3336 std::string Buffer;
3337 raw_string_ostream OS(Buffer);
3338 DIDumpOptions DumpOpts;
3339 if (!File.Dwarf->verify(OS, DumpOpts.noImplicitRecursion())) {
3340 if (Options.InputVerificationHandler)
3341 Options.InputVerificationHandler(File, OS.str());
3342 }
3343}
3344
3345} // namespace llvm
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static uint32_t hashFullyQualifiedName(CompileUnit &InputCU, DWARFDie &InputDIE, int ChildRecurseDepth=0)
This file implements the BitVector class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
dxil DXContainer Global Emitter
Provides ErrorOr<T> smart pointer.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
void setChildrenFlag(bool hasChild)
Definition DIE.h:105
An integer value DIE.
Definition DIE.h:169
value_range values()
Definition DIE.h:816
value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V)
Definition DIE.h:749
A structured debug information entry.
Definition DIE.h:828
unsigned getAbbrevNumber() const
Definition DIE.h:863
DIE & addChild(DIE *Child)
Add a child to the DIE.
Definition DIE.h:944
LLVM_ABI DIEAbbrev generateAbbrev() const
Generate the abbreviation for this DIE.
Definition DIE.cpp:174
void setSize(unsigned S)
Definition DIE.h:941
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
Definition DIE.h:858
void setAbbrevNumber(unsigned I)
Set the abbreviation number for this DIE.
Definition DIE.h:900
unsigned getOffset() const
Get the compile/type unit relative offset of this DIE.
Definition DIE.h:866
void setOffset(unsigned O)
Definition DIE.h:940
dwarf::Tag getTag() const
Definition DIE.h:864
static LLVM_ABI std::optional< uint64_t > getDefiningParentDieOffset(const DIE &Die)
If Die has a non-null parent and the parent is not a declaration, return its offset.
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
uint64_t getOffset() const
Get the absolute offset into the debug info or types section.
Definition DWARFDie.h:68
iterator_range< iterator > children() const
Definition DWARFDie.h:406
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition DWARFDie.cpp:317
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Get the abbreviation declaration for this DIE.
Definition DWARFDie.h:60
dwarf::Tag getTag() const
Definition DWARFDie.h:73
LLVM_ABI std::optional< unsigned > getSubCode() const
Encoding
Size and signedness of expression operations' operands.
const Description & getDescription() const
uint64_t getRawOperand(unsigned Idx) const
bool skipValue(DataExtractor DebugInfoData, uint64_t *OffsetPtr, const dwarf::FormParams Params) const
Skip a form's value in DebugInfoData at the offset specified by OffsetPtr.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
void wait() override
Blocking wait for all the tasks to execute first.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition ThreadPool.h:80
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition WithColor.cpp:83
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:25
std::map< std::string, std::string > ObjectPrefixMapTy
function_ref< void(const DWARFUnit &Unit)> CompileUnitHandlerTy
AccelTableKind
The kind of accelerator tables to be emitted.
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
std::map< std::string, std::string > SwiftInterfacesMapTy
std::function< ErrorOr< DWARFFile & >( StringRef ContainerName, StringRef Path)> ObjFileLoaderTy
const SmallVector< T > & getValues() const
Stores all information relating to a compile unit, be it in its original instance in the object file ...
void addObjectFile(DWARFFile &File, ObjFileLoaderTy Loader=nullptr, CompileUnitHandlerTy OnCUDieLoaded=[](const DWARFUnit &) {}) override
Add object file to be linked.
Error link() override
Link debug info for added objFiles. Object files are linked all together.
This class gives a tree-like API to the DenseMap that stores the DeclContext objects.
PointerIntPair< DeclContext *, 1 > getChildDeclContext(DeclContext &Context, const DWARFDie &DIE, CompileUnit &Unit, bool InClangModule)
Get the child of Context described by DIE in Unit.
A DeclContext is a named program scope that is used for ODR uniquing of types.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI StringRef FormEncodingString(unsigned Encoding)
Definition Dwarf.cpp:105
LLVM_ABI StringRef FormatString(DwarfFormat Format)
Definition Dwarf.cpp:1047
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
SmallVector< PatchLocation > RngListAttributesTy
std::vector< std::unique_ptr< CompileUnit > > UnitListTy
IndexedValuesMap< uint64_t > DebugDieValuePool
Definition DWARFLinker.h:38
AddressRangesMap RangesTy
Mapped value in the address map is the offset to apply to the linked address.
SmallVector< PatchLocation > LocListAttributesTy
StringRef guessDeveloperDir(StringRef SysRoot)
Make a best effort to guess the Xcode.app/Contents/Developer path from an SDK path.
Definition Utils.h:59
void buildStmtSeqOffsetToFirstRowIndex(const DWARFDebugLine::LineTable &LT, ArrayRef< uint64_t > SortedStmtSeqOffsets, DenseMap< uint64_t, uint64_t > &SeqOffToFirstRow)
Build a map from an input DW_AT_LLVM_stmt_sequence byte offset to the first-row index (in LT....
Definition Utils.cpp:17
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
bool isInToolchainDir(StringRef Path)
Make a best effort to determine whether Path is inside a toolchain.
Definition Utils.h:95
bool isTlsAddressOp(uint8_t O)
Definition Dwarf.h:1102
std::optional< uint64_t > toAddress(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
Attribute
Attributes.
Definition Dwarf.h:125
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
LLVM_ABI bool doesFormBelongToClass(dwarf::Form Form, DWARFFormValue::FormClass FC, uint16_t DwarfVersion)
Check whether specified Form belongs to the FC class.
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_CHILDREN_yes
Definition Dwarf.h:872
@ DW_FLAG_type_implementation
Definition Dwarf.h:959
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition Path.cpp:529
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
constexpr bool IsLittleEndianHost
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy hardware_concurrency(unsigned ThreadCount=0)
Returns a default thread strategy where all available hardware resources are to be used,...
Definition Threading.h:190
static void verifyKeepChain(CompileUnit &CU)
Verify the keep chain by looking for DIEs that are kept but who's parent isn't.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &RefInfo)
Helper that updates the completeness of the current DIE based on the completeness of the DIEs it refe...
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2128
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
static void patchAddrBase(DIE &Die, DIEInteger Offset)
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2133
static std::string remapPath(StringRef Path, const DWARFLinkerBase::ObjectPrefixMapTy &ObjectPrefixMap)
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2064
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
Op::Description Desc
static CompileUnit * getUnitForOffset(const UnitListTy &Units, uint64_t Offset)
Similar to DWARFUnitSection::getUnitForOffset(), but returning our CompileUnit object instead.
static void insertLineSequence(std::vector< TrackedRow > &Seq, std::vector< TrackedRow > &Rows)
Insert the new line info sequence Seq into the current set of already linked line info Rows.
static void resolveRelativeObjectPath(SmallVectorImpl< char > &Buf, DWARFDie CU)
Resolve the relative path to a build artifact referenced by DWARF by applying DW_AT_comp_dir.
static std::string getPCMFile(const DWARFDie &CUDie, const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
static bool shouldSkipAttribute(bool Update, DWARFAbbreviationDeclaration::AttributeSpec AttrSpec, bool SkipPC)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
static uint64_t getDebugInfoSize(DWARFContext &Dwarf)
Compute the total size of the debug info.
static bool isTypeTag(uint16_t Tag)
@ Dwarf
DWARF v5 .debug_names.
Definition DwarfDebug.h:348
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI std::optional< StringRef > StripTemplateParameters(StringRef Name)
If Name is the name of a templated function that includes template parameters, returns a substring of...
static uint64_t getDwoId(const DWARFDie &CUDie)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
static bool updatePruning(const DWARFDie &Die, CompileUnit &CU, uint64_t ModulesEndOffset)
@ Success
The lock was released successfully.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
LLVM_ABI unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition LEB128.cpp:19
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &ChildInfo)
Helper that updates the completeness of the current DIE based on the completeness of one of its child...
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
DWARFExpression::Operation Op
static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &ChildInfo)
uint32_t djbHash(StringRef Buffer, uint32_t H=5381)
The Bernstein hash function used by the DWARF accelerator tables.
Definition DJB.h:22
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI std::optional< ObjCSelectorNames > getObjCNamesIfSelector(StringRef Name)
If Name is the AT_name of a DIE which refers to an Objective-C selector, returns an instance of ObjCS...
static void analyzeContextInfo(const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU, DeclContext *CurrentDeclContext, DeclContextTree &Contexts, uint64_t ModulesEndOffset, DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces, std::function< void(const Twine &, const DWARFDie &)> ReportWarning)
Recursive helper to build the global DeclContext information and gather the child->parent relationshi...
static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag)
StrongType< NonRelocatableStringpool, OffsetsTag > OffsetsStringPool
static bool isODRCanonicalCandidate(const DWARFDie &Die, CompileUnit &CU)
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
static void analyzeImportedModule(const DWARFDie &DIE, CompileUnit &CU, DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces, std::function< void(const Twine &, const DWARFDie &)> ReportWarning)
Collect references to parseable Swift interfaces in imported DW_TAG_module blocks.
ContextWorklistItemType
The distinct types of work performed by the work loop in analyzeContextInfo.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
static bool isODRAttribute(uint16_t Attr)
static void patchStmtList(DIE &Die, DIEInteger Offset)
static void constructSeqOffsettoOrigRowMapping(CompileUnit &Unit, const DWARFDebugLine::LineTable &LT, DenseMap< uint64_t, uint64_t > &SeqOffToOrigRow)
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
This class represents an item in the work list.
CompileUnit::DIEInfo * OtherInfo
ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx, bool InImportedModule)
ContextWorklistItemType Type
ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T, CompileUnit::DIEInfo *OtherInfo=nullptr)
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:196
DIDumpOptions noImplicitRecursion() const
Return the options with RecurseDepth set to 0 unless explicitly required.
Definition DIContext.h:228
unsigned ChildRecurseDepth
Definition DIContext.h:198
static LLVM_ABI bool mayHaveLocationList(dwarf::Attribute Attr)
Identify DWARF attributes that may contain a pointer to a location list.
Definition DWARFDie.cpp:806
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Definition DWARFDie.cpp:823
Standard .debug_line state machine structure.
SmallVector< Encoding > Op
Encoding for Op operands.
Hold the input and output of the debug info size in bytes.
A helper struct to help keep track of the association between the input and output rows during line t...
DWARFDebugLine::Row Row
Information gathered about a DIE in the object file.
bool Prune
Is this a pure forward declaration we can strip?
bool Incomplete
Does DIE transitively refer an incomplete decl?