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