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