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