SparseMultiSet.h revision 249423
1//===--- llvm/ADT/SparseMultiSet.h - Sparse multiset ------------*- 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 SparseMultiSet class, which adds multiset behavior to
11// the SparseSet.
12//
13// A sparse multiset holds a small number of objects identified by integer keys
14// from a moderately sized universe. The sparse multiset uses more memory than
15// other containers in order to provide faster operations. Any key can map to
16// multiple values. A SparseMultiSetNode class is provided, which serves as a
17// convenient base class for the contents of a SparseMultiSet.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_ADT_SPARSEMULTISET_H
22#define LLVM_ADT_SPARSEMULTISET_H
23
24#include "llvm/ADT/SparseSet.h"
25
26namespace llvm {
27
28/// Fast multiset implementation for objects that can be identified by small
29/// unsigned keys.
30///
31/// SparseMultiSet allocates memory proportional to the size of the key
32/// universe, so it is not recommended for building composite data structures.
33/// It is useful for algorithms that require a single set with fast operations.
34///
35/// Compared to DenseSet and DenseMap, SparseMultiSet provides constant-time
36/// fast clear() as fast as a vector.  The find(), insert(), and erase()
37/// operations are all constant time, and typically faster than a hash table.
38/// The iteration order doesn't depend on numerical key values, it only depends
39/// on the order of insert() and erase() operations.  Iteration order is the
40/// insertion order. Iteration is only provided over elements of equivalent
41/// keys, but iterators are bidirectional.
42///
43/// Compared to BitVector, SparseMultiSet<unsigned> uses 8x-40x more memory, but
44/// offers constant-time clear() and size() operations as well as fast iteration
45/// independent on the size of the universe.
46///
47/// SparseMultiSet contains a dense vector holding all the objects and a sparse
48/// array holding indexes into the dense vector.  Most of the memory is used by
49/// the sparse array which is the size of the key universe. The SparseT template
50/// parameter provides a space/speed tradeoff for sets holding many elements.
51///
52/// When SparseT is uint32_t, find() only touches up to 3 cache lines, but the
53/// sparse array uses 4 x Universe bytes.
54///
55/// When SparseT is uint8_t (the default), find() touches up to 3+[N/256] cache
56/// lines, but the sparse array is 4x smaller.  N is the number of elements in
57/// the set.
58///
59/// For sets that may grow to thousands of elements, SparseT should be set to
60/// uint16_t or uint32_t.
61///
62/// Multiset behavior is provided by providing doubly linked lists for values
63/// that are inlined in the dense vector. SparseMultiSet is a good choice when
64/// one desires a growable number of entries per key, as it will retain the
65/// SparseSet algorithmic properties despite being growable. Thus, it is often a
66/// better choice than a SparseSet of growable containers or a vector of
67/// vectors. SparseMultiSet also keeps iterators valid after erasure (provided
68/// the iterators don't point to the element erased), allowing for more
69/// intuitive and fast removal.
70///
71/// @tparam ValueT      The type of objects in the set.
72/// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
73/// @tparam SparseT     An unsigned integer type. See above.
74///
75template<typename ValueT,
76         typename KeyFunctorT = llvm::identity<unsigned>,
77         typename SparseT = uint8_t>
78class SparseMultiSet {
79  /// The actual data that's stored, as a doubly-linked list implemented via
80  /// indices into the DenseVector.  The doubly linked list is implemented
81  /// circular in Prev indices, and INVALID-terminated in Next indices. This
82  /// provides efficient access to list tails. These nodes can also be
83  /// tombstones, in which case they are actually nodes in a single-linked
84  /// freelist of recyclable slots.
85  struct SMSNode {
86    static const unsigned INVALID = ~0U;
87
88    ValueT Data;
89    unsigned Prev;
90    unsigned Next;
91
92    SMSNode(ValueT D, unsigned P, unsigned N) : Data(D), Prev(P), Next(N) { }
93
94    /// List tails have invalid Nexts.
95    bool isTail() const {
96      return Next == INVALID;
97    }
98
99    /// Whether this node is a tombstone node, and thus is in our freelist.
100    bool isTombstone() const {
101      return Prev == INVALID;
102    }
103
104    /// Since the list is circular in Prev, all non-tombstone nodes have a valid
105    /// Prev.
106    bool isValid() const { return Prev != INVALID; }
107  };
108
109  typedef typename KeyFunctorT::argument_type KeyT;
110  typedef SmallVector<SMSNode, 8> DenseT;
111  DenseT Dense;
112  SparseT *Sparse;
113  unsigned Universe;
114  KeyFunctorT KeyIndexOf;
115  SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
116
117  /// We have a built-in recycler for reusing tombstone slots. This recycler
118  /// puts a singly-linked free list into tombstone slots, allowing us quick
119  /// erasure, iterator preservation, and dense size.
120  unsigned FreelistIdx;
121  unsigned NumFree;
122
123  unsigned sparseIndex(const ValueT &Val) const {
124    assert(ValIndexOf(Val) < Universe &&
125           "Invalid key in set. Did object mutate?");
126    return ValIndexOf(Val);
127  }
128  unsigned sparseIndex(const SMSNode &N) const { return sparseIndex(N.Data); }
129
130  // Disable copy construction and assignment.
131  // This data structure is not meant to be used that way.
132  SparseMultiSet(const SparseMultiSet&) LLVM_DELETED_FUNCTION;
133  SparseMultiSet &operator=(const SparseMultiSet&) LLVM_DELETED_FUNCTION;
134
135  /// Whether the given entry is the head of the list. List heads's previous
136  /// pointers are to the tail of the list, allowing for efficient access to the
137  /// list tail. D must be a valid entry node.
138  bool isHead(const SMSNode &D) const {
139    assert(D.isValid() && "Invalid node for head");
140    return Dense[D.Prev].isTail();
141  }
142
143  /// Whether the given entry is a singleton entry, i.e. the only entry with
144  /// that key.
145  bool isSingleton(const SMSNode &N) const {
146    assert(N.isValid() && "Invalid node for singleton");
147    // Is N its own predecessor?
148    return &Dense[N.Prev] == &N;
149  }
150
151  /// Add in the given SMSNode. Uses a free entry in our freelist if
152  /// available. Returns the index of the added node.
153  unsigned addValue(const ValueT& V, unsigned Prev, unsigned Next) {
154    if (NumFree == 0) {
155      Dense.push_back(SMSNode(V, Prev, Next));
156      return Dense.size() - 1;
157    }
158
159    // Peel off a free slot
160    unsigned Idx = FreelistIdx;
161    unsigned NextFree = Dense[Idx].Next;
162    assert(Dense[Idx].isTombstone() && "Non-tombstone free?");
163
164    Dense[Idx] = SMSNode(V, Prev, Next);
165    FreelistIdx = NextFree;
166    --NumFree;
167    return Idx;
168  }
169
170  /// Make the current index a new tombstone. Pushes it onto the freelist.
171  void makeTombstone(unsigned Idx) {
172    Dense[Idx].Prev = SMSNode::INVALID;
173    Dense[Idx].Next = FreelistIdx;
174    FreelistIdx = Idx;
175    ++NumFree;
176  }
177
178public:
179  typedef ValueT value_type;
180  typedef ValueT &reference;
181  typedef const ValueT &const_reference;
182  typedef ValueT *pointer;
183  typedef const ValueT *const_pointer;
184
185  SparseMultiSet()
186    : Sparse(0), Universe(0), FreelistIdx(SMSNode::INVALID), NumFree(0) { }
187
188  ~SparseMultiSet() { free(Sparse); }
189
190  /// Set the universe size which determines the largest key the set can hold.
191  /// The universe must be sized before any elements can be added.
192  ///
193  /// @param U Universe size. All object keys must be less than U.
194  ///
195  void setUniverse(unsigned U) {
196    // It's not hard to resize the universe on a non-empty set, but it doesn't
197    // seem like a likely use case, so we can add that code when we need it.
198    assert(empty() && "Can only resize universe on an empty map");
199    // Hysteresis prevents needless reallocations.
200    if (U >= Universe/4 && U <= Universe)
201      return;
202    free(Sparse);
203    // The Sparse array doesn't actually need to be initialized, so malloc
204    // would be enough here, but that will cause tools like valgrind to
205    // complain about branching on uninitialized data.
206    Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
207    Universe = U;
208  }
209
210  /// Our iterators are iterators over the collection of objects that share a
211  /// key.
212  template<typename SMSPtrTy>
213  class iterator_base : public std::iterator<std::bidirectional_iterator_tag,
214                                             ValueT> {
215    friend class SparseMultiSet;
216    SMSPtrTy SMS;
217    unsigned Idx;
218    unsigned SparseIdx;
219
220    iterator_base(SMSPtrTy P, unsigned I, unsigned SI)
221      : SMS(P), Idx(I), SparseIdx(SI) { }
222
223    /// Whether our iterator has fallen outside our dense vector.
224    bool isEnd() const {
225      if (Idx == SMSNode::INVALID)
226        return true;
227
228      assert(Idx < SMS->Dense.size() && "Out of range, non-INVALID Idx?");
229      return false;
230    }
231
232    /// Whether our iterator is properly keyed, i.e. the SparseIdx is valid
233    bool isKeyed() const { return SparseIdx < SMS->Universe; }
234
235    unsigned Prev() const { return SMS->Dense[Idx].Prev; }
236    unsigned Next() const { return SMS->Dense[Idx].Next; }
237
238    void setPrev(unsigned P) { SMS->Dense[Idx].Prev = P; }
239    void setNext(unsigned N) { SMS->Dense[Idx].Next = N; }
240
241  public:
242    typedef std::iterator<std::bidirectional_iterator_tag, ValueT> super;
243    typedef typename super::value_type value_type;
244    typedef typename super::difference_type difference_type;
245    typedef typename super::pointer pointer;
246    typedef typename super::reference reference;
247
248    iterator_base(const iterator_base &RHS)
249      : SMS(RHS.SMS), Idx(RHS.Idx), SparseIdx(RHS.SparseIdx) { }
250
251    const iterator_base &operator=(const iterator_base &RHS) {
252      SMS = RHS.SMS;
253      Idx = RHS.Idx;
254      SparseIdx = RHS.SparseIdx;
255      return *this;
256    }
257
258    reference operator*() const {
259      assert(isKeyed() && SMS->sparseIndex(SMS->Dense[Idx].Data) == SparseIdx &&
260             "Dereferencing iterator of invalid key or index");
261
262      return SMS->Dense[Idx].Data;
263    }
264    pointer operator->() const { return &operator*(); }
265
266    /// Comparison operators
267    bool operator==(const iterator_base &RHS) const {
268      // end compares equal
269      if (SMS == RHS.SMS && Idx == RHS.Idx) {
270        assert((isEnd() || SparseIdx == RHS.SparseIdx) &&
271               "Same dense entry, but different keys?");
272        return true;
273      }
274
275      return false;
276    }
277
278    bool operator!=(const iterator_base &RHS) const {
279      return !operator==(RHS);
280    }
281
282    /// Increment and decrement operators
283    iterator_base &operator--() { // predecrement - Back up
284      assert(isKeyed() && "Decrementing an invalid iterator");
285      assert((isEnd() || !SMS->isHead(SMS->Dense[Idx])) &&
286             "Decrementing head of list");
287
288      // If we're at the end, then issue a new find()
289      if (isEnd())
290        Idx = SMS->findIndex(SparseIdx).Prev();
291      else
292        Idx = Prev();
293
294      return *this;
295    }
296    iterator_base &operator++() { // preincrement - Advance
297      assert(!isEnd() && isKeyed() && "Incrementing an invalid/end iterator");
298      Idx = Next();
299      return *this;
300    }
301    iterator_base operator--(int) { // postdecrement
302      iterator_base I(*this);
303      --*this;
304      return I;
305    }
306    iterator_base operator++(int) { // postincrement
307      iterator_base I(*this);
308      ++*this;
309      return I;
310    }
311  };
312  typedef iterator_base<SparseMultiSet *> iterator;
313  typedef iterator_base<const SparseMultiSet *> const_iterator;
314
315  // Convenience types
316  typedef std::pair<iterator, iterator> RangePair;
317
318  /// Returns an iterator past this container. Note that such an iterator cannot
319  /// be decremented, but will compare equal to other end iterators.
320  iterator end() { return iterator(this, SMSNode::INVALID, SMSNode::INVALID); }
321  const_iterator end() const {
322    return const_iterator(this, SMSNode::INVALID, SMSNode::INVALID);
323  }
324
325  /// Returns true if the set is empty.
326  ///
327  /// This is not the same as BitVector::empty().
328  ///
329  bool empty() const { return size() == 0; }
330
331  /// Returns the number of elements in the set.
332  ///
333  /// This is not the same as BitVector::size() which returns the size of the
334  /// universe.
335  ///
336  unsigned size() const {
337    assert(NumFree <= Dense.size() && "Out-of-bounds free entries");
338    return Dense.size() - NumFree;
339  }
340
341  /// Clears the set.  This is a very fast constant time operation.
342  ///
343  void clear() {
344    // Sparse does not need to be cleared, see find().
345    Dense.clear();
346    NumFree = 0;
347    FreelistIdx = SMSNode::INVALID;
348  }
349
350  /// Find an element by its index.
351  ///
352  /// @param   Idx A valid index to find.
353  /// @returns An iterator to the element identified by key, or end().
354  ///
355  iterator findIndex(unsigned Idx) {
356    assert(Idx < Universe && "Key out of range");
357    assert(std::numeric_limits<SparseT>::is_integer &&
358           !std::numeric_limits<SparseT>::is_signed &&
359           "SparseT must be an unsigned integer type");
360    const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
361    for (unsigned i = Sparse[Idx], e = Dense.size(); i < e; i += Stride) {
362      const unsigned FoundIdx = sparseIndex(Dense[i]);
363      // Check that we're pointing at the correct entry and that it is the head
364      // of a valid list.
365      if (Idx == FoundIdx && Dense[i].isValid() && isHead(Dense[i]))
366        return iterator(this, i, Idx);
367      // Stride is 0 when SparseT >= unsigned.  We don't need to loop.
368      if (!Stride)
369        break;
370    }
371    return end();
372  }
373
374  /// Find an element by its key.
375  ///
376  /// @param   Key A valid key to find.
377  /// @returns An iterator to the element identified by key, or end().
378  ///
379  iterator find(const KeyT &Key) {
380    return findIndex(KeyIndexOf(Key));
381  }
382
383  const_iterator find(const KeyT &Key) const {
384    iterator I = const_cast<SparseMultiSet*>(this)->findIndex(KeyIndexOf(Key));
385    return const_iterator(I.SMS, I.Idx, KeyIndexOf(Key));
386  }
387
388  /// Returns the number of elements identified by Key. This will be linear in
389  /// the number of elements of that key.
390  unsigned count(const KeyT &Key) const {
391    unsigned Ret = 0;
392    for (const_iterator It = find(Key); It != end(); ++It)
393      ++Ret;
394
395    return Ret;
396  }
397
398  /// Returns true if this set contains an element identified by Key.
399  bool contains(const KeyT &Key) const {
400    return find(Key) != end();
401  }
402
403  /// Return the head and tail of the subset's list, otherwise returns end().
404  iterator getHead(const KeyT &Key) { return find(Key); }
405  iterator getTail(const KeyT &Key) {
406    iterator I = find(Key);
407    if (I != end())
408      I = iterator(this, I.Prev(), KeyIndexOf(Key));
409    return I;
410  }
411
412  /// The bounds of the range of items sharing Key K. First member is the head
413  /// of the list, and the second member is a decrementable end iterator for
414  /// that key.
415  RangePair equal_range(const KeyT &K) {
416    iterator B = find(K);
417    iterator E = iterator(this, SMSNode::INVALID, B.SparseIdx);
418    return make_pair(B, E);
419  }
420
421  /// Insert a new element at the tail of the subset list. Returns an iterator
422  /// to the newly added entry.
423  iterator insert(const ValueT &Val) {
424    unsigned Idx = sparseIndex(Val);
425    iterator I = findIndex(Idx);
426
427    unsigned NodeIdx = addValue(Val, SMSNode::INVALID, SMSNode::INVALID);
428
429    if (I == end()) {
430      // Make a singleton list
431      Sparse[Idx] = NodeIdx;
432      Dense[NodeIdx].Prev = NodeIdx;
433      return iterator(this, NodeIdx, Idx);
434    }
435
436    // Stick it at the end.
437    unsigned HeadIdx = I.Idx;
438    unsigned TailIdx = I.Prev();
439    Dense[TailIdx].Next = NodeIdx;
440    Dense[HeadIdx].Prev = NodeIdx;
441    Dense[NodeIdx].Prev = TailIdx;
442
443    return iterator(this, NodeIdx, Idx);
444  }
445
446  /// Erases an existing element identified by a valid iterator.
447  ///
448  /// This invalidates iterators pointing at the same entry, but erase() returns
449  /// an iterator pointing to the next element in the subset's list. This makes
450  /// it possible to erase selected elements while iterating over the subset:
451  ///
452  ///   tie(I, E) = Set.equal_range(Key);
453  ///   while (I != E)
454  ///     if (test(*I))
455  ///       I = Set.erase(I);
456  ///     else
457  ///       ++I;
458  ///
459  /// Note that if the last element in the subset list is erased, this will
460  /// return an end iterator which can be decremented to get the new tail (if it
461  /// exists):
462  ///
463  ///  tie(B, I) = Set.equal_range(Key);
464  ///  for (bool isBegin = B == I; !isBegin; /* empty */) {
465  ///    isBegin = (--I) == B;
466  ///    if (test(I))
467  ///      break;
468  ///    I = erase(I);
469  ///  }
470  iterator erase(iterator I) {
471    assert(I.isKeyed() && !I.isEnd() && !Dense[I.Idx].isTombstone() &&
472           "erasing invalid/end/tombstone iterator");
473
474    // First, unlink the node from its list. Then swap the node out with the
475    // dense vector's last entry
476    iterator NextI = unlink(Dense[I.Idx]);
477
478    // Put in a tombstone.
479    makeTombstone(I.Idx);
480
481    return NextI;
482  }
483
484  /// Erase all elements with the given key. This invalidates all
485  /// iterators of that key.
486  void eraseAll(const KeyT &K) {
487    for (iterator I = find(K); I != end(); /* empty */)
488      I = erase(I);
489  }
490
491private:
492  /// Unlink the node from its list. Returns the next node in the list.
493  iterator unlink(const SMSNode &N) {
494    if (isSingleton(N)) {
495      // Singleton is already unlinked
496      assert(N.Next == SMSNode::INVALID && "Singleton has next?");
497      return iterator(this, SMSNode::INVALID, ValIndexOf(N.Data));
498    }
499
500    if (isHead(N)) {
501      // If we're the head, then update the sparse array and our next.
502      Sparse[sparseIndex(N)] = N.Next;
503      Dense[N.Next].Prev = N.Prev;
504      return iterator(this, N.Next, ValIndexOf(N.Data));
505    }
506
507    if (N.isTail()) {
508      // If we're the tail, then update our head and our previous.
509      findIndex(sparseIndex(N)).setPrev(N.Prev);
510      Dense[N.Prev].Next = N.Next;
511
512      // Give back an end iterator that can be decremented
513      iterator I(this, N.Prev, ValIndexOf(N.Data));
514      return ++I;
515    }
516
517    // Otherwise, just drop us
518    Dense[N.Next].Prev = N.Prev;
519    Dense[N.Prev].Next = N.Next;
520    return iterator(this, N.Next, ValIndexOf(N.Data));
521  }
522};
523
524} // end namespace llvm
525
526#endif
527