LLVM API Documentation

SmallPtrSet.h
Go to the documentation of this file.
00001 //===- llvm/ADT/SmallPtrSet.h - 'Normally small' pointer 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 defines the SmallPtrSet class.  See the doxygen comment for
00011 // SmallPtrSetImplBase for more details on the algorithm used.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_ADT_SMALLPTRSET_H
00016 #define LLVM_ADT_SMALLPTRSET_H
00017 
00018 #include "llvm/Support/Compiler.h"
00019 #include "llvm/Support/DataTypes.h"
00020 #include "llvm/Support/PointerLikeTypeTraits.h"
00021 #include <cassert>
00022 #include <cstddef>
00023 #include <cstring>
00024 #include <iterator>
00025 
00026 namespace llvm {
00027 
00028 class SmallPtrSetIteratorImpl;
00029 
00030 /// SmallPtrSetImplBase - This is the common code shared among all the
00031 /// SmallPtrSet<>'s, which is almost everything.  SmallPtrSet has two modes, one
00032 /// for small and one for large sets.
00033 ///
00034 /// Small sets use an array of pointers allocated in the SmallPtrSet object,
00035 /// which is treated as a simple array of pointers.  When a pointer is added to
00036 /// the set, the array is scanned to see if the element already exists, if not
00037 /// the element is 'pushed back' onto the array.  If we run out of space in the
00038 /// array, we grow into the 'large set' case.  SmallSet should be used when the
00039 /// sets are often small.  In this case, no memory allocation is used, and only
00040 /// light-weight and cache-efficient scanning is used.
00041 ///
00042 /// Large sets use a classic exponentially-probed hash table.  Empty buckets are
00043 /// represented with an illegal pointer value (-1) to allow null pointers to be
00044 /// inserted.  Tombstones are represented with another illegal pointer value
00045 /// (-2), to allow deletion.  The hash table is resized when the table is 3/4 or
00046 /// more.  When this happens, the table is doubled in size.
00047 ///
00048 class SmallPtrSetImplBase {
00049   friend class SmallPtrSetIteratorImpl;
00050 protected:
00051   /// SmallArray - Points to a fixed size set of buckets, used in 'small mode'.
00052   const void **SmallArray;
00053   /// CurArray - This is the current set of buckets.  If equal to SmallArray,
00054   /// then the set is in 'small mode'.
00055   const void **CurArray;
00056   /// CurArraySize - The allocated size of CurArray, always a power of two.
00057   unsigned CurArraySize;
00058 
00059   // If small, this is # elts allocated consecutively
00060   unsigned NumElements;
00061   unsigned NumTombstones;
00062 
00063   // Helpers to copy and move construct a SmallPtrSet.
00064   SmallPtrSetImplBase(const void **SmallStorage, const SmallPtrSetImplBase &that);
00065   SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize,
00066                   SmallPtrSetImplBase &&that);
00067   explicit SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize) :
00068     SmallArray(SmallStorage), CurArray(SmallStorage), CurArraySize(SmallSize) {
00069     assert(SmallSize && (SmallSize & (SmallSize-1)) == 0 &&
00070            "Initial size must be a power of two!");
00071     clear();
00072   }
00073   ~SmallPtrSetImplBase();
00074 
00075 public:
00076   typedef unsigned size_type;
00077   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return size() == 0; }
00078   size_type size() const { return NumElements; }
00079 
00080   void clear() {
00081     // If the capacity of the array is huge, and the # elements used is small,
00082     // shrink the array.
00083     if (!isSmall() && NumElements*4 < CurArraySize && CurArraySize > 32)
00084       return shrink_and_clear();
00085 
00086     // Fill the array with empty markers.
00087     memset(CurArray, -1, CurArraySize*sizeof(void*));
00088     NumElements = 0;
00089     NumTombstones = 0;
00090   }
00091 
00092 protected:
00093   static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); }
00094   static void *getEmptyMarker() {
00095     // Note that -1 is chosen to make clear() efficiently implementable with
00096     // memset and because it's not a valid pointer value.
00097     return reinterpret_cast<void*>(-1);
00098   }
00099 
00100   /// insert_imp - This returns true if the pointer was new to the set, false if
00101   /// it was already in the set.  This is hidden from the client so that the
00102   /// derived class can check that the right type of pointer is passed in.
00103   bool insert_imp(const void * Ptr);
00104 
00105   /// erase_imp - If the set contains the specified pointer, remove it and
00106   /// return true, otherwise return false.  This is hidden from the client so
00107   /// that the derived class can check that the right type of pointer is passed
00108   /// in.
00109   bool erase_imp(const void * Ptr);
00110 
00111   bool count_imp(const void * Ptr) const {
00112     if (isSmall()) {
00113       // Linear search for the item.
00114       for (const void *const *APtr = SmallArray,
00115                       *const *E = SmallArray+NumElements; APtr != E; ++APtr)
00116         if (*APtr == Ptr)
00117           return true;
00118       return false;
00119     }
00120 
00121     // Big set case.
00122     return *FindBucketFor(Ptr) == Ptr;
00123   }
00124 
00125 private:
00126   bool isSmall() const { return CurArray == SmallArray; }
00127 
00128   const void * const *FindBucketFor(const void *Ptr) const;
00129   void shrink_and_clear();
00130 
00131   /// Grow - Allocate a larger backing store for the buckets and move it over.
00132   void Grow(unsigned NewSize);
00133 
00134   void operator=(const SmallPtrSetImplBase &RHS) LLVM_DELETED_FUNCTION;
00135 protected:
00136   /// swap - Swaps the elements of two sets.
00137   /// Note: This method assumes that both sets have the same small size.
00138   void swap(SmallPtrSetImplBase &RHS);
00139 
00140   void CopyFrom(const SmallPtrSetImplBase &RHS);
00141   void MoveFrom(unsigned SmallSize, SmallPtrSetImplBase &&RHS);
00142 };
00143 
00144 /// SmallPtrSetIteratorImpl - This is the common base class shared between all
00145 /// instances of SmallPtrSetIterator.
00146 class SmallPtrSetIteratorImpl {
00147 protected:
00148   const void *const *Bucket;
00149   const void *const *End;
00150 public:
00151   explicit SmallPtrSetIteratorImpl(const void *const *BP, const void*const *E)
00152     : Bucket(BP), End(E) {
00153       AdvanceIfNotValid();
00154   }
00155 
00156   bool operator==(const SmallPtrSetIteratorImpl &RHS) const {
00157     return Bucket == RHS.Bucket;
00158   }
00159   bool operator!=(const SmallPtrSetIteratorImpl &RHS) const {
00160     return Bucket != RHS.Bucket;
00161   }
00162 
00163 protected:
00164   /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket
00165   /// that is.   This is guaranteed to stop because the end() bucket is marked
00166   /// valid.
00167   void AdvanceIfNotValid() {
00168     assert(Bucket <= End);
00169     while (Bucket != End &&
00170            (*Bucket == SmallPtrSetImplBase::getEmptyMarker() ||
00171             *Bucket == SmallPtrSetImplBase::getTombstoneMarker()))
00172       ++Bucket;
00173   }
00174 };
00175 
00176 /// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
00177 template<typename PtrTy>
00178 class SmallPtrSetIterator : public SmallPtrSetIteratorImpl {
00179   typedef PointerLikeTypeTraits<PtrTy> PtrTraits;
00180   
00181 public:
00182   typedef PtrTy                     value_type;
00183   typedef PtrTy                     reference;
00184   typedef PtrTy                     pointer;
00185   typedef std::ptrdiff_t            difference_type;
00186   typedef std::forward_iterator_tag iterator_category;
00187   
00188   explicit SmallPtrSetIterator(const void *const *BP, const void *const *E)
00189     : SmallPtrSetIteratorImpl(BP, E) {}
00190 
00191   // Most methods provided by baseclass.
00192 
00193   const PtrTy operator*() const {
00194     assert(Bucket < End);
00195     return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket));
00196   }
00197 
00198   inline SmallPtrSetIterator& operator++() {          // Preincrement
00199     ++Bucket;
00200     AdvanceIfNotValid();
00201     return *this;
00202   }
00203 
00204   SmallPtrSetIterator operator++(int) {        // Postincrement
00205     SmallPtrSetIterator tmp = *this; ++*this; return tmp;
00206   }
00207 };
00208 
00209 /// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next
00210 /// power of two (which means N itself if N is already a power of two).
00211 template<unsigned N>
00212 struct RoundUpToPowerOfTwo;
00213 
00214 /// RoundUpToPowerOfTwoH - If N is not a power of two, increase it.  This is a
00215 /// helper template used to implement RoundUpToPowerOfTwo.
00216 template<unsigned N, bool isPowerTwo>
00217 struct RoundUpToPowerOfTwoH {
00218   enum { Val = N };
00219 };
00220 template<unsigned N>
00221 struct RoundUpToPowerOfTwoH<N, false> {
00222   enum {
00223     // We could just use NextVal = N+1, but this converges faster.  N|(N-1) sets
00224     // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111.
00225     Val = RoundUpToPowerOfTwo<(N|(N-1)) + 1>::Val
00226   };
00227 };
00228 
00229 template<unsigned N>
00230 struct RoundUpToPowerOfTwo {
00231   enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val };
00232 };
00233   
00234 
00235 /// \brief A templated base class for \c SmallPtrSet which provides the
00236 /// typesafe interface that is common across all small sizes.
00237 ///
00238 /// This is particularly useful for passing around between interface boundaries
00239 /// to avoid encoding a particular small size in the interface boundary.
00240 template <typename PtrType>
00241 class SmallPtrSetImpl : public SmallPtrSetImplBase {
00242   typedef PointerLikeTypeTraits<PtrType> PtrTraits;
00243 protected:
00244   // Constructors that forward to the base.
00245   SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl &that)
00246       : SmallPtrSetImplBase(SmallStorage, that) {}
00247   SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize,
00248                   SmallPtrSetImpl &&that)
00249       : SmallPtrSetImplBase(SmallStorage, SmallSize, std::move(that)) {}
00250   explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize)
00251       : SmallPtrSetImplBase(SmallStorage, SmallSize) {}
00252 
00253 public:
00254   /// insert - This returns true if the pointer was new to the set, false if it
00255   /// was already in the set.
00256   bool insert(PtrType Ptr) {
00257     return insert_imp(PtrTraits::getAsVoidPointer(Ptr));
00258   }
00259 
00260   /// erase - If the set contains the specified pointer, remove it and return
00261   /// true, otherwise return false.
00262   bool erase(PtrType Ptr) {
00263     return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
00264   }
00265 
00266   /// count - Return 1 if the specified pointer is in the set, 0 otherwise.
00267   size_type count(PtrType Ptr) const {
00268     return count_imp(PtrTraits::getAsVoidPointer(Ptr)) ? 1 : 0;
00269   }
00270 
00271   template <typename IterT>
00272   void insert(IterT I, IterT E) {
00273     for (; I != E; ++I)
00274       insert(*I);
00275   }
00276 
00277   typedef SmallPtrSetIterator<PtrType> iterator;
00278   typedef SmallPtrSetIterator<PtrType> const_iterator;
00279   inline iterator begin() const {
00280     return iterator(CurArray, CurArray+CurArraySize);
00281   }
00282   inline iterator end() const {
00283     return iterator(CurArray+CurArraySize, CurArray+CurArraySize);
00284   }
00285 };
00286 
00287 /// SmallPtrSet - This class implements a set which is optimized for holding
00288 /// SmallSize or less elements.  This internally rounds up SmallSize to the next
00289 /// power of two if it is not already a power of two.  See the comments above
00290 /// SmallPtrSetImplBase for details of the algorithm.
00291 template<class PtrType, unsigned SmallSize>
00292 class SmallPtrSet : public SmallPtrSetImpl<PtrType> {
00293   typedef SmallPtrSetImpl<PtrType> BaseT;
00294 
00295   // Make sure that SmallSize is a power of two, round up if not.
00296   enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val };
00297   /// SmallStorage - Fixed size storage used in 'small mode'.
00298   const void *SmallStorage[SmallSizePowTwo];
00299 public:
00300   SmallPtrSet() : BaseT(SmallStorage, SmallSizePowTwo) {}
00301   SmallPtrSet(const SmallPtrSet &that) : BaseT(SmallStorage, that) {}
00302   SmallPtrSet(SmallPtrSet &&that)
00303       : BaseT(SmallStorage, SmallSizePowTwo, std::move(that)) {}
00304 
00305   template<typename It>
00306   SmallPtrSet(It I, It E) : BaseT(SmallStorage, SmallSizePowTwo) {
00307     this->insert(I, E);
00308   }
00309 
00310   SmallPtrSet<PtrType, SmallSize> &
00311   operator=(const SmallPtrSet<PtrType, SmallSize> &RHS) {
00312     if (&RHS != this)
00313       this->CopyFrom(RHS);
00314     return *this;
00315   }
00316 
00317   SmallPtrSet<PtrType, SmallSize>&
00318   operator=(SmallPtrSet<PtrType, SmallSize> &&RHS) {
00319     if (&RHS != this)
00320       this->MoveFrom(SmallSizePowTwo, std::move(RHS));
00321     return *this;
00322   }
00323 
00324   /// swap - Swaps the elements of two sets.
00325   void swap(SmallPtrSet<PtrType, SmallSize> &RHS) {
00326     SmallPtrSetImplBase::swap(RHS);
00327   }
00328 };
00329 
00330 }
00331 
00332 namespace std {
00333   /// Implement std::swap in terms of SmallPtrSet swap.
00334   template<class T, unsigned N>
00335   inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &RHS) {
00336     LHS.swap(RHS);
00337   }
00338 }
00339 
00340 #endif