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