Avoid repeatedly reallocating the FoldingSetNodeID when searching
[oota-llvm.git] / lib / Support / FoldingSet.cpp
1 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- 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 implements a hash set that can be used to remove duplication of
11 // nodes in a graph.  This code was originally created by Chris Lattner for use
12 // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code
13 // set. 
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/Support/MathExtras.h"
19 #include <cassert>
20 #include <cstring>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // FoldingSetNodeID Implementation
25
26 /// Add* - Add various data types to Bit data.
27 ///
28 void FoldingSetNodeID::AddPointer(const void *Ptr) {
29   // Note: this adds pointers to the hash using sizes and endianness that
30   // depend on the host.  It doesn't matter however, because hashing on
31   // pointer values in inherently unstable.  Nothing  should depend on the 
32   // ordering of nodes in the folding set.
33   intptr_t PtrI = (intptr_t)Ptr;
34   Bits.push_back(unsigned(PtrI));
35   if (sizeof(intptr_t) > sizeof(unsigned))
36     Bits.push_back(unsigned(uint64_t(PtrI) >> 32));
37 }
38 void FoldingSetNodeID::AddInteger(signed I) {
39   Bits.push_back(I);
40 }
41 void FoldingSetNodeID::AddInteger(unsigned I) {
42   Bits.push_back(I);
43 }
44 void FoldingSetNodeID::AddInteger(int64_t I) {
45   AddInteger((uint64_t)I);
46 }
47 void FoldingSetNodeID::AddInteger(uint64_t I) {
48   Bits.push_back(unsigned(I));
49   
50   // If the integer is small, encode it just as 32-bits.
51   if ((uint64_t)(int)I != I)
52     Bits.push_back(unsigned(I >> 32));
53 }
54 void FoldingSetNodeID::AddFloat(float F) {
55   Bits.push_back(FloatToBits(F));
56 }
57 void FoldingSetNodeID::AddDouble(double D) {
58  AddInteger(DoubleToBits(D));
59 }
60
61 void FoldingSetNodeID::AddString(const char *String) {
62   unsigned Size = static_cast<unsigned>(strlen(String));
63   Bits.push_back(Size);
64   if (!Size) return;
65
66   unsigned Units = Size / 4;
67   unsigned Pos = 0;
68   const unsigned *Base = (const unsigned *)String;
69   
70   // If the string is aligned do a bulk transfer.
71   if (!((intptr_t)Base & 3)) {
72     Bits.append(Base, Base + Units);
73     Pos = (Units + 1) * 4;
74   } else {
75     // Otherwise do it the hard way.
76     for ( Pos += 4; Pos <= Size; Pos += 4) {
77       unsigned V = ((unsigned char)String[Pos - 4] << 24) |
78                    ((unsigned char)String[Pos - 3] << 16) |
79                    ((unsigned char)String[Pos - 2] << 8) |
80                     (unsigned char)String[Pos - 1];
81       Bits.push_back(V);
82     }
83   }
84   
85   // With the leftover bits.
86   unsigned V = 0;
87   // Pos will have overshot size by 4 - #bytes left over. 
88   switch (Pos - Size) {
89   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
90   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
91   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
92   default: return; // Nothing left.
93   }
94
95   Bits.push_back(V);
96 }
97
98 void FoldingSetNodeID::AddString(const std::string &String) {
99   unsigned Size = static_cast<unsigned>(String.size());
100   Bits.push_back(Size);
101   if (!Size) return;
102
103   unsigned Units = Size / 4;
104   unsigned Pos = 0;
105   const unsigned *Base = (const unsigned *)String.data();
106   
107   // If the string is aligned do a bulk transfer.
108   if (!((intptr_t)Base & 3)) {
109     Bits.append(Base, Base + Units);
110     Pos = (Units + 1) * 4;
111   } else {
112     // Otherwise do it the hard way.
113     for ( Pos += 4; Pos <= Size; Pos += 4) {
114       unsigned V = ((unsigned char)String[Pos - 4] << 24) |
115                    ((unsigned char)String[Pos - 3] << 16) |
116                    ((unsigned char)String[Pos - 2] << 8) |
117                     (unsigned char)String[Pos - 1];
118       Bits.push_back(V);
119     }
120   }
121   
122   // With the leftover bits.
123   unsigned V = 0;
124   // Pos will have overshot size by 4 - #bytes left over. 
125   switch (Pos - Size) {
126   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
127   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
128   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
129   default: return; // Nothing left.
130   }
131
132   Bits.push_back(V);
133 }
134
135 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to 
136 /// lookup the node in the FoldingSetImpl.
137 unsigned FoldingSetNodeID::ComputeHash() const {
138   // This is adapted from SuperFastHash by Paul Hsieh.
139   unsigned Hash = static_cast<unsigned>(Bits.size());
140   for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) {
141     unsigned Data = *BP;
142     Hash         += Data & 0xFFFF;
143     unsigned Tmp  = ((Data >> 16) << 11) ^ Hash;
144     Hash          = (Hash << 16) ^ Tmp;
145     Hash         += Hash >> 11;
146   }
147   
148   // Force "avalanching" of final 127 bits.
149   Hash ^= Hash << 3;
150   Hash += Hash >> 5;
151   Hash ^= Hash << 4;
152   Hash += Hash >> 17;
153   Hash ^= Hash << 25;
154   Hash += Hash >> 6;
155   return Hash;
156 }
157
158 /// operator== - Used to compare two nodes to each other.
159 ///
160 bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS)const{
161   if (Bits.size() != RHS.Bits.size()) return false;
162   return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0;
163 }
164
165
166 //===----------------------------------------------------------------------===//
167 /// Helper functions for FoldingSetImpl.
168
169 /// GetNextPtr - In order to save space, each bucket is a
170 /// singly-linked-list. In order to make deletion more efficient, we make
171 /// the list circular, so we can delete a node without computing its hash.
172 /// The problem with this is that the start of the hash buckets are not
173 /// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null:
174 /// use GetBucketPtr when this happens.
175 static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
176   // The low bit is set if this is the pointer back to the bucket.
177   if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
178     return 0;
179   
180   return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
181 }
182
183
184 /// testing.
185 static void **GetBucketPtr(void *NextInBucketPtr) {
186   intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
187   assert((Ptr & 1) && "Not a bucket pointer");
188   return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
189 }
190
191 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
192 /// the specified ID.
193 static void **GetBucketFor(const FoldingSetNodeID &ID,
194                            void **Buckets, unsigned NumBuckets) {
195   // NumBuckets is always a power of 2.
196   unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1);
197   return Buckets + BucketNum;
198 }
199
200 //===----------------------------------------------------------------------===//
201 // FoldingSetImpl Implementation
202
203 FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) : NumNodes(0) {
204   assert(5 < Log2InitSize && Log2InitSize < 32 &&
205          "Initial hash table size out of range");
206   NumBuckets = 1 << Log2InitSize;
207   Buckets = new void*[NumBuckets+1];
208   memset(Buckets, 0, NumBuckets*sizeof(void*));
209   
210   // Set the very last bucket to be a non-null "pointer".
211   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
212 }
213 FoldingSetImpl::~FoldingSetImpl() {
214   delete [] Buckets;
215 }
216
217 /// GrowHashTable - Double the size of the hash table and rehash everything.
218 ///
219 void FoldingSetImpl::GrowHashTable() {
220   void **OldBuckets = Buckets;
221   unsigned OldNumBuckets = NumBuckets;
222   NumBuckets <<= 1;
223   
224   // Reset the node count to zero: we're going to reinsert everything.
225   NumNodes = 0;
226   
227   // Clear out new buckets.
228   Buckets = new void*[NumBuckets+1];
229   memset(Buckets, 0, NumBuckets*sizeof(void*));
230
231   // Set the very last bucket to be a non-null "pointer".
232   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
233
234   // Walk the old buckets, rehashing nodes into their new place.
235   FoldingSetNodeID ID;
236   for (unsigned i = 0; i != OldNumBuckets; ++i) {
237     void *Probe = OldBuckets[i];
238     if (!Probe) continue;
239     while (Node *NodeInBucket = GetNextPtr(Probe)) {
240       // Figure out the next link, remove NodeInBucket from the old link.
241       Probe = NodeInBucket->getNextInBucket();
242       NodeInBucket->SetNextInBucket(0);
243
244       // Insert the node into the new bucket, after recomputing the hash.
245       GetNodeProfile(ID, NodeInBucket);
246       InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets));
247       ID.clear();
248     }
249   }
250   
251   delete[] OldBuckets;
252 }
253
254 /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
255 /// return it.  If not, return the insertion token that will make insertion
256 /// faster.
257 FoldingSetImpl::Node
258 *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
259                                      void *&InsertPos) {
260   
261   void **Bucket = GetBucketFor(ID, Buckets, NumBuckets);
262   void *Probe = *Bucket;
263   
264   InsertPos = 0;
265   
266   FoldingSetNodeID OtherID;
267   while (Node *NodeInBucket = GetNextPtr(Probe)) {
268     GetNodeProfile(OtherID, NodeInBucket);
269     if (OtherID == ID)
270       return NodeInBucket;
271
272     Probe = NodeInBucket->getNextInBucket();
273     OtherID.clear();
274   }
275   
276   // Didn't find the node, return null with the bucket as the InsertPos.
277   InsertPos = Bucket;
278   return 0;
279 }
280
281 /// InsertNode - Insert the specified node into the folding set, knowing that it
282 /// is not already in the map.  InsertPos must be obtained from 
283 /// FindNodeOrInsertPos.
284 void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) {
285   assert(N->getNextInBucket() == 0);
286   // Do we need to grow the hashtable?
287   if (NumNodes+1 > NumBuckets*2) {
288     GrowHashTable();
289     FoldingSetNodeID ID;
290     GetNodeProfile(ID, N);
291     InsertPos = GetBucketFor(ID, Buckets, NumBuckets);
292   }
293
294   ++NumNodes;
295   
296   /// The insert position is actually a bucket pointer.
297   void **Bucket = static_cast<void**>(InsertPos);
298   
299   void *Next = *Bucket;
300   
301   // If this is the first insertion into this bucket, its next pointer will be
302   // null.  Pretend as if it pointed to itself, setting the low bit to indicate
303   // that it is a pointer to the bucket.
304   if (Next == 0)
305     Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
306
307   // Set the node's next pointer, and make the bucket point to the node.
308   N->SetNextInBucket(Next);
309   *Bucket = N;
310 }
311
312 /// RemoveNode - Remove a node from the folding set, returning true if one was
313 /// removed or false if the node was not in the folding set.
314 bool FoldingSetImpl::RemoveNode(Node *N) {
315   // Because each bucket is a circular list, we don't need to compute N's hash
316   // to remove it.
317   void *Ptr = N->getNextInBucket();
318   if (Ptr == 0) return false;  // Not in folding set.
319
320   --NumNodes;
321   N->SetNextInBucket(0);
322
323   // Remember what N originally pointed to, either a bucket or another node.
324   void *NodeNextPtr = Ptr;
325   
326   // Chase around the list until we find the node (or bucket) which points to N.
327   while (true) {
328     if (Node *NodeInBucket = GetNextPtr(Ptr)) {
329       // Advance pointer.
330       Ptr = NodeInBucket->getNextInBucket();
331       
332       // We found a node that points to N, change it to point to N's next node,
333       // removing N from the list.
334       if (Ptr == N) {
335         NodeInBucket->SetNextInBucket(NodeNextPtr);
336         return true;
337       }
338     } else {
339       void **Bucket = GetBucketPtr(Ptr);
340       Ptr = *Bucket;
341       
342       // If we found that the bucket points to N, update the bucket to point to
343       // whatever is next.
344       if (Ptr == N) {
345         *Bucket = NodeNextPtr;
346         return true;
347       }
348     }
349   }
350 }
351
352 /// GetOrInsertNode - If there is an existing simple Node exactly
353 /// equal to the specified node, return it.  Otherwise, insert 'N' and it
354 /// instead.
355 FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
356   FoldingSetNodeID ID;
357   GetNodeProfile(ID, N);
358   void *IP;
359   if (Node *E = FindNodeOrInsertPos(ID, IP))
360     return E;
361   InsertNode(N, IP);
362   return N;
363 }
364
365 //===----------------------------------------------------------------------===//
366 // FoldingSetIteratorImpl Implementation
367
368 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket) {
369   // Skip to the first non-null non-self-cycle bucket.
370   while (*Bucket != reinterpret_cast<void*>(-1) &&
371          (*Bucket == 0 || GetNextPtr(*Bucket) == 0))
372     ++Bucket;
373   
374   NodePtr = static_cast<FoldingSetNode*>(*Bucket);
375 }
376
377 void FoldingSetIteratorImpl::advance() {
378   // If there is another link within this bucket, go to it.
379   void *Probe = NodePtr->getNextInBucket();
380
381   if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
382     NodePtr = NextNodeInBucket;
383   else {
384     // Otherwise, this is the last link in this bucket.  
385     void **Bucket = GetBucketPtr(Probe);
386
387     // Skip to the next non-null non-self-cycle bucket.
388     do {
389       ++Bucket;
390     } while (*Bucket != reinterpret_cast<void*>(-1) &&
391              (*Bucket == 0 || GetNextPtr(*Bucket) == 0));
392     
393     NodePtr = static_cast<FoldingSetNode*>(*Bucket);
394   }
395 }
396
397 //===----------------------------------------------------------------------===//
398 // FoldingSetBucketIteratorImpl Implementation
399
400 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
401   Ptr = (*Bucket == 0 || GetNextPtr(*Bucket) == 0) ? (void*) Bucket : *Bucket;
402 }