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   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return size() == 0; }
00077   unsigned size() const { return NumElements; }
00078 
00079   void clear() {
00080     // If the capacity of the array is huge, and the # elements used is small,
00081     // shrink the array.
00082     if (!isSmall() && NumElements*4 < CurArraySize && CurArraySize > 32)
00083       return shrink_and_clear();
00084 
00085     // Fill the array with empty markers.
00086     memset(CurArray, -1, CurArraySize*sizeof(void*));
00087     NumElements = 0;
00088     NumTombstones = 0;
00089   }
00090 
00091 protected:
00092   static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); }
00093   static void *getEmptyMarker() {
00094     // Note that -1 is chosen to make clear() efficiently implementable with
00095     // memset and because it's not a valid pointer value.
00096     return reinterpret_cast<void*>(-1);
00097   }
00098 
00099   /// insert_imp - This returns true if the pointer was new to the set, false if
00100   /// it was already in the set.  This is hidden from the client so that the
00101   /// derived class can check that the right type of pointer is passed in.
00102   bool insert_imp(const void * Ptr);
00103 
00104   /// erase_imp - If the set contains the specified pointer, remove it and
00105   /// return true, otherwise return false.  This is hidden from the client so
00106   /// that the derived class can check that the right type of pointer is passed
00107   /// in.
00108   bool erase_imp(const void * Ptr);
00109 
00110   bool count_imp(const void * Ptr) const {
00111     if (isSmall()) {
00112       // Linear search for the item.
00113       for (const void *const *APtr = SmallArray,
00114                       *const *E = SmallArray+NumElements; APtr != E; ++APtr)
00115         if (*APtr == Ptr)
00116           return true;
00117       return false;
00118     }
00119 
00120     // Big set case.
00121     return *FindBucketFor(Ptr) == Ptr;
00122   }
00123 
00124 private:
00125   bool isSmall() const { return CurArray == SmallArray; }
00126 
00127   const void * const *FindBucketFor(const void *Ptr) const;
00128   void shrink_and_clear();
00129 
00130   /// Grow - Allocate a larger backing store for the buckets and move it over.
00131   void Grow(unsigned NewSize);
00132 
00133   void operator=(const SmallPtrSetImplBase &RHS) LLVM_DELETED_FUNCTION;
00134 protected:
00135   /// swap - Swaps the elements of two sets.
00136   /// Note: This method assumes that both sets have the same small size.
00137   void swap(SmallPtrSetImplBase &RHS);
00138 
00139   void CopyFrom(const SmallPtrSetImplBase &RHS);
00140   void MoveFrom(unsigned SmallSize, SmallPtrSetImplBase &&RHS);
00141 };
00142 
00143 /// SmallPtrSetIteratorImpl - This is the common base class shared between all
00144 /// instances of SmallPtrSetIterator.
00145 class SmallPtrSetIteratorImpl {
00146 protected:
00147   const void *const *Bucket;
00148   const void *const *End;
00149 public:
00150   explicit SmallPtrSetIteratorImpl(const void *const *BP, const void*const *E)
00151     : Bucket(BP), End(E) {
00152       AdvanceIfNotValid();
00153   }
00154 
00155   bool operator==(const SmallPtrSetIteratorImpl &RHS) const {
00156     return Bucket == RHS.Bucket;
00157   }
00158   bool operator!=(const SmallPtrSetIteratorImpl &RHS) const {
00159     return Bucket != RHS.Bucket;
00160   }
00161 
00162 protected:
00163   /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket
00164   /// that is.   This is guaranteed to stop because the end() bucket is marked
00165   /// valid.
00166   void AdvanceIfNotValid() {
00167     assert(Bucket <= End);
00168     while (Bucket != End &&
00169            (*Bucket == SmallPtrSetImplBase::getEmptyMarker() ||
00170             *Bucket == SmallPtrSetImplBase::getTombstoneMarker()))
00171       ++Bucket;
00172   }
00173 };
00174 
00175 /// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
00176 template<typename PtrTy>
00177 class SmallPtrSetIterator : public SmallPtrSetIteratorImpl {
00178   typedef PointerLikeTypeTraits<PtrTy> PtrTraits;
00179   
00180 public:
00181   typedef PtrTy                     value_type;
00182   typedef PtrTy                     reference;
00183   typedef PtrTy                     pointer;
00184   typedef std::ptrdiff_t            difference_type;
00185   typedef std::forward_iterator_tag iterator_category;
00186   
00187   explicit SmallPtrSetIterator(const void *const *BP, const void *const *E)
00188     : SmallPtrSetIteratorImpl(BP, E) {}
00189 
00190   // Most methods provided by baseclass.
00191 
00192   const PtrTy operator*() const {
00193     assert(Bucket < End);
00194     return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket));
00195   }
00196 
00197   inline SmallPtrSetIterator& operator++() {          // Preincrement
00198     ++Bucket;
00199     AdvanceIfNotValid();
00200     return *this;
00201   }
00202 
00203   SmallPtrSetIterator operator++(int) {        // Postincrement
00204     SmallPtrSetIterator tmp = *this; ++*this; return tmp;
00205   }
00206 };
00207 
00208 /// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next
00209 /// power of two (which means N itself if N is already a power of two).
00210 template<unsigned N>
00211 struct RoundUpToPowerOfTwo;
00212 
00213 /// RoundUpToPowerOfTwoH - If N is not a power of two, increase it.  This is a
00214 /// helper template used to implement RoundUpToPowerOfTwo.
00215 template<unsigned N, bool isPowerTwo>
00216 struct RoundUpToPowerOfTwoH {
00217   enum { Val = N };
00218 };
00219 template<unsigned N>
00220 struct RoundUpToPowerOfTwoH<N, false> {
00221   enum {
00222     // We could just use NextVal = N+1, but this converges faster.  N|(N-1) sets
00223     // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111.
00224     Val = RoundUpToPowerOfTwo<(N|(N-1)) + 1>::Val
00225   };
00226 };
00227 
00228 template<unsigned N>
00229 struct RoundUpToPowerOfTwo {
00230   enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val };
00231 };
00232   
00233 
00234 /// \brief A templated base class for \c SmallPtrSet which provides the
00235 /// typesafe interface that is common across all small sizes.
00236 ///
00237 /// This is particularly useful for passing around between interface boundaries
00238 /// to avoid encoding a particular small size in the interface boundary.
00239 template <typename PtrType>
00240 class SmallPtrSetImpl : public SmallPtrSetImplBase {
00241   typedef PointerLikeTypeTraits<PtrType> PtrTraits;
00242 protected:
00243   // Constructors that forward to the base.
00244   SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl &that)
00245       : SmallPtrSetImplBase(SmallStorage, that) {}
00246   SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize,
00247                   SmallPtrSetImpl &&that)
00248       : SmallPtrSetImplBase(SmallStorage, SmallSize, std::move(that)) {}
00249   explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize)
00250       : SmallPtrSetImplBase(SmallStorage, SmallSize) {}
00251 
00252 public:
00253   /// insert - This returns true if the pointer was new to the set, false if it
00254   /// was already in the set.
00255   bool insert(PtrType Ptr) {
00256     return insert_imp(PtrTraits::getAsVoidPointer(Ptr));
00257   }
00258 
00259   /// erase - If the set contains the specified pointer, remove it and return
00260   /// true, otherwise return false.
00261   bool erase(PtrType Ptr) {
00262     return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
00263   }
00264 
00265   /// count - Return 1 if the specified pointer is in the set, 0 otherwise.
00266   unsigned count(PtrType Ptr) const {
00267     return count_imp(PtrTraits::getAsVoidPointer(Ptr)) ? 1 : 0;
00268   }
00269 
00270   template <typename IterT>
00271   void insert(IterT I, IterT E) {
00272     for (; I != E; ++I)
00273       insert(*I);
00274   }
00275 
00276   typedef SmallPtrSetIterator<PtrType> iterator;
00277   typedef SmallPtrSetIterator<PtrType> const_iterator;
00278   inline iterator begin() const {
00279     return iterator(CurArray, CurArray+CurArraySize);
00280   }
00281   inline iterator end() const {
00282     return iterator(CurArray+CurArraySize, CurArray+CurArraySize);
00283   }
00284 };
00285 
00286 /// SmallPtrSet - This class implements a set which is optimized for holding
00287 /// SmallSize or less elements.  This internally rounds up SmallSize to the next
00288 /// power of two if it is not already a power of two.  See the comments above
00289 /// SmallPtrSetImplBase for details of the algorithm.
00290 template<class PtrType, unsigned SmallSize>
00291 class SmallPtrSet : public SmallPtrSetImpl<PtrType> {
00292   typedef SmallPtrSetImpl<PtrType> BaseT;
00293 
00294   // Make sure that SmallSize is a power of two, round up if not.
00295   enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val };
00296   /// SmallStorage - Fixed size storage used in 'small mode'.
00297   const void *SmallStorage[SmallSizePowTwo];
00298 public:
00299   SmallPtrSet() : BaseT(SmallStorage, SmallSizePowTwo) {}
00300   SmallPtrSet(const SmallPtrSet &that) : BaseT(SmallStorage, that) {}
00301   SmallPtrSet(SmallPtrSet &&that)
00302       : BaseT(SmallStorage, SmallSizePowTwo, std::move(that)) {}
00303 
00304   template<typename It>
00305   SmallPtrSet(It I, It E) : BaseT(SmallStorage, SmallSizePowTwo) {
00306     this->insert(I, E);
00307   }
00308 
00309   SmallPtrSet<PtrType, SmallSize> &
00310   operator=(const SmallPtrSet<PtrType, SmallSize> &RHS) {
00311     if (&RHS != this)
00312       this->CopyFrom(RHS);
00313     return *this;
00314   }
00315 
00316   SmallPtrSet<PtrType, SmallSize>&
00317   operator=(SmallPtrSet<PtrType, SmallSize> &&RHS) {
00318     if (&RHS != this)
00319       this->MoveFrom(SmallSizePowTwo, std::move(RHS));
00320     return *this;
00321   }
00322 
00323   /// swap - Swaps the elements of two sets.
00324   void swap(SmallPtrSet<PtrType, SmallSize> &RHS) {
00325     SmallPtrSetImplBase::swap(RHS);
00326   }
00327 };
00328 
00329 }
00330 
00331 namespace std {
00332   /// Implement std::swap in terms of SmallPtrSet swap.
00333   template<class T, unsigned N>
00334   inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &RHS) {
00335     LHS.swap(RHS);
00336   }
00337 }
00338 
00339 #endif