xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfStringPool.cpp (revision 9d50e82fb2324621dcdd43f68e08ae2d775378c3)
1 //===-- llvm/CodeGen/DwarfStringPool.cpp - Dwarf Debug Framework ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "DwarfStringPool.h"
11 #include "llvm/CodeGen/AsmPrinter.h"
12 #include "llvm/MC/MCStreamer.h"
13 
14 using namespace llvm;
15 
16 DwarfStringPool::EntryRef DwarfStringPool::getEntry(AsmPrinter &Asm,
17                                                     StringRef Str) {
18   auto I = Pool.insert(std::make_pair(Str, EntryTy()));
19   if (I.second) {
20     auto &Entry = I.first->second;
21     Entry.Index = Pool.size() - 1;
22     Entry.Offset = NumBytes;
23     Entry.Symbol = Asm.createTempSymbol(Prefix);
24 
25     NumBytes += Str.size() + 1;
26     assert(NumBytes > Entry.Offset && "Unexpected overflow");
27   }
28   return EntryRef(*I.first);
29 }
30 
31 void DwarfStringPool::emit(AsmPrinter &Asm, MCSection *StrSection,
32                            MCSection *OffsetSection) {
33   if (Pool.empty())
34     return;
35 
36   // Start the dwarf str section.
37   Asm.OutStreamer->SwitchSection(StrSection);
38 
39   // Get all of the string pool entries and put them in an array by their ID so
40   // we can sort them.
41   SmallVector<const StringMapEntry<EntryTy> *, 64> Entries(Pool.size());
42 
43   for (const auto &E : Pool)
44     Entries[E.getValue().Index] = &E;
45 
46   for (const auto &Entry : Entries) {
47     // Emit a label for reference from debug information entries.
48     Asm.OutStreamer->EmitLabel(Entry->getValue().Symbol);
49 
50     // Emit the string itself with a terminating null byte.
51     Asm.OutStreamer->AddComment("string offset=" +
52                                 Twine(Entry->getValue().Offset));
53     Asm.OutStreamer->EmitBytes(
54         StringRef(Entry->getKeyData(), Entry->getKeyLength() + 1));
55   }
56 
57   // If we've got an offset section go ahead and emit that now as well.
58   if (OffsetSection) {
59     Asm.OutStreamer->SwitchSection(OffsetSection);
60     unsigned size = 4; // FIXME: DWARF64 is 8.
61     for (const auto &Entry : Entries)
62       Asm.OutStreamer->EmitIntValue(Entry->getValue().Offset, size);
63   }
64 }
65