LLVM API Documentation

FoldingSet.cpp

Go to the documentation of this file.
00001 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a hash set that can be used to remove duplication of
00011 // nodes in a graph.  This code was originally created by Chris Lattner for use
00012 // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code
00013 // set. 
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/ADT/FoldingSet.h"
00018 #include "llvm/Support/MathExtras.h"
00019 #include <cassert>
00020 #include <cstring>
00021 using namespace llvm;
00022 
00023 //===----------------------------------------------------------------------===//
00024 // FoldingSetNodeID Implementation
00025 
00026 /// Add* - Add various data types to Bit data.
00027 ///
00028 void FoldingSetNodeID::AddPointer(const void *Ptr) {
00029   // Note: this adds pointers to the hash using sizes and endianness that
00030   // depend on the host.  It doesn't matter however, because hashing on
00031   // pointer values in inherently unstable.  Nothing  should depend on the 
00032   // ordering of nodes in the folding set.
00033   intptr_t PtrI = (intptr_t)Ptr;
00034   Bits.push_back(unsigned(PtrI));
00035   if (sizeof(intptr_t) > sizeof(unsigned))
00036     Bits.push_back(unsigned(uint64_t(PtrI) >> 32));
00037 }
00038 void FoldingSetNodeID::AddInteger(signed I) {
00039   Bits.push_back(I);
00040 }
00041 void FoldingSetNodeID::AddInteger(unsigned I) {
00042   Bits.push_back(I);
00043 }
00044 void FoldingSetNodeID::AddInteger(long I) {
00045   AddInteger((unsigned long)I);
00046 }
00047 void FoldingSetNodeID::AddInteger(unsigned long I) {
00048   if (sizeof(long) == sizeof(int))
00049     AddInteger(unsigned(I));
00050   else if (sizeof(long) == sizeof(long long)) {
00051     AddInteger((unsigned long long)I);
00052   } else {
00053     assert(0 && "unexpected sizeof(long)");
00054   }
00055 }
00056 void FoldingSetNodeID::AddInteger(long long I) {
00057   AddInteger((unsigned long long)I);
00058 }
00059 void FoldingSetNodeID::AddInteger(unsigned long long I) {
00060   AddInteger(unsigned(I));
00061   if ((uint64_t)(int)I != I)
00062     Bits.push_back(unsigned(I >> 32));
00063 }
00064 
00065 void FoldingSetNodeID::AddString(const char *String) {
00066   unsigned Size = static_cast<unsigned>(strlen(String));
00067   Bits.push_back(Size);
00068   if (!Size) return;
00069 
00070   unsigned Units = Size / 4;
00071   unsigned Pos = 0;
00072   const unsigned *Base = (const unsigned *)String;
00073   
00074   // If the string is aligned do a bulk transfer.
00075   if (!((intptr_t)Base & 3)) {
00076     Bits.append(Base, Base + Units);
00077     Pos = (Units + 1) * 4;
00078   } else {
00079     // Otherwise do it the hard way.
00080     for ( Pos += 4; Pos <= Size; Pos += 4) {
00081       unsigned V = ((unsigned char)String[Pos - 4] << 24) |
00082                    ((unsigned char)String[Pos - 3] << 16) |
00083                    ((unsigned char)String[Pos - 2] << 8) |
00084                     (unsigned char)String[Pos - 1];
00085       Bits.push_back(V);
00086     }
00087   }
00088   
00089   // With the leftover bits.
00090   unsigned V = 0;
00091   // Pos will have overshot size by 4 - #bytes left over. 
00092   switch (Pos - Size) {
00093   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
00094   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
00095   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
00096   default: return; // Nothing left.
00097   }
00098 
00099   Bits.push_back(V);
00100 }
00101 
00102 void FoldingSetNodeID::AddString(const std::string &String) {
00103   unsigned Size = static_cast<unsigned>(String.size());
00104   Bits.push_back(Size);
00105   if (!Size) return;
00106 
00107   unsigned Units = Size / 4;
00108   unsigned Pos = 0;
00109   const unsigned *Base = (const unsigned *)String.data();
00110   
00111   // If the string is aligned do a bulk transfer.
00112   if (!((intptr_t)Base & 3)) {
00113     Bits.append(Base, Base + Units);
00114     Pos = (Units + 1) * 4;
00115   } else {
00116     // Otherwise do it the hard way.
00117     for ( Pos += 4; Pos <= Size; Pos += 4) {
00118       unsigned V = ((unsigned char)String[Pos - 4] << 24) |
00119                    ((unsigned char)String[Pos - 3] << 16) |
00120                    ((unsigned char)String[Pos - 2] << 8) |
00121                     (unsigned char)String[Pos - 1];
00122       Bits.push_back(V);
00123     }
00124   }
00125   
00126   // With the leftover bits.
00127   unsigned V = 0;
00128   // Pos will have overshot size by 4 - #bytes left over. 
00129   switch (Pos - Size) {
00130   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
00131   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
00132   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
00133   default: return; // Nothing left.
00134   }
00135 
00136   Bits.push_back(V);
00137 }
00138 
00139 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to 
00140 /// lookup the node in the FoldingSetImpl.
00141 unsigned FoldingSetNodeID::ComputeHash() const {
00142   // This is adapted from SuperFastHash by Paul Hsieh.
00143   unsigned Hash = static_cast<unsigned>(Bits.size());
00144   for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) {
00145     unsigned Data = *BP;
00146     Hash         += Data & 0xFFFF;
00147     unsigned Tmp  = ((Data >> 16) << 11) ^ Hash;
00148     Hash          = (Hash << 16) ^ Tmp;
00149     Hash         += Hash >> 11;
00150   }
00151   
00152   // Force "avalanching" of final 127 bits.
00153   Hash ^= Hash << 3;
00154   Hash += Hash >> 5;
00155   Hash ^= Hash << 4;
00156   Hash += Hash >> 17;
00157   Hash ^= Hash << 25;
00158   Hash += Hash >> 6;
00159   return Hash;
00160 }
00161 
00162 /// operator== - Used to compare two nodes to each other.
00163 ///
00164 bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS)const{
00165   if (Bits.size() != RHS.Bits.size()) return false;
00166   return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0;
00167 }
00168 
00169 
00170 //===----------------------------------------------------------------------===//
00171 /// Helper functions for FoldingSetImpl.
00172 
00173 /// GetNextPtr - In order to save space, each bucket is a
00174 /// singly-linked-list. In order to make deletion more efficient, we make
00175 /// the list circular, so we can delete a node without computing its hash.
00176 /// The problem with this is that the start of the hash buckets are not
00177 /// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null:
00178 /// use GetBucketPtr when this happens.
00179 static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
00180   // The low bit is set if this is the pointer back to the bucket.
00181   if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
00182     return 0;
00183   
00184   return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
00185 }
00186 
00187 
00188 /// testing.
00189 static void **GetBucketPtr(void *NextInBucketPtr) {
00190   intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
00191   assert((Ptr & 1) && "Not a bucket pointer");
00192   return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
00193 }
00194 
00195 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
00196 /// the specified ID.
00197 static void **GetBucketFor(const FoldingSetNodeID &ID,
00198                            void **Buckets, unsigned NumBuckets) {
00199   // NumBuckets is always a power of 2.
00200   unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1);
00201   return Buckets + BucketNum;
00202 }
00203 
00204 //===----------------------------------------------------------------------===//
00205 // FoldingSetImpl Implementation
00206 
00207 FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) {
00208   assert(5 < Log2InitSize && Log2InitSize < 32 &&
00209          "Initial hash table size out of range");
00210   NumBuckets = 1 << Log2InitSize;
00211   Buckets = new void*[NumBuckets+1];
00212   clear();
00213 }
00214 FoldingSetImpl::~FoldingSetImpl() {
00215   delete [] Buckets;
00216 }
00217 void FoldingSetImpl::clear() {
00218   // Set all but the last bucket to null pointers.
00219   memset(Buckets, 0, NumBuckets*sizeof(void*));
00220 
00221   // Set the very last bucket to be a non-null "pointer".
00222   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
00223 
00224   // Reset the node count to zero.
00225   NumNodes = 0;
00226 }
00227 
00228 /// GrowHashTable - Double the size of the hash table and rehash everything.
00229 ///
00230 void FoldingSetImpl::GrowHashTable() {
00231   void **OldBuckets = Buckets;
00232   unsigned OldNumBuckets = NumBuckets;
00233   NumBuckets <<= 1;
00234   
00235   // Clear out new buckets.
00236   Buckets = new void*[NumBuckets+1];
00237   clear();
00238 
00239   // Walk the old buckets, rehashing nodes into their new place.
00240   FoldingSetNodeID ID;
00241   for (unsigned i = 0; i != OldNumBuckets; ++i) {
00242     void *Probe = OldBuckets[i];
00243     if (!Probe) continue;
00244     while (Node *NodeInBucket = GetNextPtr(Probe)) {
00245       // Figure out the next link, remove NodeInBucket from the old link.
00246       Probe = NodeInBucket->getNextInBucket();
00247       NodeInBucket->SetNextInBucket(0);
00248 
00249       // Insert the node into the new bucket, after recomputing the hash.
00250       GetNodeProfile(ID, NodeInBucket);
00251       InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets));
00252       ID.clear();
00253     }
00254   }
00255   
00256   delete[] OldBuckets;
00257 }
00258 
00259 /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
00260 /// return it.  If not, return the insertion token that will make insertion
00261 /// faster.
00262 FoldingSetImpl::Node
00263 *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
00264                                      void *&InsertPos) {
00265   
00266   void **Bucket = GetBucketFor(ID, Buckets, NumBuckets);
00267   void *Probe = *Bucket;
00268   
00269   InsertPos = 0;
00270   
00271   FoldingSetNodeID OtherID;
00272   while (Node *NodeInBucket = GetNextPtr(Probe)) {
00273     GetNodeProfile(OtherID, NodeInBucket);
00274     if (OtherID == ID)
00275       return NodeInBucket;
00276 
00277     Probe = NodeInBucket->getNextInBucket();
00278     OtherID.clear();
00279   }
00280   
00281   // Didn't find the node, return null with the bucket as the InsertPos.
00282   InsertPos = Bucket;
00283   return 0;
00284 }
00285 
00286 /// InsertNode - Insert the specified node into the folding set, knowing that it
00287 /// is not already in the map.  InsertPos must be obtained from 
00288 /// FindNodeOrInsertPos.
00289 void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) {
00290   assert(N->getNextInBucket() == 0);
00291   // Do we need to grow the hashtable?
00292   if (NumNodes+1 > NumBuckets*2) {
00293     GrowHashTable();
00294     FoldingSetNodeID ID;
00295     GetNodeProfile(ID, N);
00296     InsertPos = GetBucketFor(ID, Buckets, NumBuckets);
00297   }
00298 
00299   ++NumNodes;
00300   
00301   /// The insert position is actually a bucket pointer.
00302   void **Bucket = static_cast<void**>(InsertPos);
00303   
00304   void *Next = *Bucket;
00305   
00306   // If this is the first insertion into this bucket, its next pointer will be
00307   // null.  Pretend as if it pointed to itself, setting the low bit to indicate
00308   // that it is a pointer to the bucket.
00309   if (Next == 0)
00310     Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
00311 
00312   // Set the node's next pointer, and make the bucket point to the node.
00313   N->SetNextInBucket(Next);
00314   *Bucket = N;
00315 }
00316 
00317 /// RemoveNode - Remove a node from the folding set, returning true if one was
00318 /// removed or false if the node was not in the folding set.
00319 bool FoldingSetImpl::RemoveNode(Node *N) {
00320   // Because each bucket is a circular list, we don't need to compute N's hash
00321   // to remove it.
00322   void *Ptr = N->getNextInBucket();
00323   if (Ptr == 0) return false;  // Not in folding set.
00324 
00325   --NumNodes;
00326   N->SetNextInBucket(0);
00327 
00328   // Remember what N originally pointed to, either a bucket or another node.
00329   void *NodeNextPtr = Ptr;
00330   
00331   // Chase around the list until we find the node (or bucket) which points to N.
00332   while (true) {
00333     if (Node *NodeInBucket = GetNextPtr(Ptr)) {
00334       // Advance pointer.
00335       Ptr = NodeInBucket->getNextInBucket();
00336       
00337       // We found a node that points to N, change it to point to N's next node,
00338       // removing N from the list.
00339       if (Ptr == N) {
00340         NodeInBucket->SetNextInBucket(NodeNextPtr);
00341         return true;
00342       }
00343     } else {
00344       void **Bucket = GetBucketPtr(Ptr);
00345       Ptr = *Bucket;
00346       
00347       // If we found that the bucket points to N, update the bucket to point to
00348       // whatever is next.
00349       if (Ptr == N) {
00350         *Bucket = NodeNextPtr;
00351         return true;
00352       }
00353     }
00354   }
00355 }
00356 
00357 /// GetOrInsertNode - If there is an existing simple Node exactly
00358 /// equal to the specified node, return it.  Otherwise, insert 'N' and it
00359 /// instead.
00360 FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
00361   FoldingSetNodeID ID;
00362   GetNodeProfile(ID, N);
00363   void *IP;
00364   if (Node *E = FindNodeOrInsertPos(ID, IP))
00365     return E;
00366   InsertNode(N, IP);
00367   return N;
00368 }
00369 
00370 //===----------------------------------------------------------------------===//
00371 // FoldingSetIteratorImpl Implementation
00372 
00373 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket) {
00374   // Skip to the first non-null non-self-cycle bucket.
00375   while (*Bucket != reinterpret_cast<void*>(-1) &&
00376          (*Bucket == 0 || GetNextPtr(*Bucket) == 0))
00377     ++Bucket;
00378   
00379   NodePtr = static_cast<FoldingSetNode*>(*Bucket);
00380 }
00381 
00382 void FoldingSetIteratorImpl::advance() {
00383   // If there is another link within this bucket, go to it.
00384   void *Probe = NodePtr->getNextInBucket();
00385 
00386   if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
00387     NodePtr = NextNodeInBucket;
00388   else {
00389     // Otherwise, this is the last link in this bucket.  
00390     void **Bucket = GetBucketPtr(Probe);
00391 
00392     // Skip to the next non-null non-self-cycle bucket.
00393     do {
00394       ++Bucket;
00395     } while (*Bucket != reinterpret_cast<void*>(-1) &&
00396              (*Bucket == 0 || GetNextPtr(*Bucket) == 0));
00397     
00398     NodePtr = static_cast<FoldingSetNode*>(*Bucket);
00399   }
00400 }
00401 
00402 //===----------------------------------------------------------------------===//
00403 // FoldingSetBucketIteratorImpl Implementation
00404 
00405 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
00406   Ptr = (*Bucket == 0 || GetNextPtr(*Bucket) == 0) ? (void*) Bucket : *Bucket;
00407 }