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