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