Home | History | Annotate | Download | only in MC
      1 //===-- StringTableBuilder.h - String table building utility ------*- C++ -*-=//
      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 #ifndef LLVM_MC_STRINGTABLEBUILDER_H
     11 #define LLVM_MC_STRINGTABLEBUILDER_H
     12 
     13 #include "llvm/ADT/SmallString.h"
     14 #include "llvm/ADT/DenseMap.h"
     15 #include <cassert>
     16 
     17 namespace llvm {
     18 
     19 /// \brief Utility for building string tables with deduplicated suffixes.
     20 class StringTableBuilder {
     21 public:
     22   enum Kind { ELF, WinCOFF, MachO, RAW };
     23 
     24 private:
     25   SmallString<256> StringTable;
     26   DenseMap<CachedHash<StringRef>, size_t> StringIndexMap;
     27   size_t Size = 0;
     28   Kind K;
     29   unsigned Alignment;
     30 
     31   void finalizeStringTable(bool Optimize);
     32 
     33 public:
     34   StringTableBuilder(Kind K, unsigned Alignment = 1);
     35 
     36   /// \brief Add a string to the builder. Returns the position of S in the
     37   /// table. The position will be changed if finalize is used.
     38   /// Can only be used before the table is finalized.
     39   size_t add(StringRef S);
     40 
     41   /// \brief Analyze the strings and build the final table. No more strings can
     42   /// be added after this point.
     43   void finalize();
     44 
     45   /// Finalize the string table without reording it. In this mode, offsets
     46   /// returned by add will still be valid.
     47   void finalizeInOrder();
     48 
     49   /// \brief Retrieve the string table data. Can only be used after the table
     50   /// is finalized.
     51   StringRef data() const {
     52     assert(isFinalized());
     53     return StringTable;
     54   }
     55 
     56   /// \brief Get the offest of a string in the string table. Can only be used
     57   /// after the table is finalized.
     58   size_t getOffset(StringRef S) const;
     59 
     60   const DenseMap<CachedHash<StringRef>, size_t> &getMap() const {
     61     return StringIndexMap;
     62   }
     63 
     64   size_t getSize() const { return Size; }
     65   void clear();
     66 
     67 private:
     68   bool isFinalized() const {
     69     return !StringTable.empty();
     70   }
     71 };
     72 
     73 } // end llvm namespace
     74 
     75 #endif
     76