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