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