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