LLVM 20.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
23#include "llvm/ADT/identity.h"
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>
58 static unsigned getValIndex(const ValueT &Val) {
59 return Val.getSparseSetIndex();
60 }
61};
62
63/// SparseSetValFunctor - Helper class for selecting SparseSetValTraits. The
64/// generic implementation handles ValueT classes which either provide
65/// getSparseSetIndex() or specialize SparseSetValTraits<>.
66///
67template<typename KeyT, typename ValueT, typename KeyFunctorT>
69 unsigned operator()(const ValueT &Val) const {
71 }
72};
73
74/// SparseSetValFunctor<KeyT, KeyT> - Helper class for the common case of
75/// identity key/value sets.
76template<typename KeyT, typename KeyFunctorT>
77struct SparseSetValFunctor<KeyT, KeyT, KeyFunctorT> {
78 unsigned operator()(const KeyT &Key) const {
79 return KeyFunctorT()(Key);
80 }
81};
82
83/// SparseSet - Fast set implementation for objects that can be identified by
84/// small unsigned keys.
85///
86/// SparseSet allocates memory proportional to the size of the key universe, so
87/// it is not recommended for building composite data structures. It is useful
88/// for algorithms that require a single set with fast operations.
89///
90/// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
91/// clear() and iteration as fast as a vector. The find(), insert(), and
92/// erase() operations are all constant time, and typically faster than a hash
93/// table. The iteration order doesn't depend on numerical key values, it only
94/// depends on the order of insert() and erase() operations. When no elements
95/// have been erased, the iteration order is the insertion order.
96///
97/// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
98/// offers constant-time clear() and size() operations as well as fast
99/// iteration independent on the size of the universe.
100///
101/// SparseSet contains a dense vector holding all the objects and a sparse
102/// array holding indexes into the dense vector. Most of the memory is used by
103/// the sparse array which is the size of the key universe. The SparseT
104/// template parameter provides a space/speed tradeoff for sets holding many
105/// elements.
106///
107/// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
108/// array uses 4 x Universe bytes.
109///
110/// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
111/// lines, but the sparse array is 4x smaller. N is the number of elements in
112/// the set.
113///
114/// For sets that may grow to thousands of elements, SparseT should be set to
115/// uint16_t or uint32_t.
116///
117/// @tparam ValueT The type of objects in the set.
118/// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
119/// @tparam SparseT An unsigned integer type. See above.
120///
121template<typename ValueT,
122 typename KeyFunctorT = identity<unsigned>,
123 typename SparseT = uint8_t>
125 static_assert(std::is_unsigned_v<SparseT>,
126 "SparseT must be an unsigned integer type");
127
128 using KeyT = typename KeyFunctorT::argument_type;
130 using size_type = unsigned;
131 DenseT Dense;
132
133 struct Deleter {
134 void operator()(SparseT *S) { free(S); }
135 };
136 std::unique_ptr<SparseT[], Deleter> Sparse;
137
138 unsigned Universe = 0;
139 KeyFunctorT KeyIndexOf;
141
142public:
144 using reference = ValueT &;
145 using const_reference = const ValueT &;
146 using pointer = ValueT *;
147 using const_pointer = const ValueT *;
148
149 SparseSet() = default;
150 SparseSet(const SparseSet &) = delete;
151 SparseSet &operator=(const SparseSet &) = delete;
152 SparseSet(SparseSet &&) = default;
153
154 /// setUniverse - Set the universe size which determines the largest key the
155 /// set can hold. The universe must be sized before any elements can be
156 /// added.
157 ///
158 /// @param U Universe size. All object keys must be less than U.
159 ///
160 void setUniverse(unsigned U) {
161 // It's not hard to resize the universe on a non-empty set, but it doesn't
162 // seem like a likely use case, so we can add that code when we need it.
163 assert(empty() && "Can only resize universe on an empty map");
164 // Hysteresis prevents needless reallocations.
165 if (U >= Universe/4 && U <= Universe)
166 return;
167 // The Sparse array doesn't actually need to be initialized, so malloc
168 // would be enough here, but that will cause tools like valgrind to
169 // complain about branching on uninitialized data.
170 Sparse.reset(static_cast<SparseT *>(safe_calloc(U, sizeof(SparseT))));
171 Universe = U;
172 }
173
174 // Import trivial vector stuff from DenseT.
175 using iterator = typename DenseT::iterator;
177
178 const_iterator begin() const { return Dense.begin(); }
179 const_iterator end() const { return Dense.end(); }
180 iterator begin() { return Dense.begin(); }
181 iterator end() { return Dense.end(); }
182
183 /// empty - Returns true if the set is empty.
184 ///
185 /// This is not the same as BitVector::empty().
186 ///
187 bool empty() const { return Dense.empty(); }
188
189 /// size - Returns the number of elements in the set.
190 ///
191 /// This is not the same as BitVector::size() which returns the size of the
192 /// universe.
193 ///
194 size_type size() const { return Dense.size(); }
195
196 /// clear - Clears the set. This is a very fast constant time operation.
197 ///
198 void clear() {
199 // Sparse does not need to be cleared, see find().
200 Dense.clear();
201 }
202
203 /// findIndex - Find an element by its index.
204 ///
205 /// @param Idx A valid index to find.
206 /// @returns An iterator to the element identified by key, or end().
207 ///
209 assert(Idx < Universe && "Key out of range");
210 assert(Sparse != nullptr && "Invalid sparse type");
211 const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
212 for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
213 const unsigned FoundIdx = ValIndexOf(Dense[i]);
214 assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
215 if (Idx == FoundIdx)
216 return begin() + i;
217 // Stride is 0 when SparseT >= unsigned. We don't need to loop.
218 if (!Stride)
219 break;
220 }
221 return end();
222 }
223
224 /// find - Find an element by its key.
225 ///
226 /// @param Key A valid key to find.
227 /// @returns An iterator to the element identified by key, or end().
228 ///
229 iterator find(const KeyT &Key) {
230 return findIndex(KeyIndexOf(Key));
231 }
232
233 const_iterator find(const KeyT &Key) const {
234 return const_cast<SparseSet*>(this)->findIndex(KeyIndexOf(Key));
235 }
236
237 /// Check if the set contains the given \c Key.
238 ///
239 /// @param Key A valid key to find.
240 bool contains(const KeyT &Key) const { return find(Key) != end(); }
241
242 /// count - Returns 1 if this set contains an element identified by Key,
243 /// 0 otherwise.
244 ///
245 size_type count(const KeyT &Key) const { return contains(Key) ? 1 : 0; }
246
247 /// insert - Attempts to insert a new element.
248 ///
249 /// If Val is successfully inserted, return (I, true), where I is an iterator
250 /// pointing to the newly inserted element.
251 ///
252 /// If the set already contains an element with the same key as Val, return
253 /// (I, false), where I is an iterator pointing to the existing element.
254 ///
255 /// Insertion invalidates all iterators.
256 ///
257 std::pair<iterator, bool> insert(const ValueT &Val) {
258 unsigned Idx = ValIndexOf(Val);
260 if (I != end())
261 return std::make_pair(I, false);
262 Sparse[Idx] = size();
263 Dense.push_back(Val);
264 return std::make_pair(end() - 1, true);
265 }
266
267 /// array subscript - If an element already exists with this key, return it.
268 /// Otherwise, automatically construct a new value from Key, insert it,
269 /// and return the newly inserted element.
270 ValueT &operator[](const KeyT &Key) {
271 return *insert(ValueT(Key)).first;
272 }
273
275 // Sparse does not need to be cleared, see find().
276 return Dense.pop_back_val();
277 }
278
279 /// erase - Erases an existing element identified by a valid iterator.
280 ///
281 /// This invalidates all iterators, but erase() returns an iterator pointing
282 /// to the next element. This makes it possible to erase selected elements
283 /// while iterating over the set:
284 ///
285 /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
286 /// if (test(*I))
287 /// I = Set.erase(I);
288 /// else
289 /// ++I;
290 ///
291 /// Note that end() changes when elements are erased, unlike std::list.
292 ///
294 assert(unsigned(I - begin()) < size() && "Invalid iterator");
295 if (I != end() - 1) {
296 *I = Dense.back();
297 unsigned BackIdx = ValIndexOf(Dense.back());
298 assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
299 Sparse[BackIdx] = I - begin();
300 }
301 // This depends on SmallVector::pop_back() not invalidating iterators.
302 // std::vector::pop_back() doesn't give that guarantee.
303 Dense.pop_back();
304 return I;
305 }
306
307 /// erase - Erases an element identified by Key, if it exists.
308 ///
309 /// @param Key The key identifying the element to erase.
310 /// @returns True when an element was erased, false if no element was found.
311 ///
312 bool erase(const KeyT &Key) {
313 iterator I = find(Key);
314 if (I == end())
315 return false;
316 erase(I);
317 return true;
318 }
319};
320
321} // end namespace llvm
322
323#endif // LLVM_ADT_SPARSESET_H
This file defines MallocAllocator.
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
SparseSet - Fast set implementation for objects that can be identified by small unsigned keys.
Definition: SparseSet.h:124
size_type size() const
size - Returns the number of elements in the set.
Definition: SparseSet.h:194
iterator findIndex(unsigned Idx)
findIndex - Find an element by its index.
Definition: SparseSet.h:208
SparseSet & operator=(const SparseSet &)=delete
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
Definition: SparseSet.h:293
const_iterator find(const KeyT &Key) const
Definition: SparseSet.h:233
SparseSet(SparseSet &&)=default
typename DenseT::iterator iterator
Definition: SparseSet.h:175
bool empty() const
empty - Returns true if the set is empty.
Definition: SparseSet.h:187
size_type count(const KeyT &Key) const
count - Returns 1 if this set contains an element identified by Key, 0 otherwise.
Definition: SparseSet.h:245
ValueT pop_back_val()
Definition: SparseSet.h:274
void clear()
clear - Clears the set.
Definition: SparseSet.h:198
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition: SparseSet.h:257
iterator begin()
Definition: SparseSet.h:180
SparseSet(const SparseSet &)=delete
const_iterator begin() const
Definition: SparseSet.h:178
const_iterator end() const
Definition: SparseSet.h:179
ValueT & operator[](const KeyT &Key)
array subscript - If an element already exists with this key, return it.
Definition: SparseSet.h:270
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
Definition: SparseSet.h:160
bool erase(const KeyT &Key)
erase - Erases an element identified by Key, if it exists.
Definition: SparseSet.h:312
typename DenseT::const_iterator const_iterator
Definition: SparseSet.h:176
SparseSet()=default
bool contains(const KeyT &Key) const
Check if the set contains the given Key.
Definition: SparseSet.h:240
iterator find(const KeyT &Key)
find - Find an element by its key.
Definition: SparseSet.h:229
iterator end()
Definition: SparseSet.h:181
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_calloc(size_t Count, size_t Sz)
Definition: MemAlloc.h:38
unsigned operator()(const KeyT &Key) const
Definition: SparseSet.h:78
SparseSetValFunctor - Helper class for selecting SparseSetValTraits.
Definition: SparseSet.h:68
unsigned operator()(const ValueT &Val) const
Definition: SparseSet.h:69
SparseSetValTraits - Objects in a SparseSet are identified by keys that can be uniquely converted to ...
Definition: SparseSet.h:57
static unsigned getValIndex(const ValueT &Val)
Definition: SparseSet.h:58