LLVM 19.0.0git
AccelTable.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/AsmPrinter/AccelTable.cpp - Accelerator Tables --------===//
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// This file contains support for writing accelerator tables.
10//
11//===----------------------------------------------------------------------===//
12
14#include "DwarfCompileUnit.h"
15#include "DwarfUnit.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Twine.h"
21#include "llvm/CodeGen/DIE.h"
22#include "llvm/MC/MCStreamer.h"
23#include "llvm/MC/MCSymbol.h"
26#include <algorithm>
27#include <cstddef>
28#include <cstdint>
29#include <limits>
30#include <vector>
31
32using namespace llvm;
33
35 // First get the number of unique hashes.
37 Uniques.reserve(Entries.size());
38 for (const auto &E : Entries)
39 Uniques.push_back(E.second.HashValue);
40
42}
43
45 // Create the individual hash data outputs.
46 for (auto &E : Entries) {
47 // Unique the entries.
48 llvm::stable_sort(E.second.Values,
49 [](const AccelTableData *A, const AccelTableData *B) {
50 return *A < *B;
51 });
52 E.second.Values.erase(
53 std::unique(E.second.Values.begin(), E.second.Values.end()),
54 E.second.Values.end());
55 }
56
57 // Figure out how many buckets we need, then compute the bucket contents and
58 // the final ordering. The hashes and offsets can be emitted by walking these
59 // data structures. We add temporary symbols to the data so they can be
60 // referenced when emitting the offsets.
62
63 // Compute bucket contents and final ordering.
64 Buckets.resize(BucketCount);
65 for (auto &E : Entries) {
66 uint32_t Bucket = E.second.HashValue % BucketCount;
67 Buckets[Bucket].push_back(&E.second);
68 E.second.Sym = Asm->createTempSymbol(Prefix);
69 }
70
71 // Sort the contents of the buckets by hash value so that hash collisions end
72 // up together. Stable sort makes testing easier and doesn't cost much more.
73 for (auto &Bucket : Buckets)
75 return LHS->HashValue < RHS->HashValue;
76 });
77}
78
79namespace {
80/// Base class for writing out Accelerator tables. It holds the common
81/// functionality for the two Accelerator table types.
82class AccelTableWriter {
83protected:
84 AsmPrinter *const Asm; ///< Destination.
85 const AccelTableBase &Contents; ///< Data to emit.
86
87 /// Controls whether to emit duplicate hash and offset table entries for names
88 /// with identical hashes. Apple tables don't emit duplicate entries, DWARF v5
89 /// tables do.
90 const bool SkipIdenticalHashes;
91
92 void emitHashes() const;
93
94 /// Emit offsets to lists of entries with identical names. The offsets are
95 /// relative to the Base argument.
96 void emitOffsets(const MCSymbol *Base) const;
97
98public:
99 AccelTableWriter(AsmPrinter *Asm, const AccelTableBase &Contents,
100 bool SkipIdenticalHashes)
101 : Asm(Asm), Contents(Contents), SkipIdenticalHashes(SkipIdenticalHashes) {
102 }
103};
104
105class AppleAccelTableWriter : public AccelTableWriter {
106 using Atom = AppleAccelTableData::Atom;
107
108 /// The fixed header of an Apple Accelerator Table.
109 struct Header {
110 uint32_t Magic = MagicHash;
111 uint16_t Version = 1;
113 uint32_t BucketCount;
114 uint32_t HashCount;
115 uint32_t HeaderDataLength;
116
117 /// 'HASH' magic value to detect endianness.
118 static const uint32_t MagicHash = 0x48415348;
119
120 Header(uint32_t BucketCount, uint32_t UniqueHashCount, uint32_t DataLength)
121 : BucketCount(BucketCount), HashCount(UniqueHashCount),
122 HeaderDataLength(DataLength) {}
123
124 void emit(AsmPrinter *Asm) const;
125#ifndef NDEBUG
126 void print(raw_ostream &OS) const;
127 void dump() const { print(dbgs()); }
128#endif
129 };
130
131 /// The HeaderData describes the structure of an Apple accelerator table
132 /// through a list of Atoms.
133 struct HeaderData {
134 /// In the case of data that is referenced via DW_FORM_ref_* the offset
135 /// base is used to describe the offset for all forms in the list of atoms.
136 uint32_t DieOffsetBase;
137
138 const SmallVector<Atom, 4> Atoms;
139
140 HeaderData(ArrayRef<Atom> AtomList, uint32_t Offset = 0)
141 : DieOffsetBase(Offset), Atoms(AtomList.begin(), AtomList.end()) {}
142
143 void emit(AsmPrinter *Asm) const;
144#ifndef NDEBUG
145 void print(raw_ostream &OS) const;
146 void dump() const { print(dbgs()); }
147#endif
148 };
149
150 Header Header;
151 HeaderData HeaderData;
152 const MCSymbol *SecBegin;
153
154 void emitBuckets() const;
155 void emitData() const;
156
157public:
158 AppleAccelTableWriter(AsmPrinter *Asm, const AccelTableBase &Contents,
159 ArrayRef<Atom> Atoms, const MCSymbol *SecBegin)
160 : AccelTableWriter(Asm, Contents, true),
161 Header(Contents.getBucketCount(), Contents.getUniqueHashCount(),
162 8 + (Atoms.size() * 4)),
163 HeaderData(Atoms), SecBegin(SecBegin) {}
164
165 void emit() const;
166
167#ifndef NDEBUG
168 void print(raw_ostream &OS) const;
169 void dump() const { print(dbgs()); }
170#endif
171};
172
173/// Class responsible for emitting a DWARF v5 Accelerator Table. The only
174/// public function is emit(), which performs the actual emission.
175///
176/// A callback abstracts the logic to provide a CU index for a given entry.
177class Dwarf5AccelTableWriter : public AccelTableWriter {
178 struct Header {
179 uint16_t Version = 5;
180 uint16_t Padding = 0;
181 uint32_t CompUnitCount;
182 uint32_t LocalTypeUnitCount = 0;
183 uint32_t ForeignTypeUnitCount = 0;
184 uint32_t BucketCount = 0;
185 uint32_t NameCount = 0;
186 uint32_t AbbrevTableSize = 0;
187 uint32_t AugmentationStringSize = sizeof(AugmentationString);
188 char AugmentationString[8] = {'L', 'L', 'V', 'M', '0', '7', '0', '0'};
189
190 Header(uint32_t CompUnitCount, uint32_t LocalTypeUnitCount,
191 uint32_t ForeignTypeUnitCount, uint32_t BucketCount,
192 uint32_t NameCount)
193 : CompUnitCount(CompUnitCount), LocalTypeUnitCount(LocalTypeUnitCount),
194 ForeignTypeUnitCount(ForeignTypeUnitCount), BucketCount(BucketCount),
195 NameCount(NameCount) {}
196
197 void emit(Dwarf5AccelTableWriter &Ctx);
198 };
199
200 Header Header;
201 /// FoldingSet that uniques the abbreviations.
202 FoldingSet<DebugNamesAbbrev> AbbreviationsSet;
203 /// Vector containing DebugNames abbreviations for iteration in order.
204 SmallVector<DebugNamesAbbrev *, 5> AbbreviationsVector;
205 /// The bump allocator to use when creating DIEAbbrev objects in the uniqued
206 /// storage container.
207 BumpPtrAllocator Alloc;
211 const DWARF5AccelTableData &)>
212 getIndexForEntry;
213 MCSymbol *ContributionEnd = nullptr;
214 MCSymbol *AbbrevStart = Asm->createTempSymbol("names_abbrev_start");
215 MCSymbol *AbbrevEnd = Asm->createTempSymbol("names_abbrev_end");
216 MCSymbol *EntryPool = Asm->createTempSymbol("names_entries");
217 // Indicates if this module is built with Split Dwarf enabled.
218 bool IsSplitDwarf = false;
219 /// Stores the DIE offsets which are indexed by this table.
220 DenseSet<OffsetAndUnitID> IndexedOffsets;
221
222 void populateAbbrevsMap();
223
224 void emitCUList() const;
225 void emitTUList() const;
226 void emitBuckets() const;
227 void emitStringOffsets() const;
228 void emitAbbrevs() const;
229 void emitEntry(
230 const DWARF5AccelTableData &Entry,
231 const DenseMap<OffsetAndUnitID, MCSymbol *> &DIEOffsetToAccelEntryLabel,
232 DenseSet<MCSymbol *> &EmittedAccelEntrySymbols);
233 void emitData();
234
235public:
236 Dwarf5AccelTableWriter(
237 AsmPrinter *Asm, const AccelTableBase &Contents,
238 ArrayRef<std::variant<MCSymbol *, uint64_t>> CompUnits,
239 ArrayRef<std::variant<MCSymbol *, uint64_t>> TypeUnits,
240 llvm::function_ref<std::optional<DWARF5AccelTable::UnitIndexAndEncoding>(
241 const DWARF5AccelTableData &)>
242 getIndexForEntry,
243 bool IsSplitDwarf);
244 ~Dwarf5AccelTableWriter() {
245 for (DebugNamesAbbrev *Abbrev : AbbreviationsVector)
246 Abbrev->~DebugNamesAbbrev();
247 }
248 void emit();
249};
250} // namespace
251
252void AccelTableWriter::emitHashes() const {
253 uint64_t PrevHash = std::numeric_limits<uint64_t>::max();
254 unsigned BucketIdx = 0;
255 for (const auto &Bucket : Contents.getBuckets()) {
256 for (const auto &Hash : Bucket) {
257 uint32_t HashValue = Hash->HashValue;
258 if (SkipIdenticalHashes && PrevHash == HashValue)
259 continue;
260 Asm->OutStreamer->AddComment("Hash in Bucket " + Twine(BucketIdx));
261 Asm->emitInt32(HashValue);
262 PrevHash = HashValue;
263 }
264 BucketIdx++;
265 }
266}
267
268void AccelTableWriter::emitOffsets(const MCSymbol *Base) const {
269 const auto &Buckets = Contents.getBuckets();
270 uint64_t PrevHash = std::numeric_limits<uint64_t>::max();
271 for (size_t i = 0, e = Buckets.size(); i < e; ++i) {
272 for (auto *Hash : Buckets[i]) {
273 uint32_t HashValue = Hash->HashValue;
274 if (SkipIdenticalHashes && PrevHash == HashValue)
275 continue;
276 PrevHash = HashValue;
277 Asm->OutStreamer->AddComment("Offset in Bucket " + Twine(i));
278 Asm->emitLabelDifference(Hash->Sym, Base, Asm->getDwarfOffsetByteSize());
279 }
280 }
281}
282
283void AppleAccelTableWriter::Header::emit(AsmPrinter *Asm) const {
284 Asm->OutStreamer->AddComment("Header Magic");
285 Asm->emitInt32(Magic);
286 Asm->OutStreamer->AddComment("Header Version");
287 Asm->emitInt16(Version);
288 Asm->OutStreamer->AddComment("Header Hash Function");
289 Asm->emitInt16(HashFunction);
290 Asm->OutStreamer->AddComment("Header Bucket Count");
291 Asm->emitInt32(BucketCount);
292 Asm->OutStreamer->AddComment("Header Hash Count");
293 Asm->emitInt32(HashCount);
294 Asm->OutStreamer->AddComment("Header Data Length");
295 Asm->emitInt32(HeaderDataLength);
296}
297
298void AppleAccelTableWriter::HeaderData::emit(AsmPrinter *Asm) const {
299 Asm->OutStreamer->AddComment("HeaderData Die Offset Base");
300 Asm->emitInt32(DieOffsetBase);
301 Asm->OutStreamer->AddComment("HeaderData Atom Count");
302 Asm->emitInt32(Atoms.size());
303
304 for (const Atom &A : Atoms) {
305 Asm->OutStreamer->AddComment(dwarf::AtomTypeString(A.Type));
306 Asm->emitInt16(A.Type);
307 Asm->OutStreamer->AddComment(dwarf::FormEncodingString(A.Form));
308 Asm->emitInt16(A.Form);
309 }
310}
311
312void AppleAccelTableWriter::emitBuckets() const {
313 const auto &Buckets = Contents.getBuckets();
314 unsigned index = 0;
315 for (size_t i = 0, e = Buckets.size(); i < e; ++i) {
316 Asm->OutStreamer->AddComment("Bucket " + Twine(i));
317 if (!Buckets[i].empty())
318 Asm->emitInt32(index);
319 else
320 Asm->emitInt32(std::numeric_limits<uint32_t>::max());
321 // Buckets point in the list of hashes, not to the data. Do not increment
322 // the index multiple times in case of hash collisions.
323 uint64_t PrevHash = std::numeric_limits<uint64_t>::max();
324 for (auto *HD : Buckets[i]) {
325 uint32_t HashValue = HD->HashValue;
326 if (PrevHash != HashValue)
327 ++index;
328 PrevHash = HashValue;
329 }
330 }
331}
332
333void AppleAccelTableWriter::emitData() const {
334 const auto &Buckets = Contents.getBuckets();
335 for (const AccelTableBase::HashList &Bucket : Buckets) {
336 uint64_t PrevHash = std::numeric_limits<uint64_t>::max();
337 for (const auto &Hash : Bucket) {
338 // Terminate the previous entry if there is no hash collision with the
339 // current one.
340 if (PrevHash != std::numeric_limits<uint64_t>::max() &&
341 PrevHash != Hash->HashValue)
342 Asm->emitInt32(0);
343 // Remember to emit the label for our offset.
344 Asm->OutStreamer->emitLabel(Hash->Sym);
345 Asm->OutStreamer->AddComment(Hash->Name.getString());
346 Asm->emitDwarfStringOffset(Hash->Name);
347 Asm->OutStreamer->AddComment("Num DIEs");
348 Asm->emitInt32(Hash->Values.size());
349 for (const auto *V : Hash->getValues<const AppleAccelTableData *>())
350 V->emit(Asm);
351 PrevHash = Hash->HashValue;
352 }
353 // Emit the final end marker for the bucket.
354 if (!Bucket.empty())
355 Asm->emitInt32(0);
356 }
357}
358
359void AppleAccelTableWriter::emit() const {
360 Header.emit(Asm);
361 HeaderData.emit(Asm);
362 emitBuckets();
363 emitHashes();
364 emitOffsets(SecBegin);
365 emitData();
366}
367
369 const uint32_t UnitID,
370 const bool IsTU)
371 : OffsetVal(&Die), DieTag(Die.getTag()), IsTU(IsTU), UnitID(UnitID) {}
372
373void Dwarf5AccelTableWriter::Header::emit(Dwarf5AccelTableWriter &Ctx) {
374 assert(CompUnitCount > 0 && "Index must have at least one CU.");
375
376 AsmPrinter *Asm = Ctx.Asm;
377 Ctx.ContributionEnd =
378 Asm->emitDwarfUnitLength("names", "Header: unit length");
379 Asm->OutStreamer->AddComment("Header: version");
380 Asm->emitInt16(Version);
381 Asm->OutStreamer->AddComment("Header: padding");
382 Asm->emitInt16(Padding);
383 Asm->OutStreamer->AddComment("Header: compilation unit count");
384 Asm->emitInt32(CompUnitCount);
385 Asm->OutStreamer->AddComment("Header: local type unit count");
386 Asm->emitInt32(LocalTypeUnitCount);
387 Asm->OutStreamer->AddComment("Header: foreign type unit count");
388 Asm->emitInt32(ForeignTypeUnitCount);
389 Asm->OutStreamer->AddComment("Header: bucket count");
390 Asm->emitInt32(BucketCount);
391 Asm->OutStreamer->AddComment("Header: name count");
392 Asm->emitInt32(NameCount);
393 Asm->OutStreamer->AddComment("Header: abbreviation table size");
394 Asm->emitLabelDifference(Ctx.AbbrevEnd, Ctx.AbbrevStart, sizeof(uint32_t));
395 Asm->OutStreamer->AddComment("Header: augmentation string size");
396 assert(AugmentationStringSize % 4 == 0);
397 Asm->emitInt32(AugmentationStringSize);
398 Asm->OutStreamer->AddComment("Header: augmentation string");
399 Asm->OutStreamer->emitBytes({AugmentationString, AugmentationStringSize});
400}
401
402std::optional<uint64_t>
404 if (auto *Parent = Die.getParent();
405 Parent && !Parent->findAttribute(dwarf::Attribute::DW_AT_declaration))
406 return Parent->getOffset();
407 return {};
408}
409
410static std::optional<dwarf::Form>
412 std::optional<OffsetAndUnitID> ParentOffset) {
413 // No parent information
414 if (!ParentOffset)
415 return std::nullopt;
416 // Parent is indexed by this table.
417 if (IndexedOffsets.contains(*ParentOffset))
418 return dwarf::Form::DW_FORM_ref4;
419 // Parent is not indexed by this table.
420 return dwarf::Form::DW_FORM_flag_present;
421}
422
424 ID.AddInteger(DieTag);
425 for (const DebugNamesAbbrev::AttributeEncoding &Enc : AttrVect) {
426 ID.AddInteger(Enc.Index);
427 ID.AddInteger(Enc.Form);
428 }
429}
430
431void Dwarf5AccelTableWriter::populateAbbrevsMap() {
432 for (auto &Bucket : Contents.getBuckets()) {
433 for (auto *Hash : Bucket) {
434 for (auto *Value : Hash->getValues<DWARF5AccelTableData *>()) {
435 std::optional<DWARF5AccelTable::UnitIndexAndEncoding> EntryRet =
436 getIndexForEntry(*Value);
437 std::optional<dwarf::Form> MaybeParentForm = getFormForIdxParent(
438 IndexedOffsets, Value->getParentDieOffsetAndUnitID());
439 DebugNamesAbbrev Abbrev(Value->getDieTag());
440 if (EntryRet)
441 Abbrev.addAttribute(EntryRet->Encoding);
442 Abbrev.addAttribute({dwarf::DW_IDX_die_offset, dwarf::DW_FORM_ref4});
443 if (MaybeParentForm)
444 Abbrev.addAttribute({dwarf::DW_IDX_parent, *MaybeParentForm});
446 Abbrev.Profile(ID);
447 void *InsertPos;
448 if (DebugNamesAbbrev *Existing =
449 AbbreviationsSet.FindNodeOrInsertPos(ID, InsertPos)) {
450 Value->setAbbrevNumber(Existing->getNumber());
451 continue;
452 }
453 DebugNamesAbbrev *NewAbbrev =
454 new (Alloc) DebugNamesAbbrev(std::move(Abbrev));
455 AbbreviationsVector.push_back(NewAbbrev);
456 NewAbbrev->setNumber(AbbreviationsVector.size());
457 AbbreviationsSet.InsertNode(NewAbbrev, InsertPos);
458 Value->setAbbrevNumber(NewAbbrev->getNumber());
459 }
460 }
461 }
462}
463
464void Dwarf5AccelTableWriter::emitCUList() const {
465 for (const auto &CU : enumerate(CompUnits)) {
466 Asm->OutStreamer->AddComment("Compilation unit " + Twine(CU.index()));
467 if (std::holds_alternative<MCSymbol *>(CU.value()))
468 Asm->emitDwarfSymbolReference(std::get<MCSymbol *>(CU.value()));
469 else
470 Asm->emitDwarfLengthOrOffset(std::get<uint64_t>(CU.value()));
471 }
472}
473
474void Dwarf5AccelTableWriter::emitTUList() const {
475 for (const auto &TU : enumerate(TypeUnits)) {
476 Asm->OutStreamer->AddComment("Type unit " + Twine(TU.index()));
477 if (std::holds_alternative<MCSymbol *>(TU.value()))
478 Asm->emitDwarfSymbolReference(std::get<MCSymbol *>(TU.value()));
479 else if (IsSplitDwarf)
480 Asm->emitInt64(std::get<uint64_t>(TU.value()));
481 else
482 Asm->emitDwarfLengthOrOffset(std::get<uint64_t>(TU.value()));
483 }
484}
485
486void Dwarf5AccelTableWriter::emitBuckets() const {
487 uint32_t Index = 1;
488 for (const auto &Bucket : enumerate(Contents.getBuckets())) {
489 Asm->OutStreamer->AddComment("Bucket " + Twine(Bucket.index()));
490 Asm->emitInt32(Bucket.value().empty() ? 0 : Index);
491 Index += Bucket.value().size();
492 }
493}
494
495void Dwarf5AccelTableWriter::emitStringOffsets() const {
496 for (const auto &Bucket : enumerate(Contents.getBuckets())) {
497 for (auto *Hash : Bucket.value()) {
498 DwarfStringPoolEntryRef String = Hash->Name;
499 Asm->OutStreamer->AddComment("String in Bucket " + Twine(Bucket.index()) +
500 ": " + String.getString());
501 Asm->emitDwarfStringOffset(String);
502 }
503 }
504}
505
506void Dwarf5AccelTableWriter::emitAbbrevs() const {
507 Asm->OutStreamer->emitLabel(AbbrevStart);
508 for (const DebugNamesAbbrev *Abbrev : AbbreviationsVector) {
509 Asm->OutStreamer->AddComment("Abbrev code");
510 Asm->emitULEB128(Abbrev->getNumber());
511 Asm->OutStreamer->AddComment(dwarf::TagString(Abbrev->getDieTag()));
512 Asm->emitULEB128(Abbrev->getDieTag());
513 for (const DebugNamesAbbrev::AttributeEncoding &AttrEnc :
514 Abbrev->getAttributes()) {
515 Asm->emitULEB128(AttrEnc.Index, dwarf::IndexString(AttrEnc.Index).data());
516 Asm->emitULEB128(AttrEnc.Form,
517 dwarf::FormEncodingString(AttrEnc.Form).data());
518 }
519 Asm->emitULEB128(0, "End of abbrev");
520 Asm->emitULEB128(0, "End of abbrev");
521 }
522 Asm->emitULEB128(0, "End of abbrev list");
523 Asm->OutStreamer->emitLabel(AbbrevEnd);
524}
525
526void Dwarf5AccelTableWriter::emitEntry(
527 const DWARF5AccelTableData &Entry,
528 const DenseMap<OffsetAndUnitID, MCSymbol *> &DIEOffsetToAccelEntryLabel,
529 DenseSet<MCSymbol *> &EmittedAccelEntrySymbols) {
530 unsigned AbbrevIndex = Entry.getAbbrevNumber() - 1;
531 assert(AbbrevIndex < AbbreviationsVector.size() &&
532 "Entry abbrev index is outside of abbreviations vector range.");
533 DebugNamesAbbrev *Abbrev = AbbreviationsVector[AbbrevIndex];
534 std::optional<DWARF5AccelTable::UnitIndexAndEncoding> EntryRet =
535 getIndexForEntry(Entry);
536 std::optional<OffsetAndUnitID> MaybeParentOffset =
537 Entry.getParentDieOffsetAndUnitID();
538 auto EntrySymbolIt =
539 DIEOffsetToAccelEntryLabel.find(Entry.getDieOffsetAndUnitID());
540 assert(EntrySymbolIt != DIEOffsetToAccelEntryLabel.end());
541 MCSymbol *EntrySymbol = EntrySymbolIt->getSecond();
542
543 // Emit the label for this Entry, so that IDX_parents may refer to it.
544 // Note: a DIE may have multiple accelerator Entries; this check avoids
545 // creating/emitting multiple labels for the same DIE.
546 if (EmittedAccelEntrySymbols.insert(EntrySymbol).second)
547 Asm->OutStreamer->emitLabel(EntrySymbol);
548
549 Asm->emitULEB128(Entry.getAbbrevNumber(), "Abbreviation code");
550
551 for (const DebugNamesAbbrev::AttributeEncoding &AttrEnc :
552 Abbrev->getAttributes()) {
553 Asm->OutStreamer->AddComment(dwarf::IndexString(AttrEnc.Index));
554 switch (AttrEnc.Index) {
555 case dwarf::DW_IDX_compile_unit:
556 case dwarf::DW_IDX_type_unit: {
557 DIEInteger ID(EntryRet->Index);
558 ID.emitValue(Asm, AttrEnc.Form);
559 break;
560 }
561 case dwarf::DW_IDX_die_offset:
562 assert(AttrEnc.Form == dwarf::DW_FORM_ref4);
563 Asm->emitInt32(Entry.getDieOffset());
564 break;
565 case dwarf::DW_IDX_parent: {
566 if (AttrEnc.Form == dwarf::Form::DW_FORM_flag_present)
567 break;
568 auto ParentSymbolIt = DIEOffsetToAccelEntryLabel.find(*MaybeParentOffset);
569 assert(ParentSymbolIt != DIEOffsetToAccelEntryLabel.end());
570 Asm->emitLabelDifference(ParentSymbolIt->getSecond(), EntryPool, 4);
571 break;
572 }
573 default:
574 llvm_unreachable("Unexpected index attribute!");
575 }
576 }
577}
578
579void Dwarf5AccelTableWriter::emitData() {
580 DenseMap<OffsetAndUnitID, MCSymbol *> DIEOffsetToAccelEntryLabel;
581
582 for (OffsetAndUnitID Offset : IndexedOffsets)
583 DIEOffsetToAccelEntryLabel.insert({Offset, Asm->createTempSymbol("")});
584
585 Asm->OutStreamer->emitLabel(EntryPool);
586 DenseSet<MCSymbol *> EmittedAccelEntrySymbols;
587 for (auto &Bucket : Contents.getBuckets()) {
588 for (auto *Hash : Bucket) {
589 // Remember to emit the label for our offset.
590 Asm->OutStreamer->emitLabel(Hash->Sym);
591 for (const auto *Value : Hash->getValues<DWARF5AccelTableData *>())
592 emitEntry(*Value, DIEOffsetToAccelEntryLabel, EmittedAccelEntrySymbols);
593 Asm->OutStreamer->AddComment("End of list: " + Hash->Name.getString());
594 Asm->emitInt8(0);
595 }
596 }
597}
598
599Dwarf5AccelTableWriter::Dwarf5AccelTableWriter(
600 AsmPrinter *Asm, const AccelTableBase &Contents,
601 ArrayRef<std::variant<MCSymbol *, uint64_t>> CompUnits,
602 ArrayRef<std::variant<MCSymbol *, uint64_t>> TypeUnits,
603 llvm::function_ref<std::optional<DWARF5AccelTable::UnitIndexAndEncoding>(
604 const DWARF5AccelTableData &)>
605 getIndexForEntry,
606 bool IsSplitDwarf)
607 : AccelTableWriter(Asm, Contents, false),
608 Header(CompUnits.size(), IsSplitDwarf ? 0 : TypeUnits.size(),
609 IsSplitDwarf ? TypeUnits.size() : 0, Contents.getBucketCount(),
610 Contents.getUniqueNameCount()),
611 CompUnits(CompUnits), TypeUnits(TypeUnits),
612 getIndexForEntry(std::move(getIndexForEntry)),
613 IsSplitDwarf(IsSplitDwarf) {
614
615 for (auto &Bucket : Contents.getBuckets())
616 for (auto *Hash : Bucket)
617 for (auto *Value : Hash->getValues<DWARF5AccelTableData *>())
618 IndexedOffsets.insert(Value->getDieOffsetAndUnitID());
619
620 populateAbbrevsMap();
621}
622
623void Dwarf5AccelTableWriter::emit() {
624 Header.emit(*this);
625 emitCUList();
626 emitTUList();
627 emitBuckets();
628 emitHashes();
629 emitStringOffsets();
630 emitOffsets(EntryPool);
631 emitAbbrevs();
632 emitData();
633 Asm->OutStreamer->emitValueToAlignment(Align(4), 0);
634 Asm->OutStreamer->emitLabel(ContributionEnd);
635}
636
638 StringRef Prefix, const MCSymbol *SecBegin,
640 Contents.finalize(Asm, Prefix);
641 AppleAccelTableWriter(Asm, Contents, Atoms, SecBegin).emit();
642}
643
645 AsmPrinter *Asm, DWARF5AccelTable &Contents, const DwarfDebug &DD,
646 ArrayRef<std::unique_ptr<DwarfCompileUnit>> CUs) {
647 TUVectorTy TUSymbols = Contents.getTypeUnitsSymbols();
648 std::vector<std::variant<MCSymbol *, uint64_t>> CompUnits;
649 std::vector<std::variant<MCSymbol *, uint64_t>> TypeUnits;
650 SmallVector<unsigned, 1> CUIndex(CUs.size());
651 DenseMap<unsigned, unsigned> TUIndex(TUSymbols.size());
652 int CUCount = 0;
653 int TUCount = 0;
654 for (const auto &CU : enumerate(CUs)) {
655 switch (CU.value()->getCUNode()->getNameTableKind()) {
658 break;
659 default:
660 continue;
661 }
662 CUIndex[CU.index()] = CUCount++;
663 assert(CU.index() == CU.value()->getUniqueID());
664 const DwarfCompileUnit *MainCU =
665 DD.useSplitDwarf() ? CU.value()->getSkeleton() : CU.value().get();
666 CompUnits.push_back(MainCU->getLabelBegin());
667 }
668
669 for (const auto &TU : TUSymbols) {
670 TUIndex[TU.UniqueID] = TUCount++;
671 if (DD.useSplitDwarf())
672 TypeUnits.push_back(std::get<uint64_t>(TU.LabelOrSignature));
673 else
674 TypeUnits.push_back(std::get<MCSymbol *>(TU.LabelOrSignature));
675 }
676
677 if (CompUnits.empty())
678 return;
679
680 Asm->OutStreamer->switchSection(
681 Asm->getObjFileLowering().getDwarfDebugNamesSection());
682
683 Contents.finalize(Asm, "names");
684 dwarf::Form CUIndexForm =
685 DIEInteger::BestForm(/*IsSigned*/ false, CompUnits.size() - 1);
686 dwarf::Form TUIndexForm =
687 DIEInteger::BestForm(/*IsSigned*/ false, TypeUnits.size() - 1);
688 Dwarf5AccelTableWriter(
689 Asm, Contents, CompUnits, TypeUnits,
690 [&](const DWARF5AccelTableData &Entry)
691 -> std::optional<DWARF5AccelTable::UnitIndexAndEncoding> {
692 if (Entry.isTU())
693 return {{TUIndex[Entry.getUnitID()],
694 {dwarf::DW_IDX_type_unit, TUIndexForm}}};
695 if (CUIndex.size() > 1)
696 return {{CUIndex[Entry.getUnitID()],
697 {dwarf::DW_IDX_compile_unit, CUIndexForm}}};
698 return std::nullopt;
699 },
700 DD.useSplitDwarf())
701 .emit();
702}
703
705 TUSymbolsOrHashes.push_back({U.getLabelBegin(), U.getUniqueID()});
706}
707
709 TUSymbolsOrHashes.push_back({U.getTypeSignature(), U.getUniqueID()});
710}
711
713 AsmPrinter *Asm, DWARF5AccelTable &Contents,
714 ArrayRef<std::variant<MCSymbol *, uint64_t>> CUs,
715 llvm::function_ref<std::optional<DWARF5AccelTable::UnitIndexAndEncoding>(
716 const DWARF5AccelTableData &)>
717 getIndexForEntry) {
718 std::vector<std::variant<MCSymbol *, uint64_t>> TypeUnits;
719 Contents.finalize(Asm, "names");
720 Dwarf5AccelTableWriter(Asm, Contents, CUs, TypeUnits, getIndexForEntry, false)
721 .emit();
722}
723
725 assert(Die.getDebugSectionOffset() <= UINT32_MAX &&
726 "The section offset exceeds the limit.");
727 Asm->emitInt32(Die.getDebugSectionOffset());
728}
729
731 assert(Die.getDebugSectionOffset() <= UINT32_MAX &&
732 "The section offset exceeds the limit.");
733 Asm->emitInt32(Die.getDebugSectionOffset());
734 Asm->emitInt16(Die.getTag());
735 Asm->emitInt8(0);
736}
737
739 Asm->emitInt32(Offset);
740}
741
743 Asm->emitInt32(Offset);
744 Asm->emitInt16(Tag);
746 : 0);
747 Asm->emitInt32(QualifiedNameHash);
748}
749
754
755#ifndef NDEBUG
756void AppleAccelTableWriter::Header::print(raw_ostream &OS) const {
757 OS << "Magic: " << format("0x%x", Magic) << "\n"
758 << "Version: " << Version << "\n"
759 << "Hash Function: " << HashFunction << "\n"
760 << "Bucket Count: " << BucketCount << "\n"
761 << "Header Data Length: " << HeaderDataLength << "\n";
762}
763
765 OS << "Type: " << dwarf::AtomTypeString(Type) << "\n"
766 << "Form: " << dwarf::FormEncodingString(Form) << "\n";
767}
768
769void AppleAccelTableWriter::HeaderData::print(raw_ostream &OS) const {
770 OS << "DIE Offset Base: " << DieOffsetBase << "\n";
771 for (auto Atom : Atoms)
772 Atom.print(OS);
773}
774
775void AppleAccelTableWriter::print(raw_ostream &OS) const {
776 Header.print(OS);
777 HeaderData.print(OS);
778 Contents.print(OS);
779 SecBegin->print(OS, nullptr);
780}
781
783 OS << "Name: " << Name.getString() << "\n";
784 OS << " Hash Value: " << format("0x%x", HashValue) << "\n";
785 OS << " Symbol: ";
786 if (Sym)
787 OS << *Sym;
788 else
789 OS << "<none>";
790 OS << "\n";
791 for (auto *Value : Values)
792 Value->print(OS);
793}
794
796 // Print Content.
797 OS << "Entries: \n";
798 for (const auto &[Name, Data] : Entries) {
799 OS << "Name: " << Name << "\n";
800 for (auto *V : Data.Values)
801 V->print(OS);
802 }
803
804 OS << "Buckets and Hashes: \n";
805 for (const auto &Bucket : Buckets)
806 for (const auto &Hash : Bucket)
807 Hash->print(OS);
808
809 OS << "Data: \n";
810 for (const auto &E : Entries)
811 E.second.print(OS);
812}
813
815 OS << " Offset: " << getDieOffset() << "\n";
816 OS << " Tag: " << dwarf::TagString(getDieTag()) << "\n";
817}
818
820 OS << " Offset: " << Die.getOffset() << "\n";
821}
822
824 OS << " Offset: " << Die.getOffset() << "\n";
825 OS << " Tag: " << dwarf::TagString(Die.getTag()) << "\n";
826}
827
829 OS << " Static Offset: " << Offset << "\n";
830}
831
833 OS << " Static Offset: " << Offset << "\n";
834 OS << " QualifiedNameHash: " << format("%x\n", QualifiedNameHash) << "\n";
835 OS << " Tag: " << dwarf::TagString(Tag) << "\n";
836 OS << " ObjCClassIsImplementation: "
837 << (ObjCClassIsImplementation ? "true" : "false");
838 OS << "\n";
839}
840#endif
static std::optional< dwarf::Form > getFormForIdxParent(const DenseSet< OffsetAndUnitID > &IndexedOffsets, std::optional< OffsetAndUnitID > ParentOffset)
Definition: AccelTable.cpp:411
This file contains support for writing accelerator tables.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
basic Basic Alias true
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
dxil metadata emit
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
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
Value * RHS
Value * LHS
A base class holding non-template-dependant functionality of the AccelTable class.
Definition: AccelTable.h:135
BucketList Buckets
Definition: AccelTable.h:175
std::vector< HashData * > HashList
Definition: AccelTable.h:160
void finalize(AsmPrinter *Asm, StringRef Prefix)
Definition: AccelTable.cpp:44
void print(raw_ostream &OS) const
Definition: AccelTable.cpp:795
ArrayRef< HashList > getBuckets() const
Definition: AccelTable.h:183
uint32_t UniqueHashCount
Definition: AccelTable.h:172
StringEntries Entries
Definition: AccelTable.h:168
Interface which the different types of accelerator table data have to conform.
Definition: AccelTable.h:114
A base class for different implementations of Data classes for Apple Accelerator Tables.
Definition: AccelTable.h:232
void emit(AsmPrinter *Asm) const override
Definition: AccelTable.cpp:724
void print(raw_ostream &OS) const override
Definition: AccelTable.cpp:819
static constexpr Atom Atoms[]
Definition: AccelTable.h:462
static constexpr Atom Atoms[]
Definition: AccelTable.h:499
void emit(AsmPrinter *Asm) const override
Definition: AccelTable.cpp:738
void print(raw_ostream &OS) const override
Definition: AccelTable.cpp:828
void emit(AsmPrinter *Asm) const override
Definition: AccelTable.cpp:742
void print(raw_ostream &OS) const override
Definition: AccelTable.cpp:832
static constexpr Atom Atoms[]
Definition: AccelTable.h:524
void print(raw_ostream &OS) const override
Definition: AccelTable.cpp:823
void emit(AsmPrinter *Asm) const override
Definition: AccelTable.cpp:730
static constexpr Atom Atoms[]
Definition: AccelTable.h:481
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:84
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
An integer value DIE.
Definition: DIE.h:168
static dwarf::Form BestForm(bool IsSigned, uint64_t Int)
Choose the best form for integer.
Definition: DIE.h:175
A structured debug information entry.
Definition: DIE.h:819
DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
Definition: DIE.cpp:214
uint64_t getDebugSectionOffset() const
Get the absolute offset within the .debug_info or .debug_types section for this DIE.
Definition: DIE.cpp:189
dwarf::Tag getTag() const
Definition: DIE.h:855
DIE * getParent() const
Definition: DIE.cpp:176
The Data class implementation for DWARF v5 accelerator table.
Definition: AccelTable.h:276
void print(raw_ostream &OS) const override
Definition: AccelTable.cpp:814
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:403
DWARF5AccelTableData(const DIE &Die, const uint32_t UnitID, const bool IsTU=false)
Definition: AccelTable.cpp:368
void addTypeUnitSignature(DwarfTypeUnit &U)
Add a type unit Signature.
Definition: AccelTable.cpp:708
const TUVectorTy & getTypeUnitsSymbols()
Returns type units that were constructed.
Definition: AccelTable.h:395
void addTypeUnitSymbol(DwarfTypeUnit &U)
Add a type unit start symbol.
Definition: AccelTable.cpp:704
void setNumber(uint32_t AbbrevNumber)
Set abbreviation tag index.
Definition: AccelTable.h:362
const SmallVector< AttributeEncoding, 1 > & getAttributes() const
Returns attributes for an abbreviation.
Definition: AccelTable.h:370
void Profile(FoldingSetNodeID &ID) const
Used to gather unique data for the abbreviation folding set.
Definition: AccelTable.cpp:423
uint32_t getNumber() const
Get abbreviation tag index.
Definition: AccelTable.h:364
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:351
bool useSplitDwarf() const
Returns whether or not to change the current debug info for the split dwarf proposal support.
Definition: DwarfDebug.h:806
DwarfStringPoolEntryRef: Dwarf string pool entry reference.
MCSymbol * getLabelBegin() const
Get the the symbol for start of the section for this unit.
Definition: DwarfUnit.h:105
void InsertNode(T *N, void *InsertPos)
InsertNode - Insert the specified node into the folding set, knowing that it is not already in the fo...
Definition: FoldingSet.h:498
T * FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos)
FindNodeOrInsertPos - Look up the node specified by ID.
Definition: FoldingSet.h:490
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition: FoldingSet.h:319
FoldingSet - This template class is used to instantiate a specialized implementation of the folding s...
Definition: FoldingSet.h:521
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:58
size_type size() const
Definition: MapVector.h:60
size_t size() const
Definition: SmallVector.h:91
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
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
LLVM Value Representation.
Definition: Value.h:74
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:4969
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
StringRef FormEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:105
StringRef IndexString(unsigned Idx)
Definition: Dwarf.cpp:718
StringRef AtomTypeString(unsigned Atom)
Definition: Dwarf.cpp:622
StringRef TagString(unsigned Tag)
Definition: Dwarf.cpp:21
unsigned getTag(StringRef TagString)
Definition: Dwarf.cpp:32
#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
const uint64_t Version
Definition: InstrProf.h:1042
const uint64_t Magic
Definition: InstrProf.h:1005
uint32_t getDebugNamesBucketCount(MutableArrayRef< uint32_t > hashes, uint32_t &uniqueHashCount)
Definition: Dwarf.h:619
@ DW_FLAG_type_implementation
Definition: Dwarf.h:608
@ DW_hash_function_djb
Definition: Dwarf.h:613
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:228
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:237
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition: DWP.cpp:456
void stable_sort(R &&Range)
Definition: STLExtras.h:1975
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1689
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2386
void emitAppleAccelTableImpl(AsmPrinter *Asm, AccelTableBase &Contents, StringRef Prefix, const MCSymbol *SecBegin, ArrayRef< AppleAccelTableData::Atom > Atoms)
Definition: AccelTable.cpp:637
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1858
void emitDWARF5AccelTable(AsmPrinter *Asm, DWARF5AccelTable &Contents, const DwarfDebug &DD, ArrayRef< std::unique_ptr< DwarfCompileUnit > > CUs)
Definition: AccelTable.cpp:644
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Represents a group of entries with identical name (and hence, hash value).
Definition: AccelTable.h:140
void print(raw_ostream &OS) const
Definition: AccelTable.cpp:782
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
An Atom defines the form of the data in an Apple accelerator table.
Definition: AccelTable.h:237
void print(raw_ostream &OS) const
Definition: AccelTable.cpp:764
Helper class to identify an entry in DWARF5AccelTable based on their DIE offset and UnitID.
Definition: AccelTable.h:260