• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- StringMap.h - String Hash table map interface ----------*- 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 // This file defines the StringMap class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
16 
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Allocator.h"
19 #include <cstring>
20 
21 namespace llvm {
22   template<typename ValueT>
23   class StringMapConstIterator;
24   template<typename ValueT>
25   class StringMapIterator;
26   template<typename ValueTy>
27   class StringMapEntry;
28 
29 /// StringMapEntryInitializer - This datatype can be partially specialized for
30 /// various datatypes in a stringmap to allow them to be initialized when an
31 /// entry is default constructed for the map.
32 template<typename ValueTy>
33 class StringMapEntryInitializer {
34 public:
35   template <typename InitTy>
Initialize(StringMapEntry<ValueTy> & T,InitTy InitVal)36   static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
37     T.second = InitVal;
38   }
39 };
40 
41 
42 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
43 class StringMapEntryBase {
44   unsigned StrLen;
45 public:
StringMapEntryBase(unsigned Len)46   explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
47 
getKeyLength()48   unsigned getKeyLength() const { return StrLen; }
49 };
50 
51 /// StringMapImpl - This is the base class of StringMap that is shared among
52 /// all of its instantiations.
53 class StringMapImpl {
54 public:
55   /// ItemBucket - The hash table consists of an array of these.  If Item is
56   /// non-null, this is an extant entry, otherwise, it is a hole.
57   struct ItemBucket {
58     /// FullHashValue - This remembers the full hash value of the key for
59     /// easy scanning.
60     unsigned FullHashValue;
61 
62     /// Item - This is a pointer to the actual item object.
63     StringMapEntryBase *Item;
64   };
65 
66 protected:
67   ItemBucket *TheTable;
68   unsigned NumBuckets;
69   unsigned NumItems;
70   unsigned NumTombstones;
71   unsigned ItemSize;
72 protected:
StringMapImpl(unsigned itemSize)73   explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
74     // Initialize the map with zero buckets to allocation.
75     TheTable = 0;
76     NumBuckets = 0;
77     NumItems = 0;
78     NumTombstones = 0;
79   }
80   StringMapImpl(unsigned InitSize, unsigned ItemSize);
81   void RehashTable();
82 
83   /// LookupBucketFor - Look up the bucket that the specified string should end
84   /// up in.  If it already exists as a key in the map, the Item pointer for the
85   /// specified bucket will be non-null.  Otherwise, it will be null.  In either
86   /// case, the FullHashValue field of the bucket will be set to the hash value
87   /// of the string.
88   unsigned LookupBucketFor(StringRef Key);
89 
90   /// FindKey - Look up the bucket that contains the specified key. If it exists
91   /// in the map, return the bucket number of the key.  Otherwise return -1.
92   /// This does not modify the map.
93   int FindKey(StringRef Key) const;
94 
95   /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
96   /// delete it.  This aborts if the value isn't in the table.
97   void RemoveKey(StringMapEntryBase *V);
98 
99   /// RemoveKey - Remove the StringMapEntry for the specified key from the
100   /// table, returning it.  If the key is not in the table, this returns null.
101   StringMapEntryBase *RemoveKey(StringRef Key);
102 private:
103   void init(unsigned Size);
104 public:
getTombstoneVal()105   static StringMapEntryBase *getTombstoneVal() {
106     return (StringMapEntryBase*)-1;
107   }
108 
getNumBuckets()109   unsigned getNumBuckets() const { return NumBuckets; }
getNumItems()110   unsigned getNumItems() const { return NumItems; }
111 
empty()112   bool empty() const { return NumItems == 0; }
size()113   unsigned size() const { return NumItems; }
114 };
115 
116 /// StringMapEntry - This is used to represent one value that is inserted into
117 /// a StringMap.  It contains the Value itself and the key: the string length
118 /// and data.
119 template<typename ValueTy>
120 class StringMapEntry : public StringMapEntryBase {
121 public:
122   ValueTy second;
123 
StringMapEntry(unsigned strLen)124   explicit StringMapEntry(unsigned strLen)
125     : StringMapEntryBase(strLen), second() {}
StringMapEntry(unsigned strLen,const ValueTy & V)126   StringMapEntry(unsigned strLen, const ValueTy &V)
127     : StringMapEntryBase(strLen), second(V) {}
128 
getKey()129   StringRef getKey() const {
130     return StringRef(getKeyData(), getKeyLength());
131   }
132 
getValue()133   const ValueTy &getValue() const { return second; }
getValue()134   ValueTy &getValue() { return second; }
135 
setValue(const ValueTy & V)136   void setValue(const ValueTy &V) { second = V; }
137 
138   /// getKeyData - Return the start of the string data that is the key for this
139   /// value.  The string data is always stored immediately after the
140   /// StringMapEntry object.
getKeyData()141   const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
142 
first()143   StringRef first() const { return StringRef(getKeyData(), getKeyLength()); }
144 
145   /// Create - Create a StringMapEntry for the specified key and default
146   /// construct the value.
147   template<typename AllocatorTy, typename InitType>
Create(const char * KeyStart,const char * KeyEnd,AllocatorTy & Allocator,InitType InitVal)148   static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
149                                 AllocatorTy &Allocator,
150                                 InitType InitVal) {
151     unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
152 
153     // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
154     // in.  Allocate a new item with space for the string at the end and a null
155     // terminator.
156 
157     unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
158       KeyLength+1;
159     unsigned Alignment = alignOf<StringMapEntry>();
160 
161     StringMapEntry *NewItem =
162       static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
163 
164     // Default construct the value.
165     new (NewItem) StringMapEntry(KeyLength);
166 
167     // Copy the string information.
168     char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
169     memcpy(StrBuffer, KeyStart, KeyLength);
170     StrBuffer[KeyLength] = 0;  // Null terminate for convenience of clients.
171 
172     // Initialize the value if the client wants to.
173     StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
174     return NewItem;
175   }
176 
177   template<typename AllocatorTy>
Create(const char * KeyStart,const char * KeyEnd,AllocatorTy & Allocator)178   static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
179                                 AllocatorTy &Allocator) {
180     return Create(KeyStart, KeyEnd, Allocator, 0);
181   }
182 
183 
184   /// Create - Create a StringMapEntry with normal malloc/free.
185   template<typename InitType>
Create(const char * KeyStart,const char * KeyEnd,InitType InitVal)186   static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
187                                 InitType InitVal) {
188     MallocAllocator A;
189     return Create(KeyStart, KeyEnd, A, InitVal);
190   }
191 
Create(const char * KeyStart,const char * KeyEnd)192   static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
193     return Create(KeyStart, KeyEnd, ValueTy());
194   }
195 
196   /// GetStringMapEntryFromValue - Given a value that is known to be embedded
197   /// into a StringMapEntry, return the StringMapEntry itself.
GetStringMapEntryFromValue(ValueTy & V)198   static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
199     StringMapEntry *EPtr = 0;
200     char *Ptr = reinterpret_cast<char*>(&V) -
201                   (reinterpret_cast<char*>(&EPtr->second) -
202                    reinterpret_cast<char*>(EPtr));
203     return *reinterpret_cast<StringMapEntry*>(Ptr);
204   }
GetStringMapEntryFromValue(const ValueTy & V)205   static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
206     return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
207   }
208 
209   /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
210   /// into a StringMapEntry, return the StringMapEntry itself.
GetStringMapEntryFromKeyData(const char * KeyData)211   static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
212     char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
213     return *reinterpret_cast<StringMapEntry*>(Ptr);
214   }
215 
216 
217   /// Destroy - Destroy this StringMapEntry, releasing memory back to the
218   /// specified allocator.
219   template<typename AllocatorTy>
Destroy(AllocatorTy & Allocator)220   void Destroy(AllocatorTy &Allocator) {
221     // Free memory referenced by the item.
222     this->~StringMapEntry();
223     Allocator.Deallocate(this);
224   }
225 
226   /// Destroy this object, releasing memory back to the malloc allocator.
Destroy()227   void Destroy() {
228     MallocAllocator A;
229     Destroy(A);
230   }
231 };
232 
233 
234 /// StringMap - This is an unconventional map that is specialized for handling
235 /// keys that are "strings", which are basically ranges of bytes. This does some
236 /// funky memory allocation and hashing things to make it extremely efficient,
237 /// storing the string data *after* the value in the map.
238 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
239 class StringMap : public StringMapImpl {
240   AllocatorTy Allocator;
241   typedef StringMapEntry<ValueTy> MapEntryTy;
242 public:
StringMap()243   StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
StringMap(unsigned InitialSize)244   explicit StringMap(unsigned InitialSize)
245     : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
246 
StringMap(AllocatorTy A)247   explicit StringMap(AllocatorTy A)
248     : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
249 
StringMap(const StringMap & RHS)250   explicit StringMap(const StringMap &RHS)
251     : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
252     assert(RHS.empty() &&
253            "Copy ctor from non-empty stringmap not implemented yet!");
254     (void)RHS;
255   }
256   void operator=(const StringMap &RHS) {
257     assert(RHS.empty() &&
258            "assignment from non-empty stringmap not implemented yet!");
259     (void)RHS;
260     clear();
261   }
262 
263   typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
264   typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
getAllocator()265   AllocatorRefTy getAllocator() { return Allocator; }
getAllocator()266   AllocatorCRefTy getAllocator() const { return Allocator; }
267 
268   typedef const char* key_type;
269   typedef ValueTy mapped_type;
270   typedef StringMapEntry<ValueTy> value_type;
271   typedef size_t size_type;
272 
273   typedef StringMapConstIterator<ValueTy> const_iterator;
274   typedef StringMapIterator<ValueTy> iterator;
275 
begin()276   iterator begin() {
277     return iterator(TheTable, NumBuckets == 0);
278   }
end()279   iterator end() {
280     return iterator(TheTable+NumBuckets, true);
281   }
begin()282   const_iterator begin() const {
283     return const_iterator(TheTable, NumBuckets == 0);
284   }
end()285   const_iterator end() const {
286     return const_iterator(TheTable+NumBuckets, true);
287   }
288 
find(StringRef Key)289   iterator find(StringRef Key) {
290     int Bucket = FindKey(Key);
291     if (Bucket == -1) return end();
292     return iterator(TheTable+Bucket);
293   }
294 
find(StringRef Key)295   const_iterator find(StringRef Key) const {
296     int Bucket = FindKey(Key);
297     if (Bucket == -1) return end();
298     return const_iterator(TheTable+Bucket);
299   }
300 
301    /// lookup - Return the entry for the specified key, or a default
302   /// constructed value if no such entry exists.
lookup(StringRef Key)303   ValueTy lookup(StringRef Key) const {
304     const_iterator it = find(Key);
305     if (it != end())
306       return it->second;
307     return ValueTy();
308   }
309 
310   ValueTy &operator[](StringRef Key) {
311     return GetOrCreateValue(Key).getValue();
312   }
313 
count(StringRef Key)314   size_type count(StringRef Key) const {
315     return find(Key) == end() ? 0 : 1;
316   }
317 
318   /// insert - Insert the specified key/value pair into the map.  If the key
319   /// already exists in the map, return false and ignore the request, otherwise
320   /// insert it and return true.
insert(MapEntryTy * KeyValue)321   bool insert(MapEntryTy *KeyValue) {
322     unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
323     ItemBucket &Bucket = TheTable[BucketNo];
324     if (Bucket.Item && Bucket.Item != getTombstoneVal())
325       return false;  // Already exists in map.
326 
327     if (Bucket.Item == getTombstoneVal())
328       --NumTombstones;
329     Bucket.Item = KeyValue;
330     ++NumItems;
331     assert(NumItems + NumTombstones <= NumBuckets);
332 
333     RehashTable();
334     return true;
335   }
336 
337   // clear - Empties out the StringMap
clear()338   void clear() {
339     if (empty()) return;
340 
341     // Zap all values, resetting the keys back to non-present (not tombstone),
342     // which is safe because we're removing all elements.
343     for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
344       if (I->Item && I->Item != getTombstoneVal()) {
345         static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
346         I->Item = 0;
347       }
348     }
349 
350     NumItems = 0;
351     NumTombstones = 0;
352   }
353 
354   /// GetOrCreateValue - Look up the specified key in the table.  If a value
355   /// exists, return it.  Otherwise, default construct a value, insert it, and
356   /// return.
357   template <typename InitTy>
GetOrCreateValue(StringRef Key,InitTy Val)358   MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
359     unsigned BucketNo = LookupBucketFor(Key);
360     ItemBucket &Bucket = TheTable[BucketNo];
361     if (Bucket.Item && Bucket.Item != getTombstoneVal())
362       return *static_cast<MapEntryTy*>(Bucket.Item);
363 
364     MapEntryTy *NewItem =
365       MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
366 
367     if (Bucket.Item == getTombstoneVal())
368       --NumTombstones;
369     ++NumItems;
370     assert(NumItems + NumTombstones <= NumBuckets);
371 
372     // Fill in the bucket for the hash table.  The FullHashValue was already
373     // filled in by LookupBucketFor.
374     Bucket.Item = NewItem;
375 
376     RehashTable();
377     return *NewItem;
378   }
379 
GetOrCreateValue(StringRef Key)380   MapEntryTy &GetOrCreateValue(StringRef Key) {
381     return GetOrCreateValue(Key, ValueTy());
382   }
383 
384   /// remove - Remove the specified key/value pair from the map, but do not
385   /// erase it.  This aborts if the key is not in the map.
remove(MapEntryTy * KeyValue)386   void remove(MapEntryTy *KeyValue) {
387     RemoveKey(KeyValue);
388   }
389 
erase(iterator I)390   void erase(iterator I) {
391     MapEntryTy &V = *I;
392     remove(&V);
393     V.Destroy(Allocator);
394   }
395 
erase(StringRef Key)396   bool erase(StringRef Key) {
397     iterator I = find(Key);
398     if (I == end()) return false;
399     erase(I);
400     return true;
401   }
402 
~StringMap()403   ~StringMap() {
404     clear();
405     free(TheTable);
406   }
407 };
408 
409 
410 template<typename ValueTy>
411 class StringMapConstIterator {
412 protected:
413   StringMapImpl::ItemBucket *Ptr;
414 public:
415   typedef StringMapEntry<ValueTy> value_type;
416 
417   explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
418                                   bool NoAdvance = false)
Ptr(Bucket)419   : Ptr(Bucket) {
420     if (!NoAdvance) AdvancePastEmptyBuckets();
421   }
422 
423   const value_type &operator*() const {
424     return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
425   }
426   const value_type *operator->() const {
427     return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
428   }
429 
430   bool operator==(const StringMapConstIterator &RHS) const {
431     return Ptr == RHS.Ptr;
432   }
433   bool operator!=(const StringMapConstIterator &RHS) const {
434     return Ptr != RHS.Ptr;
435   }
436 
437   inline StringMapConstIterator& operator++() {          // Preincrement
438     ++Ptr;
439     AdvancePastEmptyBuckets();
440     return *this;
441   }
442   StringMapConstIterator operator++(int) {        // Postincrement
443     StringMapConstIterator tmp = *this; ++*this; return tmp;
444   }
445 
446 private:
AdvancePastEmptyBuckets()447   void AdvancePastEmptyBuckets() {
448     while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
449       ++Ptr;
450   }
451 };
452 
453 template<typename ValueTy>
454 class StringMapIterator : public StringMapConstIterator<ValueTy> {
455 public:
456   explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
457                              bool NoAdvance = false)
458     : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
459   }
460   StringMapEntry<ValueTy> &operator*() const {
461     return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
462   }
463   StringMapEntry<ValueTy> *operator->() const {
464     return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
465   }
466 };
467 
468 }
469 
470 #endif
471