[Allocator] Pass the size to the deallocation function. This, on some
[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     unsigned AllocSize =
202         static_cast<unsigned>(sizeof(StringMapEntry)) + getKeyLength() + 1;
203     this->~StringMapEntry();
204     Allocator.Deallocate(static_cast<void *>(this), AllocSize);
205   }
206
207   /// Destroy this object, releasing memory back to the malloc allocator.
208   void Destroy() {
209     MallocAllocator A;
210     Destroy(A);
211   }
212 };
213
214
215 /// StringMap - This is an unconventional map that is specialized for handling
216 /// keys that are "strings", which are basically ranges of bytes. This does some
217 /// funky memory allocation and hashing things to make it extremely efficient,
218 /// storing the string data *after* the value in the map.
219 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
220 class StringMap : public StringMapImpl {
221   AllocatorTy Allocator;
222 public:
223   typedef StringMapEntry<ValueTy> MapEntryTy;
224   
225   StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
226   explicit StringMap(unsigned InitialSize)
227     : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
228
229   explicit StringMap(AllocatorTy A)
230     : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
231
232   StringMap(unsigned InitialSize, AllocatorTy A)
233     : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))),
234       Allocator(A) {}
235
236   StringMap(const StringMap &RHS)
237     : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
238     assert(RHS.empty() &&
239            "Copy ctor from non-empty stringmap not implemented yet!");
240     (void)RHS;
241   }
242   void operator=(const StringMap &RHS) {
243     assert(RHS.empty() &&
244            "assignment from non-empty stringmap not implemented yet!");
245     (void)RHS;
246     clear();
247   }
248
249   typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
250   typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
251   AllocatorRefTy getAllocator() { return Allocator; }
252   AllocatorCRefTy getAllocator() const { return Allocator; }
253
254   typedef const char* key_type;
255   typedef ValueTy mapped_type;
256   typedef StringMapEntry<ValueTy> value_type;
257   typedef size_t size_type;
258
259   typedef StringMapConstIterator<ValueTy> const_iterator;
260   typedef StringMapIterator<ValueTy> iterator;
261
262   iterator begin() {
263     return iterator(TheTable, NumBuckets == 0);
264   }
265   iterator end() {
266     return iterator(TheTable+NumBuckets, true);
267   }
268   const_iterator begin() const {
269     return const_iterator(TheTable, NumBuckets == 0);
270   }
271   const_iterator end() const {
272     return const_iterator(TheTable+NumBuckets, true);
273   }
274
275   iterator find(StringRef Key) {
276     int Bucket = FindKey(Key);
277     if (Bucket == -1) return end();
278     return iterator(TheTable+Bucket, true);
279   }
280
281   const_iterator find(StringRef Key) const {
282     int Bucket = FindKey(Key);
283     if (Bucket == -1) return end();
284     return const_iterator(TheTable+Bucket, true);
285   }
286
287   /// lookup - Return the entry for the specified key, or a default
288   /// constructed value if no such entry exists.
289   ValueTy lookup(StringRef Key) const {
290     const_iterator it = find(Key);
291     if (it != end())
292       return it->second;
293     return ValueTy();
294   }
295
296   ValueTy &operator[](StringRef Key) {
297     return GetOrCreateValue(Key).getValue();
298   }
299
300   /// count - Return 1 if the element is in the map, 0 otherwise.
301   size_type count(StringRef Key) const {
302     return find(Key) == end() ? 0 : 1;
303   }
304
305   /// insert - Insert the specified key/value pair into the map.  If the key
306   /// already exists in the map, return false and ignore the request, otherwise
307   /// insert it and return true.
308   bool insert(MapEntryTy *KeyValue) {
309     unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
310     StringMapEntryBase *&Bucket = TheTable[BucketNo];
311     if (Bucket && Bucket != getTombstoneVal())
312       return false;  // Already exists in map.
313
314     if (Bucket == getTombstoneVal())
315       --NumTombstones;
316     Bucket = KeyValue;
317     ++NumItems;
318     assert(NumItems + NumTombstones <= NumBuckets);
319
320     RehashTable();
321     return true;
322   }
323
324   // clear - Empties out the StringMap
325   void clear() {
326     if (empty()) return;
327
328     // Zap all values, resetting the keys back to non-present (not tombstone),
329     // which is safe because we're removing all elements.
330     for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
331       StringMapEntryBase *&Bucket = TheTable[I];
332       if (Bucket && Bucket != getTombstoneVal()) {
333         static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
334       }
335       Bucket = nullptr;
336     }
337
338     NumItems = 0;
339     NumTombstones = 0;
340   }
341
342   /// GetOrCreateValue - Look up the specified key in the table.  If a value
343   /// exists, return it.  Otherwise, default construct a value, insert it, and
344   /// return.
345   template <typename InitTy>
346   MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
347     unsigned BucketNo = LookupBucketFor(Key);
348     StringMapEntryBase *&Bucket = TheTable[BucketNo];
349     if (Bucket && Bucket != getTombstoneVal())
350       return *static_cast<MapEntryTy*>(Bucket);
351
352     MapEntryTy *NewItem =
353       MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
354
355     if (Bucket == getTombstoneVal())
356       --NumTombstones;
357     ++NumItems;
358     assert(NumItems + NumTombstones <= NumBuckets);
359
360     // Fill in the bucket for the hash table.  The FullHashValue was already
361     // filled in by LookupBucketFor.
362     Bucket = NewItem;
363
364     RehashTable();
365     return *NewItem;
366   }
367
368   MapEntryTy &GetOrCreateValue(StringRef Key) {
369     return GetOrCreateValue(Key, ValueTy());
370   }
371
372   /// remove - Remove the specified key/value pair from the map, but do not
373   /// erase it.  This aborts if the key is not in the map.
374   void remove(MapEntryTy *KeyValue) {
375     RemoveKey(KeyValue);
376   }
377
378   void erase(iterator I) {
379     MapEntryTy &V = *I;
380     remove(&V);
381     V.Destroy(Allocator);
382   }
383
384   bool erase(StringRef Key) {
385     iterator I = find(Key);
386     if (I == end()) return false;
387     erase(I);
388     return true;
389   }
390
391   ~StringMap() {
392     // Delete all the elements in the map, but don't reset the elements
393     // to default values.  This is a copy of clear(), but avoids unnecessary
394     // work not required in the destructor.
395     if (!empty()) {
396       for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
397         StringMapEntryBase *Bucket = TheTable[I];
398         if (Bucket && Bucket != getTombstoneVal()) {
399           static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
400         }
401       }
402     }
403     free(TheTable);
404   }
405 };
406
407
408 template<typename ValueTy>
409 class StringMapConstIterator {
410 protected:
411   StringMapEntryBase **Ptr;
412 public:
413   typedef StringMapEntry<ValueTy> value_type;
414
415   StringMapConstIterator() : Ptr(nullptr) { }
416
417   explicit StringMapConstIterator(StringMapEntryBase **Bucket,
418                                   bool NoAdvance = false)
419   : Ptr(Bucket) {
420     if (!NoAdvance) AdvancePastEmptyBuckets();
421   }
422
423   const value_type &operator*() const {
424     return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
425   }
426   const value_type *operator->() const {
427     return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
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:
447   void AdvancePastEmptyBuckets() {
448     while (*Ptr == nullptr || *Ptr == StringMapImpl::getTombstoneVal())
449       ++Ptr;
450   }
451 };
452
453 template<typename ValueTy>
454 class StringMapIterator : public StringMapConstIterator<ValueTy> {
455 public:
456   StringMapIterator() {}
457   explicit StringMapIterator(StringMapEntryBase **Bucket,
458                              bool NoAdvance = false)
459     : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
460   }
461   StringMapEntry<ValueTy> &operator*() const {
462     return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
463   }
464   StringMapEntry<ValueTy> *operator->() const {
465     return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
466   }
467 };
468
469 }
470
471 #endif