1 //===--- llvm/ADT/SparseSet.h - Sparse set ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_ADT_SPARSESET_H
21 #define LLVM_ADT_SPARSESET_H
23 #include "llvm/ADT/SmallVector.h"
27 /// SparseSetFunctor - Objects in a SparseSet are identified by small integer
28 /// keys. A functor object is used to compute the key of an object. The
29 /// functor's operator() must return an unsigned smaller than the universe.
31 /// The default functor implementation forwards to a getSparseSetKey() method
32 /// on the object. It is intended for sparse sets holding ad-hoc structs.
34 template<typename ValueT>
35 struct SparseSetFunctor {
36 unsigned operator()(const ValueT &Val) {
37 return Val.getSparseSetKey();
41 /// SparseSetFunctor<unsigned> - Provide a trivial identity functor for
42 /// SparseSet<unsigned>.
44 template<> struct SparseSetFunctor<unsigned> {
45 unsigned operator()(unsigned Val) { return Val; }
48 /// SparseSet - Fast set implementation for objects that can be identified by
49 /// small unsigned keys.
51 /// SparseSet allocates memory proportional to the size of the key universe, so
52 /// it is not recommended for building composite data structures. It is useful
53 /// for algorithms that require a single set with fast operations.
55 /// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
56 /// clear() and iteration as fast as a vector. The find(), insert(), and
57 /// erase() operations are all constant time, and typically faster than a hash
58 /// table. The iteration order doesn't depend on numerical key values, it only
59 /// depends on the order of insert() and erase() operations. When no elements
60 /// have been erased, the iteration order is the insertion order.
62 /// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
63 /// offers constant-time clear() and size() operations as well as fast
64 /// iteration independent on the size of the universe.
66 /// SparseSet contains a dense vector holding all the objects and a sparse
67 /// array holding indexes into the dense vector. Most of the memory is used by
68 /// the sparse array which is the size of the key universe. The SparseT
69 /// template parameter provides a space/speed tradeoff for sets holding many
72 /// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
73 /// array uses 4 x Universe bytes.
75 /// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
76 /// lines, but the sparse array is 4x smaller. N is the number of elements in
79 /// For sets that may grow to thousands of elements, SparseT should be set to
80 /// uint16_t or uint32_t.
82 /// @param ValueT The type of objects in the set.
83 /// @param SparseT An unsigned integer type. See above.
84 /// @param KeyFunctorT A functor that computes the unsigned key of a ValueT.
86 template<typename ValueT,
87 typename SparseT = uint8_t,
88 typename KeyFunctorT = SparseSetFunctor<ValueT> >
90 typedef SmallVector<ValueT, 8> DenseT;
96 // Disable copy construction and assignment.
97 // This data structure is not meant to be used that way.
98 SparseSet(const SparseSet&); // DO NOT IMPLEMENT.
99 SparseSet &operator=(const SparseSet&); // DO NOT IMPLEMENT.
102 typedef ValueT value_type;
103 typedef ValueT &reference;
104 typedef const ValueT &const_reference;
105 typedef ValueT *pointer;
106 typedef const ValueT *const_pointer;
108 SparseSet() : Sparse(0), Universe(0) {}
109 ~SparseSet() { free(Sparse); }
111 /// setUniverse - Set the universe size which determines the largest key the
112 /// set can hold. The universe must be sized before any elements can be
115 /// @param U Universe size. All object keys must be less than U.
117 void setUniverse(unsigned U) {
118 // It's not hard to resize the universe on a non-empty set, but it doesn't
119 // seem like a likely use case, so we can add that code when we need it.
120 assert(empty() && "Can only resize universe on an empty map");
121 // Hysteresis prevents needless reallocations.
122 if (U >= Universe/4 && U <= Universe)
125 // The Sparse array doesn't actually need to be initialized, so malloc
126 // would be enough here, but that will cause tools like valgrind to
127 // complain about branching on uninitialized data.
128 Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
132 // Import trivial vector stuff from DenseT.
133 typedef typename DenseT::iterator iterator;
134 typedef typename DenseT::const_iterator const_iterator;
136 const_iterator begin() const { return Dense.begin(); }
137 const_iterator end() const { return Dense.end(); }
138 iterator begin() { return Dense.begin(); }
139 iterator end() { return Dense.end(); }
141 /// empty - Returns true if the set is empty.
143 /// This is not the same as BitVector::empty().
145 bool empty() const { return Dense.empty(); }
147 /// size - Returns the number of elements in the set.
149 /// This is not the same as BitVector::size() which returns the size of the
152 unsigned size() const { return Dense.size(); }
154 /// clear - Clears the set. This is a very fast constant time operation.
157 // Sparse does not need to be cleared, see find().
161 /// find - Find an element by its key.
163 /// @param Key A valid key to find.
164 /// @returns An iterator to the element identified by key, or end().
166 iterator find(unsigned Key) {
167 assert(Key < Universe && "Key out of range");
168 assert(std::numeric_limits<SparseT>::is_integer &&
169 !std::numeric_limits<SparseT>::is_signed &&
170 "SparseT must be an unsigned integer type");
171 const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
172 for (unsigned i = Sparse[Key], e = size(); i < e; i += Stride) {
173 const unsigned FoundKey = KeyOf(Dense[i]);
174 assert(FoundKey < Universe && "Invalid key in set. Did object mutate?");
177 // Stride is 0 when SparseT >= unsigned. We don't need to loop.
184 const_iterator find(unsigned Key) const {
185 return const_cast<SparseSet*>(this)->find(Key);
188 /// count - Returns true if this set contains an element identified by Key.
190 bool count(unsigned Key) const {
191 return find(Key) != end();
194 /// insert - Attempts to insert a new element.
196 /// If Val is successfully inserted, return (I, true), where I is an iterator
197 /// pointing to the newly inserted element.
199 /// If the set already contains an element with the same key as Val, return
200 /// (I, false), where I is an iterator pointing to the existing element.
202 /// Insertion invalidates all iterators.
204 std::pair<iterator, bool> insert(const ValueT &Val) {
205 unsigned Key = KeyOf(Val);
206 iterator I = find(Key);
208 return std::make_pair(I, false);
209 Sparse[Key] = size();
210 Dense.push_back(Val);
211 return std::make_pair(end() - 1, true);
214 /// erase - Erases an existing element identified by a valid iterator.
216 /// This invalidates all iterators, but erase() returns an iterator pointing
217 /// to the next element. This makes it possible to erase selected elements
218 /// while iterating over the set:
220 /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
222 /// I = Set.erase(I);
226 /// Note that end() changes when elements are erased, unlike std::list.
228 iterator erase(iterator I) {
229 assert(I - begin() < size() && "Invalid iterator");
230 if (I != end() - 1) {
232 unsigned BackKey = KeyOf(Dense.back());
233 assert(BackKey < Universe && "Invalid key in set. Did object mutate?");
234 Sparse[BackKey] = I - begin();
236 // This depends on SmallVector::pop_back() not invalidating iterators.
237 // std::vector::pop_back() doesn't give that guarantee.
242 /// erase - Erases an element identified by Key, if it exists.
244 /// @param Key The key identifying the element to erase.
245 /// @returns True when an element was erased, false if no element was found.
247 bool erase(unsigned Key) {
248 iterator I = find(Key);
257 } // end namespace llvm