LLVM 22.0.0git
SparseSet.h
Go to the documentation of this file.
1//===- llvm/ADT/SparseSet.h - Sparse set ------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
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
26#include <cassert>
27#include <cstdint>
28#include <cstdlib>
29#include <limits>
30#include <utility>
31
32namespace llvm {
33
34/// SparseSetValTraits - Objects in a SparseSet are identified by keys that can
35/// be uniquely converted to a small integer less than the set's universe. This
36/// class allows the set to hold values that differ from the set's key type as
37/// long as an index can still be derived from the value. SparseSet never
38/// directly compares ValueT, only their indices, so it can map keys to
39/// arbitrary values. SparseSetValTraits computes the index from the value
40/// object. To compute the index from a key, SparseSet uses a separate
41/// KeyFunctorT template argument.
42///
43/// A simple type declaration, SparseSet<Type>, handles these cases:
44/// - unsigned key, identity index, identity value
45/// - unsigned key, identity index, fat value providing getSparseSetIndex()
46///
47/// The type declaration SparseSet<Type, UnaryFunction> handles:
48/// - unsigned key, remapped index, identity value (virtual registers)
49/// - pointer key, pointer-derived index, identity value (node+ID)
50/// - pointer key, pointer-derived index, fat value with getSparseSetIndex()
51///
52/// Only other, unexpected cases require specializing SparseSetValTraits.
53///
54/// For best results, ValueT should not require a destructor.
55///
56template <typename ValueT> struct SparseSetValTraits {
57 static unsigned getValIndex(const ValueT &Val) {
58 return Val.getSparseSetIndex();
59 }
60};
61
62/// SparseSetValFunctor - Helper class for getting a value's index.
63///
64/// In the generic case, this is done via SparseSetValTraits. When the value
65/// type is the same as the key type, the KeyFunctor is used directly.
66template <typename KeyT, typename ValueT, typename KeyFunctorT>
68 unsigned operator()(const ValueT &Val) const {
69 if constexpr (std::is_same_v<KeyT, ValueT>)
70 return KeyFunctorT()(Val);
71 else
73 }
74};
75
76/// SparseSet - Fast set implementation for objects that can be identified by
77/// small unsigned keys.
78///
79/// SparseSet allocates memory proportional to the size of the key universe, so
80/// it is not recommended for building composite data structures. It is useful
81/// for algorithms that require a single set with fast operations.
82///
83/// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
84/// clear() and iteration as fast as a vector. The find(), insert(), and
85/// erase() operations are all constant time, and typically faster than a hash
86/// table. The iteration order doesn't depend on numerical key values, it only
87/// depends on the order of insert() and erase() operations. When no elements
88/// have been erased, the iteration order is the insertion order.
89///
90/// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
91/// offers constant-time clear() and size() operations as well as fast
92/// iteration independent on the size of the universe.
93///
94/// SparseSet contains a dense vector holding all the objects and a sparse
95/// array holding indexes into the dense vector. Most of the memory is used by
96/// the sparse array which is the size of the key universe. The SparseT
97/// template parameter provides a space/speed tradeoff for sets holding many
98/// elements.
99///
100/// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
101/// array uses 4 x Universe bytes.
102///
103/// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
104/// lines, but the sparse array is 4x smaller. N is the number of elements in
105/// the set.
106///
107/// For sets that may grow to thousands of elements, SparseT should be set to
108/// uint16_t or uint32_t.
109///
110/// @tparam ValueT The type of objects in the set.
111/// @tparam KeyT The type of the key, which is passed to the key functor.
112/// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
113/// @tparam SparseT An unsigned integer type. See above.
114///
115template <typename ValueT, typename KeyT = unsigned,
116 typename KeyFunctorT = identity, typename SparseT = uint8_t>
118 static_assert(std::is_unsigned_v<SparseT>,
119 "SparseT must be an unsigned integer type");
120
121 using DenseT = SmallVector<ValueT, 8>;
122 using size_type = unsigned;
123 DenseT Dense;
124
125 struct Deleter {
126 void operator()(SparseT *S) { free(S); }
127 };
128 std::unique_ptr<SparseT[], Deleter> Sparse;
129
130 unsigned Universe = 0;
131 KeyFunctorT KeyIndexOf;
133
134public:
135 using value_type = ValueT;
136 using reference = ValueT &;
137 using const_reference = const ValueT &;
138 using pointer = ValueT *;
139 using const_pointer = const ValueT *;
140
141 SparseSet() = default;
142 SparseSet(const SparseSet &) = delete;
143 SparseSet &operator=(const SparseSet &) = delete;
144 SparseSet(SparseSet &&) = default;
145
146 /// setUniverse - Set the universe size which determines the largest key the
147 /// set can hold. The universe must be sized before any elements can be
148 /// added.
149 ///
150 /// @param U Universe size. All object keys must be less than U.
151 ///
152 void setUniverse(unsigned U) {
153 // It's not hard to resize the universe on a non-empty set, but it doesn't
154 // seem like a likely use case, so we can add that code when we need it.
155 assert(empty() && "Can only resize universe on an empty map");
156 // Hysteresis prevents needless reallocations.
157 if (U >= Universe / 4 && U <= Universe)
158 return;
159 // The Sparse array doesn't actually need to be initialized, so malloc
160 // would be enough here, but that will cause tools like valgrind to
161 // complain about branching on uninitialized data.
162 Sparse.reset(static_cast<SparseT *>(safe_calloc(U, sizeof(SparseT))));
163 Universe = U;
164 }
165
166 // Import trivial vector stuff from DenseT.
167 using iterator = typename DenseT::iterator;
169
170 [[nodiscard]] const_iterator begin() const { return Dense.begin(); }
171 [[nodiscard]] const_iterator end() const { return Dense.end(); }
172 [[nodiscard]] iterator begin() { return Dense.begin(); }
173 [[nodiscard]] iterator end() { return Dense.end(); }
174
175 /// empty - Returns true if the set is empty.
176 ///
177 /// This is not the same as BitVector::empty().
178 ///
179 [[nodiscard]] bool empty() const { return Dense.empty(); }
180
181 /// size - Returns the number of elements in the set.
182 ///
183 /// This is not the same as BitVector::size() which returns the size of the
184 /// universe.
185 ///
186 [[nodiscard]] size_type size() const { return Dense.size(); }
187
188 /// clear - Clears the set. This is a very fast constant time operation.
189 ///
190 void clear() {
191 // Sparse does not need to be cleared, see find().
192 Dense.clear();
193 }
194
195 /// findIndex - Find an element by its index.
196 ///
197 /// @param Idx A valid index to find.
198 /// @returns An iterator to the element identified by key, or end().
199 ///
200 iterator findIndex(unsigned Idx) {
201 assert(Idx < Universe && "Key out of range");
202 assert(Sparse != nullptr && "Invalid sparse type");
203 const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
204 for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
205 const unsigned FoundIdx = ValIndexOf(Dense[i]);
206 assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
207 if (Idx == FoundIdx)
208 return begin() + i;
209 // Stride is 0 when SparseT >= unsigned. We don't need to loop.
210 if (!Stride)
211 break;
212 }
213 return end();
214 }
215
216 /// find - Find an element by its key.
217 ///
218 /// @param Key A valid key to find.
219 /// @returns An iterator to the element identified by key, or end().
220 ///
221 [[nodiscard]] iterator find(const KeyT &Key) {
222 return findIndex(KeyIndexOf(Key));
223 }
224
225 [[nodiscard]] const_iterator find(const KeyT &Key) const {
226 return const_cast<SparseSet *>(this)->findIndex(KeyIndexOf(Key));
227 }
228
229 /// Check if the set contains the given \c Key.
230 ///
231 /// @param Key A valid key to find.
232 [[nodiscard]] bool contains(const KeyT &Key) const {
233 return find(Key) != end();
234 }
235
236 /// count - Returns 1 if this set contains an element identified by Key,
237 /// 0 otherwise.
238 ///
239 [[nodiscard]] size_type count(const KeyT &Key) const {
240 return contains(Key) ? 1 : 0;
241 }
242
243 /// insert - Attempts to insert a new element.
244 ///
245 /// If Val is successfully inserted, return (I, true), where I is an iterator
246 /// pointing to the newly inserted element.
247 ///
248 /// If the set already contains an element with the same key as Val, return
249 /// (I, false), where I is an iterator pointing to the existing element.
250 ///
251 /// Insertion invalidates all iterators.
252 ///
253 std::pair<iterator, bool> insert(const ValueT &Val) {
254 unsigned Idx = ValIndexOf(Val);
255 iterator I = findIndex(Idx);
256 if (I != end())
257 return {I, false};
258 Sparse[Idx] = size();
259 Dense.push_back(Val);
260 return {end() - 1, true};
261 }
262
263 /// array subscript - If an element already exists with this key, return it.
264 /// Otherwise, automatically construct a new value from Key, insert it,
265 /// and return the newly inserted element.
266 ValueT &operator[](const KeyT &Key) { return *insert(ValueT(Key)).first; }
267
268 ValueT pop_back_val() {
269 // Sparse does not need to be cleared, see find().
270 return Dense.pop_back_val();
271 }
272
273 /// erase - Erases an existing element identified by a valid iterator.
274 ///
275 /// This invalidates all iterators, but erase() returns an iterator pointing
276 /// to the next element. This makes it possible to erase selected elements
277 /// while iterating over the set:
278 ///
279 /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
280 /// if (test(*I))
281 /// I = Set.erase(I);
282 /// else
283 /// ++I;
284 ///
285 /// Note that end() changes when elements are erased, unlike std::list.
286 ///
288 assert(unsigned(I - begin()) < size() && "Invalid iterator");
289 if (I != end() - 1) {
290 *I = Dense.back();
291 unsigned BackIdx = ValIndexOf(Dense.back());
292 assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
293 Sparse[BackIdx] = I - begin();
294 }
295 // This depends on SmallVector::pop_back() not invalidating iterators.
296 // std::vector::pop_back() doesn't give that guarantee.
297 Dense.pop_back();
298 return I;
299 }
300
301 /// erase - Erases an element identified by Key, if it exists.
302 ///
303 /// @param Key The key identifying the element to erase.
304 /// @returns True when an element was erased, false if no element was found.
305 ///
306 bool erase(const KeyT &Key) {
307 iterator I = find(Key);
308 if (I == end())
309 return false;
310 erase(I);
311 return true;
312 }
313};
314
315} // namespace llvm
316
317#endif // LLVM_ADT_SPARSESET_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines MallocAllocator.
#define I(x, y, z)
Definition MD5.cpp:58
This file contains library features backported from future STL versions.
This file defines the SmallVector class.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
Definition SparseSet.h:287
ValueT & operator[](const KeyT &Key)
array subscript - If an element already exists with this key, return it.
Definition SparseSet.h:266
SparseSet & operator=(const SparseSet &)=delete
void clear()
clear - Clears the set.
Definition SparseSet.h:190
const_iterator begin() const
Definition SparseSet.h:170
ValueT value_type
Definition SparseSet.h:135
iterator findIndex(unsigned Idx)
findIndex - Find an element by its index.
Definition SparseSet.h:200
SparseSet(const SparseSet &)=delete
typename DenseT::const_iterator const_iterator
Definition SparseSet.h:168
const_iterator end() const
Definition SparseSet.h:171
bool erase(const KeyT &Key)
erase - Erases an element identified by Key, if it exists.
Definition SparseSet.h:306
typename DenseT::iterator iterator
Definition SparseSet.h:167
ValueT * pointer
Definition SparseSet.h:138
size_type size() const
size - Returns the number of elements in the set.
Definition SparseSet.h:186
const_iterator find(const KeyT &Key) const
Definition SparseSet.h:225
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition SparseSet.h:253
ValueT & reference
Definition SparseSet.h:136
iterator begin()
Definition SparseSet.h:172
ValueT pop_back_val()
Definition SparseSet.h:268
iterator end()
Definition SparseSet.h:173
SparseSet(SparseSet &&)=default
size_type count(const KeyT &Key) const
count - Returns 1 if this set contains an element identified by Key, 0 otherwise.
Definition SparseSet.h:239
const ValueT * const_pointer
Definition SparseSet.h:139
SparseSet()=default
const ValueT & const_reference
Definition SparseSet.h:137
iterator find(const KeyT &Key)
find - Find an element by its key.
Definition SparseSet.h:221
bool contains(const KeyT &Key) const
Check if the set contains the given Key.
Definition SparseSet.h:232
bool empty() const
empty - Returns true if the set is empty.
Definition SparseSet.h:179
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
Definition SparseSet.h:152
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_calloc(size_t Count, size_t Sz)
Definition MemAlloc.h:38
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
SparseSetValFunctor - Helper class for getting a value's index.
Definition SparseSet.h:67
unsigned operator()(const ValueT &Val) const
Definition SparseSet.h:68
SparseSetValTraits - Objects in a SparseSet are identified by keys that can be uniquely converted to ...
Definition SparseSet.h:56
static unsigned getValIndex(const ValueT &Val)
Definition SparseSet.h:57