1 //===- llvm/ADT/SmallPtrSet.cpp - 'Normally small' pointer set ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SmallPtrSet class.  See SmallPtrSet.h for an
11 // overview of the algorithm.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/Support/MathExtras.h"
18 #include <algorithm>
19 #include <cstdlib>
20 
21 using namespace llvm;
22 
23 void SmallPtrSetImplBase::shrink_and_clear() {
24   assert(!isSmall() && "Can't shrink a small set!");
25   free(CurArray);
26 
27   // Reduce the number of buckets.
28   CurArraySize = NumElements > 16 ? 1 << (Log2_32_Ceil(NumElements) + 1) : 32;
29   NumElements = NumTombstones = 0;
30 
31   // Install the new array.  Clear all the buckets to empty.
32   CurArray = (const void**)malloc(sizeof(void*) * CurArraySize);
33   assert(CurArray && "Failed to allocate memory?");
34   memset(CurArray, -1, CurArraySize*sizeof(void*));
35 }
36 
37 std::pair<const void *const *, bool>
38 SmallPtrSetImplBase::insert_imp_big(const void *Ptr) {
39   if (LLVM_UNLIKELY(NumElements * 4 >= CurArraySize * 3)) {
40     // If more than 3/4 of the array is full, grow.
41     Grow(CurArraySize < 64 ? 128 : CurArraySize*2);
42   } else if (LLVM_UNLIKELY(CurArraySize - (NumElements + NumTombstones) <
43                            CurArraySize / 8)) {
44     // If fewer of 1/8 of the array is empty (meaning that many are filled with
45     // tombstones), rehash.
46     Grow(CurArraySize);
47   }
48 
49   // Okay, we know we have space.  Find a hash bucket.
50   const void **Bucket = const_cast<const void**>(FindBucketFor(Ptr));
51   if (*Bucket == Ptr)
52     return std::make_pair(Bucket, false); // Already inserted, good.
53 
54   // Otherwise, insert it!
55   if (*Bucket == getTombstoneMarker())
56     --NumTombstones;
57   *Bucket = Ptr;
58   ++NumElements;  // Track density.
59   return std::make_pair(Bucket, true);
60 }
61 
62 bool SmallPtrSetImplBase::erase_imp(const void * Ptr) {
63   if (isSmall()) {
64     // Check to see if it is in the set.
65     for (const void **APtr = SmallArray, **E = SmallArray+NumElements;
66          APtr != E; ++APtr)
67       if (*APtr == Ptr) {
68         // If it is in the set, replace this element.
69         *APtr = E[-1];
70         E[-1] = getEmptyMarker();
71         --NumElements;
72         return true;
73       }
74 
75     return false;
76   }
77 
78   // Okay, we know we have space.  Find a hash bucket.
79   void **Bucket = const_cast<void**>(FindBucketFor(Ptr));
80   if (*Bucket != Ptr) return false;  // Not in the set?
81 
82   // Set this as a tombstone.
83   *Bucket = getTombstoneMarker();
84   --NumElements;
85   ++NumTombstones;
86   return true;
87 }
88 
89 const void * const *SmallPtrSetImplBase::FindBucketFor(const void *Ptr) const {
90   unsigned Bucket = DenseMapInfo<void *>::getHashValue(Ptr) & (CurArraySize-1);
91   unsigned ArraySize = CurArraySize;
92   unsigned ProbeAmt = 1;
93   const void *const *Array = CurArray;
94   const void *const *Tombstone = nullptr;
95   while (1) {
96     // If we found an empty bucket, the pointer doesn't exist in the set.
97     // Return a tombstone if we've seen one so far, or the empty bucket if
98     // not.
99     if (LLVM_LIKELY(Array[Bucket] == getEmptyMarker()))
100       return Tombstone ? Tombstone : Array+Bucket;
101 
102     // Found Ptr's bucket?
103     if (LLVM_LIKELY(Array[Bucket] == Ptr))
104       return Array+Bucket;
105 
106     // If this is a tombstone, remember it.  If Ptr ends up not in the set, we
107     // prefer to return it than something that would require more probing.
108     if (Array[Bucket] == getTombstoneMarker() && !Tombstone)
109       Tombstone = Array+Bucket;  // Remember the first tombstone found.
110 
111     // It's a hash collision or a tombstone. Reprobe.
112     Bucket = (Bucket + ProbeAmt++) & (ArraySize-1);
113   }
114 }
115 
116 /// Grow - Allocate a larger backing store for the buckets and move it over.
117 ///
118 void SmallPtrSetImplBase::Grow(unsigned NewSize) {
119   // Allocate at twice as many buckets, but at least 128.
120   unsigned OldSize = CurArraySize;
121 
122   const void **OldBuckets = CurArray;
123   bool WasSmall = isSmall();
124 
125   // Install the new array.  Clear all the buckets to empty.
126   CurArray = (const void**)malloc(sizeof(void*) * NewSize);
127   assert(CurArray && "Failed to allocate memory?");
128   CurArraySize = NewSize;
129   memset(CurArray, -1, NewSize*sizeof(void*));
130 
131   // Copy over all the elements.
132   if (WasSmall) {
133     // Small sets store their elements in order.
134     for (const void **BucketPtr = OldBuckets, **E = OldBuckets+NumElements;
135          BucketPtr != E; ++BucketPtr) {
136       const void *Elt = *BucketPtr;
137       *const_cast<void**>(FindBucketFor(Elt)) = const_cast<void*>(Elt);
138     }
139   } else {
140     // Copy over all valid entries.
141     for (const void **BucketPtr = OldBuckets, **E = OldBuckets+OldSize;
142          BucketPtr != E; ++BucketPtr) {
143       // Copy over the element if it is valid.
144       const void *Elt = *BucketPtr;
145       if (Elt != getTombstoneMarker() && Elt != getEmptyMarker())
146         *const_cast<void**>(FindBucketFor(Elt)) = const_cast<void*>(Elt);
147     }
148 
149     free(OldBuckets);
150     NumTombstones = 0;
151   }
152 }
153 
154 SmallPtrSetImplBase::SmallPtrSetImplBase(const void **SmallStorage,
155                                          const SmallPtrSetImplBase &that) {
156   SmallArray = SmallStorage;
157 
158   // If we're becoming small, prepare to insert into our stack space
159   if (that.isSmall()) {
160     CurArray = SmallArray;
161   // Otherwise, allocate new heap space (unless we were the same size)
162   } else {
163     CurArray = (const void**)malloc(sizeof(void*) * that.CurArraySize);
164     assert(CurArray && "Failed to allocate memory?");
165   }
166 
167   // Copy over the that array.
168   CopyHelper(that);
169 }
170 
171 SmallPtrSetImplBase::SmallPtrSetImplBase(const void **SmallStorage,
172                                          unsigned SmallSize,
173                                          SmallPtrSetImplBase &&that) {
174   SmallArray = SmallStorage;
175   MoveHelper(SmallSize, std::move(that));
176 }
177 
178 void SmallPtrSetImplBase::CopyFrom(const SmallPtrSetImplBase &RHS) {
179   assert(&RHS != this && "Self-copy should be handled by the caller.");
180 
181   if (isSmall() && RHS.isSmall())
182     assert(CurArraySize == RHS.CurArraySize &&
183            "Cannot assign sets with different small sizes");
184 
185   // If we're becoming small, prepare to insert into our stack space
186   if (RHS.isSmall()) {
187     if (!isSmall())
188       free(CurArray);
189     CurArray = SmallArray;
190   // Otherwise, allocate new heap space (unless we were the same size)
191   } else if (CurArraySize != RHS.CurArraySize) {
192     if (isSmall())
193       CurArray = (const void**)malloc(sizeof(void*) * RHS.CurArraySize);
194     else {
195       const void **T = (const void**)realloc(CurArray,
196                                              sizeof(void*) * RHS.CurArraySize);
197       if (!T)
198         free(CurArray);
199       CurArray = T;
200     }
201     assert(CurArray && "Failed to allocate memory?");
202   }
203 
204   CopyHelper(RHS);
205 }
206 
207 void SmallPtrSetImplBase::CopyHelper(const SmallPtrSetImplBase &RHS) {
208   // Copy over the new array size
209   CurArraySize = RHS.CurArraySize;
210 
211   // Copy over the contents from the other set
212   memcpy(CurArray, RHS.CurArray, sizeof(void*)*CurArraySize);
213 
214   NumElements = RHS.NumElements;
215   NumTombstones = RHS.NumTombstones;
216 }
217 
218 void SmallPtrSetImplBase::MoveFrom(unsigned SmallSize,
219                                    SmallPtrSetImplBase &&RHS) {
220   if (!isSmall())
221     free(CurArray);
222   MoveHelper(SmallSize, std::move(RHS));
223 }
224 
225 void SmallPtrSetImplBase::MoveHelper(unsigned SmallSize,
226                                      SmallPtrSetImplBase &&RHS) {
227   assert(&RHS != this && "Self-move should be handled by the caller.");
228 
229   if (RHS.isSmall()) {
230     // Copy a small RHS rather than moving.
231     CurArray = SmallArray;
232     memcpy(CurArray, RHS.CurArray, sizeof(void*)*RHS.CurArraySize);
233   } else {
234     CurArray = RHS.CurArray;
235     RHS.CurArray = RHS.SmallArray;
236   }
237 
238   // Copy the rest of the trivial members.
239   CurArraySize = RHS.CurArraySize;
240   NumElements = RHS.NumElements;
241   NumTombstones = RHS.NumTombstones;
242 
243   // Make the RHS small and empty.
244   RHS.CurArraySize = SmallSize;
245   assert(RHS.CurArray == RHS.SmallArray);
246   RHS.NumElements = 0;
247   RHS.NumTombstones = 0;
248 }
249 
250 void SmallPtrSetImplBase::swap(SmallPtrSetImplBase &RHS) {
251   if (this == &RHS) return;
252 
253   // We can only avoid copying elements if neither set is small.
254   if (!this->isSmall() && !RHS.isSmall()) {
255     std::swap(this->CurArray, RHS.CurArray);
256     std::swap(this->CurArraySize, RHS.CurArraySize);
257     std::swap(this->NumElements, RHS.NumElements);
258     std::swap(this->NumTombstones, RHS.NumTombstones);
259     return;
260   }
261 
262   // FIXME: From here on we assume that both sets have the same small size.
263 
264   // If only RHS is small, copy the small elements into LHS and move the pointer
265   // from LHS to RHS.
266   if (!this->isSmall() && RHS.isSmall()) {
267     std::copy(RHS.SmallArray, RHS.SmallArray+RHS.CurArraySize,
268               this->SmallArray);
269     std::swap(this->NumElements, RHS.NumElements);
270     std::swap(this->CurArraySize, RHS.CurArraySize);
271     RHS.CurArray = this->CurArray;
272     RHS.NumTombstones = this->NumTombstones;
273     this->CurArray = this->SmallArray;
274     this->NumTombstones = 0;
275     return;
276   }
277 
278   // If only LHS is small, copy the small elements into RHS and move the pointer
279   // from RHS to LHS.
280   if (this->isSmall() && !RHS.isSmall()) {
281     std::copy(this->SmallArray, this->SmallArray+this->CurArraySize,
282               RHS.SmallArray);
283     std::swap(RHS.NumElements, this->NumElements);
284     std::swap(RHS.CurArraySize, this->CurArraySize);
285     this->CurArray = RHS.CurArray;
286     this->NumTombstones = RHS.NumTombstones;
287     RHS.CurArray = RHS.SmallArray;
288     RHS.NumTombstones = 0;
289     return;
290   }
291 
292   // Both a small, just swap the small elements.
293   assert(this->isSmall() && RHS.isSmall());
294   assert(this->CurArraySize == RHS.CurArraySize);
295   std::swap_ranges(this->SmallArray, this->SmallArray+this->CurArraySize,
296                    RHS.SmallArray);
297   std::swap(this->NumElements, RHS.NumElements);
298 }
299