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