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