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