Fix typos.
[oota-llvm.git] / include / llvm / ADT / SparseSet.h
1 //===--- llvm/ADT/SparseSet.h - Sparse set ----------------------*- C++ -*-===//
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 defines the SparseSet class derived from the version described in
11 // Briggs, Torczon, "An efficient representation for sparse sets", ACM Letters
12 // on Programming Languages and Systems, Volume 2 Issue 1-4, March-Dec.  1993.
13 //
14 // A sparse set holds a small number of objects identified by integer keys from
15 // a moderately sized universe. The sparse set uses more memory than other
16 // containers in order to provide faster operations.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_ADT_SPARSESET_H
21 #define LLVM_ADT_SPARSESET_H
22
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/DataTypes.h"
25 #include <limits>
26
27 namespace llvm {
28
29 /// SparseSetFunctor - Objects in a SparseSet are identified by small integer
30 /// keys.  A functor object is used to compute the key of an object.  The
31 /// functor's operator() must return an unsigned smaller than the universe.
32 ///
33 /// The default functor implementation forwards to a getSparseSetKey() method
34 /// on the object.  It is intended for sparse sets holding ad-hoc structs.
35 ///
36 template<typename ValueT>
37 struct SparseSetFunctor {
38   unsigned operator()(const ValueT &Val) {
39     return Val.getSparseSetKey();
40   }
41 };
42
43 /// SparseSetFunctor<unsigned> - Provide a trivial identity functor for
44 /// SparseSet<unsigned>.
45 ///
46 template<> struct SparseSetFunctor<unsigned> {
47   unsigned operator()(unsigned Val) { return Val; }
48 };
49
50 /// SparseSet - Fast set implementation for objects that can be identified by
51 /// small unsigned keys.
52 ///
53 /// SparseSet allocates memory proportional to the size of the key universe, so
54 /// it is not recommended for building composite data structures.  It is useful
55 /// for algorithms that require a single set with fast operations.
56 ///
57 /// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
58 /// clear() and iteration as fast as a vector.  The find(), insert(), and
59 /// erase() operations are all constant time, and typically faster than a hash
60 /// table.  The iteration order doesn't depend on numerical key values, it only
61 /// depends on the order of insert() and erase() operations.  When no elements
62 /// have been erased, the iteration order is the insertion order.
63 ///
64 /// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
65 /// offers constant-time clear() and size() operations as well as fast
66 /// iteration independent on the size of the universe.
67 ///
68 /// SparseSet contains a dense vector holding all the objects and a sparse
69 /// array holding indexes into the dense vector.  Most of the memory is used by
70 /// the sparse array which is the size of the key universe.  The SparseT
71 /// template parameter provides a space/speed tradeoff for sets holding many
72 /// elements.
73 ///
74 /// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
75 /// array uses 4 x Universe bytes.
76 ///
77 /// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
78 /// lines, but the sparse array is 4x smaller.  N is the number of elements in
79 /// the set.
80 ///
81 /// For sets that may grow to thousands of elements, SparseT should be set to
82 /// uint16_t or uint32_t.
83 ///
84 /// @param ValueT      The type of objects in the set.
85 /// @param SparseT     An unsigned integer type. See above.
86 /// @param KeyFunctorT A functor that computes the unsigned key of a ValueT.
87 ///
88 template<typename ValueT,
89          typename SparseT = uint8_t,
90          typename KeyFunctorT = SparseSetFunctor<ValueT> >
91 class SparseSet {
92   typedef SmallVector<ValueT, 8> DenseT;
93   DenseT Dense;
94   SparseT *Sparse;
95   unsigned Universe;
96   KeyFunctorT KeyOf;
97
98   // Disable copy construction and assignment.
99   // This data structure is not meant to be used that way.
100   SparseSet(const SparseSet&); // DO NOT IMPLEMENT.
101   SparseSet &operator=(const SparseSet&); // DO NOT IMPLEMENT.
102
103 public:
104   typedef ValueT value_type;
105   typedef ValueT &reference;
106   typedef const ValueT &const_reference;
107   typedef ValueT *pointer;
108   typedef const ValueT *const_pointer;
109
110   SparseSet() : Sparse(0), Universe(0) {}
111   ~SparseSet() { free(Sparse); }
112
113   /// setUniverse - Set the universe size which determines the largest key the
114   /// set can hold.  The universe must be sized before any elements can be
115   /// added.
116   ///
117   /// @param U Universe size. All object keys must be less than U.
118   ///
119   void setUniverse(unsigned U) {
120     // It's not hard to resize the universe on a non-empty set, but it doesn't
121     // seem like a likely use case, so we can add that code when we need it.
122     assert(empty() && "Can only resize universe on an empty map");
123     // Hysteresis prevents needless reallocations.
124     if (U >= Universe/4 && U <= Universe)
125       return;
126     free(Sparse);
127     // The Sparse array doesn't actually need to be initialized, so malloc
128     // would be enough here, but that will cause tools like valgrind to
129     // complain about branching on uninitialized data.
130     Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
131     Universe = U;
132   }
133
134   // Import trivial vector stuff from DenseT.
135   typedef typename DenseT::iterator iterator;
136   typedef typename DenseT::const_iterator const_iterator;
137
138   const_iterator begin() const { return Dense.begin(); }
139   const_iterator end() const { return Dense.end(); }
140   iterator begin() { return Dense.begin(); }
141   iterator end() { return Dense.end(); }
142
143   /// empty - Returns true if the set is empty.
144   ///
145   /// This is not the same as BitVector::empty().
146   ///
147   bool empty() const { return Dense.empty(); }
148
149   /// size - Returns the number of elements in the set.
150   ///
151   /// This is not the same as BitVector::size() which returns the size of the
152   /// universe.
153   ///
154   unsigned size() const { return Dense.size(); }
155
156   /// clear - Clears the set.  This is a very fast constant time operation.
157   ///
158   void clear() {
159     // Sparse does not need to be cleared, see find().
160     Dense.clear();
161   }
162
163   /// find - Find an element by its key.
164   ///
165   /// @param   Key A valid key to find.
166   /// @returns An iterator to the element identified by key, or end().
167   ///
168   iterator find(unsigned Key) {
169     assert(Key < Universe && "Key out of range");
170     assert(std::numeric_limits<SparseT>::is_integer &&
171            !std::numeric_limits<SparseT>::is_signed &&
172            "SparseT must be an unsigned integer type");
173     const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
174     for (unsigned i = Sparse[Key], e = size(); i < e; i += Stride) {
175       const unsigned FoundKey = KeyOf(Dense[i]);
176       assert(FoundKey < Universe && "Invalid key in set. Did object mutate?");
177       if (Key == FoundKey)
178         return begin() + i;
179       // Stride is 0 when SparseT >= unsigned.  We don't need to loop.
180       if (!Stride)
181         break;
182     }
183     return end();
184   }
185
186   const_iterator find(unsigned Key) const {
187     return const_cast<SparseSet*>(this)->find(Key);
188   }
189
190   /// count - Returns true if this set contains an element identified by Key.
191   ///
192   bool count(unsigned Key) const {
193     return find(Key) != end();
194   }
195
196   /// insert - Attempts to insert a new element.
197   ///
198   /// If Val is successfully inserted, return (I, true), where I is an iterator
199   /// pointing to the newly inserted element.
200   ///
201   /// If the set already contains an element with the same key as Val, return
202   /// (I, false), where I is an iterator pointing to the existing element.
203   ///
204   /// Insertion invalidates all iterators.
205   ///
206   std::pair<iterator, bool> insert(const ValueT &Val) {
207     unsigned Key = KeyOf(Val);
208     iterator I = find(Key);
209     if (I != end())
210       return std::make_pair(I, false);
211     Sparse[Key] = size();
212     Dense.push_back(Val);
213     return std::make_pair(end() - 1, true);
214   }
215
216   /// erase - Erases an existing element identified by a valid iterator.
217   ///
218   /// This invalidates all iterators, but erase() returns an iterator pointing
219   /// to the next element.  This makes it possible to erase selected elements
220   /// while iterating over the set:
221   ///
222   ///   for (SparseSet::iterator I = Set.begin(); I != Set.end();)
223   ///     if (test(*I))
224   ///       I = Set.erase(I);
225   ///     else
226   ///       ++I;
227   ///
228   /// Note that end() changes when elements are erased, unlike std::list.
229   ///
230   iterator erase(iterator I) {
231     assert(I - begin() < size() && "Invalid iterator");
232     if (I != end() - 1) {
233       *I = Dense.back();
234       unsigned BackKey = KeyOf(Dense.back());
235       assert(BackKey < Universe && "Invalid key in set. Did object mutate?");
236       Sparse[BackKey] = I - begin();
237     }
238     // This depends on SmallVector::pop_back() not invalidating iterators.
239     // std::vector::pop_back() doesn't give that guarantee.
240     Dense.pop_back();
241     return I;
242   }
243
244   /// erase - Erases an element identified by Key, if it exists.
245   ///
246   /// @param   Key The key identifying the element to erase.
247   /// @returns True when an element was erased, false if no element was found.
248   ///
249   bool erase(unsigned Key) {
250     iterator I = find(Key);
251     if (I == end())
252       return false;
253     erase(I);
254     return true;
255   }
256
257 };
258
259 } // end namespace llvm
260
261 #endif