• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a hash set that can be used to remove duplication of
10 // nodes in a graph.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/FoldingSet.h"
15 #include "llvm/ADT/Hashing.h"
16 #include "llvm/Support/Allocator.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Host.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <cassert>
21 #include <cstring>
22 using namespace llvm;
23 
24 //===----------------------------------------------------------------------===//
25 // FoldingSetNodeIDRef Implementation
26 
27 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
28 /// used to lookup the node in the FoldingSetBase.
ComputeHash() const29 unsigned FoldingSetNodeIDRef::ComputeHash() const {
30   return static_cast<unsigned>(hash_combine_range(Data, Data+Size));
31 }
32 
operator ==(FoldingSetNodeIDRef RHS) const33 bool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS) const {
34   if (Size != RHS.Size) return false;
35   return memcmp(Data, RHS.Data, Size*sizeof(*Data)) == 0;
36 }
37 
38 /// Used to compare the "ordering" of two nodes as defined by the
39 /// profiled bits and their ordering defined by memcmp().
operator <(FoldingSetNodeIDRef RHS) const40 bool FoldingSetNodeIDRef::operator<(FoldingSetNodeIDRef RHS) const {
41   if (Size != RHS.Size)
42     return Size < RHS.Size;
43   return memcmp(Data, RHS.Data, Size*sizeof(*Data)) < 0;
44 }
45 
46 //===----------------------------------------------------------------------===//
47 // FoldingSetNodeID Implementation
48 
49 /// Add* - Add various data types to Bit data.
50 ///
AddPointer(const void * Ptr)51 void FoldingSetNodeID::AddPointer(const void *Ptr) {
52   // Note: this adds pointers to the hash using sizes and endianness that
53   // depend on the host. It doesn't matter, however, because hashing on
54   // pointer values is inherently unstable. Nothing should depend on the
55   // ordering of nodes in the folding set.
56   static_assert(sizeof(uintptr_t) <= sizeof(unsigned long long),
57                 "unexpected pointer size");
58   AddInteger(reinterpret_cast<uintptr_t>(Ptr));
59 }
AddInteger(signed I)60 void FoldingSetNodeID::AddInteger(signed I) {
61   Bits.push_back(I);
62 }
AddInteger(unsigned I)63 void FoldingSetNodeID::AddInteger(unsigned I) {
64   Bits.push_back(I);
65 }
AddInteger(long I)66 void FoldingSetNodeID::AddInteger(long I) {
67   AddInteger((unsigned long)I);
68 }
AddInteger(unsigned long I)69 void FoldingSetNodeID::AddInteger(unsigned long I) {
70   if (sizeof(long) == sizeof(int))
71     AddInteger(unsigned(I));
72   else if (sizeof(long) == sizeof(long long)) {
73     AddInteger((unsigned long long)I);
74   } else {
75     llvm_unreachable("unexpected sizeof(long)");
76   }
77 }
AddInteger(long long I)78 void FoldingSetNodeID::AddInteger(long long I) {
79   AddInteger((unsigned long long)I);
80 }
AddInteger(unsigned long long I)81 void FoldingSetNodeID::AddInteger(unsigned long long I) {
82   AddInteger(unsigned(I));
83   AddInteger(unsigned(I >> 32));
84 }
85 
AddString(StringRef String)86 void FoldingSetNodeID::AddString(StringRef String) {
87   unsigned Size =  String.size();
88   Bits.push_back(Size);
89   if (!Size) return;
90 
91   unsigned Units = Size / 4;
92   unsigned Pos = 0;
93   const unsigned *Base = (const unsigned*) String.data();
94 
95   // If the string is aligned do a bulk transfer.
96   if (!((intptr_t)Base & 3)) {
97     Bits.append(Base, Base + Units);
98     Pos = (Units + 1) * 4;
99   } else {
100     // Otherwise do it the hard way.
101     // To be compatible with above bulk transfer, we need to take endianness
102     // into account.
103     static_assert(sys::IsBigEndianHost || sys::IsLittleEndianHost,
104                   "Unexpected host endianness");
105     if (sys::IsBigEndianHost) {
106       for (Pos += 4; Pos <= Size; Pos += 4) {
107         unsigned V = ((unsigned char)String[Pos - 4] << 24) |
108                      ((unsigned char)String[Pos - 3] << 16) |
109                      ((unsigned char)String[Pos - 2] << 8) |
110                       (unsigned char)String[Pos - 1];
111         Bits.push_back(V);
112       }
113     } else {  // Little-endian host
114       for (Pos += 4; Pos <= Size; Pos += 4) {
115         unsigned V = ((unsigned char)String[Pos - 1] << 24) |
116                      ((unsigned char)String[Pos - 2] << 16) |
117                      ((unsigned char)String[Pos - 3] << 8) |
118                       (unsigned char)String[Pos - 4];
119         Bits.push_back(V);
120       }
121     }
122   }
123 
124   // With the leftover bits.
125   unsigned V = 0;
126   // Pos will have overshot size by 4 - #bytes left over.
127   // No need to take endianness into account here - this is always executed.
128   switch (Pos - Size) {
129   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; LLVM_FALLTHROUGH;
130   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; LLVM_FALLTHROUGH;
131   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
132   default: return; // Nothing left.
133   }
134 
135   Bits.push_back(V);
136 }
137 
138 // AddNodeID - Adds the Bit data of another ID to *this.
AddNodeID(const FoldingSetNodeID & ID)139 void FoldingSetNodeID::AddNodeID(const FoldingSetNodeID &ID) {
140   Bits.append(ID.Bits.begin(), ID.Bits.end());
141 }
142 
143 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to
144 /// lookup the node in the FoldingSetBase.
ComputeHash() const145 unsigned FoldingSetNodeID::ComputeHash() const {
146   return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
147 }
148 
149 /// operator== - Used to compare two nodes to each other.
150 ///
operator ==(const FoldingSetNodeID & RHS) const151 bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS) const {
152   return *this == FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
153 }
154 
155 /// operator== - Used to compare two nodes to each other.
156 ///
operator ==(FoldingSetNodeIDRef RHS) const157 bool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS) const {
158   return FoldingSetNodeIDRef(Bits.data(), Bits.size()) == RHS;
159 }
160 
161 /// Used to compare the "ordering" of two nodes as defined by the
162 /// profiled bits and their ordering defined by memcmp().
operator <(const FoldingSetNodeID & RHS) const163 bool FoldingSetNodeID::operator<(const FoldingSetNodeID &RHS) const {
164   return *this < FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
165 }
166 
operator <(FoldingSetNodeIDRef RHS) const167 bool FoldingSetNodeID::operator<(FoldingSetNodeIDRef RHS) const {
168   return FoldingSetNodeIDRef(Bits.data(), Bits.size()) < RHS;
169 }
170 
171 /// Intern - Copy this node's data to a memory region allocated from the
172 /// given allocator and return a FoldingSetNodeIDRef describing the
173 /// interned data.
174 FoldingSetNodeIDRef
Intern(BumpPtrAllocator & Allocator) const175 FoldingSetNodeID::Intern(BumpPtrAllocator &Allocator) const {
176   unsigned *New = Allocator.Allocate<unsigned>(Bits.size());
177   std::uninitialized_copy(Bits.begin(), Bits.end(), New);
178   return FoldingSetNodeIDRef(New, Bits.size());
179 }
180 
181 //===----------------------------------------------------------------------===//
182 /// Helper functions for FoldingSetBase.
183 
184 /// GetNextPtr - In order to save space, each bucket is a
185 /// singly-linked-list. In order to make deletion more efficient, we make
186 /// the list circular, so we can delete a node without computing its hash.
187 /// The problem with this is that the start of the hash buckets are not
188 /// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null:
189 /// use GetBucketPtr when this happens.
GetNextPtr(void * NextInBucketPtr)190 static FoldingSetBase::Node *GetNextPtr(void *NextInBucketPtr) {
191   // The low bit is set if this is the pointer back to the bucket.
192   if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
193     return nullptr;
194 
195   return static_cast<FoldingSetBase::Node*>(NextInBucketPtr);
196 }
197 
198 
199 /// testing.
GetBucketPtr(void * NextInBucketPtr)200 static void **GetBucketPtr(void *NextInBucketPtr) {
201   intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
202   assert((Ptr & 1) && "Not a bucket pointer");
203   return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
204 }
205 
206 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
207 /// the specified ID.
GetBucketFor(unsigned Hash,void ** Buckets,unsigned NumBuckets)208 static void **GetBucketFor(unsigned Hash, void **Buckets, unsigned NumBuckets) {
209   // NumBuckets is always a power of 2.
210   unsigned BucketNum = Hash & (NumBuckets-1);
211   return Buckets + BucketNum;
212 }
213 
214 /// AllocateBuckets - Allocated initialized bucket memory.
AllocateBuckets(unsigned NumBuckets)215 static void **AllocateBuckets(unsigned NumBuckets) {
216   void **Buckets = static_cast<void**>(safe_calloc(NumBuckets + 1,
217                                                    sizeof(void*)));
218   // Set the very last bucket to be a non-null "pointer".
219   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
220   return Buckets;
221 }
222 
223 //===----------------------------------------------------------------------===//
224 // FoldingSetBase Implementation
225 
anchor()226 void FoldingSetBase::anchor() {}
227 
FoldingSetBase(unsigned Log2InitSize)228 FoldingSetBase::FoldingSetBase(unsigned Log2InitSize) {
229   assert(5 < Log2InitSize && Log2InitSize < 32 &&
230          "Initial hash table size out of range");
231   NumBuckets = 1 << Log2InitSize;
232   Buckets = AllocateBuckets(NumBuckets);
233   NumNodes = 0;
234 }
235 
FoldingSetBase(FoldingSetBase && Arg)236 FoldingSetBase::FoldingSetBase(FoldingSetBase &&Arg)
237     : Buckets(Arg.Buckets), NumBuckets(Arg.NumBuckets), NumNodes(Arg.NumNodes) {
238   Arg.Buckets = nullptr;
239   Arg.NumBuckets = 0;
240   Arg.NumNodes = 0;
241 }
242 
operator =(FoldingSetBase && RHS)243 FoldingSetBase &FoldingSetBase::operator=(FoldingSetBase &&RHS) {
244   free(Buckets); // This may be null if the set is in a moved-from state.
245   Buckets = RHS.Buckets;
246   NumBuckets = RHS.NumBuckets;
247   NumNodes = RHS.NumNodes;
248   RHS.Buckets = nullptr;
249   RHS.NumBuckets = 0;
250   RHS.NumNodes = 0;
251   return *this;
252 }
253 
~FoldingSetBase()254 FoldingSetBase::~FoldingSetBase() {
255   free(Buckets);
256 }
257 
clear()258 void FoldingSetBase::clear() {
259   // Set all but the last bucket to null pointers.
260   memset(Buckets, 0, NumBuckets*sizeof(void*));
261 
262   // Set the very last bucket to be a non-null "pointer".
263   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
264 
265   // Reset the node count to zero.
266   NumNodes = 0;
267 }
268 
GrowBucketCount(unsigned NewBucketCount)269 void FoldingSetBase::GrowBucketCount(unsigned NewBucketCount) {
270   assert((NewBucketCount > NumBuckets) && "Can't shrink a folding set with GrowBucketCount");
271   assert(isPowerOf2_32(NewBucketCount) && "Bad bucket count!");
272   void **OldBuckets = Buckets;
273   unsigned OldNumBuckets = NumBuckets;
274 
275   // Clear out new buckets.
276   Buckets = AllocateBuckets(NewBucketCount);
277   // Set NumBuckets only if allocation of new buckets was successful.
278   NumBuckets = NewBucketCount;
279   NumNodes = 0;
280 
281   // Walk the old buckets, rehashing nodes into their new place.
282   FoldingSetNodeID TempID;
283   for (unsigned i = 0; i != OldNumBuckets; ++i) {
284     void *Probe = OldBuckets[i];
285     if (!Probe) continue;
286     while (Node *NodeInBucket = GetNextPtr(Probe)) {
287       // Figure out the next link, remove NodeInBucket from the old link.
288       Probe = NodeInBucket->getNextInBucket();
289       NodeInBucket->SetNextInBucket(nullptr);
290 
291       // Insert the node into the new bucket, after recomputing the hash.
292       InsertNode(NodeInBucket,
293                  GetBucketFor(ComputeNodeHash(NodeInBucket, TempID),
294                               Buckets, NumBuckets));
295       TempID.clear();
296     }
297   }
298 
299   free(OldBuckets);
300 }
301 
302 /// GrowHashTable - Double the size of the hash table and rehash everything.
303 ///
GrowHashTable()304 void FoldingSetBase::GrowHashTable() {
305   GrowBucketCount(NumBuckets * 2);
306 }
307 
reserve(unsigned EltCount)308 void FoldingSetBase::reserve(unsigned EltCount) {
309   // This will give us somewhere between EltCount / 2 and
310   // EltCount buckets.  This puts us in the load factor
311   // range of 1.0 - 2.0.
312   if(EltCount < capacity())
313     return;
314   GrowBucketCount(PowerOf2Floor(EltCount));
315 }
316 
317 /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
318 /// return it.  If not, return the insertion token that will make insertion
319 /// faster.
320 FoldingSetBase::Node *
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)321 FoldingSetBase::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
322                                     void *&InsertPos) {
323   unsigned IDHash = ID.ComputeHash();
324   void **Bucket = GetBucketFor(IDHash, Buckets, NumBuckets);
325   void *Probe = *Bucket;
326 
327   InsertPos = nullptr;
328 
329   FoldingSetNodeID TempID;
330   while (Node *NodeInBucket = GetNextPtr(Probe)) {
331     if (NodeEquals(NodeInBucket, ID, IDHash, TempID))
332       return NodeInBucket;
333     TempID.clear();
334 
335     Probe = NodeInBucket->getNextInBucket();
336   }
337 
338   // Didn't find the node, return null with the bucket as the InsertPos.
339   InsertPos = Bucket;
340   return nullptr;
341 }
342 
343 /// InsertNode - Insert the specified node into the folding set, knowing that it
344 /// is not already in the map.  InsertPos must be obtained from
345 /// FindNodeOrInsertPos.
InsertNode(Node * N,void * InsertPos)346 void FoldingSetBase::InsertNode(Node *N, void *InsertPos) {
347   assert(!N->getNextInBucket());
348   // Do we need to grow the hashtable?
349   if (NumNodes+1 > capacity()) {
350     GrowHashTable();
351     FoldingSetNodeID TempID;
352     InsertPos = GetBucketFor(ComputeNodeHash(N, TempID), Buckets, NumBuckets);
353   }
354 
355   ++NumNodes;
356 
357   /// The insert position is actually a bucket pointer.
358   void **Bucket = static_cast<void**>(InsertPos);
359 
360   void *Next = *Bucket;
361 
362   // If this is the first insertion into this bucket, its next pointer will be
363   // null.  Pretend as if it pointed to itself, setting the low bit to indicate
364   // that it is a pointer to the bucket.
365   if (!Next)
366     Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
367 
368   // Set the node's next pointer, and make the bucket point to the node.
369   N->SetNextInBucket(Next);
370   *Bucket = N;
371 }
372 
373 /// RemoveNode - Remove a node from the folding set, returning true if one was
374 /// removed or false if the node was not in the folding set.
RemoveNode(Node * N)375 bool FoldingSetBase::RemoveNode(Node *N) {
376   // Because each bucket is a circular list, we don't need to compute N's hash
377   // to remove it.
378   void *Ptr = N->getNextInBucket();
379   if (!Ptr) return false;  // Not in folding set.
380 
381   --NumNodes;
382   N->SetNextInBucket(nullptr);
383 
384   // Remember what N originally pointed to, either a bucket or another node.
385   void *NodeNextPtr = Ptr;
386 
387   // Chase around the list until we find the node (or bucket) which points to N.
388   while (true) {
389     if (Node *NodeInBucket = GetNextPtr(Ptr)) {
390       // Advance pointer.
391       Ptr = NodeInBucket->getNextInBucket();
392 
393       // We found a node that points to N, change it to point to N's next node,
394       // removing N from the list.
395       if (Ptr == N) {
396         NodeInBucket->SetNextInBucket(NodeNextPtr);
397         return true;
398       }
399     } else {
400       void **Bucket = GetBucketPtr(Ptr);
401       Ptr = *Bucket;
402 
403       // If we found that the bucket points to N, update the bucket to point to
404       // whatever is next.
405       if (Ptr == N) {
406         *Bucket = NodeNextPtr;
407         return true;
408       }
409     }
410   }
411 }
412 
413 /// GetOrInsertNode - If there is an existing simple Node exactly
414 /// equal to the specified node, return it.  Otherwise, insert 'N' and it
415 /// instead.
GetOrInsertNode(FoldingSetBase::Node * N)416 FoldingSetBase::Node *FoldingSetBase::GetOrInsertNode(FoldingSetBase::Node *N) {
417   FoldingSetNodeID ID;
418   GetNodeProfile(N, ID);
419   void *IP;
420   if (Node *E = FindNodeOrInsertPos(ID, IP))
421     return E;
422   InsertNode(N, IP);
423   return N;
424 }
425 
426 //===----------------------------------------------------------------------===//
427 // FoldingSetIteratorImpl Implementation
428 
FoldingSetIteratorImpl(void ** Bucket)429 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket) {
430   // Skip to the first non-null non-self-cycle bucket.
431   while (*Bucket != reinterpret_cast<void*>(-1) &&
432          (!*Bucket || !GetNextPtr(*Bucket)))
433     ++Bucket;
434 
435   NodePtr = static_cast<FoldingSetNode*>(*Bucket);
436 }
437 
advance()438 void FoldingSetIteratorImpl::advance() {
439   // If there is another link within this bucket, go to it.
440   void *Probe = NodePtr->getNextInBucket();
441 
442   if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
443     NodePtr = NextNodeInBucket;
444   else {
445     // Otherwise, this is the last link in this bucket.
446     void **Bucket = GetBucketPtr(Probe);
447 
448     // Skip to the next non-null non-self-cycle bucket.
449     do {
450       ++Bucket;
451     } while (*Bucket != reinterpret_cast<void*>(-1) &&
452              (!*Bucket || !GetNextPtr(*Bucket)));
453 
454     NodePtr = static_cast<FoldingSetNode*>(*Bucket);
455   }
456 }
457 
458 //===----------------------------------------------------------------------===//
459 // FoldingSetBucketIteratorImpl Implementation
460 
FoldingSetBucketIteratorImpl(void ** Bucket)461 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
462   Ptr = (!*Bucket || !GetNextPtr(*Bucket)) ? (void*) Bucket : *Bucket;
463 }
464