WinCOFFObjectWriter: optimize the string table for common suffices
[oota-llvm.git] / lib / MC / StringTableBuilder.cpp
1 //===-- StringTableBuilder.cpp - String table building utility ------------===//
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 "llvm/MC/StringTableBuilder.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/Support/COFF.h"
13 #include "llvm/Support/Endian.h"
14
15 using namespace llvm;
16
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];
24     if (ca != cb)
25       return ca > cb;
26   }
27   return sizeA > sizeB;
28 }
29
30 void StringTableBuilder::finalize(Kind kind) {
31   SmallVector<StringRef, 8> Strings;
32   Strings.reserve(StringIndexMap.size());
33
34   for (auto i = StringIndexMap.begin(), e = StringIndexMap.end(); i != e; ++i)
35     Strings.push_back(i->getKey());
36
37   std::sort(Strings.begin(), Strings.end(), compareBySuffix);
38
39   if (kind == ELF) {
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');
45   }
46
47   StringRef Previous;
48   for (StringRef s : Strings) {
49     if (kind == WinCOFF)
50       assert(s.size() > COFF::NameSize && "Short string in COFF string table!");
51
52     if (Previous.endswith(s)) {
53       StringIndexMap[s] = StringTable.size() - 1 - s.size();
54       continue;
55     }
56
57     StringIndexMap[s] = StringTable.size();
58     StringTable += s;
59     StringTable += '\x00';
60     Previous = s;
61   }
62
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);
68   }
69 }
70
71 void StringTableBuilder::clear() {
72   StringTable.clear();
73   StringIndexMap.clear();
74 }