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