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