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