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