1//===- StringTableBuilder.h - String table building utility -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_MC_STRINGTABLEBUILDER_H
10#define LLVM_MC_STRINGTABLEBUILDER_H
11
12#include "llvm/ADT/CachedHashString.h"
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/Alignment.h"
16#include <cstddef>
17#include <cstdint>
18
19namespace llvm {
20
21class raw_ostream;
22
23/// Utility for building string tables with deduplicated suffixes.
24class StringTableBuilder {
25public:
26  enum Kind {
27    ELF,
28    WinCOFF,
29    MachO,
30    MachO64,
31    MachOLinked,
32    MachO64Linked,
33    RAW,
34    DWARF,
35    XCOFF,
36    DXContainer
37  };
38
39private:
40  DenseMap<CachedHashStringRef, size_t> StringIndexMap;
41  size_t Size = 0;
42  Kind K;
43  Align Alignment;
44  bool Finalized = false;
45
46  void finalizeStringTable(bool Optimize);
47  void initSize();
48
49public:
50  StringTableBuilder(Kind K, Align Alignment = Align(1));
51  ~StringTableBuilder();
52
53  /// Add a string to the builder. Returns the position of S in the
54  /// table. The position will be changed if finalize is used.
55  /// Can only be used before the table is finalized.
56  size_t add(CachedHashStringRef S);
57  size_t add(StringRef S) { return add(CachedHashStringRef(S)); }
58
59  /// Analyze the strings and build the final table. No more strings can
60  /// be added after this point.
61  void finalize();
62
63  /// Finalize the string table without reording it. In this mode, offsets
64  /// returned by add will still be valid.
65  void finalizeInOrder();
66
67  /// Get the offest of a string in the string table. Can only be used
68  /// after the table is finalized.
69  size_t getOffset(CachedHashStringRef S) const;
70  size_t getOffset(StringRef S) const {
71    return getOffset(CachedHashStringRef(S));
72  }
73
74  /// Check if a string is contained in the string table. Since this class
75  /// doesn't store the string values, this function can be used to check if
76  /// storage needs to be done prior to adding the string.
77  bool contains(StringRef S) const {
78    return contains(CachedHashStringRef(S));
79  }
80  bool contains(CachedHashStringRef S) const {
81    return StringIndexMap.count(S);
82  }
83
84  size_t getSize() const { return Size; }
85  void clear();
86
87  void write(raw_ostream &OS) const;
88  void write(uint8_t *Buf) const;
89
90  bool isFinalized() const { return Finalized; }
91};
92
93} // end namespace llvm
94
95#endif // LLVM_MC_STRINGTABLEBUILDER_H
96