LLVM API Documentation
00001 //===--- llvm/ADT/SparseMultiSet.h - Sparse multiset ------------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the SparseMultiSet class, which adds multiset behavior to 00011 // the SparseSet. 00012 // 00013 // A sparse multiset holds a small number of objects identified by integer keys 00014 // from a moderately sized universe. The sparse multiset uses more memory than 00015 // other containers in order to provide faster operations. Any key can map to 00016 // multiple values. A SparseMultiSetNode class is provided, which serves as a 00017 // convenient base class for the contents of a SparseMultiSet. 00018 // 00019 //===----------------------------------------------------------------------===// 00020 00021 #ifndef LLVM_ADT_SPARSEMULTISET_H 00022 #define LLVM_ADT_SPARSEMULTISET_H 00023 00024 #include "llvm/ADT/SparseSet.h" 00025 00026 namespace llvm { 00027 00028 /// Fast multiset implementation for objects that can be identified by small 00029 /// unsigned keys. 00030 /// 00031 /// SparseMultiSet allocates memory proportional to the size of the key 00032 /// universe, so it is not recommended for building composite data structures. 00033 /// It is useful for algorithms that require a single set with fast operations. 00034 /// 00035 /// Compared to DenseSet and DenseMap, SparseMultiSet provides constant-time 00036 /// fast clear() as fast as a vector. The find(), insert(), and erase() 00037 /// operations are all constant time, and typically faster than a hash table. 00038 /// The iteration order doesn't depend on numerical key values, it only depends 00039 /// on the order of insert() and erase() operations. Iteration order is the 00040 /// insertion order. Iteration is only provided over elements of equivalent 00041 /// keys, but iterators are bidirectional. 00042 /// 00043 /// Compared to BitVector, SparseMultiSet<unsigned> uses 8x-40x more memory, but 00044 /// offers constant-time clear() and size() operations as well as fast iteration 00045 /// independent on the size of the universe. 00046 /// 00047 /// SparseMultiSet contains a dense vector holding all the objects and a sparse 00048 /// array holding indexes into the dense vector. Most of the memory is used by 00049 /// the sparse array which is the size of the key universe. The SparseT template 00050 /// parameter provides a space/speed tradeoff for sets holding many elements. 00051 /// 00052 /// When SparseT is uint32_t, find() only touches up to 3 cache lines, but the 00053 /// sparse array uses 4 x Universe bytes. 00054 /// 00055 /// When SparseT is uint8_t (the default), find() touches up to 3+[N/256] cache 00056 /// lines, but the sparse array is 4x smaller. N is the number of elements in 00057 /// the set. 00058 /// 00059 /// For sets that may grow to thousands of elements, SparseT should be set to 00060 /// uint16_t or uint32_t. 00061 /// 00062 /// Multiset behavior is provided by providing doubly linked lists for values 00063 /// that are inlined in the dense vector. SparseMultiSet is a good choice when 00064 /// one desires a growable number of entries per key, as it will retain the 00065 /// SparseSet algorithmic properties despite being growable. Thus, it is often a 00066 /// better choice than a SparseSet of growable containers or a vector of 00067 /// vectors. SparseMultiSet also keeps iterators valid after erasure (provided 00068 /// the iterators don't point to the element erased), allowing for more 00069 /// intuitive and fast removal. 00070 /// 00071 /// @tparam ValueT The type of objects in the set. 00072 /// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT. 00073 /// @tparam SparseT An unsigned integer type. See above. 00074 /// 00075 template<typename ValueT, 00076 typename KeyFunctorT = llvm::identity<unsigned>, 00077 typename SparseT = uint8_t> 00078 class SparseMultiSet { 00079 static_assert(std::numeric_limits<SparseT>::is_integer && 00080 !std::numeric_limits<SparseT>::is_signed, 00081 "SparseT must be an unsigned integer type"); 00082 00083 /// The actual data that's stored, as a doubly-linked list implemented via 00084 /// indices into the DenseVector. The doubly linked list is implemented 00085 /// circular in Prev indices, and INVALID-terminated in Next indices. This 00086 /// provides efficient access to list tails. These nodes can also be 00087 /// tombstones, in which case they are actually nodes in a single-linked 00088 /// freelist of recyclable slots. 00089 struct SMSNode { 00090 static const unsigned INVALID = ~0U; 00091 00092 ValueT Data; 00093 unsigned Prev; 00094 unsigned Next; 00095 00096 SMSNode(ValueT D, unsigned P, unsigned N) : Data(D), Prev(P), Next(N) { } 00097 00098 /// List tails have invalid Nexts. 00099 bool isTail() const { 00100 return Next == INVALID; 00101 } 00102 00103 /// Whether this node is a tombstone node, and thus is in our freelist. 00104 bool isTombstone() const { 00105 return Prev == INVALID; 00106 } 00107 00108 /// Since the list is circular in Prev, all non-tombstone nodes have a valid 00109 /// Prev. 00110 bool isValid() const { return Prev != INVALID; } 00111 }; 00112 00113 typedef typename KeyFunctorT::argument_type KeyT; 00114 typedef SmallVector<SMSNode, 8> DenseT; 00115 DenseT Dense; 00116 SparseT *Sparse; 00117 unsigned Universe; 00118 KeyFunctorT KeyIndexOf; 00119 SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf; 00120 00121 /// We have a built-in recycler for reusing tombstone slots. This recycler 00122 /// puts a singly-linked free list into tombstone slots, allowing us quick 00123 /// erasure, iterator preservation, and dense size. 00124 unsigned FreelistIdx; 00125 unsigned NumFree; 00126 00127 unsigned sparseIndex(const ValueT &Val) const { 00128 assert(ValIndexOf(Val) < Universe && 00129 "Invalid key in set. Did object mutate?"); 00130 return ValIndexOf(Val); 00131 } 00132 unsigned sparseIndex(const SMSNode &N) const { return sparseIndex(N.Data); } 00133 00134 // Disable copy construction and assignment. 00135 // This data structure is not meant to be used that way. 00136 SparseMultiSet(const SparseMultiSet&) LLVM_DELETED_FUNCTION; 00137 SparseMultiSet &operator=(const SparseMultiSet&) LLVM_DELETED_FUNCTION; 00138 00139 /// Whether the given entry is the head of the list. List heads's previous 00140 /// pointers are to the tail of the list, allowing for efficient access to the 00141 /// list tail. D must be a valid entry node. 00142 bool isHead(const SMSNode &D) const { 00143 assert(D.isValid() && "Invalid node for head"); 00144 return Dense[D.Prev].isTail(); 00145 } 00146 00147 /// Whether the given entry is a singleton entry, i.e. the only entry with 00148 /// that key. 00149 bool isSingleton(const SMSNode &N) const { 00150 assert(N.isValid() && "Invalid node for singleton"); 00151 // Is N its own predecessor? 00152 return &Dense[N.Prev] == &N; 00153 } 00154 00155 /// Add in the given SMSNode. Uses a free entry in our freelist if 00156 /// available. Returns the index of the added node. 00157 unsigned addValue(const ValueT& V, unsigned Prev, unsigned Next) { 00158 if (NumFree == 0) { 00159 Dense.push_back(SMSNode(V, Prev, Next)); 00160 return Dense.size() - 1; 00161 } 00162 00163 // Peel off a free slot 00164 unsigned Idx = FreelistIdx; 00165 unsigned NextFree = Dense[Idx].Next; 00166 assert(Dense[Idx].isTombstone() && "Non-tombstone free?"); 00167 00168 Dense[Idx] = SMSNode(V, Prev, Next); 00169 FreelistIdx = NextFree; 00170 --NumFree; 00171 return Idx; 00172 } 00173 00174 /// Make the current index a new tombstone. Pushes it onto the freelist. 00175 void makeTombstone(unsigned Idx) { 00176 Dense[Idx].Prev = SMSNode::INVALID; 00177 Dense[Idx].Next = FreelistIdx; 00178 FreelistIdx = Idx; 00179 ++NumFree; 00180 } 00181 00182 public: 00183 typedef ValueT value_type; 00184 typedef ValueT &reference; 00185 typedef const ValueT &const_reference; 00186 typedef ValueT *pointer; 00187 typedef const ValueT *const_pointer; 00188 typedef unsigned size_type; 00189 00190 SparseMultiSet() 00191 : Sparse(nullptr), Universe(0), FreelistIdx(SMSNode::INVALID), NumFree(0) {} 00192 00193 ~SparseMultiSet() { free(Sparse); } 00194 00195 /// Set the universe size which determines the largest key the set can hold. 00196 /// The universe must be sized before any elements can be added. 00197 /// 00198 /// @param U Universe size. All object keys must be less than U. 00199 /// 00200 void setUniverse(unsigned U) { 00201 // It's not hard to resize the universe on a non-empty set, but it doesn't 00202 // seem like a likely use case, so we can add that code when we need it. 00203 assert(empty() && "Can only resize universe on an empty map"); 00204 // Hysteresis prevents needless reallocations. 00205 if (U >= Universe/4 && U <= Universe) 00206 return; 00207 free(Sparse); 00208 // The Sparse array doesn't actually need to be initialized, so malloc 00209 // would be enough here, but that will cause tools like valgrind to 00210 // complain about branching on uninitialized data. 00211 Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT))); 00212 Universe = U; 00213 } 00214 00215 /// Our iterators are iterators over the collection of objects that share a 00216 /// key. 00217 template<typename SMSPtrTy> 00218 class iterator_base : public std::iterator<std::bidirectional_iterator_tag, 00219 ValueT> { 00220 friend class SparseMultiSet; 00221 SMSPtrTy SMS; 00222 unsigned Idx; 00223 unsigned SparseIdx; 00224 00225 iterator_base(SMSPtrTy P, unsigned I, unsigned SI) 00226 : SMS(P), Idx(I), SparseIdx(SI) { } 00227 00228 /// Whether our iterator has fallen outside our dense vector. 00229 bool isEnd() const { 00230 if (Idx == SMSNode::INVALID) 00231 return true; 00232 00233 assert(Idx < SMS->Dense.size() && "Out of range, non-INVALID Idx?"); 00234 return false; 00235 } 00236 00237 /// Whether our iterator is properly keyed, i.e. the SparseIdx is valid 00238 bool isKeyed() const { return SparseIdx < SMS->Universe; } 00239 00240 unsigned Prev() const { return SMS->Dense[Idx].Prev; } 00241 unsigned Next() const { return SMS->Dense[Idx].Next; } 00242 00243 void setPrev(unsigned P) { SMS->Dense[Idx].Prev = P; } 00244 void setNext(unsigned N) { SMS->Dense[Idx].Next = N; } 00245 00246 public: 00247 typedef std::iterator<std::bidirectional_iterator_tag, ValueT> super; 00248 typedef typename super::value_type value_type; 00249 typedef typename super::difference_type difference_type; 00250 typedef typename super::pointer pointer; 00251 typedef typename super::reference reference; 00252 00253 reference operator*() const { 00254 assert(isKeyed() && SMS->sparseIndex(SMS->Dense[Idx].Data) == SparseIdx && 00255 "Dereferencing iterator of invalid key or index"); 00256 00257 return SMS->Dense[Idx].Data; 00258 } 00259 pointer operator->() const { return &operator*(); } 00260 00261 /// Comparison operators 00262 bool operator==(const iterator_base &RHS) const { 00263 // end compares equal 00264 if (SMS == RHS.SMS && Idx == RHS.Idx) { 00265 assert((isEnd() || SparseIdx == RHS.SparseIdx) && 00266 "Same dense entry, but different keys?"); 00267 return true; 00268 } 00269 00270 return false; 00271 } 00272 00273 bool operator!=(const iterator_base &RHS) const { 00274 return !operator==(RHS); 00275 } 00276 00277 /// Increment and decrement operators 00278 iterator_base &operator--() { // predecrement - Back up 00279 assert(isKeyed() && "Decrementing an invalid iterator"); 00280 assert((isEnd() || !SMS->isHead(SMS->Dense[Idx])) && 00281 "Decrementing head of list"); 00282 00283 // If we're at the end, then issue a new find() 00284 if (isEnd()) 00285 Idx = SMS->findIndex(SparseIdx).Prev(); 00286 else 00287 Idx = Prev(); 00288 00289 return *this; 00290 } 00291 iterator_base &operator++() { // preincrement - Advance 00292 assert(!isEnd() && isKeyed() && "Incrementing an invalid/end iterator"); 00293 Idx = Next(); 00294 return *this; 00295 } 00296 iterator_base operator--(int) { // postdecrement 00297 iterator_base I(*this); 00298 --*this; 00299 return I; 00300 } 00301 iterator_base operator++(int) { // postincrement 00302 iterator_base I(*this); 00303 ++*this; 00304 return I; 00305 } 00306 }; 00307 typedef iterator_base<SparseMultiSet *> iterator; 00308 typedef iterator_base<const SparseMultiSet *> const_iterator; 00309 00310 // Convenience types 00311 typedef std::pair<iterator, iterator> RangePair; 00312 00313 /// Returns an iterator past this container. Note that such an iterator cannot 00314 /// be decremented, but will compare equal to other end iterators. 00315 iterator end() { return iterator(this, SMSNode::INVALID, SMSNode::INVALID); } 00316 const_iterator end() const { 00317 return const_iterator(this, SMSNode::INVALID, SMSNode::INVALID); 00318 } 00319 00320 /// Returns true if the set is empty. 00321 /// 00322 /// This is not the same as BitVector::empty(). 00323 /// 00324 bool empty() const { return size() == 0; } 00325 00326 /// Returns the number of elements in the set. 00327 /// 00328 /// This is not the same as BitVector::size() which returns the size of the 00329 /// universe. 00330 /// 00331 size_type size() const { 00332 assert(NumFree <= Dense.size() && "Out-of-bounds free entries"); 00333 return Dense.size() - NumFree; 00334 } 00335 00336 /// Clears the set. This is a very fast constant time operation. 00337 /// 00338 void clear() { 00339 // Sparse does not need to be cleared, see find(). 00340 Dense.clear(); 00341 NumFree = 0; 00342 FreelistIdx = SMSNode::INVALID; 00343 } 00344 00345 /// Find an element by its index. 00346 /// 00347 /// @param Idx A valid index to find. 00348 /// @returns An iterator to the element identified by key, or end(). 00349 /// 00350 iterator findIndex(unsigned Idx) { 00351 assert(Idx < Universe && "Key out of range"); 00352 const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u; 00353 for (unsigned i = Sparse[Idx], e = Dense.size(); i < e; i += Stride) { 00354 const unsigned FoundIdx = sparseIndex(Dense[i]); 00355 // Check that we're pointing at the correct entry and that it is the head 00356 // of a valid list. 00357 if (Idx == FoundIdx && Dense[i].isValid() && isHead(Dense[i])) 00358 return iterator(this, i, Idx); 00359 // Stride is 0 when SparseT >= unsigned. We don't need to loop. 00360 if (!Stride) 00361 break; 00362 } 00363 return end(); 00364 } 00365 00366 /// Find an element by its key. 00367 /// 00368 /// @param Key A valid key to find. 00369 /// @returns An iterator to the element identified by key, or end(). 00370 /// 00371 iterator find(const KeyT &Key) { 00372 return findIndex(KeyIndexOf(Key)); 00373 } 00374 00375 const_iterator find(const KeyT &Key) const { 00376 iterator I = const_cast<SparseMultiSet*>(this)->findIndex(KeyIndexOf(Key)); 00377 return const_iterator(I.SMS, I.Idx, KeyIndexOf(Key)); 00378 } 00379 00380 /// Returns the number of elements identified by Key. This will be linear in 00381 /// the number of elements of that key. 00382 size_type count(const KeyT &Key) const { 00383 unsigned Ret = 0; 00384 for (const_iterator It = find(Key); It != end(); ++It) 00385 ++Ret; 00386 00387 return Ret; 00388 } 00389 00390 /// Returns true if this set contains an element identified by Key. 00391 bool contains(const KeyT &Key) const { 00392 return find(Key) != end(); 00393 } 00394 00395 /// Return the head and tail of the subset's list, otherwise returns end(). 00396 iterator getHead(const KeyT &Key) { return find(Key); } 00397 iterator getTail(const KeyT &Key) { 00398 iterator I = find(Key); 00399 if (I != end()) 00400 I = iterator(this, I.Prev(), KeyIndexOf(Key)); 00401 return I; 00402 } 00403 00404 /// The bounds of the range of items sharing Key K. First member is the head 00405 /// of the list, and the second member is a decrementable end iterator for 00406 /// that key. 00407 RangePair equal_range(const KeyT &K) { 00408 iterator B = find(K); 00409 iterator E = iterator(this, SMSNode::INVALID, B.SparseIdx); 00410 return make_pair(B, E); 00411 } 00412 00413 /// Insert a new element at the tail of the subset list. Returns an iterator 00414 /// to the newly added entry. 00415 iterator insert(const ValueT &Val) { 00416 unsigned Idx = sparseIndex(Val); 00417 iterator I = findIndex(Idx); 00418 00419 unsigned NodeIdx = addValue(Val, SMSNode::INVALID, SMSNode::INVALID); 00420 00421 if (I == end()) { 00422 // Make a singleton list 00423 Sparse[Idx] = NodeIdx; 00424 Dense[NodeIdx].Prev = NodeIdx; 00425 return iterator(this, NodeIdx, Idx); 00426 } 00427 00428 // Stick it at the end. 00429 unsigned HeadIdx = I.Idx; 00430 unsigned TailIdx = I.Prev(); 00431 Dense[TailIdx].Next = NodeIdx; 00432 Dense[HeadIdx].Prev = NodeIdx; 00433 Dense[NodeIdx].Prev = TailIdx; 00434 00435 return iterator(this, NodeIdx, Idx); 00436 } 00437 00438 /// Erases an existing element identified by a valid iterator. 00439 /// 00440 /// This invalidates iterators pointing at the same entry, but erase() returns 00441 /// an iterator pointing to the next element in the subset's list. This makes 00442 /// it possible to erase selected elements while iterating over the subset: 00443 /// 00444 /// tie(I, E) = Set.equal_range(Key); 00445 /// while (I != E) 00446 /// if (test(*I)) 00447 /// I = Set.erase(I); 00448 /// else 00449 /// ++I; 00450 /// 00451 /// Note that if the last element in the subset list is erased, this will 00452 /// return an end iterator which can be decremented to get the new tail (if it 00453 /// exists): 00454 /// 00455 /// tie(B, I) = Set.equal_range(Key); 00456 /// for (bool isBegin = B == I; !isBegin; /* empty */) { 00457 /// isBegin = (--I) == B; 00458 /// if (test(I)) 00459 /// break; 00460 /// I = erase(I); 00461 /// } 00462 iterator erase(iterator I) { 00463 assert(I.isKeyed() && !I.isEnd() && !Dense[I.Idx].isTombstone() && 00464 "erasing invalid/end/tombstone iterator"); 00465 00466 // First, unlink the node from its list. Then swap the node out with the 00467 // dense vector's last entry 00468 iterator NextI = unlink(Dense[I.Idx]); 00469 00470 // Put in a tombstone. 00471 makeTombstone(I.Idx); 00472 00473 return NextI; 00474 } 00475 00476 /// Erase all elements with the given key. This invalidates all 00477 /// iterators of that key. 00478 void eraseAll(const KeyT &K) { 00479 for (iterator I = find(K); I != end(); /* empty */) 00480 I = erase(I); 00481 } 00482 00483 private: 00484 /// Unlink the node from its list. Returns the next node in the list. 00485 iterator unlink(const SMSNode &N) { 00486 if (isSingleton(N)) { 00487 // Singleton is already unlinked 00488 assert(N.Next == SMSNode::INVALID && "Singleton has next?"); 00489 return iterator(this, SMSNode::INVALID, ValIndexOf(N.Data)); 00490 } 00491 00492 if (isHead(N)) { 00493 // If we're the head, then update the sparse array and our next. 00494 Sparse[sparseIndex(N)] = N.Next; 00495 Dense[N.Next].Prev = N.Prev; 00496 return iterator(this, N.Next, ValIndexOf(N.Data)); 00497 } 00498 00499 if (N.isTail()) { 00500 // If we're the tail, then update our head and our previous. 00501 findIndex(sparseIndex(N)).setPrev(N.Prev); 00502 Dense[N.Prev].Next = N.Next; 00503 00504 // Give back an end iterator that can be decremented 00505 iterator I(this, N.Prev, ValIndexOf(N.Data)); 00506 return ++I; 00507 } 00508 00509 // Otherwise, just drop us 00510 Dense[N.Next].Prev = N.Prev; 00511 Dense[N.Prev].Next = N.Next; 00512 return iterator(this, N.Next, ValIndexOf(N.Data)); 00513 } 00514 }; 00515 00516 } // end namespace llvm 00517 00518 #endif