SparseSet.h 12 KB

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