1 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements a hash set that can be used to remove duplication of
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/FoldingSet.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/Allocator.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/SwapByteOrder.h"
24 //===----------------------------------------------------------------------===//
25 // FoldingSetNodeIDRef Implementation
27 bool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS
) const {
28 if (Size
!= RHS
.Size
) return false;
29 return memcmp(Data
, RHS
.Data
, Size
*sizeof(*Data
)) == 0;
32 /// Used to compare the "ordering" of two nodes as defined by the
33 /// profiled bits and their ordering defined by memcmp().
34 bool FoldingSetNodeIDRef::operator<(FoldingSetNodeIDRef RHS
) const {
36 return Size
< RHS
.Size
;
37 return memcmp(Data
, RHS
.Data
, Size
*sizeof(*Data
)) < 0;
40 //===----------------------------------------------------------------------===//
41 // FoldingSetNodeID Implementation
43 /// Add* - Add various data types to Bit data.
45 void FoldingSetNodeID::AddString(StringRef String
) {
46 unsigned Size
= String
.size();
48 unsigned NumInserts
= 1 + divideCeil(Size
, 4);
49 Bits
.reserve(Bits
.size() + NumInserts
);
54 unsigned Units
= Size
/ 4;
56 const unsigned *Base
= (const unsigned*) String
.data();
58 // If the string is aligned do a bulk transfer.
59 if (!((intptr_t)Base
& 3)) {
60 Bits
.append(Base
, Base
+ Units
);
61 Pos
= (Units
+ 1) * 4;
63 // Otherwise do it the hard way.
64 // To be compatible with above bulk transfer, we need to take endianness
66 static_assert(sys::IsBigEndianHost
|| sys::IsLittleEndianHost
,
67 "Unexpected host endianness");
68 if (sys::IsBigEndianHost
) {
69 for (Pos
+= 4; Pos
<= Size
; Pos
+= 4) {
70 unsigned V
= ((unsigned char)String
[Pos
- 4] << 24) |
71 ((unsigned char)String
[Pos
- 3] << 16) |
72 ((unsigned char)String
[Pos
- 2] << 8) |
73 (unsigned char)String
[Pos
- 1];
76 } else { // Little-endian host
77 for (Pos
+= 4; Pos
<= Size
; Pos
+= 4) {
78 unsigned V
= ((unsigned char)String
[Pos
- 1] << 24) |
79 ((unsigned char)String
[Pos
- 2] << 16) |
80 ((unsigned char)String
[Pos
- 3] << 8) |
81 (unsigned char)String
[Pos
- 4];
87 // With the leftover bits.
89 // Pos will have overshot size by 4 - #bytes left over.
90 // No need to take endianness into account here - this is always executed.
92 case 1: V
= (V
<< 8) | (unsigned char)String
[Size
- 3]; [[fallthrough
]];
93 case 2: V
= (V
<< 8) | (unsigned char)String
[Size
- 2]; [[fallthrough
]];
94 case 3: V
= (V
<< 8) | (unsigned char)String
[Size
- 1]; break;
95 default: return; // Nothing left.
101 // AddNodeID - Adds the Bit data of another ID to *this.
102 void FoldingSetNodeID::AddNodeID(const FoldingSetNodeID
&ID
) {
103 Bits
.append(ID
.Bits
.begin(), ID
.Bits
.end());
106 /// operator== - Used to compare two nodes to each other.
108 bool FoldingSetNodeID::operator==(const FoldingSetNodeID
&RHS
) const {
109 return *this == FoldingSetNodeIDRef(RHS
.Bits
.data(), RHS
.Bits
.size());
112 /// operator== - Used to compare two nodes to each other.
114 bool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS
) const {
115 return FoldingSetNodeIDRef(Bits
.data(), Bits
.size()) == RHS
;
118 /// Used to compare the "ordering" of two nodes as defined by the
119 /// profiled bits and their ordering defined by memcmp().
120 bool FoldingSetNodeID::operator<(const FoldingSetNodeID
&RHS
) const {
121 return *this < FoldingSetNodeIDRef(RHS
.Bits
.data(), RHS
.Bits
.size());
124 bool FoldingSetNodeID::operator<(FoldingSetNodeIDRef RHS
) const {
125 return FoldingSetNodeIDRef(Bits
.data(), Bits
.size()) < RHS
;
128 /// Intern - Copy this node's data to a memory region allocated from the
129 /// given allocator and return a FoldingSetNodeIDRef describing the
132 FoldingSetNodeID::Intern(BumpPtrAllocator
&Allocator
) const {
133 unsigned *New
= Allocator
.Allocate
<unsigned>(Bits
.size());
134 std::uninitialized_copy(Bits
.begin(), Bits
.end(), New
);
135 return FoldingSetNodeIDRef(New
, Bits
.size());
138 //===----------------------------------------------------------------------===//
139 /// Helper functions for FoldingSetBase.
141 /// GetNextPtr - In order to save space, each bucket is a
142 /// singly-linked-list. In order to make deletion more efficient, we make
143 /// the list circular, so we can delete a node without computing its hash.
144 /// The problem with this is that the start of the hash buckets are not
145 /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null:
146 /// use GetBucketPtr when this happens.
147 static FoldingSetBase::Node
*GetNextPtr(void *NextInBucketPtr
) {
148 // The low bit is set if this is the pointer back to the bucket.
149 if (reinterpret_cast<intptr_t>(NextInBucketPtr
) & 1)
152 return static_cast<FoldingSetBase::Node
*>(NextInBucketPtr
);
157 static void **GetBucketPtr(void *NextInBucketPtr
) {
158 intptr_t Ptr
= reinterpret_cast<intptr_t>(NextInBucketPtr
);
159 assert((Ptr
& 1) && "Not a bucket pointer");
160 return reinterpret_cast<void**>(Ptr
& ~intptr_t(1));
163 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
164 /// the specified ID.
165 static void **GetBucketFor(unsigned Hash
, void **Buckets
, unsigned NumBuckets
) {
166 // NumBuckets is always a power of 2.
167 unsigned BucketNum
= Hash
& (NumBuckets
-1);
168 return Buckets
+ BucketNum
;
171 /// AllocateBuckets - Allocated initialized bucket memory.
172 static void **AllocateBuckets(unsigned NumBuckets
) {
173 void **Buckets
= static_cast<void**>(safe_calloc(NumBuckets
+ 1,
175 // Set the very last bucket to be a non-null "pointer".
176 Buckets
[NumBuckets
] = reinterpret_cast<void*>(-1);
180 //===----------------------------------------------------------------------===//
181 // FoldingSetBase Implementation
183 FoldingSetBase::FoldingSetBase(unsigned Log2InitSize
) {
184 assert(5 < Log2InitSize
&& Log2InitSize
< 32 &&
185 "Initial hash table size out of range");
186 NumBuckets
= 1 << Log2InitSize
;
187 Buckets
= AllocateBuckets(NumBuckets
);
191 FoldingSetBase::FoldingSetBase(FoldingSetBase
&&Arg
)
192 : Buckets(Arg
.Buckets
), NumBuckets(Arg
.NumBuckets
), NumNodes(Arg
.NumNodes
) {
193 Arg
.Buckets
= nullptr;
198 FoldingSetBase
&FoldingSetBase::operator=(FoldingSetBase
&&RHS
) {
199 free(Buckets
); // This may be null if the set is in a moved-from state.
200 Buckets
= RHS
.Buckets
;
201 NumBuckets
= RHS
.NumBuckets
;
202 NumNodes
= RHS
.NumNodes
;
203 RHS
.Buckets
= nullptr;
209 FoldingSetBase::~FoldingSetBase() {
213 void FoldingSetBase::clear() {
214 // Set all but the last bucket to null pointers.
215 memset(Buckets
, 0, NumBuckets
*sizeof(void*));
217 // Set the very last bucket to be a non-null "pointer".
218 Buckets
[NumBuckets
] = reinterpret_cast<void*>(-1);
220 // Reset the node count to zero.
224 void FoldingSetBase::GrowBucketCount(unsigned NewBucketCount
,
225 const FoldingSetInfo
&Info
) {
226 assert((NewBucketCount
> NumBuckets
) &&
227 "Can't shrink a folding set with GrowBucketCount");
228 assert(isPowerOf2_32(NewBucketCount
) && "Bad bucket count!");
229 void **OldBuckets
= Buckets
;
230 unsigned OldNumBuckets
= NumBuckets
;
232 // Clear out new buckets.
233 Buckets
= AllocateBuckets(NewBucketCount
);
234 // Set NumBuckets only if allocation of new buckets was successful.
235 NumBuckets
= NewBucketCount
;
238 // Walk the old buckets, rehashing nodes into their new place.
239 FoldingSetNodeID TempID
;
240 for (unsigned i
= 0; i
!= OldNumBuckets
; ++i
) {
241 void *Probe
= OldBuckets
[i
];
242 if (!Probe
) continue;
243 while (Node
*NodeInBucket
= GetNextPtr(Probe
)) {
244 // Figure out the next link, remove NodeInBucket from the old link.
245 Probe
= NodeInBucket
->getNextInBucket();
246 NodeInBucket
->SetNextInBucket(nullptr);
248 // Insert the node into the new bucket, after recomputing the hash.
249 InsertNode(NodeInBucket
,
250 GetBucketFor(Info
.ComputeNodeHash(this, NodeInBucket
, TempID
),
251 Buckets
, NumBuckets
),
260 /// GrowHashTable - Double the size of the hash table and rehash everything.
262 void FoldingSetBase::GrowHashTable(const FoldingSetInfo
&Info
) {
263 GrowBucketCount(NumBuckets
* 2, Info
);
266 void FoldingSetBase::reserve(unsigned EltCount
, const FoldingSetInfo
&Info
) {
267 // This will give us somewhere between EltCount / 2 and
268 // EltCount buckets. This puts us in the load factor
269 // range of 1.0 - 2.0.
270 if(EltCount
< capacity())
272 GrowBucketCount(llvm::bit_floor(EltCount
), Info
);
275 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
276 /// return it. If not, return the insertion token that will make insertion
278 FoldingSetBase::Node
*FoldingSetBase::FindNodeOrInsertPos(
279 const FoldingSetNodeID
&ID
, void *&InsertPos
, const FoldingSetInfo
&Info
) {
280 unsigned IDHash
= ID
.ComputeHash();
281 void **Bucket
= GetBucketFor(IDHash
, Buckets
, NumBuckets
);
282 void *Probe
= *Bucket
;
286 FoldingSetNodeID TempID
;
287 while (Node
*NodeInBucket
= GetNextPtr(Probe
)) {
288 if (Info
.NodeEquals(this, NodeInBucket
, ID
, IDHash
, TempID
))
292 Probe
= NodeInBucket
->getNextInBucket();
295 // Didn't find the node, return null with the bucket as the InsertPos.
300 /// InsertNode - Insert the specified node into the folding set, knowing that it
301 /// is not already in the map. InsertPos must be obtained from
302 /// FindNodeOrInsertPos.
303 void FoldingSetBase::InsertNode(Node
*N
, void *InsertPos
,
304 const FoldingSetInfo
&Info
) {
305 assert(!N
->getNextInBucket());
306 // Do we need to grow the hashtable?
307 if (NumNodes
+1 > capacity()) {
309 FoldingSetNodeID TempID
;
310 InsertPos
= GetBucketFor(Info
.ComputeNodeHash(this, N
, TempID
), Buckets
,
316 /// The insert position is actually a bucket pointer.
317 void **Bucket
= static_cast<void**>(InsertPos
);
319 void *Next
= *Bucket
;
321 // If this is the first insertion into this bucket, its next pointer will be
322 // null. Pretend as if it pointed to itself, setting the low bit to indicate
323 // that it is a pointer to the bucket.
325 Next
= reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket
)|1);
327 // Set the node's next pointer, and make the bucket point to the node.
328 N
->SetNextInBucket(Next
);
332 /// RemoveNode - Remove a node from the folding set, returning true if one was
333 /// removed or false if the node was not in the folding set.
334 bool FoldingSetBase::RemoveNode(Node
*N
) {
335 // Because each bucket is a circular list, we don't need to compute N's hash
337 void *Ptr
= N
->getNextInBucket();
338 if (!Ptr
) return false; // Not in folding set.
341 N
->SetNextInBucket(nullptr);
343 // Remember what N originally pointed to, either a bucket or another node.
344 void *NodeNextPtr
= Ptr
;
346 // Chase around the list until we find the node (or bucket) which points to N.
348 if (Node
*NodeInBucket
= GetNextPtr(Ptr
)) {
350 Ptr
= NodeInBucket
->getNextInBucket();
352 // We found a node that points to N, change it to point to N's next node,
353 // removing N from the list.
355 NodeInBucket
->SetNextInBucket(NodeNextPtr
);
359 void **Bucket
= GetBucketPtr(Ptr
);
362 // If we found that the bucket points to N, update the bucket to point to
365 *Bucket
= NodeNextPtr
;
372 /// GetOrInsertNode - If there is an existing simple Node exactly
373 /// equal to the specified node, return it. Otherwise, insert 'N' and it
375 FoldingSetBase::Node
*
376 FoldingSetBase::GetOrInsertNode(FoldingSetBase::Node
*N
,
377 const FoldingSetInfo
&Info
) {
379 Info
.GetNodeProfile(this, N
, ID
);
381 if (Node
*E
= FindNodeOrInsertPos(ID
, IP
, Info
))
383 InsertNode(N
, IP
, Info
);
387 //===----------------------------------------------------------------------===//
388 // FoldingSetIteratorImpl Implementation
390 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket
) {
391 // Skip to the first non-null non-self-cycle bucket.
392 while (*Bucket
!= reinterpret_cast<void*>(-1) &&
393 (!*Bucket
|| !GetNextPtr(*Bucket
)))
396 NodePtr
= static_cast<FoldingSetNode
*>(*Bucket
);
399 void FoldingSetIteratorImpl::advance() {
400 // If there is another link within this bucket, go to it.
401 void *Probe
= NodePtr
->getNextInBucket();
403 if (FoldingSetNode
*NextNodeInBucket
= GetNextPtr(Probe
))
404 NodePtr
= NextNodeInBucket
;
406 // Otherwise, this is the last link in this bucket.
407 void **Bucket
= GetBucketPtr(Probe
);
409 // Skip to the next non-null non-self-cycle bucket.
412 } while (*Bucket
!= reinterpret_cast<void*>(-1) &&
413 (!*Bucket
|| !GetNextPtr(*Bucket
)));
415 NodePtr
= static_cast<FoldingSetNode
*>(*Bucket
);
419 //===----------------------------------------------------------------------===//
420 // FoldingSetBucketIteratorImpl Implementation
422 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket
) {
423 Ptr
= (!*Bucket
|| !GetNextPtr(*Bucket
)) ? (void*) Bucket
: *Bucket
;