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/Support/COFF.h"
13 #include "llvm/Support/Endian.h"
17 static bool compareBySuffix(StringRef a, StringRef b) {
18 size_t sizeA = a.size();
19 size_t sizeB = b.size();
20 size_t len = std::min(sizeA, sizeB);
21 for (size_t i = 0; i < len; ++i) {
22 char ca = a[sizeA - i - 1];
23 char cb = b[sizeB - i - 1];
30 void StringTableBuilder::finalize(Kind kind) {
31 SmallVector<StringRef, 8> Strings;
32 Strings.reserve(StringIndexMap.size());
34 for (auto i = StringIndexMap.begin(), e = StringIndexMap.end(); i != e; ++i)
35 Strings.push_back(i->getKey());
37 std::sort(Strings.begin(), Strings.end(), compareBySuffix);
40 // Start the table with a NUL byte.
41 StringTable += '\x00';
42 } else if (kind == WinCOFF) {
43 // Make room to write the table size later.
44 StringTable.append(4, '\x00');
48 for (StringRef s : Strings) {
50 assert(s.size() > COFF::NameSize && "Short string in COFF string table!");
52 if (Previous.endswith(s)) {
53 StringIndexMap[s] = StringTable.size() - 1 - s.size();
57 StringIndexMap[s] = StringTable.size();
59 StringTable += '\x00';
63 if (kind == WinCOFF) {
64 assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
65 uint32_t size = static_cast<uint32_t>(StringTable.size());
66 support::endian::write<uint32_t, support::little, support::unaligned>(
67 StringTable.data(), size);
71 void StringTableBuilder::clear() {
73 StringIndexMap.clear();