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> >;
80 explicit SparseBitVectorElement(unsigned Idx) {
82 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
85 ~SparseBitVectorElement() {
89 SparseBitVectorElement(const SparseBitVectorElement &RHS) {
90 ElementIndex = RHS.ElementIndex;
91 std::copy(&RHS.Bits[0], &RHS.Bits[BITWORDS_PER_ELEMENT], Bits);
95 bool operator==(const SparseBitVectorElement &RHS) const {
96 if (ElementIndex != RHS.ElementIndex)
98 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
99 if (Bits[i] != RHS.Bits[i])
104 bool operator!=(const SparseBitVectorElement &RHS) const {
105 return !(*this == RHS);
108 // Return the bits that make up word Idx in our element.
109 BitWord word(unsigned Idx) const {
110 assert (Idx < BITWORDS_PER_ELEMENT);
114 unsigned index() const {
119 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
125 void set(unsigned Idx) {
126 Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
129 bool test_and_set (unsigned Idx) {
130 bool old = test(Idx);
138 void reset(unsigned Idx) {
139 Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
142 bool test(unsigned Idx) const {
143 return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
146 unsigned count() const {
147 unsigned NumBits = 0;
148 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
149 if (sizeof(BitWord) == 4)
150 NumBits += CountPopulation_32(Bits[i]);
151 else if (sizeof(BitWord) == 8)
152 NumBits += CountPopulation_64(Bits[i]);
154 assert(0 && "Unsupported!");
158 /// find_first - Returns the index of the first set bit.
159 int find_first() const {
160 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
162 if (sizeof(BitWord) == 4)
163 return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
164 else if (sizeof(BitWord) == 8)
165 return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
167 assert(0 && "Unsupported!");
169 assert(0 && "Illegal empty element");
172 /// find_next - Returns the index of the next set bit following the
173 /// "Prev" bit. Returns -1 if the next set bit is not found.
174 int find_next(unsigned Prev) const {
176 if (Prev >= BITS_PER_ELEMENT)
179 unsigned WordPos = Prev / BITWORD_SIZE;
180 unsigned BitPos = Prev % BITWORD_SIZE;
181 BitWord Copy = Bits[WordPos];
182 assert (WordPos <= BITWORDS_PER_ELEMENT
183 && "Word Position outside of element");
185 // Mask off previous bits.
186 Copy &= ~0L << BitPos;
189 if (sizeof(BitWord) == 4)
190 return WordPos * BITWORD_SIZE + CountTrailingZeros_32(Copy);
191 else if (sizeof(BitWord) == 8)
192 return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
194 assert(0 && "Unsupported!");
197 // Check subsequent words.
198 for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
200 if (sizeof(BitWord) == 4)
201 return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
202 else if (sizeof(BitWord) == 8)
203 return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
205 assert(0 && "Unsupported!");
210 // Union this element with RHS and return true if this one changed.
211 bool unionWith(const SparseBitVectorElement &RHS) {
212 bool changed = false;
213 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
214 BitWord old = changed ? 0 : Bits[i];
216 Bits[i] |= RHS.Bits[i];
217 if (!changed && old != Bits[i])
223 // Return true if we have any bits in common with RHS
224 bool intersects(const SparseBitVectorElement &RHS) const {
225 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
226 if (RHS.Bits[i] & Bits[i])
232 // Intersect this Element with RHS and return true if this one changed.
233 // BecameZero is set to true if this element became all-zero bits.
234 bool intersectWith(const SparseBitVectorElement &RHS,
236 bool changed = false;
240 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
241 BitWord old = changed ? 0 : Bits[i];
243 Bits[i] &= RHS.Bits[i];
247 if (!changed && old != Bits[i])
250 BecameZero = allzero;
253 // Intersect this Element with the complement of RHS and return true if this
254 // one changed. BecameZero is set to true if this element became all-zero
256 bool intersectWithComplement(const SparseBitVectorElement &RHS,
258 bool changed = false;
262 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
263 BitWord old = changed ? 0 : Bits[i];
265 Bits[i] &= ~RHS.Bits[i];
269 if (!changed && old != Bits[i])
272 BecameZero = allzero;
275 // Three argument version of intersectWithComplement that intersects
276 // RHS1 & ~RHS2 into this element
277 void intersectWithComplement(const SparseBitVectorElement &RHS1,
278 const SparseBitVectorElement &RHS2,
283 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
284 Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
288 BecameZero = allzero;
292 template <unsigned ElementSize = 128>
293 class SparseBitVector {
294 typedef ilist<SparseBitVectorElement<ElementSize> > ElementList;
295 typedef typename ElementList::iterator ElementListIter;
296 typedef typename ElementList::const_iterator ElementListConstIter;
298 BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
301 // Pointer to our current Element.
302 ElementListIter CurrElementIter;
303 ElementList Elements;
305 // This is like std::lower_bound, except we do linear searching from the
307 ElementListIter FindLowerBound(unsigned ElementIndex) {
309 if (Elements.empty()) {
310 CurrElementIter = Elements.begin();
311 return Elements.begin();
314 // Make sure our current iterator is valid.
315 if (CurrElementIter == Elements.end())
318 // Search from our current iterator, either backwards or forwards,
319 // depending on what element we are looking for.
320 ElementListIter ElementIter = CurrElementIter;
321 if (CurrElementIter->index() == ElementIndex) {
323 } else if (CurrElementIter->index() > ElementIndex) {
324 while (ElementIter != Elements.begin()
325 && ElementIter->index() > ElementIndex)
328 while (ElementIter != Elements.end() &&
329 ElementIter->index() <= ElementIndex)
333 CurrElementIter = ElementIter;
337 // Iterator to walk set bits in the bitmap. This iterator is a lot uglier
338 // than it would be, in order to be efficient.
339 class SparseBitVectorIterator {
343 const SparseBitVector<ElementSize> *BitVector;
345 // Current element inside of bitmap.
346 ElementListConstIter Iter;
348 // Current bit number inside of our bitmap.
351 // Current word number inside of our element.
354 // Current bits from the element.
355 typename SparseBitVectorElement<ElementSize>::BitWord Bits;
357 // Move our iterator to the first non-zero bit in the bitmap.
358 void AdvanceToFirstNonZero() {
361 if (BitVector->Elements.empty()) {
365 Iter = BitVector->Elements.begin();
366 BitNumber = Iter->index() * ElementSize;
367 unsigned BitPos = Iter->find_first();
369 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
370 Bits = Iter->word(WordNumber);
371 Bits >>= BitPos % BITWORD_SIZE;
374 // Move our iterator to the next non-zero bit.
375 void AdvanceToNextNonZero() {
379 while (Bits && !(Bits & 1)) {
384 // See if we ran out of Bits in this word.
386 int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
387 // If we ran out of set bits in this element, move to next element.
388 if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
392 // We may run out of elements in the bitmap.
393 if (Iter == BitVector->Elements.end()) {
397 // Set up for next non zero word in bitmap.
398 BitNumber = Iter->index() * ElementSize;
399 NextSetBitNumber = Iter->find_first();
400 BitNumber += NextSetBitNumber;
401 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
402 Bits = Iter->word(WordNumber);
403 Bits >>= NextSetBitNumber % BITWORD_SIZE;
405 WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
406 Bits = Iter->word(WordNumber);
407 Bits >>= NextSetBitNumber % BITWORD_SIZE;
408 BitNumber = Iter->index() * ElementSize;
409 BitNumber += NextSetBitNumber;
415 inline SparseBitVectorIterator& operator++() {
418 AdvanceToNextNonZero();
423 inline SparseBitVectorIterator operator++(int) {
424 SparseBitVectorIterator tmp = *this;
429 // Return the current set bit number.
430 unsigned operator*() const {
434 bool operator==(const SparseBitVectorIterator &RHS) const {
435 // If they are both at the end, ignore the rest of the fields.
436 if (AtEnd == RHS.AtEnd)
438 // Otherwise they are the same if they have the same bit number and
440 return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
442 bool operator!=(const SparseBitVectorIterator &RHS) const {
443 return !(*this == RHS);
445 SparseBitVectorIterator(): BitVector(NULL) {
449 SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
450 bool end = false):BitVector(RHS) {
451 Iter = BitVector->Elements.begin();
456 AdvanceToFirstNonZero();
460 typedef SparseBitVectorIterator iterator;
463 CurrElementIter = Elements.begin ();
469 // SparseBitVector copy ctor.
470 SparseBitVector(const SparseBitVector &RHS) {
471 ElementListConstIter ElementIter = RHS.Elements.begin();
472 while (ElementIter != RHS.Elements.end()) {
473 Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
477 CurrElementIter = Elements.begin ();
480 // Test, Reset, and Set a bit in the bitmap.
481 bool test(unsigned Idx) {
482 if (Elements.empty())
485 unsigned ElementIndex = Idx / ElementSize;
486 ElementListIter ElementIter = FindLowerBound(ElementIndex);
488 // If we can't find an element that is supposed to contain this bit, there
489 // is nothing more to do.
490 if (ElementIter == Elements.end() ||
491 ElementIter->index() != ElementIndex)
493 return ElementIter->test(Idx % ElementSize);
496 void reset(unsigned Idx) {
497 if (Elements.empty())
500 unsigned ElementIndex = Idx / ElementSize;
501 ElementListIter ElementIter = FindLowerBound(ElementIndex);
503 // If we can't find an element that is supposed to contain this bit, there
504 // is nothing more to do.
505 if (ElementIter == Elements.end() ||
506 ElementIter->index() != ElementIndex)
508 ElementIter->reset(Idx % ElementSize);
510 // When the element is zeroed out, delete it.
511 if (ElementIter->empty()) {
513 Elements.erase(ElementIter);
517 void set(unsigned Idx) {
518 unsigned ElementIndex = Idx / ElementSize;
519 SparseBitVectorElement<ElementSize> *Element;
520 ElementListIter ElementIter;
521 if (Elements.empty()) {
522 Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
523 ElementIter = Elements.insert(Elements.end(), Element);
526 ElementIter = FindLowerBound(ElementIndex);
528 if (ElementIter == Elements.end() ||
529 ElementIter->index() != ElementIndex) {
530 Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
531 // Insert does insert before, and lower bound gives the one before.
532 ElementIter = Elements.insert(++ElementIter, Element);
535 ElementIter->set(Idx % ElementSize);
538 bool test_and_set (unsigned Idx) {
539 bool old = test(Idx);
547 bool operator!=(const SparseBitVector &RHS) {
548 return !(*this == RHS);
551 bool operator==(const SparseBitVector &RHS) {
552 ElementListConstIter Iter1 = Elements.begin();
553 ElementListConstIter Iter2 = RHS.Elements.begin();
555 while (Iter2 != RHS.Elements.end()) {
556 if (Iter1->index() != Iter2->index()
562 return Iter1 == Elements.end();
565 // Union our bitmap with the RHS and return true if we changed.
566 bool operator|=(const SparseBitVector &RHS) {
567 bool changed = false;
568 ElementListIter Iter1 = Elements.begin();
569 ElementListConstIter Iter2 = RHS.Elements.begin();
571 // Check if both bitmaps are empty
572 if (Elements.empty() && RHS.Elements.empty())
575 while (Iter2 != RHS.Elements.end()) {
576 if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
577 Elements.insert(Iter1,
578 new SparseBitVectorElement<ElementSize>(*Iter2));
581 } else if (Iter1->index() == Iter2->index()) {
582 changed |= Iter1->unionWith(*Iter2);
589 CurrElementIter = Elements.begin();
593 // Intersect our bitmap with the RHS and return true if ours changed.
594 bool operator&=(const SparseBitVector &RHS) {
595 bool changed = false;
596 ElementListIter Iter1 = Elements.begin();
597 ElementListConstIter Iter2 = RHS.Elements.begin();
599 // Check if both bitmaps are empty.
600 if (Elements.empty() && RHS.Elements.empty())
603 // Loop through, intersecting as we go, erasing elements when necessary.
604 while (Iter2 != RHS.Elements.end()) {
605 if (Iter1 == Elements.end())
608 if (Iter1->index() > Iter2->index()) {
610 } else if (Iter1->index() == Iter2->index()) {
612 changed |= Iter1->intersectWith(*Iter2, BecameZero);
614 ElementListIter IterTmp = Iter1;
616 Elements.erase(IterTmp);
622 ElementListIter IterTmp = Iter1;
624 Elements.erase(IterTmp);
627 Elements.erase(Iter1, Elements.end());
628 CurrElementIter = Elements.begin();
632 // Intersect our bitmap with the complement of the RHS and return true if ours
634 bool intersectWithComplement(const SparseBitVector &RHS) {
635 bool changed = false;
636 ElementListIter Iter1 = Elements.begin();
637 ElementListConstIter Iter2 = RHS.Elements.begin();
639 // Check if they are both empty
640 if (Elements.empty() && RHS.Elements.empty())
643 // Loop through, intersecting as we go, erasing elements when necessary.
644 while (Iter2 != RHS.Elements.end()) {
645 if (Iter1 == Elements.end())
648 if (Iter1->index() > Iter2->index()) {
650 } else if (Iter1->index() == Iter2->index()) {
652 changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
654 ElementListIter IterTmp = Iter1;
656 Elements.erase(IterTmp);
662 ElementListIter IterTmp = Iter1;
664 Elements.erase(IterTmp);
667 CurrElementIter = Elements.begin();
671 bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
672 return intersectWithComplement(*RHS);
676 // Three argument version of intersectWithComplement. Result of RHS1 & ~RHS2
677 // is stored into this bitmap.
678 void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
679 const SparseBitVector<ElementSize> &RHS2)
682 ElementListConstIter Iter1 = RHS1.Elements.begin();
683 ElementListConstIter Iter2 = RHS2.Elements.begin();
685 // Check if they are both empty.
686 if (RHS1.empty() && RHS2.empty())
689 // Loop through, intersecting as we go, erasing elements when necessary.
690 while (Iter2 != RHS2.Elements.end()) {
691 if (Iter1 == RHS1.Elements.end())
694 if (Iter1->index() > Iter2->index()) {
696 } else if (Iter1->index() == Iter2->index()) {
697 bool BecameZero = false;
698 SparseBitVectorElement<ElementSize> *NewElement =
699 new SparseBitVectorElement<ElementSize>(Iter1->index());
700 NewElement->intersectWithComplement(*Iter1, *Iter2, BecameZero);
702 Elements.push_back(NewElement);
713 // copy the remaining elements
714 while (Iter1 != RHS1.Elements.end()) {
715 SparseBitVectorElement<ElementSize> *NewElement =
716 new SparseBitVectorElement<ElementSize>(*Iter1);
717 Elements.push_back(NewElement);
721 CurrElementIter = Elements.begin();
725 void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
726 const SparseBitVector<ElementSize> *RHS2) {
727 intersectWithComplement(*RHS1, *RHS2);
730 bool intersects(const SparseBitVector<ElementSize> *RHS) const {
731 return intersects(*RHS);
734 // Return true if we share any bits in common with RHS
735 bool intersects(const SparseBitVector<ElementSize> &RHS) const {
736 ElementListConstIter Iter1 = Elements.begin();
737 ElementListConstIter Iter2 = RHS.Elements.begin();
739 // Check if both bitmaps are empty.
740 if (Elements.empty() && RHS.Elements.empty())
743 // Loop through, intersecting stopping when we hit bits in common.
744 while (Iter2 != RHS.Elements.end()) {
745 if (Iter1 == Elements.end())
748 if (Iter1->index() > Iter2->index()) {
750 } else if (Iter1->index() == Iter2->index()) {
751 if (Iter1->intersects(*Iter2))
762 // Return the first set bit in the bitmap. Return -1 if no bits are set.
763 int find_first() const {
764 if (Elements.empty())
766 const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
767 return (First.index() * ElementSize) + First.find_first();
770 // Return true if the SparseBitVector is empty
772 return Elements.empty();
775 unsigned count() const {
776 unsigned BitCount = 0;
777 for (ElementListConstIter Iter = Elements.begin();
778 Iter != Elements.end();
780 BitCount += Iter->count();
784 iterator begin() const {
785 return iterator(this);
788 iterator end() const {
789 return iterator(this, ~0);
794 // Convenience functions to allow Or and And without dereferencing in the user
797 template <unsigned ElementSize>
798 inline bool operator |=(SparseBitVector<ElementSize> &LHS,
799 const SparseBitVector<ElementSize> *RHS) {
803 template <unsigned ElementSize>
804 inline bool operator |=(SparseBitVector<ElementSize> *LHS,
805 const SparseBitVector<ElementSize> &RHS) {
806 return LHS->operator|=(RHS);
809 template <unsigned ElementSize>
810 inline bool operator &=(SparseBitVector<ElementSize> *LHS,
811 const SparseBitVector<ElementSize> &RHS) {
812 return LHS->operator&=(RHS);
815 template <unsigned ElementSize>
816 inline bool operator &=(SparseBitVector<ElementSize> &LHS,
817 const SparseBitVector<ElementSize> *RHS) {
818 return LHS &= (*RHS);
822 // Dump a SparseBitVector to a stream
823 template <unsigned ElementSize>
824 void dump(const SparseBitVector<ElementSize> &LHS, llvm::OStream &out) {
827 typename SparseBitVector<ElementSize>::iterator bi;
828 for (bi = LHS.begin(); bi != LHS.end(); ++bi) {