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/SmallVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/Support/COFF.h"
14 #include "llvm/Support/Endian.h"
18 static int compareBySuffix(StringMapEntry<size_t> *const *AP,
19 StringMapEntry<size_t> *const *BP) {
20 StringRef a = (*AP)->first();
21 StringRef b = (*BP)->first();
22 size_t sizeA = a.size();
23 size_t sizeB = b.size();
24 size_t len = std::min(sizeA, sizeB);
25 for (size_t i = 0; i < len; ++i) {
26 char ca = a[sizeA - i - 1];
27 char cb = b[sizeB - i - 1];
34 void StringTableBuilder::finalize(Kind kind) {
35 std::vector<StringMapEntry<size_t> *> Strings;
36 Strings.reserve(StringIndexMap.size());
37 for (StringMapEntry<size_t> &P : StringIndexMap)
38 Strings.push_back(&P);
40 array_pod_sort(Strings.begin(), Strings.end(), compareBySuffix);
45 // Start the table with a NUL byte.
46 StringTable += '\x00';
49 // Make room to write the table size later.
50 StringTable.append(4, '\x00');
55 for (StringMapEntry<size_t> *P : Strings) {
56 StringRef s = P->first();
58 assert(s.size() > COFF::NameSize && "Short string in COFF string table!");
60 if (Previous.endswith(s)) {
61 P->second = StringTable.size() - 1 - s.size();
65 P->second = StringTable.size();
67 StringTable += '\x00';
75 // Pad to multiple of 4.
76 while (StringTable.size() % 4)
77 StringTable += '\x00';
80 // Write the table size in the first word.
81 assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
82 uint32_t size = static_cast<uint32_t>(StringTable.size());
83 support::endian::write<uint32_t, support::little, support::unaligned>(
84 StringTable.data(), size);
89 void StringTableBuilder::clear() {
91 StringIndexMap.clear();