LLVM 24.0.0git
DWARFLinkerCompileUnit.h
Go to the documentation of this file.
1//===- DWARFLinkerCompileUnit.h ---------------------------------*- C++ -*-===//
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
9#ifndef LLVM_LIB_DWARFLINKER_PARALLEL_DWARFLINKERCOMPILEUNIT_H
10#define LLVM_LIB_DWARFLINKER_PARALLEL_DWARFLINKERCOMPILEUNIT_H
11
12#include "DWARFLinkerUnit.h"
15#include <limits>
16#include <optional>
17
18namespace llvm {
19namespace dwarf_linker {
20namespace parallel {
21
23
25class DIEGenerator;
26class TypeUnit;
28
29class CompileUnit;
30
31/// This is a helper structure which keeps a debug info entry
32/// with it's containing compilation unit.
34 UnitEntryPairTy() = default;
37
38 CompileUnit *CU = nullptr;
39 const DWARFDebugInfoEntry *DieEntry = nullptr;
40
42 std::optional<UnitEntryPairTy> getParent();
43};
44
46 Resolve = true,
48};
49
50/// Stores all information related to a compile unit, be it in its original
51/// instance of the object file or its brand new cloned and generated DIE tree.
52/// NOTE: we need alignment of at least 8 bytes as we use
53/// PointerIntPair<CompileUnit *, 3> in the DependencyTracker.h
54class alignas(8) CompileUnit : public DwarfUnit {
55public:
56 /// The stages of new compile unit processing.
57 enum class Stage : uint8_t {
58 /// Created, linked with input DWARF file.
60
61 /// Input DWARF is loaded.
63
64 /// DIEs with a live address are found. Marking a unit reads whether the
65 /// DIEs it references in other units have an address, so every
66 /// inter-connected unit gets here before any of them is marked.
68
69 /// Input DWARF is analysed(DIEs pointing to the real code section and the
70 /// DIEs they depend on are marked).
72
73 /// Check if dependencies have incompatible placement.
74 /// If that is the case modify placement to be compatible.
76
77 /// Type names assigned to DIEs.
79
80 /// Output DWARF is generated.
82
83 /// Offsets inside patch records are updated.
85
86 /// Resources(Input DWARF, Output DWARF tree) are released.
88
89 /// Compile Unit should be skipped
91 };
92
96 llvm::endianness Endianess);
97
98 CompileUnit(LinkingGlobalData &GlobalData, DWARFUnit &OrigUnit, unsigned ID,
101 llvm::endianness Endianess);
102
103 /// Returns stage of overall processing.
104 Stage getStage() const { return Stage; }
105
106 /// Returns raw DW_AT_language of the input compile unit.
107 std::optional<uint16_t> getLanguage() const { return Language; }
108
109 /// Set stage of overall processing.
110 void setStage(Stage Stage) { this->Stage = Stage; }
111
112 /// Loads unit line table.
113 void loadLineTable();
114
115 /// Returns name of the file for the \p FileIdx
116 /// from the unit`s line table.
117 StringEntry *getFileName(unsigned FileIdx, StringPool &GlobalStrings);
118
119 /// Returns DWARFFile containing this compile unit.
120 const DWARFFile &getContainingFile() const { return File; }
121
122 std::string remapPath(StringRef Path) const override {
123 return File.remapPath(Path);
124 }
125
126 /// Appends the names of the DW_TAG_module enclosing \p DieEntry, outermost
127 /// first. Returns false when one of them has no name making the module
128 /// unidentifiable across units.
129 bool getModulePath(const DWARFDebugInfoEntry *DieEntry,
131
132 /// Must run while the output offsets are still available, and once they are
133 /// final.
134 void noteModuleAnchors();
135
136 /// Set deterministic priority for type DIE allocation ordering. Units compare
137 /// by \p ObjFileIdx first and by \p LocalIdx second.
138 /// Lower priority values win when multiple CUs race to define the same type.
139 llvm::Error setPriority(uint64_t ObjFileIdx, uint64_t LocalIdx);
140
141 uint64_t getPriority() const { return Priority; }
142
143 /// Load DIEs of input compilation unit. \returns true if input DIEs
144 /// successfully loaded.
145 bool loadInputDIEs();
146
147 /// Reset compile units data(results of liveness analysis, clonning)
148 /// if current stage greater than Stage::Loaded. We need to reset data
149 /// as we are going to repeat stages.
151
152 /// Collect references to parseable Swift interfaces in imported
153 /// DW_TAG_module blocks. The entries are staged on the CompileUnit and
154 /// merged into the shared map after the parallel analysis phase.
155 void analyzeImportedModule(const DWARFDebugInfoEntry *DieEntry);
156
157 /// Merge the Swift interface entries collected by analyzeImportedModule
158 /// into \p Map, emitting a warning for each conflicting path. Must be
159 /// called serially after analysis has completed.
161
162 /// Navigate DWARF tree and set die properties.
164 analyzeDWARFStructureRec(getUnitDIE().getDebugInfoEntry(), false);
165 }
166
167 /// Cleanup unneeded resources after compile unit is cloned.
169
170 RelocationFixups &getRelocFixups() { return RelocFixups; }
171
172 /// Saves the relocations, at offsets relative to the output of the unit,
173 /// which reportUnitOffsets() tells once the sections are placed.
174 void saveRelocations();
175 void reportUnitOffsets();
176
177 /// After cloning stage the output DIEs offsets are deallocated.
178 /// This method copies output offsets for referenced DIEs into DIEs patches.
180
181 /// Search for subprograms and variables referencing live code.
182 void collectLiveRoots();
183
184 /// Discover the DIEs the live roots depend on. Mark live DIEs, set placement
185 /// for DIEs.
187 bool InterCUProcessingStarted,
188 std::atomic<bool> &HasNewInterconnectedCUs);
189
190 /// Check dependend DIEs for incompatible placement.
191 /// Make placement to be consistent.
193
194 /// Check DIEs to have a consistent marking(keep marking, placement marking).
195 void verifyDependencies();
196
197 /// Search for type entries and assign names.
198 Error assignTypeNames(TypePool &TypePoolRef);
199
200 /// Kinds of placement for the output die.
203
204 /// Corresponding DIE goes to the type table only.
206
207 /// Corresponding DIE goes to the plain dwarf only.
209
210 /// Corresponding DIE goes to type table and to plain dwarf.
211 Both = 3,
212 };
213
214 /// Information gathered about source DIEs.
215 struct DIEInfo {
216 DIEInfo() = default;
217 DIEInfo(const DIEInfo &Other) { Flags = Other.Flags.load(); }
219 Flags = Other.Flags.load();
220 return *this;
221 }
222
223 /// Data member keeping various flags.
224 std::atomic<uint16_t> Flags = {0};
225
226 /// \returns Placement kind for the corresponding die.
228 return DieOutputPlacement(Flags & 0x7);
229 }
230
231 /// Sets Placement kind for the corresponding die.
233 auto InputData = Flags.load();
234 while (!Flags.compare_exchange_weak(InputData,
235 ((InputData & ~0x7) | Placement))) {
236 }
237 }
238
239 /// Unsets Placement kind for the corresponding die.
241 auto InputData = Flags.load();
242 while (!Flags.compare_exchange_weak(InputData, (InputData & ~0x7))) {
243 }
244 }
245
246 /// Sets Placement kind for the corresponding die.
248 auto InputData = Flags.load();
249 if ((InputData & 0x7) == NotSet)
250 if (Flags.compare_exchange_strong(InputData, (InputData | Placement)))
251 return true;
252
253 return false;
254 }
255
256 /// Atomically joins \p Placement into the current placement: the
257 /// least-upper-bound of the lattice NotSet < {TypeTable, PlainDwarf} <
258 /// Both, which is a plain OR because the values are bit flags. The join is
259 /// monotone and never clears a bit, so unlike setPlacement it composes
260 /// correctly when applied concurrently from several marks.
262 auto InputData = Flags.load();
263 while (!Flags.compare_exchange_weak(InputData, (InputData | Placement))) {
264 }
265 }
266
267 /// Atomically joins \p Placement for a DW_TAG_variable, for which
268 /// PlainDwarf is absorbing because a variable cannot occupy the type table
269 /// and plain DWARF at once. Once the placement is (or concurrently becomes)
270 /// PlainDwarf it stays PlainDwarf, otherwise \p Placement is OR-joined.
271 /// Recomputing inside the compare_exchange loop keeps a racing PlainDwarf
272 /// mark from turning the variable into Both.
274 auto InputData = Flags.load();
275 uint16_t Desired;
276 do {
277 DieOutputPlacement Current = DieOutputPlacement(InputData & 0x7);
278 DieOutputPlacement Joined =
279 (Current == PlainDwarf || Current == Both)
280 ? PlainDwarf
281 : DieOutputPlacement(Current | Placement);
282 Desired = (InputData & ~0x7) | Joined;
283 } while (!Flags.compare_exchange_weak(InputData, Desired));
284 }
285
286#define SINGLE_FLAG_METHODS_SET(Name, Value) \
287 bool get##Name() const { return Flags & Value; } \
288 void set##Name() { \
289 auto InputData = Flags.load(); \
290 while (!Flags.compare_exchange_weak(InputData, InputData | Value)) { \
291 } \
292 } \
293 void unset##Name() { \
294 auto InputData = Flags.load(); \
295 while (!Flags.compare_exchange_weak(InputData, InputData & ~Value)) { \
296 } \
297 }
298
299 /// DIE is a part of the linked output.
301
302 /// DIE has children which are part of the linked output.
303 SINGLE_FLAG_METHODS_SET(KeepPlainChildren, 0x10)
304
305 /// DIE has children which are part of the type table.
306 SINGLE_FLAG_METHODS_SET(KeepTypeChildren, 0x20)
307
308 /// DIE is in module scope.
309 SINGLE_FLAG_METHODS_SET(IsInMouduleScope, 0x40)
310
311 /// DIE is in function scope.
312 SINGLE_FLAG_METHODS_SET(IsInFunctionScope, 0x80)
313
314 /// DIE is in anonymous namespace scope.
315 SINGLE_FLAG_METHODS_SET(IsInAnonNamespaceScope, 0x100)
316
317 /// DIE is available for ODR type deduplication.
318 SINGLE_FLAG_METHODS_SET(ODRAvailable, 0x200)
319
320 /// Track liveness for the DIE.
321 SINGLE_FLAG_METHODS_SET(TrackLiveness, 0x400)
322
323 /// Track liveness for the DIE.
324 SINGLE_FLAG_METHODS_SET(HasAnAddress, 0x800)
325
326 /// DIE is a function-local variable with a live address that does not keep
327 /// its function, and is kept wherever the function is.
328 SINGLE_FLAG_METHODS_SET(KeepWithParent, 0x1000)
329
331 auto InputData = Flags.load();
332 while (!Flags.compare_exchange_weak(
333 InputData, InputData & ~(0x7 | 0x8 | 0x10 | 0x20))) {
334 }
335 }
336
337 /// Erase all flags.
338 void eraseData() { Flags = 0; }
339
340#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
341 LLVM_DUMP_METHOD void dump();
342#endif
343
345 return (getKeep() && (getPlacement() == CompileUnit::TypeTable ||
347 getKeepTypeChildren();
348 }
349
351 return (getKeep() && (getPlacement() == CompileUnit::PlainDwarf ||
353 getKeepPlainChildren();
354 }
355 };
356
357 /// \defgroup Group of functions returning DIE info.
358 ///
359 /// @{
360
361 /// \p Idx index of the DIE.
362 /// \returns DieInfo descriptor.
363 DIEInfo &getDIEInfo(unsigned Idx) { return DieInfoArray[Idx]; }
364
365 /// \p Idx index of the DIE.
366 /// \returns DieInfo descriptor.
367 const DIEInfo &getDIEInfo(unsigned Idx) const { return DieInfoArray[Idx]; }
368
369 /// \p Idx index of the DIE.
370 /// \returns DieInfo descriptor.
372 return DieInfoArray[getOrigUnit().getDIEIndex(Entry)];
373 }
374
375 /// \p Idx index of the DIE.
376 /// \returns DieInfo descriptor.
377 const DIEInfo &getDIEInfo(const DWARFDebugInfoEntry *Entry) const {
378 return DieInfoArray[getOrigUnit().getDIEIndex(Entry)];
379 }
380
381 /// \p Die
382 /// \returns PlainDieInfo descriptor.
384 return DieInfoArray[getOrigUnit().getDIEIndex(Die)];
385 }
386
387 /// \p Die
388 /// \returns PlainDieInfo descriptor.
389 const DIEInfo &getDIEInfo(const DWARFDie &Die) const {
390 return DieInfoArray[getOrigUnit().getDIEIndex(Die)];
391 }
392
393 /// \p Idx index of the DIE.
394 /// \returns DieInfo descriptor.
396 return reinterpret_cast<std::atomic<uint64_t> *>(&OutDieOffsetArray[Idx])
397 ->load();
398 }
399
400 /// \p Idx index of the DIE.
401 /// \returns type entry.
403 return reinterpret_cast<std::atomic<TypeEntry *> *>(&TypeEntries[Idx])
404 ->load();
405 }
406
407 /// \p InputDieEntry debug info entry.
408 /// \returns DieInfo descriptor.
410 return reinterpret_cast<std::atomic<uint64_t> *>(
411 &OutDieOffsetArray[getOrigUnit().getDIEIndex(InputDieEntry)])
412 ->load();
413 }
414
415 /// \p InputDieEntry debug info entry.
416 /// \returns type entry.
418 return reinterpret_cast<std::atomic<TypeEntry *> *>(
419 &TypeEntries[getOrigUnit().getDIEIndex(InputDieEntry)])
420 ->load();
421 }
422
423 /// \p Idx index of the DIE.
424 /// \returns DieInfo descriptor.
426 reinterpret_cast<std::atomic<uint64_t> *>(&OutDieOffsetArray[Idx])
427 ->store(Offset);
428 }
429
430 /// \p Idx index of the DIE.
431 /// \p Type entry.
433 reinterpret_cast<std::atomic<TypeEntry *> *>(&TypeEntries[Idx])
434 ->store(Entry);
435 }
436
437 /// \p InputDieEntry debug info entry.
438 /// \p Type entry.
439 void setDieTypeEntry(const DWARFDebugInfoEntry *InputDieEntry,
440 TypeEntry *Entry) {
441 reinterpret_cast<std::atomic<TypeEntry *> *>(
442 &TypeEntries[getOrigUnit().getDIEIndex(InputDieEntry)])
443 ->store(Entry);
444 }
445
446 /// @}
447
448 /// Returns value of DW_AT_low_pc attribute.
449 std::optional<uint64_t> getLowPc() const { return LowPc; }
450
451 /// Returns value of DW_AT_high_pc attribute.
452 uint64_t getHighPc() const { return HighPc; }
453
454 /// Returns true if there is a label corresponding to the specified \p Addr.
455 bool hasLabelAt(uint64_t Addr) const { return Labels.count(Addr); }
456
457 /// Add the low_pc of a label that is relocated by applying
458 /// offset \p PCOffset.
459 void addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset);
460
461 /// Resolve the DIE attribute reference that has been extracted in \p
462 /// RefValue. The resulting DIE might be in another CompileUnit.
463 /// \returns referenced die and corresponding compilation unit.
464 /// compilation unit is null if reference could not be resolved.
465 std::optional<UnitEntryPairTy>
466 resolveDIEReference(const DWARFFormValue &RefValue,
467 ResolveInterCUReferencesMode CanResolveInterCUReferences);
468
469 std::optional<UnitEntryPairTy>
471 dwarf::Attribute Attr,
472 ResolveInterCUReferencesMode CanResolveInterCUReferences);
473
474 /// @}
475
476 /// Add a function range [\p LowPC, \p HighPC) that is relocated by applying
477 /// offset \p PCOffset.
478 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
479
480 /// Returns function ranges of this unit.
481 const RangesTy &getFunctionRanges() const { return Ranges; }
482
483 /// Record that a DW_AT_LLVM_stmt_sequence attribute on this unit
484 /// references the input line-table sequence whose header sits at
485 /// \p InputStmtSeqOffset. Resolution of that offset to an input
486 /// first-row index (via parser results plus a manual boundary-based
487 /// fallback) happens in a post-cloning pass, before \p V is rewritten
488 /// to the byte offset of the matching output sequence. Keying on row
489 /// index rather than address avoids collisions when two input
490 /// sequences would relocate to the same output address (e.g. ICF).
491 void noteStmtSeqListAttribute(DIEValue *V, uint64_t InputStmtSeqOffset) {
492 StmtSeqListAttributes.push_back({V, InputStmtSeqOffset});
493 }
494
495 /// Clone and emit this compilation unit.
496 Error
497 cloneAndEmit(std::optional<std::reference_wrapper<const Triple>> TargetTriple,
498 TypeUnit *ArtificialTypeUnit);
499
500 /// Clone and emit debug locations(.debug_loc/.debug_loclists).
502
503 /// Clone and emit ranges.
505
506 /// Clone and emit debug macros(.debug_macinfo/.debug_macro).
508
509 // Clone input DIE entry. \p SiblingOrdinal is this DIE's position in its
510 // parent's child list, or UINT32_MAX for the unit DIE.
511 std::pair<DIE *, TypeEntry *>
512 cloneDIE(const DWARFDebugInfoEntry *InputDieEntry,
513 TypeEntry *ClonedParentTypeDIE, uint64_t OutOffset,
514 std::optional<int64_t> FuncAddressAdjustment,
515 std::optional<int64_t> VarAddressAdjustment,
516 BumpPtrAllocator &Allocator, TypeUnit *ArtificialTypeUnit,
517 uint32_t SiblingOrdinal = std::numeric_limits<uint32_t>::max());
518
519 // Clone and emit line table.
520 Error cloneAndEmitLineTable(const Triple &TargetTriple);
521
522 /// Clone attribute location expression. \p Cloned, if set, receives where
523 /// its operations were cloned to in \p OutputExpression. With
524 /// \p KeepAddrIndices, DW_OP_addrx and DW_OP_constx index the output
525 /// .debug_addr, whose entries carry their relocations.
526 void
527 cloneDieAttrExpression(const DWARFExpression &InputExpression,
528 SmallVectorImpl<uint8_t> &OutputExpression,
529 SectionDescriptor &Section,
530 std::optional<int64_t> VarAddressAdjustment,
531 OffsetsPtrVector &PatchesOffsets,
533 bool KeepAddrIndices = false);
534
535 /// Returns index(inside .debug_addr) of an address.
537 return DebugAddrIndexMap.getValueIndex(Addr);
538 }
539
540 /// Returns directory and file from the line table by index.
541 std::optional<std::pair<StringRef, StringRef>>
543
544 /// Returns directory and file from the line table by index.
545 std::optional<std::pair<StringRef, StringRef>>
547
548 /// \defgroup Helper methods to access OrigUnit.
549 ///
550 /// @{
551
552 /// Returns paired compile unit from input DWARF.
554 assert(OrigUnit != nullptr);
555 return *OrigUnit;
556 }
557
558 const DWARFDebugInfoEntry *
560 assert(OrigUnit != nullptr);
561 return OrigUnit->getFirstChildEntry(Die);
562 }
563
564 const DWARFDebugInfoEntry *
566 assert(OrigUnit != nullptr);
567 return OrigUnit->getSiblingEntry(Die);
568 }
569
571 assert(OrigUnit != nullptr);
572 return OrigUnit->getParent(Die);
573 }
574
575 DWARFDie getDIEAtIndex(unsigned Index) {
576 assert(OrigUnit != nullptr);
577 return OrigUnit->getDIEAtIndex(Index);
578 }
579
580 const DWARFDebugInfoEntry *getDebugInfoEntry(unsigned Index) const {
581 assert(OrigUnit != nullptr);
582 return OrigUnit->getDebugInfoEntry(Index);
583 }
584
585 DWARFDie getUnitDIE(bool ExtractUnitDIEOnly = true) {
586 assert(OrigUnit != nullptr);
587 return OrigUnit->getUnitDIE(ExtractUnitDIEOnly);
588 }
589
591 assert(OrigUnit != nullptr);
592 return DWARFDie(OrigUnit, Die);
593 }
594
596 assert(OrigUnit != nullptr);
597 return OrigUnit->getDIEIndex(Die);
598 }
599
600 uint32_t getDIEIndex(const DWARFDie &Die) const {
601 assert(OrigUnit != nullptr);
602 return OrigUnit->getDIEIndex(Die);
603 }
604
605 std::optional<DWARFFormValue> find(uint32_t DieIdx,
606 ArrayRef<dwarf::Attribute> Attrs) const {
607 assert(OrigUnit != nullptr);
608 return find(OrigUnit->getDebugInfoEntry(DieIdx), Attrs);
609 }
610
611 std::optional<DWARFFormValue> find(const DWARFDebugInfoEntry *Die,
612 ArrayRef<dwarf::Attribute> Attrs) const {
613 if (!Die)
614 return std::nullopt;
615 auto AbbrevDecl = Die->getAbbreviationDeclarationPtr();
616 if (AbbrevDecl) {
617 for (auto Attr : Attrs) {
618 if (auto Value = AbbrevDecl->getAttributeValue(Die->getOffset(), Attr,
619 *OrigUnit))
620 return Value;
621 }
622 }
623 return std::nullopt;
624 }
625
626 std::optional<uint32_t> getDIEIndexForOffset(uint64_t Offset) {
627 return OrigUnit->getDIEIndexForOffset(Offset);
628 }
629
630 /// @}
631
632 /// \defgroup Methods used for reporting warnings and errors:
633 ///
634 /// @{
635
636 void warn(const Twine &Warning, const DWARFDie *DIE = nullptr) {
638 }
639
640 void warn(Error Warning, const DWARFDie *DIE = nullptr) {
641 handleAllErrors(std::move(Warning), [&](ErrorInfoBase &Info) {
642 GlobalData.warn(Info.message(), getUnitName(), DIE);
643 });
644 }
645
646 void warn(const Twine &Warning, const DWARFDebugInfoEntry *DieEntry) {
647 if (DieEntry != nullptr) {
648 DWARFDie DIE(&getOrigUnit(), DieEntry);
650 return;
651 }
652
654 }
655
656 void error(const Twine &Err, const DWARFDie *DIE = nullptr) {
657 GlobalData.warn(Err, getUnitName(), DIE);
658 }
659
660 void error(Error Err, const DWARFDie *DIE = nullptr) {
661 handleAllErrors(std::move(Err), [&](ErrorInfoBase &Info) {
662 GlobalData.error(Info.message(), getUnitName(), DIE);
663 });
664 }
665
666 /// @}
667
668 /// Save specified accelerator info \p Info.
670 AcceleratorRecords.add(Info);
671 }
672
673 /// Enumerates all units accelerator records.
674 void
676 AcceleratorRecords.forEach(Handler);
677 }
678
679 /// Output unit selector.
681 public:
684
685 /// Accessor for common functionality.
687
688 bool isCompileUnit();
689
690 bool isTypeUnit();
691
692 /// Returns CompileUnit if applicable.
694
695 /// Returns TypeUnit if applicable.
697
698 protected:
700 };
701
702private:
703 /// Navigate DWARF tree recursively and set die properties.
704 void analyzeDWARFStructureRec(const DWARFDebugInfoEntry *DieEntry,
705 bool IsODRUnavailableFunctionScope);
706
707 struct LinkedLocationExpressionsWithOffsetPatches {
709 OffsetsPtrVector Patches;
710 };
711 using LinkedLocationExpressionsVector =
713
714 /// Emit debug locations.
715 void emitLocations(DebugSectionKind LocationSectionKind);
716
717 /// Emit location list header.
718 uint64_t emitLocListHeader(SectionDescriptor &OutLocationSection);
719
720 /// Emit location list fragment.
721 uint64_t emitLocListFragment(
722 const LinkedLocationExpressionsVector &LinkedLocationExpression,
723 SectionDescriptor &OutLocationSection);
724
725 /// Emit the .debug_addr section fragment for current unit.
726 Error emitDebugAddrSection();
727
728 /// Emit .debug_aranges.
729 void emitAranges(AddressRanges &LinkedFunctionRanges);
730
731 /// Clone and emit .debug_ranges/.debug_rnglists.
732 void cloneAndEmitRangeList(DebugSectionKind RngSectionKind,
733 AddressRanges &LinkedFunctionRanges);
734
735 /// Emit range list header.
736 uint64_t emitRangeListHeader(SectionDescriptor &OutRangeSection);
737
738 /// Emit range list fragment.
739 void emitRangeListFragment(const AddressRanges &LinkedRanges,
740 SectionDescriptor &OutRangeSection);
741
742 /// Insert the new line info sequence \p Seq into the current
743 /// set of already linked line info \p Rows. \p SeqIndices carries the
744 /// input Row index that each entry in \p Seq originated from (or the
745 /// invalid-row-index sentinel for manufactured end-of-range rows), and
746 /// is kept in lockstep with \p RowIndices.
747 void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
748 SmallVectorImpl<uint64_t> &SeqIndices,
749 std::vector<DWARFDebugLine::Row> &Rows,
750 SmallVectorImpl<uint64_t> &RowIndices);
751
752 /// Filter \p InputLineTable's rows to those covered by this unit's
753 /// function ranges, relocating addresses in the process, and store the
754 /// result in \p NewRows. \p NewRowIndices is populated in lockstep with
755 /// \p NewRows and carries, for each output row, the index of the input
756 /// row it originated from — or InvalidRowIndex for manufactured
757 /// end-of-range rows.
758 void filterLineTableRows(const DWARFDebugLine::LineTable &InputLineTable,
759 std::vector<DWARFDebugLine::Row> &NewRows,
760 SmallVectorImpl<uint64_t> &NewRowIndices);
761
762 /// Rewrite every DW_AT_LLVM_stmt_sequence DIEValue recorded on this
763 /// unit with the local .debug_line offset of the output sequence
764 /// containing the corresponding input first row.
765 /// \p SeqOffsetToFirstRowIndex maps an input stmt-sequence offset to
766 /// its first-row index (built by buildStmtSeqOffsetToFirstRowIndex so
767 /// that sequences missed by the DWARF parser are recovered from row
768 /// boundaries). \p RowIndexToSeqStartOffset maps an input first-row
769 /// index to the byte offset of the output DW_LNE_set_address that
770 /// opens the matching output sequence.
771 void patchStmtSeqAttributes(
772 const DenseMap<uint64_t, uint64_t> &SeqOffsetToFirstRowIndex,
773 const DenseMap<uint64_t, uint64_t> &RowIndexToSeqStartOffset);
774
775 /// Build a map from input stmt-sequence offset to the first-row index
776 /// of the corresponding sequence in \p InputLineTable. Seeds the map
777 /// from \p InputLineTable.Sequences (the DWARF parser's results), then
778 /// augments it by manually walking row boundaries and realigning them
779 /// against the recorded DW_AT_LLVM_stmt_sequence values so that
780 /// sequences missed by the parser still resolve. Mirrors the
781 /// classic DWARFLinker's constructSeqOffsettoOrigRowMapping.
783 const DWARFDebugLine::LineTable &InputLineTable) const;
784
785 /// Emits body for both macro sections.
786 void emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
787 uint64_t OffsetToMacroTable, bool hasDWARFv5Header);
788
789 /// Creates DIE which would be placed into the "Plain" compile unit.
790 DIE *createPlainDIEandCloneAttributes(
791 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &PlainDIEGenerator,
792 uint64_t &OutOffset, std::optional<int64_t> &FuncAddressAdjustment,
793 std::optional<int64_t> &VarAddressAdjustment);
794
795 /// Creates DIE which would be placed into the "Type" compile unit.
796 /// \p SiblingOrdinal is the input DIE's position in its parent's child list.
797 TypeEntry *createTypeDIEandCloneAttributes(
798 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &TypeDIEGenerator,
799 TypeEntry *ClonedParentTypeDIE, TypeUnit *ArtificialTypeUnit,
800 uint32_t SiblingOrdinal);
801
802 /// Create output DIE inside specified \p TypeDescriptor.
803 DIE *allocateTypeDie(TypeEntryBody *TypeDescriptor,
804 DIEGenerator &TypeDIEGenerator, dwarf::Tag DieTag,
805 bool IsDeclaration, bool IsParentDeclaration);
806
807 /// Enumerate \p DieEntry children and assign names for them.
808 Error assignTypeNamesRec(const DWARFDebugInfoEntry *DieEntry,
809 SyntheticTypeNameBuilder &NameBuilder);
810
811 /// DWARFFile containing this compile unit.
812 DWARFFile &File;
813
814 /// Pointer to the paired compile unit from the input DWARF.
815 DWARFUnit *OrigUnit = nullptr;
816
817 /// Raw DW_AT_language from the input (not ODR-filtered).
818 std::optional<uint16_t> Language;
819
820 /// Parseable Swift interface entries staged during the parallel analysis
821 /// phase. Merged serially afterwards.
822 struct PendingSwiftInterface {
823 PendingSwiftInterface(StringRef ModuleName, StringRef ResolvedPath)
824 : ModuleName(ModuleName), ResolvedPath(ResolvedPath) {}
825 std::string ModuleName;
826 std::string ResolvedPath;
827 };
828 SmallVector<PendingSwiftInterface> PendingSwiftInterfaces;
829
830 /// Line table for this unit.
831 const DWARFDebugLine::LineTable *LineTablePtr = nullptr;
832
833 /// Cached resolved paths from the line table.
834 /// The key is <UniqueUnitID, FileIdx>.
835 using ResolvedPathsMap = DenseMap<unsigned, StringEntry *>;
836 ResolvedPathsMap ResolvedFullPaths;
837 StringMap<StringEntry *> ResolvedParentPaths;
838
839 /// Maps an address into the index inside .debug_addr section.
840 IndexedValuesMap<uint64_t> DebugAddrIndexMap;
841
842 RelocationFixups RelocFixups;
843
844 /// The input offset of the unit, kept by saveRelocations() for
845 /// reportUnitOffsets(), as the input is unloaded in between.
846 std::optional<uint64_t> SavedRelocsUnitOffset;
847
848 std::unique_ptr<DependencyTracker> Dependencies;
849
850 /// \defgroup Data Members accessed asynchronously.
851 ///
852 /// @{
853 OffsetToUnitTy getUnitFromOffset;
854
855 std::optional<uint64_t> LowPc;
856 uint64_t HighPc = 0;
857
858 /// Flag indicating whether type de-duplication is forbidden.
859 bool NoODR = true;
860
861 /// Deterministic priority for type DIE allocation (lower wins).
862 uint64_t Priority = std::numeric_limits<uint64_t>::max();
863
864 /// The ranges in that map are the PC ranges for functions in this unit,
865 /// associated with the PC offset to apply to the addresses to get
866 /// the linked address.
867 RangesTy Ranges;
868 std::mutex RangesMutex;
869
870 /// The DW_AT_low_pc of each DW_TAG_label.
871 using LabelMapTy = SmallDenseMap<uint64_t, uint64_t, 1>;
872 LabelMapTy Labels;
873
874 /// Recorded DW_AT_LLVM_stmt_sequence attributes for this unit. Each
875 /// entry pairs the DIEValue holding the attribute with the input-side
876 /// byte offset of the referenced line-table sequence. The value is
877 /// rewritten with the matching output offset after the line table has
878 /// been emitted; resolution from input offset to input first-row
879 /// index (including the parser-miss fallback) happens at patch time.
880 struct StmtSeqPatch {
881 DIEValue *Value = nullptr;
882 uint64_t InputStmtSeqOffset = 0;
883 };
884 SmallVector<StmtSeqPatch, 4> StmtSeqListAttributes;
885 std::mutex LabelsMutex;
886
887 /// This field keeps current stage of overall compile unit processing.
888 std::atomic<Stage> Stage;
889
890 /// DIE info indexed by DIE index.
891 SmallVector<DIEInfo> DieInfoArray;
892 SmallVector<uint64_t> OutDieOffsetArray;
893 SmallVector<TypeEntry *> TypeEntries;
894
895 /// The list of accelerator records for this unit.
896 ArrayList<AccelInfo> AcceleratorRecords;
897 /// @}
898};
899
900/// \returns list of attributes referencing type DIEs which might be
901/// deduplicated.
902/// Note: it does not include DW_AT_containing_type attribute to avoid
903/// infinite recursion.
905
906} // end of namespace parallel
907} // end of namespace dwarf_linker
908} // end of namespace llvm
909
910#endif // LLVM_LIB_DWARFLINKER_PARALLEL_DWARFLINKERCOMPILEUNIT_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Mark last scratch load
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
Branch Probability Basic Block Placement
Basic Register Allocator
The AddressRanges class helps normalize address range collections.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A structured debug information entry.
Definition DIE.h:835
DWARFDebugInfoEntry - A DIE with only the minimum required data.
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
uint32_t getDIEIndex(const DWARFDebugInfoEntry *Die) const
Return the index of a Die entry inside the unit's DIE vector.
Definition DWARFUnit.h:276
Base class for error info classes.
Definition Error.h:44
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Class representing an expression and its matching format.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:27
std::map< std::string, std::string > SwiftInterfacesMapTy
This class stores values sequentually and assigns index to the each value.
Where the operations of an expression were cloned to.
Where the attributes of a unit were cloned to, so that their relocations can be saved once the output...
CompileUnit * getAsCompileUnit()
Returns CompileUnit if applicable.
Stores all information related to a compile unit, be it in its original instance of the object file o...
void addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset)
Add the low_pc of a label that is relocated by applying offset PCOffset.
void collectLiveRoots()
Search for subprograms and variables referencing live code.
Error cloneAndEmitDebugLocations()
Clone and emit debug locations(.debug_loc/.debug_loclists).
void maybeResetToLoadedStage()
Reset compile units data(results of liveness analysis, clonning) if current stage greater than Stage:...
void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset)
Add a function range [LowPC, HighPC) that is relocated by applying offset PCOffset.
void analyzeImportedModule(const DWARFDebugInfoEntry *DieEntry)
Collect references to parseable Swift interfaces in imported DW_TAG_module blocks.
std::pair< DIE *, TypeEntry * > cloneDIE(const DWARFDebugInfoEntry *InputDieEntry, TypeEntry *ClonedParentTypeDIE, uint64_t OutOffset, std::optional< int64_t > FuncAddressAdjustment, std::optional< int64_t > VarAddressAdjustment, BumpPtrAllocator &Allocator, TypeUnit *ArtificialTypeUnit, uint32_t SiblingOrdinal=std::numeric_limits< uint32_t >::max())
void cleanupDataAfterClonning()
Cleanup unneeded resources after compile unit is cloned.
Error assignTypeNames(TypePool &TypePoolRef)
Search for type entries and assign names.
llvm::Error setPriority(uint64_t ObjFileIdx, uint64_t LocalIdx)
Set deterministic priority for type DIE allocation ordering.
uint64_t getHighPc() const
Returns value of DW_AT_high_pc attribute.
void noteModuleAnchors()
Must run while the output offsets are still available, and once they are final.
void cloneDieAttrExpression(const DWARFExpression &InputExpression, SmallVectorImpl< uint8_t > &OutputExpression, SectionDescriptor &Section, std::optional< int64_t > VarAddressAdjustment, OffsetsPtrVector &PatchesOffsets, RelocationFixups::ClonedExpression *Cloned=nullptr, bool KeepAddrIndices=false)
Clone attribute location expression.
DieOutputPlacement
Kinds of placement for the output die.
@ Both
Corresponding DIE goes to type table and to plain dwarf.
@ TypeTable
Corresponding DIE goes to the type table only.
@ PlainDwarf
Corresponding DIE goes to the plain dwarf only.
Error cloneAndEmitLineTable(const Triple &TargetTriple)
const DWARFFile & getContainingFile() const
Returns DWARFFile containing this compile unit.
void analyzeDWARFStructure()
Navigate DWARF tree and set die properties.
void mergeSwiftInterfaces(DWARFLinkerBase::SwiftInterfacesMapTy &Map)
Merge the Swift interface entries collected by analyzeImportedModule into Map, emitting a warning for...
void updateDieRefPatchesWithClonedOffsets()
After cloning stage the output DIEs offsets are deallocated.
uint64_t getDebugAddrIndex(uint64_t Addr)
Returns index(inside .debug_addr) of an address.
void saveRelocations()
Saves the relocations, at offsets relative to the output of the unit, which reportUnitOffsets() tells...
bool resolveDependenciesAndMarkLiveness(bool InterCUProcessingStarted, std::atomic< bool > &HasNewInterconnectedCUs)
Discover the DIEs the live roots depend on.
std::optional< uint16_t > getLanguage() const
Returns raw DW_AT_language of the input compile unit.
bool hasLabelAt(uint64_t Addr) const
Returns true if there is a label corresponding to the specified Addr.
bool updateDependenciesCompleteness()
Check dependend DIEs for incompatible placement.
bool loadInputDIEs()
Load DIEs of input compilation unit.
void noteStmtSeqListAttribute(DIEValue *V, uint64_t InputStmtSeqOffset)
Record that a DW_AT_LLVM_stmt_sequence attribute on this unit references the input line-table sequenc...
const RangesTy & getFunctionRanges() const
Returns function ranges of this unit.
void saveAcceleratorInfo(const DwarfUnit::AccelInfo &Info)
Save specified accelerator info Info.
Error cloneAndEmitDebugMacro()
Clone and emit debug macros(.debug_macinfo/.debug_macro).
Error cloneAndEmit(std::optional< std::reference_wrapper< const Triple > > TargetTriple, TypeUnit *ArtificialTypeUnit)
Clone and emit this compilation unit.
void setStage(Stage Stage)
Set stage of overall processing.
Stage getStage() const
Returns stage of overall processing.
CompileUnit(LinkingGlobalData &GlobalData, unsigned ID, StringRef ClangModuleName, DWARFFile &File, OffsetToUnitTy UnitFromOffset, dwarf::FormParams Format, llvm::endianness Endianess)
void verifyDependencies()
Check DIEs to have a consistent marking(keep marking, placement marking).
Stage
The stages of new compile unit processing.
@ LiveRootsCollected
DIEs with a live address are found.
@ CreatedNotLoaded
Created, linked with input DWARF file.
@ PatchesUpdated
Offsets inside patch records are updated.
@ Cleaned
Resources(Input DWARF, Output DWARF tree) are released.
@ LivenessAnalysisDone
Input DWARF is analysed(DIEs pointing to the real code section and theDIEs they depend on are marked)...
@ UpdateDependenciesCompleteness
Check if dependencies have incompatible placement.
std::string remapPath(StringRef Path) const override
void forEachAcceleratorRecord(function_ref< void(AccelInfo &)> Handler) override
Enumerates all units accelerator records.
std::optional< uint64_t > getLowPc() const
Returns value of DW_AT_low_pc attribute.
std::optional< std::pair< StringRef, StringRef > > getDirAndFilenameFromLineTable(const DWARFFormValue &FileIdxValue)
Returns directory and file from the line table by index.
std::optional< UnitEntryPairTy > resolveDIEReference(const DWARFFormValue &RefValue, ResolveInterCUReferencesMode CanResolveInterCUReferences)
Resolve the DIE attribute reference that has been extracted in RefValue.
bool getModulePath(const DWARFDebugInfoEntry *DieEntry, SmallVectorImpl< char > &Path)
Appends the names of the DW_TAG_module enclosing DieEntry, outermost first.
StringEntry * getFileName(unsigned FileIdx, StringPool &GlobalStrings)
Returns name of the file for the FileIdx from the unit`s line table.
This class is a helper to create output DIE tree.
This class discovers DIEs dependencies: marks "live" DIEs, marks DIE locations (whether DIE should be...
StringRef getUnitName() const
Returns this unit name.
DwarfUnit(LinkingGlobalData &GlobalData, unsigned ID, StringRef ClangModuleName)
std::string ClangModuleName
If this is a Clang module, this holds the module's name.
This class keeps data and services common for the whole linking process.
The helper class to build type name based on DIE properties.
Keeps cloned data for the type DIE.
Definition TypePool.h:75
TypePool keeps type descriptors which contain partially cloned DIE correspinding to each type.
Definition TypePool.h:147
Type Unit is used to represent an artificial compilation unit which keeps all type information.
An efficient, type-erasing, non-owning reference to a callable.
uint64_t getDieOutOffset(const DWARFDebugInfoEntry *InputDieEntry)
InputDieEntry debug info entry.
void rememberDieOutOffset(uint32_t Idx, uint64_t Offset)
Idx index of the DIE.
TypeEntry * getDieTypeEntry(uint32_t Idx)
Idx index of the DIE.
DIEInfo & getDIEInfo(unsigned Idx)
Idx index of the DIE.
const DIEInfo & getDIEInfo(const DWARFDebugInfoEntry *Entry) const
Idx index of the DIE.
uint64_t getDieOutOffset(uint32_t Idx)
Idx index of the DIE.
const DIEInfo & getDIEInfo(const DWARFDie &Die) const
Die
const DIEInfo & getDIEInfo(unsigned Idx) const
Idx index of the DIE.
DIEInfo & getDIEInfo(const DWARFDebugInfoEntry *Entry)
Idx index of the DIE.
TypeEntry * getDieTypeEntry(const DWARFDebugInfoEntry *InputDieEntry)
InputDieEntry debug info entry.
void setDieTypeEntry(const DWARFDebugInfoEntry *InputDieEntry, TypeEntry *Entry)
InputDieEntry debug info entry.
void setDieTypeEntry(uint32_t Idx, TypeEntry *Entry)
Idx index of the DIE.
DIEInfo & getDIEInfo(const DWARFDie &Die)
Die
const DWARFDebugInfoEntry * getSiblingEntry(const DWARFDebugInfoEntry *Die) const
const DWARFDebugInfoEntry * getFirstChildEntry(const DWARFDebugInfoEntry *Die) const
std::optional< uint32_t > getDIEIndexForOffset(uint64_t Offset)
DWARFDie getDIE(const DWARFDebugInfoEntry *Die)
std::optional< DWARFFormValue > find(const DWARFDebugInfoEntry *Die, ArrayRef< dwarf::Attribute > Attrs) const
const DWARFDebugInfoEntry * getDebugInfoEntry(unsigned Index) const
DWARFUnit & getOrigUnit() const
Returns paired compile unit from input DWARF.
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
DWARFDie getParent(const DWARFDebugInfoEntry *Die)
uint32_t getDIEIndex(const DWARFDebugInfoEntry *Die) const
uint32_t getDIEIndex(const DWARFDie &Die) const
std::optional< DWARFFormValue > find(uint32_t DieIdx, ArrayRef< dwarf::Attribute > Attrs) const
void error(Error Err, const DWARFDie *DIE=nullptr)
void warn(Error Warning, const DWARFDie *DIE=nullptr)
void warn(const Twine &Warning, const DWARFDie *DIE=nullptr)
void error(const Twine &Err, const DWARFDie *DIE=nullptr)
void warn(const Twine &Warning, const DWARFDebugInfoEntry *DieEntry)
#define SINGLE_FLAG_METHODS_SET(Name, Value)
function_ref< CompileUnit *(uint64_t Offset)> OffsetToUnitTy
SmallVector< uint64_t * > OffsetsPtrVector
Type for list of pointers to patches offsets.
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:30
ArrayRef< dwarf::Attribute > getODRAttributes()
DebugSectionKind
List of tracked debug tables.
LLVM_ABI void buildStmtSeqOffsetToFirstRowIndex(const DWARFDebugLine::LineTable &LT, ArrayRef< uint64_t > SortedStmtSeqOffsets, DenseMap< uint64_t, uint64_t > &SeqOffToFirstRow)
Build a map from an input DW_AT_LLVM_stmt_sequence byte offset to the first-row index (in LT....
Definition Utils.cpp:135
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
AddressRangesMap RangesTy
Mapped value in the address map is the offset to apply to the linked address.
Attribute
Attributes.
Definition Dwarf.h:125
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
static void insertLineSequence(std::vector< TrackedRow > &Seq, std::vector< TrackedRow > &Rows)
Insert the new line info sequence Seq into the current set of already linked line info Rows.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
ArrayRef(const T &OneElt) -> ArrayRef< T >
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
endianness
Definition bit.h:71
@ Keep
No function return thunk.
Definition CodeGen.h:370
Represents a single DWARF expression, whose value is location-dependent.
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition Dwarf.h:1221
void setPlacement(DieOutputPlacement Placement)
Sets Placement kind for the corresponding die.
std::atomic< uint16_t > Flags
Data member keeping various flags.
void joinVariablePlacement(DieOutputPlacement Placement)
Atomically joins Placement for a DW_TAG_variable, for which PlainDwarf is absorbing because a variabl...
void unsetPlacement()
Unsets Placement kind for the corresponding die.
bool setPlacementIfUnset(DieOutputPlacement Placement)
Sets Placement kind for the corresponding die.
void joinPlacement(DieOutputPlacement Placement)
Atomically joins Placement into the current placement: the least-upper-bound of the lattice NotSet < ...
void unsetFlagsWhichSetDuringLiveAnalysis()
DIE is a part of the linked output.
This structure keeps fields which would be used for creating accelerator table.
This structure is used to keep data of the concrete section.
UnitEntryPairTy(CompileUnit *CU, const DWARFDebugInfoEntry *DieEntry)