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