109467b48Spatrick //===- llvm/ADT/SparseMultiSet.h - Sparse multiset --------------*- C++ -*-===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
8*d415bd75Srobert ///
9*d415bd75Srobert /// \file
10*d415bd75Srobert /// This file defines the SparseMultiSet class, which adds multiset behavior to
11*d415bd75Srobert /// the SparseSet.
12*d415bd75Srobert ///
13*d415bd75Srobert /// A sparse multiset holds a small number of objects identified by integer keys
14*d415bd75Srobert /// from a moderately sized universe. The sparse multiset uses more memory than
15*d415bd75Srobert /// other containers in order to provide faster operations. Any key can map to
16*d415bd75Srobert /// multiple values. A SparseMultiSetNode class is provided, which serves as a
17*d415bd75Srobert /// convenient base class for the contents of a SparseMultiSet.
18*d415bd75Srobert ///
1909467b48Spatrick //===----------------------------------------------------------------------===//
2009467b48Spatrick 
2109467b48Spatrick #ifndef LLVM_ADT_SPARSEMULTISET_H
2209467b48Spatrick #define LLVM_ADT_SPARSEMULTISET_H
2309467b48Spatrick 
24*d415bd75Srobert #include "llvm/ADT/identity.h"
2509467b48Spatrick #include "llvm/ADT/SmallVector.h"
2609467b48Spatrick #include "llvm/ADT/SparseSet.h"
2709467b48Spatrick #include <cassert>
2809467b48Spatrick #include <cstdint>
2909467b48Spatrick #include <cstdlib>
3009467b48Spatrick #include <iterator>
3109467b48Spatrick #include <limits>
3209467b48Spatrick #include <utility>
3309467b48Spatrick 
3409467b48Spatrick namespace llvm {
3509467b48Spatrick 
3609467b48Spatrick /// Fast multiset implementation for objects that can be identified by small
3709467b48Spatrick /// unsigned keys.
3809467b48Spatrick ///
3909467b48Spatrick /// SparseMultiSet allocates memory proportional to the size of the key
4009467b48Spatrick /// universe, so it is not recommended for building composite data structures.
4109467b48Spatrick /// It is useful for algorithms that require a single set with fast operations.
4209467b48Spatrick ///
4309467b48Spatrick /// Compared to DenseSet and DenseMap, SparseMultiSet provides constant-time
4409467b48Spatrick /// fast clear() as fast as a vector.  The find(), insert(), and erase()
4509467b48Spatrick /// operations are all constant time, and typically faster than a hash table.
4609467b48Spatrick /// The iteration order doesn't depend on numerical key values, it only depends
4709467b48Spatrick /// on the order of insert() and erase() operations.  Iteration order is the
4809467b48Spatrick /// insertion order. Iteration is only provided over elements of equivalent
4909467b48Spatrick /// keys, but iterators are bidirectional.
5009467b48Spatrick ///
5109467b48Spatrick /// Compared to BitVector, SparseMultiSet<unsigned> uses 8x-40x more memory, but
5209467b48Spatrick /// offers constant-time clear() and size() operations as well as fast iteration
5309467b48Spatrick /// independent on the size of the universe.
5409467b48Spatrick ///
5509467b48Spatrick /// SparseMultiSet contains a dense vector holding all the objects and a sparse
5609467b48Spatrick /// array holding indexes into the dense vector.  Most of the memory is used by
5709467b48Spatrick /// the sparse array which is the size of the key universe. The SparseT template
5809467b48Spatrick /// parameter provides a space/speed tradeoff for sets holding many elements.
5909467b48Spatrick ///
6009467b48Spatrick /// When SparseT is uint32_t, find() only touches up to 3 cache lines, but the
6109467b48Spatrick /// sparse array uses 4 x Universe bytes.
6209467b48Spatrick ///
6309467b48Spatrick /// When SparseT is uint8_t (the default), find() touches up to 3+[N/256] cache
6409467b48Spatrick /// lines, but the sparse array is 4x smaller.  N is the number of elements in
6509467b48Spatrick /// the set.
6609467b48Spatrick ///
6709467b48Spatrick /// For sets that may grow to thousands of elements, SparseT should be set to
6809467b48Spatrick /// uint16_t or uint32_t.
6909467b48Spatrick ///
7009467b48Spatrick /// Multiset behavior is provided by providing doubly linked lists for values
7109467b48Spatrick /// that are inlined in the dense vector. SparseMultiSet is a good choice when
7209467b48Spatrick /// one desires a growable number of entries per key, as it will retain the
7309467b48Spatrick /// SparseSet algorithmic properties despite being growable. Thus, it is often a
7409467b48Spatrick /// better choice than a SparseSet of growable containers or a vector of
7509467b48Spatrick /// vectors. SparseMultiSet also keeps iterators valid after erasure (provided
7609467b48Spatrick /// the iterators don't point to the element erased), allowing for more
7709467b48Spatrick /// intuitive and fast removal.
7809467b48Spatrick ///
7909467b48Spatrick /// @tparam ValueT      The type of objects in the set.
8009467b48Spatrick /// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
8109467b48Spatrick /// @tparam SparseT     An unsigned integer type. See above.
8209467b48Spatrick ///
8309467b48Spatrick template<typename ValueT,
8409467b48Spatrick          typename KeyFunctorT = identity<unsigned>,
8509467b48Spatrick          typename SparseT = uint8_t>
8609467b48Spatrick class SparseMultiSet {
87*d415bd75Srobert   static_assert(std::is_unsigned_v<SparseT>,
8809467b48Spatrick                 "SparseT must be an unsigned integer type");
8909467b48Spatrick 
9009467b48Spatrick   /// The actual data that's stored, as a doubly-linked list implemented via
9109467b48Spatrick   /// indices into the DenseVector.  The doubly linked list is implemented
9209467b48Spatrick   /// circular in Prev indices, and INVALID-terminated in Next indices. This
9309467b48Spatrick   /// provides efficient access to list tails. These nodes can also be
9409467b48Spatrick   /// tombstones, in which case they are actually nodes in a single-linked
9509467b48Spatrick   /// freelist of recyclable slots.
9609467b48Spatrick   struct SMSNode {
97097a140dSpatrick     static constexpr unsigned INVALID = ~0U;
9809467b48Spatrick 
9909467b48Spatrick     ValueT Data;
10009467b48Spatrick     unsigned Prev;
10109467b48Spatrick     unsigned Next;
10209467b48Spatrick 
SMSNodeSMSNode10309467b48Spatrick     SMSNode(ValueT D, unsigned P, unsigned N) : Data(D), Prev(P), Next(N) {}
10409467b48Spatrick 
10509467b48Spatrick     /// List tails have invalid Nexts.
isTailSMSNode10609467b48Spatrick     bool isTail() const {
10709467b48Spatrick       return Next == INVALID;
10809467b48Spatrick     }
10909467b48Spatrick 
11009467b48Spatrick     /// Whether this node is a tombstone node, and thus is in our freelist.
isTombstoneSMSNode11109467b48Spatrick     bool isTombstone() const {
11209467b48Spatrick       return Prev == INVALID;
11309467b48Spatrick     }
11409467b48Spatrick 
11509467b48Spatrick     /// Since the list is circular in Prev, all non-tombstone nodes have a valid
11609467b48Spatrick     /// Prev.
isValidSMSNode11709467b48Spatrick     bool isValid() const { return Prev != INVALID; }
11809467b48Spatrick   };
11909467b48Spatrick 
12009467b48Spatrick   using KeyT = typename KeyFunctorT::argument_type;
12109467b48Spatrick   using DenseT = SmallVector<SMSNode, 8>;
12209467b48Spatrick   DenseT Dense;
12309467b48Spatrick   SparseT *Sparse = nullptr;
12409467b48Spatrick   unsigned Universe = 0;
12509467b48Spatrick   KeyFunctorT KeyIndexOf;
12609467b48Spatrick   SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
12709467b48Spatrick 
12809467b48Spatrick   /// We have a built-in recycler for reusing tombstone slots. This recycler
12909467b48Spatrick   /// puts a singly-linked free list into tombstone slots, allowing us quick
13009467b48Spatrick   /// erasure, iterator preservation, and dense size.
13109467b48Spatrick   unsigned FreelistIdx = SMSNode::INVALID;
13209467b48Spatrick   unsigned NumFree = 0;
13309467b48Spatrick 
sparseIndex(const ValueT & Val)13409467b48Spatrick   unsigned sparseIndex(const ValueT &Val) const {
13509467b48Spatrick     assert(ValIndexOf(Val) < Universe &&
13609467b48Spatrick            "Invalid key in set. Did object mutate?");
13709467b48Spatrick     return ValIndexOf(Val);
13809467b48Spatrick   }
sparseIndex(const SMSNode & N)13909467b48Spatrick   unsigned sparseIndex(const SMSNode &N) const { return sparseIndex(N.Data); }
14009467b48Spatrick 
14109467b48Spatrick   /// Whether the given entry is the head of the list. List heads's previous
14209467b48Spatrick   /// pointers are to the tail of the list, allowing for efficient access to the
14309467b48Spatrick   /// list tail. D must be a valid entry node.
isHead(const SMSNode & D)14409467b48Spatrick   bool isHead(const SMSNode &D) const {
14509467b48Spatrick     assert(D.isValid() && "Invalid node for head");
14609467b48Spatrick     return Dense[D.Prev].isTail();
14709467b48Spatrick   }
14809467b48Spatrick 
14909467b48Spatrick   /// Whether the given entry is a singleton entry, i.e. the only entry with
15009467b48Spatrick   /// that key.
isSingleton(const SMSNode & N)15109467b48Spatrick   bool isSingleton(const SMSNode &N) const {
15209467b48Spatrick     assert(N.isValid() && "Invalid node for singleton");
15309467b48Spatrick     // Is N its own predecessor?
15409467b48Spatrick     return &Dense[N.Prev] == &N;
15509467b48Spatrick   }
15609467b48Spatrick 
15709467b48Spatrick   /// Add in the given SMSNode. Uses a free entry in our freelist if
15809467b48Spatrick   /// available. Returns the index of the added node.
addValue(const ValueT & V,unsigned Prev,unsigned Next)15909467b48Spatrick   unsigned addValue(const ValueT& V, unsigned Prev, unsigned Next) {
16009467b48Spatrick     if (NumFree == 0) {
16109467b48Spatrick       Dense.push_back(SMSNode(V, Prev, Next));
16209467b48Spatrick       return Dense.size() - 1;
16309467b48Spatrick     }
16409467b48Spatrick 
16509467b48Spatrick     // Peel off a free slot
16609467b48Spatrick     unsigned Idx = FreelistIdx;
16709467b48Spatrick     unsigned NextFree = Dense[Idx].Next;
16809467b48Spatrick     assert(Dense[Idx].isTombstone() && "Non-tombstone free?");
16909467b48Spatrick 
17009467b48Spatrick     Dense[Idx] = SMSNode(V, Prev, Next);
17109467b48Spatrick     FreelistIdx = NextFree;
17209467b48Spatrick     --NumFree;
17309467b48Spatrick     return Idx;
17409467b48Spatrick   }
17509467b48Spatrick 
17609467b48Spatrick   /// Make the current index a new tombstone. Pushes it onto the freelist.
makeTombstone(unsigned Idx)17709467b48Spatrick   void makeTombstone(unsigned Idx) {
17809467b48Spatrick     Dense[Idx].Prev = SMSNode::INVALID;
17909467b48Spatrick     Dense[Idx].Next = FreelistIdx;
18009467b48Spatrick     FreelistIdx = Idx;
18109467b48Spatrick     ++NumFree;
18209467b48Spatrick   }
18309467b48Spatrick 
18409467b48Spatrick public:
18509467b48Spatrick   using value_type = ValueT;
18609467b48Spatrick   using reference = ValueT &;
18709467b48Spatrick   using const_reference = const ValueT &;
18809467b48Spatrick   using pointer = ValueT *;
18909467b48Spatrick   using const_pointer = const ValueT *;
19009467b48Spatrick   using size_type = unsigned;
19109467b48Spatrick 
19209467b48Spatrick   SparseMultiSet() = default;
19309467b48Spatrick   SparseMultiSet(const SparseMultiSet &) = delete;
19409467b48Spatrick   SparseMultiSet &operator=(const SparseMultiSet &) = delete;
~SparseMultiSet()19509467b48Spatrick   ~SparseMultiSet() { free(Sparse); }
19609467b48Spatrick 
19709467b48Spatrick   /// Set the universe size which determines the largest key the set can hold.
19809467b48Spatrick   /// The universe must be sized before any elements can be added.
19909467b48Spatrick   ///
20009467b48Spatrick   /// @param U Universe size. All object keys must be less than U.
20109467b48Spatrick   ///
setUniverse(unsigned U)20209467b48Spatrick   void setUniverse(unsigned U) {
20309467b48Spatrick     // It's not hard to resize the universe on a non-empty set, but it doesn't
20409467b48Spatrick     // seem like a likely use case, so we can add that code when we need it.
20509467b48Spatrick     assert(empty() && "Can only resize universe on an empty map");
20609467b48Spatrick     // Hysteresis prevents needless reallocations.
20709467b48Spatrick     if (U >= Universe/4 && U <= Universe)
20809467b48Spatrick       return;
20909467b48Spatrick     free(Sparse);
21009467b48Spatrick     // The Sparse array doesn't actually need to be initialized, so malloc
21109467b48Spatrick     // would be enough here, but that will cause tools like valgrind to
21209467b48Spatrick     // complain about branching on uninitialized data.
21309467b48Spatrick     Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
21409467b48Spatrick     Universe = U;
21509467b48Spatrick   }
21609467b48Spatrick 
21709467b48Spatrick   /// Our iterators are iterators over the collection of objects that share a
21809467b48Spatrick   /// key.
21973471bf0Spatrick   template <typename SMSPtrTy> class iterator_base {
22009467b48Spatrick     friend class SparseMultiSet;
22109467b48Spatrick 
22273471bf0Spatrick   public:
22373471bf0Spatrick     using iterator_category = std::bidirectional_iterator_tag;
22473471bf0Spatrick     using value_type = ValueT;
22573471bf0Spatrick     using difference_type = std::ptrdiff_t;
22673471bf0Spatrick     using pointer = value_type *;
22773471bf0Spatrick     using reference = value_type &;
22873471bf0Spatrick 
22973471bf0Spatrick   private:
23009467b48Spatrick     SMSPtrTy SMS;
23109467b48Spatrick     unsigned Idx;
23209467b48Spatrick     unsigned SparseIdx;
23309467b48Spatrick 
iterator_base(SMSPtrTy P,unsigned I,unsigned SI)23409467b48Spatrick     iterator_base(SMSPtrTy P, unsigned I, unsigned SI)
23509467b48Spatrick       : SMS(P), Idx(I), SparseIdx(SI) {}
23609467b48Spatrick 
23709467b48Spatrick     /// Whether our iterator has fallen outside our dense vector.
isEnd()23809467b48Spatrick     bool isEnd() const {
23909467b48Spatrick       if (Idx == SMSNode::INVALID)
24009467b48Spatrick         return true;
24109467b48Spatrick 
24209467b48Spatrick       assert(Idx < SMS->Dense.size() && "Out of range, non-INVALID Idx?");
24309467b48Spatrick       return false;
24409467b48Spatrick     }
24509467b48Spatrick 
24609467b48Spatrick     /// Whether our iterator is properly keyed, i.e. the SparseIdx is valid
isKeyed()24709467b48Spatrick     bool isKeyed() const { return SparseIdx < SMS->Universe; }
24809467b48Spatrick 
Prev()24909467b48Spatrick     unsigned Prev() const { return SMS->Dense[Idx].Prev; }
Next()25009467b48Spatrick     unsigned Next() const { return SMS->Dense[Idx].Next; }
25109467b48Spatrick 
setPrev(unsigned P)25209467b48Spatrick     void setPrev(unsigned P) { SMS->Dense[Idx].Prev = P; }
setNext(unsigned N)25309467b48Spatrick     void setNext(unsigned N) { SMS->Dense[Idx].Next = N; }
25409467b48Spatrick 
25509467b48Spatrick   public:
25609467b48Spatrick     reference operator*() const {
25709467b48Spatrick       assert(isKeyed() && SMS->sparseIndex(SMS->Dense[Idx].Data) == SparseIdx &&
25809467b48Spatrick              "Dereferencing iterator of invalid key or index");
25909467b48Spatrick 
26009467b48Spatrick       return SMS->Dense[Idx].Data;
26109467b48Spatrick     }
26209467b48Spatrick     pointer operator->() const { return &operator*(); }
26309467b48Spatrick 
26409467b48Spatrick     /// Comparison operators
26509467b48Spatrick     bool operator==(const iterator_base &RHS) const {
26609467b48Spatrick       // end compares equal
26709467b48Spatrick       if (SMS == RHS.SMS && Idx == RHS.Idx) {
26809467b48Spatrick         assert((isEnd() || SparseIdx == RHS.SparseIdx) &&
26909467b48Spatrick                "Same dense entry, but different keys?");
27009467b48Spatrick         return true;
27109467b48Spatrick       }
27209467b48Spatrick 
27309467b48Spatrick       return false;
27409467b48Spatrick     }
27509467b48Spatrick 
27609467b48Spatrick     bool operator!=(const iterator_base &RHS) const {
27709467b48Spatrick       return !operator==(RHS);
27809467b48Spatrick     }
27909467b48Spatrick 
28009467b48Spatrick     /// Increment and decrement operators
28109467b48Spatrick     iterator_base &operator--() { // predecrement - Back up
28209467b48Spatrick       assert(isKeyed() && "Decrementing an invalid iterator");
28309467b48Spatrick       assert((isEnd() || !SMS->isHead(SMS->Dense[Idx])) &&
28409467b48Spatrick              "Decrementing head of list");
28509467b48Spatrick 
28609467b48Spatrick       // If we're at the end, then issue a new find()
28709467b48Spatrick       if (isEnd())
28809467b48Spatrick         Idx = SMS->findIndex(SparseIdx).Prev();
28909467b48Spatrick       else
29009467b48Spatrick         Idx = Prev();
29109467b48Spatrick 
29209467b48Spatrick       return *this;
29309467b48Spatrick     }
29409467b48Spatrick     iterator_base &operator++() { // preincrement - Advance
29509467b48Spatrick       assert(!isEnd() && isKeyed() && "Incrementing an invalid/end iterator");
29609467b48Spatrick       Idx = Next();
29709467b48Spatrick       return *this;
29809467b48Spatrick     }
29909467b48Spatrick     iterator_base operator--(int) { // postdecrement
30009467b48Spatrick       iterator_base I(*this);
30109467b48Spatrick       --*this;
30209467b48Spatrick       return I;
30309467b48Spatrick     }
30409467b48Spatrick     iterator_base operator++(int) { // postincrement
30509467b48Spatrick       iterator_base I(*this);
30609467b48Spatrick       ++*this;
30709467b48Spatrick       return I;
30809467b48Spatrick     }
30909467b48Spatrick   };
31009467b48Spatrick 
31109467b48Spatrick   using iterator = iterator_base<SparseMultiSet *>;
31209467b48Spatrick   using const_iterator = iterator_base<const SparseMultiSet *>;
31309467b48Spatrick 
31409467b48Spatrick   // Convenience types
31509467b48Spatrick   using RangePair = std::pair<iterator, iterator>;
31609467b48Spatrick 
31709467b48Spatrick   /// Returns an iterator past this container. Note that such an iterator cannot
31809467b48Spatrick   /// be decremented, but will compare equal to other end iterators.
end()31909467b48Spatrick   iterator end() { return iterator(this, SMSNode::INVALID, SMSNode::INVALID); }
end()32009467b48Spatrick   const_iterator end() const {
32109467b48Spatrick     return const_iterator(this, SMSNode::INVALID, SMSNode::INVALID);
32209467b48Spatrick   }
32309467b48Spatrick 
32409467b48Spatrick   /// Returns true if the set is empty.
32509467b48Spatrick   ///
32609467b48Spatrick   /// This is not the same as BitVector::empty().
32709467b48Spatrick   ///
empty()32809467b48Spatrick   bool empty() const { return size() == 0; }
32909467b48Spatrick 
33009467b48Spatrick   /// Returns the number of elements in the set.
33109467b48Spatrick   ///
33209467b48Spatrick   /// This is not the same as BitVector::size() which returns the size of the
33309467b48Spatrick   /// universe.
33409467b48Spatrick   ///
size()33509467b48Spatrick   size_type size() const {
33609467b48Spatrick     assert(NumFree <= Dense.size() && "Out-of-bounds free entries");
33709467b48Spatrick     return Dense.size() - NumFree;
33809467b48Spatrick   }
33909467b48Spatrick 
34009467b48Spatrick   /// Clears the set.  This is a very fast constant time operation.
34109467b48Spatrick   ///
clear()34209467b48Spatrick   void clear() {
34309467b48Spatrick     // Sparse does not need to be cleared, see find().
34409467b48Spatrick     Dense.clear();
34509467b48Spatrick     NumFree = 0;
34609467b48Spatrick     FreelistIdx = SMSNode::INVALID;
34709467b48Spatrick   }
34809467b48Spatrick 
34909467b48Spatrick   /// Find an element by its index.
35009467b48Spatrick   ///
35109467b48Spatrick   /// @param   Idx A valid index to find.
35209467b48Spatrick   /// @returns An iterator to the element identified by key, or end().
35309467b48Spatrick   ///
findIndex(unsigned Idx)35409467b48Spatrick   iterator findIndex(unsigned Idx) {
35509467b48Spatrick     assert(Idx < Universe && "Key out of range");
35609467b48Spatrick     const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
35709467b48Spatrick     for (unsigned i = Sparse[Idx], e = Dense.size(); i < e; i += Stride) {
35809467b48Spatrick       const unsigned FoundIdx = sparseIndex(Dense[i]);
35909467b48Spatrick       // Check that we're pointing at the correct entry and that it is the head
36009467b48Spatrick       // of a valid list.
36109467b48Spatrick       if (Idx == FoundIdx && Dense[i].isValid() && isHead(Dense[i]))
36209467b48Spatrick         return iterator(this, i, Idx);
36309467b48Spatrick       // Stride is 0 when SparseT >= unsigned.  We don't need to loop.
36409467b48Spatrick       if (!Stride)
36509467b48Spatrick         break;
36609467b48Spatrick     }
36709467b48Spatrick     return end();
36809467b48Spatrick   }
36909467b48Spatrick 
37009467b48Spatrick   /// Find an element by its key.
37109467b48Spatrick   ///
37209467b48Spatrick   /// @param   Key A valid key to find.
37309467b48Spatrick   /// @returns An iterator to the element identified by key, or end().
37409467b48Spatrick   ///
find(const KeyT & Key)37509467b48Spatrick   iterator find(const KeyT &Key) {
37609467b48Spatrick     return findIndex(KeyIndexOf(Key));
37709467b48Spatrick   }
37809467b48Spatrick 
find(const KeyT & Key)37909467b48Spatrick   const_iterator find(const KeyT &Key) const {
38009467b48Spatrick     iterator I = const_cast<SparseMultiSet*>(this)->findIndex(KeyIndexOf(Key));
38109467b48Spatrick     return const_iterator(I.SMS, I.Idx, KeyIndexOf(Key));
38209467b48Spatrick   }
38309467b48Spatrick 
38409467b48Spatrick   /// Returns the number of elements identified by Key. This will be linear in
38509467b48Spatrick   /// the number of elements of that key.
count(const KeyT & Key)38609467b48Spatrick   size_type count(const KeyT &Key) const {
38709467b48Spatrick     unsigned Ret = 0;
38809467b48Spatrick     for (const_iterator It = find(Key); It != end(); ++It)
38909467b48Spatrick       ++Ret;
39009467b48Spatrick 
39109467b48Spatrick     return Ret;
39209467b48Spatrick   }
39309467b48Spatrick 
39409467b48Spatrick   /// Returns true if this set contains an element identified by Key.
contains(const KeyT & Key)39509467b48Spatrick   bool contains(const KeyT &Key) const {
39609467b48Spatrick     return find(Key) != end();
39709467b48Spatrick   }
39809467b48Spatrick 
39909467b48Spatrick   /// Return the head and tail of the subset's list, otherwise returns end().
getHead(const KeyT & Key)40009467b48Spatrick   iterator getHead(const KeyT &Key) { return find(Key); }
getTail(const KeyT & Key)40109467b48Spatrick   iterator getTail(const KeyT &Key) {
40209467b48Spatrick     iterator I = find(Key);
40309467b48Spatrick     if (I != end())
40409467b48Spatrick       I = iterator(this, I.Prev(), KeyIndexOf(Key));
40509467b48Spatrick     return I;
40609467b48Spatrick   }
40709467b48Spatrick 
40809467b48Spatrick   /// The bounds of the range of items sharing Key K. First member is the head
40909467b48Spatrick   /// of the list, and the second member is a decrementable end iterator for
41009467b48Spatrick   /// that key.
equal_range(const KeyT & K)41109467b48Spatrick   RangePair equal_range(const KeyT &K) {
41209467b48Spatrick     iterator B = find(K);
41309467b48Spatrick     iterator E = iterator(this, SMSNode::INVALID, B.SparseIdx);
41473471bf0Spatrick     return std::make_pair(B, E);
41509467b48Spatrick   }
41609467b48Spatrick 
41709467b48Spatrick   /// Insert a new element at the tail of the subset list. Returns an iterator
41809467b48Spatrick   /// to the newly added entry.
insert(const ValueT & Val)41909467b48Spatrick   iterator insert(const ValueT &Val) {
42009467b48Spatrick     unsigned Idx = sparseIndex(Val);
42109467b48Spatrick     iterator I = findIndex(Idx);
42209467b48Spatrick 
42309467b48Spatrick     unsigned NodeIdx = addValue(Val, SMSNode::INVALID, SMSNode::INVALID);
42409467b48Spatrick 
42509467b48Spatrick     if (I == end()) {
42609467b48Spatrick       // Make a singleton list
42709467b48Spatrick       Sparse[Idx] = NodeIdx;
42809467b48Spatrick       Dense[NodeIdx].Prev = NodeIdx;
42909467b48Spatrick       return iterator(this, NodeIdx, Idx);
43009467b48Spatrick     }
43109467b48Spatrick 
43209467b48Spatrick     // Stick it at the end.
43309467b48Spatrick     unsigned HeadIdx = I.Idx;
43409467b48Spatrick     unsigned TailIdx = I.Prev();
43509467b48Spatrick     Dense[TailIdx].Next = NodeIdx;
43609467b48Spatrick     Dense[HeadIdx].Prev = NodeIdx;
43709467b48Spatrick     Dense[NodeIdx].Prev = TailIdx;
43809467b48Spatrick 
43909467b48Spatrick     return iterator(this, NodeIdx, Idx);
44009467b48Spatrick   }
44109467b48Spatrick 
44209467b48Spatrick   /// Erases an existing element identified by a valid iterator.
44309467b48Spatrick   ///
44409467b48Spatrick   /// This invalidates iterators pointing at the same entry, but erase() returns
44509467b48Spatrick   /// an iterator pointing to the next element in the subset's list. This makes
44609467b48Spatrick   /// it possible to erase selected elements while iterating over the subset:
44709467b48Spatrick   ///
44809467b48Spatrick   ///   tie(I, E) = Set.equal_range(Key);
44909467b48Spatrick   ///   while (I != E)
45009467b48Spatrick   ///     if (test(*I))
45109467b48Spatrick   ///       I = Set.erase(I);
45209467b48Spatrick   ///     else
45309467b48Spatrick   ///       ++I;
45409467b48Spatrick   ///
45509467b48Spatrick   /// Note that if the last element in the subset list is erased, this will
45609467b48Spatrick   /// return an end iterator which can be decremented to get the new tail (if it
45709467b48Spatrick   /// exists):
45809467b48Spatrick   ///
45909467b48Spatrick   ///  tie(B, I) = Set.equal_range(Key);
46009467b48Spatrick   ///  for (bool isBegin = B == I; !isBegin; /* empty */) {
46109467b48Spatrick   ///    isBegin = (--I) == B;
46209467b48Spatrick   ///    if (test(I))
46309467b48Spatrick   ///      break;
46409467b48Spatrick   ///    I = erase(I);
46509467b48Spatrick   ///  }
erase(iterator I)46609467b48Spatrick   iterator erase(iterator I) {
46709467b48Spatrick     assert(I.isKeyed() && !I.isEnd() && !Dense[I.Idx].isTombstone() &&
46809467b48Spatrick            "erasing invalid/end/tombstone iterator");
46909467b48Spatrick 
47009467b48Spatrick     // First, unlink the node from its list. Then swap the node out with the
47109467b48Spatrick     // dense vector's last entry
47209467b48Spatrick     iterator NextI = unlink(Dense[I.Idx]);
47309467b48Spatrick 
47409467b48Spatrick     // Put in a tombstone.
47509467b48Spatrick     makeTombstone(I.Idx);
47609467b48Spatrick 
47709467b48Spatrick     return NextI;
47809467b48Spatrick   }
47909467b48Spatrick 
48009467b48Spatrick   /// Erase all elements with the given key. This invalidates all
48109467b48Spatrick   /// iterators of that key.
eraseAll(const KeyT & K)48209467b48Spatrick   void eraseAll(const KeyT &K) {
48309467b48Spatrick     for (iterator I = find(K); I != end(); /* empty */)
48409467b48Spatrick       I = erase(I);
48509467b48Spatrick   }
48609467b48Spatrick 
48709467b48Spatrick private:
48809467b48Spatrick   /// Unlink the node from its list. Returns the next node in the list.
unlink(const SMSNode & N)48909467b48Spatrick   iterator unlink(const SMSNode &N) {
49009467b48Spatrick     if (isSingleton(N)) {
49109467b48Spatrick       // Singleton is already unlinked
49209467b48Spatrick       assert(N.Next == SMSNode::INVALID && "Singleton has next?");
49309467b48Spatrick       return iterator(this, SMSNode::INVALID, ValIndexOf(N.Data));
49409467b48Spatrick     }
49509467b48Spatrick 
49609467b48Spatrick     if (isHead(N)) {
49709467b48Spatrick       // If we're the head, then update the sparse array and our next.
49809467b48Spatrick       Sparse[sparseIndex(N)] = N.Next;
49909467b48Spatrick       Dense[N.Next].Prev = N.Prev;
50009467b48Spatrick       return iterator(this, N.Next, ValIndexOf(N.Data));
50109467b48Spatrick     }
50209467b48Spatrick 
50309467b48Spatrick     if (N.isTail()) {
50409467b48Spatrick       // If we're the tail, then update our head and our previous.
50509467b48Spatrick       findIndex(sparseIndex(N)).setPrev(N.Prev);
50609467b48Spatrick       Dense[N.Prev].Next = N.Next;
50709467b48Spatrick 
50809467b48Spatrick       // Give back an end iterator that can be decremented
50909467b48Spatrick       iterator I(this, N.Prev, ValIndexOf(N.Data));
51009467b48Spatrick       return ++I;
51109467b48Spatrick     }
51209467b48Spatrick 
51309467b48Spatrick     // Otherwise, just drop us
51409467b48Spatrick     Dense[N.Next].Prev = N.Prev;
51509467b48Spatrick     Dense[N.Prev].Next = N.Next;
51609467b48Spatrick     return iterator(this, N.Next, ValIndexOf(N.Data));
51709467b48Spatrick   }
51809467b48Spatrick };
51909467b48Spatrick 
52009467b48Spatrick } // end namespace llvm
52109467b48Spatrick 
52209467b48Spatrick #endif // LLVM_ADT_SPARSEMULTISET_H
523