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/MC/MCStreamer.h"
12
13using namespace llvm;
14
15MCSymbol *DwarfStringPool::getSectionSymbol() { return SectionSymbol; }
16
17static std::pair<MCSymbol *, unsigned> &
18getEntry(AsmPrinter &Asm,
19         StringMap<std::pair<MCSymbol *, unsigned>, BumpPtrAllocator &> &Pool,
20         StringRef Prefix, StringRef Str) {
21  std::pair<MCSymbol *, unsigned> &Entry =
22      Pool.GetOrCreateValue(Str).getValue();
23  if (!Entry.first) {
24    Entry.second = Pool.size() - 1;
25    Entry.first = Asm.GetTempSymbol(Prefix, Entry.second);
26  }
27  return Entry;
28}
29
30MCSymbol *DwarfStringPool::getSymbol(AsmPrinter &Asm, StringRef Str) {
31  return getEntry(Asm, Pool, Prefix, Str).first;
32}
33
34unsigned DwarfStringPool::getIndex(AsmPrinter &Asm, StringRef Str) {
35  return getEntry(Asm, Pool, Prefix, Str).second;
36}
37
38void DwarfStringPool::emit(AsmPrinter &Asm, const MCSection *StrSection,
39                           const MCSection *OffsetSection,
40                           const MCSymbol *StrSecSym) {
41  if (Pool.empty())
42    return;
43
44  // Start the dwarf str section.
45  Asm.OutStreamer.SwitchSection(StrSection);
46
47  // Get all of the string pool entries and put them in an array by their ID so
48  // we can sort them.
49  SmallVector<const StringMapEntry<std::pair<MCSymbol *, unsigned>> *, 64>
50  Entries(Pool.size());
51
52  for (const auto &E : Pool)
53    Entries[E.getValue().second] = &E;
54
55  for (const auto &Entry : Entries) {
56    // Emit a label for reference from debug information entries.
57    Asm.OutStreamer.EmitLabel(Entry->getValue().first);
58
59    // Emit the string itself with a terminating null byte.
60    Asm.OutStreamer.EmitBytes(
61        StringRef(Entry->getKeyData(), Entry->getKeyLength() + 1));
62  }
63
64  // If we've got an offset section go ahead and emit that now as well.
65  if (OffsetSection) {
66    Asm.OutStreamer.SwitchSection(OffsetSection);
67    unsigned offset = 0;
68    unsigned size = 4; // FIXME: DWARF64 is 8.
69    for (const auto &Entry : Entries) {
70      Asm.OutStreamer.EmitIntValue(offset, size);
71      offset += Entry->getKeyLength() + 1;
72    }
73  }
74}
75