1 //===- llvm/ADT/SparseBitVector.h - Efficient Sparse BitVector -*- C++ -*- ===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Daniel Berlin and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SparseBitVector class. See the doxygen comment for
11 // SparseBitVector for more details on the algorithm used.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ADT_SPARSEBITVECTOR_H
16 #define LLVM_ADT_SPARSEBITVECTOR_H
21 #include "llvm/Support/DataTypes.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/ADT/ilist"
27 /// SparseBitVector is an implementation of a bitvector that is sparse by only
28 /// storing the elements that have non-zero bits set. In order to make this
29 /// fast for the most common cases, SparseBitVector is implemented as a linked
30 /// list of SparseBitVectorElements. We maintain a pointer to the last
31 /// SparseBitVectorElement accessed (in the form of a list iterator), in order
32 /// to make multiple in-order test/set constant time after the first one is
33 /// executed. Note that using vectors to store SparseBitVectorElement's does
34 /// not work out very well because it causes insertion in the middle to take
35 /// enormous amounts of time with a large amount of bits. Other structures that
36 /// have better worst cases for insertion in the middle (various balanced trees,
37 /// etc) do not perform as well in practice as a linked list with this iterator
38 /// kept up to date. They are also significantly more memory intensive.
41 template <unsigned ElementSize = 128>
42 struct SparseBitVectorElement {
44 typedef unsigned long BitWord;
46 BITWORD_SIZE = sizeof(BitWord) * 8,
47 BITWORDS_PER_ELEMENT = (ElementSize + BITWORD_SIZE - 1) / BITWORD_SIZE,
48 BITS_PER_ELEMENT = ElementSize
51 SparseBitVectorElement<ElementSize> *getNext() const {
54 SparseBitVectorElement<ElementSize> *getPrev() const {
58 void setNext(SparseBitVectorElement<ElementSize> *RHS) {
61 void setPrev(SparseBitVectorElement<ElementSize> *RHS) {
66 SparseBitVectorElement<ElementSize> *Next;
67 SparseBitVectorElement<ElementSize> *Prev;
68 // Index of Element in terms of where first bit starts.
69 unsigned ElementIndex;
70 BitWord Bits[BITWORDS_PER_ELEMENT];
71 // Needed for sentinels
72 SparseBitVectorElement() {
74 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
77 friend struct ilist_traits<SparseBitVectorElement<ElementSize> >;
79 explicit SparseBitVectorElement(unsigned Idx) {
81 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
84 ~SparseBitVectorElement() {
88 SparseBitVectorElement(const SparseBitVectorElement &RHS) {
89 ElementIndex = RHS.ElementIndex;
90 std::copy(&RHS.Bits[0], &RHS.Bits[BITWORDS_PER_ELEMENT], Bits);
94 bool operator==(const SparseBitVectorElement &RHS) const {
95 if (ElementIndex != RHS.ElementIndex)
97 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
98 if (Bits[i] != RHS.Bits[i])
103 bool operator!=(const SparseBitVectorElement &RHS) const {
104 return !(*this == RHS);
107 // Return the bits that make up word Idx in our element.
108 BitWord word(unsigned Idx) const {
109 assert (Idx < BITWORDS_PER_ELEMENT);
113 unsigned index() const {
118 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
124 void set(unsigned Idx) {
125 Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
128 bool test_and_set (unsigned Idx) {
129 bool old = test(Idx);
137 void reset(unsigned Idx) {
138 Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
141 bool test(unsigned Idx) const {
142 return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
145 unsigned count() const {
146 unsigned NumBits = 0;
147 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
148 if (sizeof(BitWord) == 4)
149 NumBits += CountPopulation_32(Bits[i]);
150 else if (sizeof(BitWord) == 8)
151 NumBits += CountPopulation_64(Bits[i]);
153 assert(0 && "Unsupported!");
157 /// find_first - Returns the index of the first set bit.
158 int find_first() const {
159 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
161 if (sizeof(BitWord) == 4)
162 return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
163 else if (sizeof(BitWord) == 8)
164 return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
166 assert(0 && "Unsupported!");
168 assert(0 && "Illegal empty element");
171 /// find_next - Returns the index of the next set bit following the
172 /// "Prev" bit. Returns -1 if the next set bit is not found.
173 int find_next(unsigned Prev) const {
175 if (Prev >= BITS_PER_ELEMENT)
178 unsigned WordPos = Prev / BITWORD_SIZE;
179 unsigned BitPos = Prev % BITWORD_SIZE;
180 BitWord Copy = Bits[WordPos];
181 assert (WordPos <= BITWORDS_PER_ELEMENT
182 && "Word Position outside of element");
184 // Mask off previous bits.
185 Copy &= ~0L << BitPos;
188 if (sizeof(BitWord) == 4)
189 return WordPos * BITWORD_SIZE + CountTrailingZeros_32(Copy);
190 else if (sizeof(BitWord) == 8)
191 return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
193 assert(0 && "Unsupported!");
196 // Check subsequent words.
197 for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
199 if (sizeof(BitWord) == 4)
200 return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
201 else if (sizeof(BitWord) == 8)
202 return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
204 assert(0 && "Unsupported!");
209 // Union this element with RHS and return true if this one changed.
210 bool unionWith(const SparseBitVectorElement &RHS) {
211 bool changed = false;
212 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
213 BitWord old = changed ? 0 : Bits[i];
215 Bits[i] |= RHS.Bits[i];
216 if (!changed && old != Bits[i])
222 // Return true if we have any bits in common with RHS
223 bool intersects(const SparseBitVectorElement &RHS) const {
224 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
225 if (RHS.Bits[i] & Bits[i])
231 // Intersect this Element with RHS and return true if this one changed.
232 // BecameZero is set to true if this element became all-zero bits.
233 bool intersectWith(const SparseBitVectorElement &RHS,
235 bool changed = false;
239 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
240 BitWord old = changed ? 0 : Bits[i];
242 Bits[i] &= RHS.Bits[i];
246 if (!changed && old != Bits[i])
249 BecameZero = allzero;
252 // Intersect this Element with the complement of RHS and return true if this
253 // one changed. BecameZero is set to true if this element became all-zero
255 bool intersectWithComplement(const SparseBitVectorElement &RHS,
257 bool changed = false;
261 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
262 BitWord old = changed ? 0 : Bits[i];
264 Bits[i] &= ~RHS.Bits[i];
268 if (!changed && old != Bits[i])
271 BecameZero = allzero;
274 // Three argument version of intersectWithComplement that intersects
275 // RHS1 & ~RHS2 into this element
276 void intersectWithComplement(const SparseBitVectorElement &RHS1,
277 const SparseBitVectorElement &RHS2,
282 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
283 Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
287 BecameZero = allzero;
290 // Get a hash value for this element;
291 uint64_t getHashValue() const {
292 uint64_t HashVal = 0;
293 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
300 template <unsigned ElementSize = 128>
301 class SparseBitVector {
302 typedef ilist<SparseBitVectorElement<ElementSize> > ElementList;
303 typedef typename ElementList::iterator ElementListIter;
304 typedef typename ElementList::const_iterator ElementListConstIter;
306 BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
309 // Pointer to our current Element.
310 ElementListIter CurrElementIter;
311 ElementList Elements;
313 // This is like std::lower_bound, except we do linear searching from the
315 ElementListIter FindLowerBound(unsigned ElementIndex) {
317 if (Elements.empty()) {
318 CurrElementIter = Elements.begin();
319 return Elements.begin();
322 // Make sure our current iterator is valid.
323 if (CurrElementIter == Elements.end())
326 // Search from our current iterator, either backwards or forwards,
327 // depending on what element we are looking for.
328 ElementListIter ElementIter = CurrElementIter;
329 if (CurrElementIter->index() == ElementIndex) {
331 } else if (CurrElementIter->index() > ElementIndex) {
332 while (ElementIter != Elements.begin()
333 && ElementIter->index() > ElementIndex)
336 while (ElementIter != Elements.end() &&
337 ElementIter->index() <= ElementIndex)
341 CurrElementIter = ElementIter;
345 // Iterator to walk set bits in the bitmap. This iterator is a lot uglier
346 // than it would be, in order to be efficient.
347 class SparseBitVectorIterator {
351 const SparseBitVector<ElementSize> *BitVector;
353 // Current element inside of bitmap.
354 ElementListConstIter Iter;
356 // Current bit number inside of our bitmap.
359 // Current word number inside of our element.
362 // Current bits from the element.
363 typename SparseBitVectorElement<ElementSize>::BitWord Bits;
365 // Move our iterator to the first non-zero bit in the bitmap.
366 void AdvanceToFirstNonZero() {
369 if (BitVector->Elements.empty()) {
373 Iter = BitVector->Elements.begin();
374 BitNumber = Iter->index() * ElementSize;
375 unsigned BitPos = Iter->find_first();
377 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
378 Bits = Iter->word(WordNumber);
379 Bits >>= BitPos % BITWORD_SIZE;
382 // Move our iterator to the next non-zero bit.
383 void AdvanceToNextNonZero() {
387 while (Bits && !(Bits & 1)) {
392 // See if we ran out of Bits in this word.
394 int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
395 // If we ran out of set bits in this element, move to next element.
396 if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
400 // We may run out of elements in the bitmap.
401 if (Iter == BitVector->Elements.end()) {
405 // Set up for next non zero word in bitmap.
406 BitNumber = Iter->index() * ElementSize;
407 NextSetBitNumber = Iter->find_first();
408 BitNumber += NextSetBitNumber;
409 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
410 Bits = Iter->word(WordNumber);
411 Bits >>= NextSetBitNumber % BITWORD_SIZE;
413 WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
414 Bits = Iter->word(WordNumber);
415 Bits >>= NextSetBitNumber % BITWORD_SIZE;
416 BitNumber = Iter->index() * ElementSize;
417 BitNumber += NextSetBitNumber;
423 inline SparseBitVectorIterator& operator++() {
426 AdvanceToNextNonZero();
431 inline SparseBitVectorIterator operator++(int) {
432 SparseBitVectorIterator tmp = *this;
437 // Return the current set bit number.
438 unsigned operator*() const {
442 bool operator==(const SparseBitVectorIterator &RHS) const {
443 // If they are both at the end, ignore the rest of the fields.
444 if (AtEnd && RHS.AtEnd)
446 // Otherwise they are the same if they have the same bit number and
448 return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
450 bool operator!=(const SparseBitVectorIterator &RHS) const {
451 return !(*this == RHS);
453 SparseBitVectorIterator(): BitVector(NULL) {
457 SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
458 bool end = false):BitVector(RHS) {
459 Iter = BitVector->Elements.begin();
464 AdvanceToFirstNonZero();
468 typedef SparseBitVectorIterator iterator;
471 CurrElementIter = Elements.begin ();
477 // SparseBitVector copy ctor.
478 SparseBitVector(const SparseBitVector &RHS) {
479 ElementListConstIter ElementIter = RHS.Elements.begin();
480 while (ElementIter != RHS.Elements.end()) {
481 Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
485 CurrElementIter = Elements.begin ();
488 // Test, Reset, and Set a bit in the bitmap.
489 bool test(unsigned Idx) {
490 if (Elements.empty())
493 unsigned ElementIndex = Idx / ElementSize;
494 ElementListIter ElementIter = FindLowerBound(ElementIndex);
496 // If we can't find an element that is supposed to contain this bit, there
497 // is nothing more to do.
498 if (ElementIter == Elements.end() ||
499 ElementIter->index() != ElementIndex)
501 return ElementIter->test(Idx % ElementSize);
504 void reset(unsigned Idx) {
505 if (Elements.empty())
508 unsigned ElementIndex = Idx / ElementSize;
509 ElementListIter ElementIter = FindLowerBound(ElementIndex);
511 // If we can't find an element that is supposed to contain this bit, there
512 // is nothing more to do.
513 if (ElementIter == Elements.end() ||
514 ElementIter->index() != ElementIndex)
516 ElementIter->reset(Idx % ElementSize);
518 // When the element is zeroed out, delete it.
519 if (ElementIter->empty()) {
521 Elements.erase(ElementIter);
525 void set(unsigned Idx) {
526 unsigned ElementIndex = Idx / ElementSize;
527 SparseBitVectorElement<ElementSize> *Element;
528 ElementListIter ElementIter;
529 if (Elements.empty()) {
530 Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
531 ElementIter = Elements.insert(Elements.end(), Element);
534 ElementIter = FindLowerBound(ElementIndex);
536 if (ElementIter == Elements.end() ||
537 ElementIter->index() != ElementIndex) {
538 Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
539 // Insert does insert before, and lower bound gives the one before.
540 ElementIter = Elements.insert(++ElementIter, Element);
543 ElementIter->set(Idx % ElementSize);
546 bool test_and_set (unsigned Idx) {
547 bool old = test(Idx);
555 bool operator!=(const SparseBitVector &RHS) const {
556 return !(*this == RHS);
559 bool operator==(const SparseBitVector &RHS) const {
560 ElementListConstIter Iter1 = Elements.begin();
561 ElementListConstIter Iter2 = RHS.Elements.begin();
563 for (; Iter1 != Elements.end() && Iter2 != RHS.Elements.end();
565 if (*Iter1 != *Iter2)
568 return Iter1 == Elements.end() && Iter2 == RHS.Elements.end();
571 // Union our bitmap with the RHS and return true if we changed.
572 bool operator|=(const SparseBitVector &RHS) {
573 bool changed = false;
574 ElementListIter Iter1 = Elements.begin();
575 ElementListConstIter Iter2 = RHS.Elements.begin();
577 // Check if both bitmaps are empty
578 if (Elements.empty() && RHS.Elements.empty())
581 while (Iter2 != RHS.Elements.end()) {
582 if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
583 Elements.insert(Iter1,
584 new SparseBitVectorElement<ElementSize>(*Iter2));
587 } else if (Iter1->index() == Iter2->index()) {
588 changed |= Iter1->unionWith(*Iter2);
595 CurrElementIter = Elements.begin();
599 // Intersect our bitmap with the RHS and return true if ours changed.
600 bool operator&=(const SparseBitVector &RHS) {
601 bool changed = false;
602 ElementListIter Iter1 = Elements.begin();
603 ElementListConstIter Iter2 = RHS.Elements.begin();
605 // Check if both bitmaps are empty.
606 if (Elements.empty() && RHS.Elements.empty())
609 // Loop through, intersecting as we go, erasing elements when necessary.
610 while (Iter2 != RHS.Elements.end()) {
611 if (Iter1 == Elements.end())
614 if (Iter1->index() > Iter2->index()) {
616 } else if (Iter1->index() == Iter2->index()) {
618 changed |= Iter1->intersectWith(*Iter2, BecameZero);
620 ElementListIter IterTmp = Iter1;
622 Elements.erase(IterTmp);
628 ElementListIter IterTmp = Iter1;
630 Elements.erase(IterTmp);
633 Elements.erase(Iter1, Elements.end());
634 CurrElementIter = Elements.begin();
638 // Intersect our bitmap with the complement of the RHS and return true if ours
640 bool intersectWithComplement(const SparseBitVector &RHS) {
641 bool changed = false;
642 ElementListIter Iter1 = Elements.begin();
643 ElementListConstIter Iter2 = RHS.Elements.begin();
645 // Check if they are both empty
646 if (Elements.empty() && RHS.Elements.empty())
649 // Loop through, intersecting as we go, erasing elements when necessary.
650 while (Iter2 != RHS.Elements.end()) {
651 if (Iter1 == Elements.end())
654 if (Iter1->index() > Iter2->index()) {
656 } else if (Iter1->index() == Iter2->index()) {
658 changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
660 ElementListIter IterTmp = Iter1;
662 Elements.erase(IterTmp);
668 ElementListIter IterTmp = Iter1;
670 Elements.erase(IterTmp);
673 CurrElementIter = Elements.begin();
677 bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
678 return intersectWithComplement(*RHS);
682 // Three argument version of intersectWithComplement. Result of RHS1 & ~RHS2
683 // is stored into this bitmap.
684 void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
685 const SparseBitVector<ElementSize> &RHS2)
688 ElementListConstIter Iter1 = RHS1.Elements.begin();
689 ElementListConstIter Iter2 = RHS2.Elements.begin();
691 // Check if they are both empty.
692 if (RHS1.empty() && RHS2.empty())
695 // Loop through, intersecting as we go, erasing elements when necessary.
696 while (Iter2 != RHS2.Elements.end()) {
697 if (Iter1 == RHS1.Elements.end())
700 if (Iter1->index() > Iter2->index()) {
702 } else if (Iter1->index() == Iter2->index()) {
703 bool BecameZero = false;
704 SparseBitVectorElement<ElementSize> *NewElement =
705 new SparseBitVectorElement<ElementSize>(Iter1->index());
706 NewElement->intersectWithComplement(*Iter1, *Iter2, BecameZero);
708 Elements.push_back(NewElement);
719 // copy the remaining elements
720 while (Iter1 != RHS1.Elements.end()) {
721 SparseBitVectorElement<ElementSize> *NewElement =
722 new SparseBitVectorElement<ElementSize>(*Iter1);
723 Elements.push_back(NewElement);
727 CurrElementIter = Elements.begin();
731 void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
732 const SparseBitVector<ElementSize> *RHS2) {
733 intersectWithComplement(*RHS1, *RHS2);
736 bool intersects(const SparseBitVector<ElementSize> *RHS) const {
737 return intersects(*RHS);
740 // Return true if we share any bits in common with RHS
741 bool intersects(const SparseBitVector<ElementSize> &RHS) const {
742 ElementListConstIter Iter1 = Elements.begin();
743 ElementListConstIter Iter2 = RHS.Elements.begin();
745 // Check if both bitmaps are empty.
746 if (Elements.empty() && RHS.Elements.empty())
749 // Loop through, intersecting stopping when we hit bits in common.
750 while (Iter2 != RHS.Elements.end()) {
751 if (Iter1 == Elements.end())
754 if (Iter1->index() > Iter2->index()) {
756 } else if (Iter1->index() == Iter2->index()) {
757 if (Iter1->intersects(*Iter2))
768 // Return the first set bit in the bitmap. Return -1 if no bits are set.
769 int find_first() const {
770 if (Elements.empty())
772 const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
773 return (First.index() * ElementSize) + First.find_first();
776 // Return true if the SparseBitVector is empty
778 return Elements.empty();
781 unsigned count() const {
782 unsigned BitCount = 0;
783 for (ElementListConstIter Iter = Elements.begin();
784 Iter != Elements.end();
786 BitCount += Iter->count();
790 iterator begin() const {
791 return iterator(this);
794 iterator end() const {
795 return iterator(this, ~0);
798 // Get a hash value for this bitmap.
799 uint64_t getHashValue() const {
800 uint64_t HashVal = 0;
801 for (ElementListConstIter Iter = Elements.begin();
802 Iter != Elements.end();
804 HashVal ^= Iter->index();
805 HashVal ^= Iter->getHashValue();
811 // Convenience functions to allow Or and And without dereferencing in the user
814 template <unsigned ElementSize>
815 inline bool operator |=(SparseBitVector<ElementSize> &LHS,
816 const SparseBitVector<ElementSize> *RHS) {
820 template <unsigned ElementSize>
821 inline bool operator |=(SparseBitVector<ElementSize> *LHS,
822 const SparseBitVector<ElementSize> &RHS) {
823 return LHS->operator|=(RHS);
826 template <unsigned ElementSize>
827 inline bool operator &=(SparseBitVector<ElementSize> *LHS,
828 const SparseBitVector<ElementSize> &RHS) {
829 return LHS->operator&=(RHS);
832 template <unsigned ElementSize>
833 inline bool operator &=(SparseBitVector<ElementSize> &LHS,
834 const SparseBitVector<ElementSize> *RHS) {
835 return LHS &= (*RHS);
839 // Dump a SparseBitVector to a stream
840 template <unsigned ElementSize>
841 void dump(const SparseBitVector<ElementSize> &LHS, llvm::OStream &out) {
844 typename SparseBitVector<ElementSize>::iterator bi;
845 for (bi = LHS.begin(); bi != LHS.end(); ++bi) {