1 //===-- StringTableBuilder.cpp - String table building utility ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/StringTableBuilder.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Support/COFF.h"
13 #include "llvm/Support/Endian.h"
19 StringTableBuilder::StringTableBuilder(Kind K) : K(K) {}
21 typedef std::pair<StringRef, size_t> StringPair;
23 // Returns the character at Pos from end of a string.
24 static int charTailAt(StringPair *P, size_t Pos) {
25 StringRef S = P->first;
28 return (unsigned char)S[S.size() - Pos - 1];
31 // Three-way radix quicksort. This is much faster than std::sort with strcmp
32 // because it does not compare characters that we already know the same.
33 static void qsort(StringPair **Begin, StringPair **End, int Pos) {
38 // Partition items. Items in [Begin, P) are greater than the pivot,
39 // [P, Q) are the same as the pivot, and [Q, End) are less than the pivot.
40 int Pivot = charTailAt(*Begin, Pos);
41 StringPair **P = Begin;
43 for (StringPair **R = Begin + 1; R < Q;) {
44 int C = charTailAt(*R, Pos);
46 std::swap(*P++, *R++);
56 // qsort(P, Q, Pos + 1), but with tail call optimization.
64 void StringTableBuilder::finalize() {
65 std::vector<std::pair<StringRef, size_t> *> Strings;
66 Strings.reserve(StringIndexMap.size());
67 for (std::pair<StringRef, size_t> &P : StringIndexMap)
68 Strings.push_back(&P);
71 qsort(&Strings[0], &Strings[0] + Strings.size(), 0);
78 // Start the table with a NUL byte.
79 StringTable += '\x00';
82 // Make room to write the table size later.
83 StringTable.append(4, '\x00');
88 for (std::pair<StringRef, size_t> *P : Strings) {
89 StringRef S = P->first;
91 assert(S.size() > COFF::NameSize && "Short string in COFF string table!");
93 if (Previous.endswith(S)) {
94 P->second = StringTable.size() - S.size() - (K != RAW);
98 P->second = StringTable.size();
101 StringTable += '\x00';
110 // Pad to multiple of 4.
111 while (StringTable.size() % 4)
112 StringTable += '\x00';
115 // Write the table size in the first word.
116 assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
117 uint32_t Size = static_cast<uint32_t>(StringTable.size());
118 support::endian::write<uint32_t, support::little, support::unaligned>(
119 StringTable.data(), Size);
123 Size = StringTable.size();
126 void StringTableBuilder::clear() {
128 StringIndexMap.clear();
131 size_t StringTableBuilder::getOffset(StringRef S) const {
132 assert(isFinalized());
133 auto I = StringIndexMap.find(S);
134 assert(I != StringIndexMap.end() && "String is not in table!");
138 size_t StringTableBuilder::add(StringRef S) {
139 assert(!isFinalized());
140 auto P = StringIndexMap.insert(std::make_pair(S, Size));
142 Size += S.size() + (K != RAW);
143 return P.first->second;