1 //===- llvm/ADT/SparseBitVector.h - Efficient Sparse BitVector --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/raw_ostream.h"
29 /// SparseBitVector is an implementation of a bitvector that is sparse by only
30 /// storing the elements that have non-zero bits set. In order to make this
31 /// fast for the most common cases, SparseBitVector is implemented as a linked
32 /// list of SparseBitVectorElements. We maintain a pointer to the last
33 /// SparseBitVectorElement accessed (in the form of a list iterator), in order
34 /// to make multiple in-order test/set constant time after the first one is
35 /// executed. Note that using vectors to store SparseBitVectorElement's does
36 /// not work out very well because it causes insertion in the middle to take
37 /// enormous amounts of time with a large amount of bits. Other structures that
38 /// have better worst cases for insertion in the middle (various balanced trees,
39 /// etc) do not perform as well in practice as a linked list with this iterator
40 /// kept up to date. They are also significantly more memory intensive.
42 template <unsigned ElementSize = 128> struct SparseBitVectorElement {
44 using BitWord = unsigned long;
45 using size_type = unsigned;
47 BITWORD_SIZE = sizeof(BitWord) * CHAR_BIT,
48 BITWORDS_PER_ELEMENT = (ElementSize + BITWORD_SIZE - 1) / BITWORD_SIZE,
49 BITS_PER_ELEMENT = ElementSize
53 // Index of Element in terms of where first bit starts.
54 unsigned ElementIndex;
55 BitWord Bits[BITWORDS_PER_ELEMENT];
57 SparseBitVectorElement() {
59 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
63 explicit SparseBitVectorElement(unsigned Idx) {
65 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
69 bool operator==(const SparseBitVectorElement &RHS) const {
70 if (ElementIndex != RHS.ElementIndex)
72 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
73 if (Bits[i] != RHS.Bits[i])
78 bool operator!=(const SparseBitVectorElement &RHS) const {
79 return !(*this == RHS);
82 // Return the bits that make up word Idx in our element.
83 BitWord word(unsigned Idx) const {
84 assert(Idx < BITWORDS_PER_ELEMENT);
88 unsigned index() const {
93 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
99 void set(unsigned Idx) {
100 Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
103 bool test_and_set(unsigned Idx) {
104 bool old = test(Idx);
112 void reset(unsigned Idx) {
113 Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
116 bool test(unsigned Idx) const {
117 return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
120 size_type count() const {
121 unsigned NumBits = 0;
122 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
123 NumBits += countPopulation(Bits[i]);
127 /// find_first - Returns the index of the first set bit.
128 int find_first() const {
129 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
131 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
132 llvm_unreachable("Illegal empty element");
135 /// find_last - Returns the index of the last set bit.
136 int find_last() const {
137 for (unsigned I = 0; I < BITWORDS_PER_ELEMENT; ++I) {
138 unsigned Idx = BITWORDS_PER_ELEMENT - I - 1;
140 return Idx * BITWORD_SIZE + BITWORD_SIZE -
141 countLeadingZeros(Bits[Idx]) - 1;
143 llvm_unreachable("Illegal empty element");
146 /// find_next - Returns the index of the next set bit starting from the
147 /// "Curr" bit. Returns -1 if the next set bit is not found.
148 int find_next(unsigned Curr) const {
149 if (Curr >= BITS_PER_ELEMENT)
152 unsigned WordPos = Curr / BITWORD_SIZE;
153 unsigned BitPos = Curr % BITWORD_SIZE;
154 BitWord Copy = Bits[WordPos];
155 assert(WordPos <= BITWORDS_PER_ELEMENT
156 && "Word Position outside of element");
158 // Mask off previous bits.
159 Copy &= ~0UL << BitPos;
162 return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
164 // Check subsequent words.
165 for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
167 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
171 // Union this element with RHS and return true if this one changed.
172 bool unionWith(const SparseBitVectorElement &RHS) {
173 bool changed = false;
174 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
175 BitWord old = changed ? 0 : Bits[i];
177 Bits[i] |= RHS.Bits[i];
178 if (!changed && old != Bits[i])
184 // Return true if we have any bits in common with RHS
185 bool intersects(const SparseBitVectorElement &RHS) const {
186 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
187 if (RHS.Bits[i] & Bits[i])
193 // Intersect this Element with RHS and return true if this one changed.
194 // BecameZero is set to true if this element became all-zero bits.
195 bool intersectWith(const SparseBitVectorElement &RHS,
197 bool changed = false;
201 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
202 BitWord old = changed ? 0 : Bits[i];
204 Bits[i] &= RHS.Bits[i];
208 if (!changed && old != Bits[i])
211 BecameZero = allzero;
215 // Intersect this Element with the complement of RHS and return true if this
216 // one changed. BecameZero is set to true if this element became all-zero
218 bool intersectWithComplement(const SparseBitVectorElement &RHS,
220 bool changed = false;
224 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
225 BitWord old = changed ? 0 : Bits[i];
227 Bits[i] &= ~RHS.Bits[i];
231 if (!changed && old != Bits[i])
234 BecameZero = allzero;
238 // Three argument version of intersectWithComplement that intersects
239 // RHS1 & ~RHS2 into this element
240 void intersectWithComplement(const SparseBitVectorElement &RHS1,
241 const SparseBitVectorElement &RHS2,
246 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
247 Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
251 BecameZero = allzero;
255 template <unsigned ElementSize = 128>
256 class SparseBitVector {
257 using ElementList = std::list<SparseBitVectorElement<ElementSize>>;
258 using ElementListIter = typename ElementList::iterator;
259 using ElementListConstIter = typename ElementList::const_iterator;
261 BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
264 // Pointer to our current Element.
265 ElementListIter CurrElementIter;
266 ElementList Elements;
268 // This is like std::lower_bound, except we do linear searching from the
270 ElementListIter FindLowerBound(unsigned ElementIndex) {
272 if (Elements.empty()) {
273 CurrElementIter = Elements.begin();
274 return Elements.begin();
277 // Make sure our current iterator is valid.
278 if (CurrElementIter == Elements.end())
281 // Search from our current iterator, either backwards or forwards,
282 // depending on what element we are looking for.
283 ElementListIter ElementIter = CurrElementIter;
284 if (CurrElementIter->index() == ElementIndex) {
286 } else if (CurrElementIter->index() > ElementIndex) {
287 while (ElementIter != Elements.begin()
288 && ElementIter->index() > ElementIndex)
291 while (ElementIter != Elements.end() &&
292 ElementIter->index() < ElementIndex)
295 CurrElementIter = ElementIter;
299 // Iterator to walk set bits in the bitmap. This iterator is a lot uglier
300 // than it would be, in order to be efficient.
301 class SparseBitVectorIterator {
305 const SparseBitVector<ElementSize> *BitVector = nullptr;
307 // Current element inside of bitmap.
308 ElementListConstIter Iter;
310 // Current bit number inside of our bitmap.
313 // Current word number inside of our element.
316 // Current bits from the element.
317 typename SparseBitVectorElement<ElementSize>::BitWord Bits;
319 // Move our iterator to the first non-zero bit in the bitmap.
320 void AdvanceToFirstNonZero() {
323 if (BitVector->Elements.empty()) {
327 Iter = BitVector->Elements.begin();
328 BitNumber = Iter->index() * ElementSize;
329 unsigned BitPos = Iter->find_first();
331 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
332 Bits = Iter->word(WordNumber);
333 Bits >>= BitPos % BITWORD_SIZE;
336 // Move our iterator to the next non-zero bit.
337 void AdvanceToNextNonZero() {
341 while (Bits && !(Bits & 1)) {
346 // See if we ran out of Bits in this word.
348 int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
349 // If we ran out of set bits in this element, move to next element.
350 if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
354 // We may run out of elements in the bitmap.
355 if (Iter == BitVector->Elements.end()) {
359 // Set up for next non-zero word in bitmap.
360 BitNumber = Iter->index() * ElementSize;
361 NextSetBitNumber = Iter->find_first();
362 BitNumber += NextSetBitNumber;
363 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
364 Bits = Iter->word(WordNumber);
365 Bits >>= NextSetBitNumber % BITWORD_SIZE;
367 WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
368 Bits = Iter->word(WordNumber);
369 Bits >>= NextSetBitNumber % BITWORD_SIZE;
370 BitNumber = Iter->index() * ElementSize;
371 BitNumber += NextSetBitNumber;
377 SparseBitVectorIterator() = default;
379 SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
380 bool end = false):BitVector(RHS) {
381 Iter = BitVector->Elements.begin();
386 AdvanceToFirstNonZero();
390 inline SparseBitVectorIterator& operator++() {
393 AdvanceToNextNonZero();
398 inline SparseBitVectorIterator operator++(int) {
399 SparseBitVectorIterator tmp = *this;
404 // Return the current set bit number.
405 unsigned operator*() const {
409 bool operator==(const SparseBitVectorIterator &RHS) const {
410 // If they are both at the end, ignore the rest of the fields.
411 if (AtEnd && RHS.AtEnd)
413 // Otherwise they are the same if they have the same bit number and
415 return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
418 bool operator!=(const SparseBitVectorIterator &RHS) const {
419 return !(*this == RHS);
424 using iterator = SparseBitVectorIterator;
427 CurrElementIter = Elements.begin();
430 // SparseBitVector copy ctor.
431 SparseBitVector(const SparseBitVector &RHS) {
432 ElementListConstIter ElementIter = RHS.Elements.begin();
433 while (ElementIter != RHS.Elements.end()) {
434 Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
438 CurrElementIter = Elements.begin ();
441 ~SparseBitVector() = default;
449 SparseBitVector& operator=(const SparseBitVector& RHS) {
455 ElementListConstIter ElementIter = RHS.Elements.begin();
456 while (ElementIter != RHS.Elements.end()) {
457 Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
461 CurrElementIter = Elements.begin ();
466 // Test, Reset, and Set a bit in the bitmap.
467 bool test(unsigned Idx) {
468 if (Elements.empty())
471 unsigned ElementIndex = Idx / ElementSize;
472 ElementListIter ElementIter = FindLowerBound(ElementIndex);
474 // If we can't find an element that is supposed to contain this bit, there
475 // is nothing more to do.
476 if (ElementIter == Elements.end() ||
477 ElementIter->index() != ElementIndex)
479 return ElementIter->test(Idx % ElementSize);
482 void reset(unsigned Idx) {
483 if (Elements.empty())
486 unsigned ElementIndex = Idx / ElementSize;
487 ElementListIter ElementIter = FindLowerBound(ElementIndex);
489 // If we can't find an element that is supposed to contain this bit, there
490 // is nothing more to do.
491 if (ElementIter == Elements.end() ||
492 ElementIter->index() != ElementIndex)
494 ElementIter->reset(Idx % ElementSize);
496 // When the element is zeroed out, delete it.
497 if (ElementIter->empty()) {
499 Elements.erase(ElementIter);
503 void set(unsigned Idx) {
504 unsigned ElementIndex = Idx / ElementSize;
505 ElementListIter ElementIter;
506 if (Elements.empty()) {
507 ElementIter = Elements.emplace(Elements.end(), ElementIndex);
509 ElementIter = FindLowerBound(ElementIndex);
511 if (ElementIter == Elements.end() ||
512 ElementIter->index() != ElementIndex) {
513 // We may have hit the beginning of our SparseBitVector, in which case,
514 // we may need to insert right after this element, which requires moving
515 // the current iterator forward one, because insert does insert before.
516 if (ElementIter != Elements.end() &&
517 ElementIter->index() < ElementIndex)
519 ElementIter = Elements.emplace(ElementIter, ElementIndex);
522 CurrElementIter = ElementIter;
524 ElementIter->set(Idx % ElementSize);
527 bool test_and_set(unsigned Idx) {
528 bool old = test(Idx);
536 bool operator!=(const SparseBitVector &RHS) const {
537 return !(*this == RHS);
540 bool operator==(const SparseBitVector &RHS) const {
541 ElementListConstIter Iter1 = Elements.begin();
542 ElementListConstIter Iter2 = RHS.Elements.begin();
544 for (; Iter1 != Elements.end() && Iter2 != RHS.Elements.end();
546 if (*Iter1 != *Iter2)
549 return Iter1 == Elements.end() && Iter2 == RHS.Elements.end();
552 // Union our bitmap with the RHS and return true if we changed.
553 bool operator|=(const SparseBitVector &RHS) {
557 bool changed = false;
558 ElementListIter Iter1 = Elements.begin();
559 ElementListConstIter Iter2 = RHS.Elements.begin();
561 // If RHS is empty, we are done
562 if (RHS.Elements.empty())
565 while (Iter2 != RHS.Elements.end()) {
566 if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
567 Elements.insert(Iter1, *Iter2);
570 } else if (Iter1->index() == Iter2->index()) {
571 changed |= Iter1->unionWith(*Iter2);
578 CurrElementIter = Elements.begin();
582 // Intersect our bitmap with the RHS and return true if ours changed.
583 bool operator&=(const SparseBitVector &RHS) {
587 bool changed = false;
588 ElementListIter Iter1 = Elements.begin();
589 ElementListConstIter Iter2 = RHS.Elements.begin();
591 // Check if both bitmaps are empty.
592 if (Elements.empty() && RHS.Elements.empty())
595 // Loop through, intersecting as we go, erasing elements when necessary.
596 while (Iter2 != RHS.Elements.end()) {
597 if (Iter1 == Elements.end()) {
598 CurrElementIter = Elements.begin();
602 if (Iter1->index() > Iter2->index()) {
604 } else if (Iter1->index() == Iter2->index()) {
606 changed |= Iter1->intersectWith(*Iter2, BecameZero);
608 ElementListIter IterTmp = Iter1;
610 Elements.erase(IterTmp);
616 ElementListIter IterTmp = Iter1;
618 Elements.erase(IterTmp);
622 if (Iter1 != Elements.end()) {
623 Elements.erase(Iter1, Elements.end());
626 CurrElementIter = Elements.begin();
630 // Intersect our bitmap with the complement of the RHS and return true
632 bool intersectWithComplement(const SparseBitVector &RHS) {
641 bool changed = false;
642 ElementListIter Iter1 = Elements.begin();
643 ElementListConstIter Iter2 = RHS.Elements.begin();
645 // If either our bitmap or RHS is empty, we are done
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()) {
652 CurrElementIter = Elements.begin();
656 if (Iter1->index() > Iter2->index()) {
658 } else if (Iter1->index() == Iter2->index()) {
660 changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
662 ElementListIter IterTmp = Iter1;
664 Elements.erase(IterTmp);
673 CurrElementIter = Elements.begin();
677 bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
678 return intersectWithComplement(*RHS);
681 // Three argument version of intersectWithComplement.
682 // Result of RHS1 & ~RHS2 is stored into this bitmap.
683 void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
684 const SparseBitVector<ElementSize> &RHS2)
687 intersectWithComplement(RHS2);
689 } else if (this == &RHS2) {
690 SparseBitVector RHS2Copy(RHS2);
691 intersectWithComplement(RHS1, RHS2Copy);
696 CurrElementIter = Elements.begin();
697 ElementListConstIter Iter1 = RHS1.Elements.begin();
698 ElementListConstIter Iter2 = RHS2.Elements.begin();
700 // If RHS1 is empty, we are done
701 // If RHS2 is empty, we still have to copy RHS1
702 if (RHS1.Elements.empty())
705 // Loop through, intersecting as we go, erasing elements when necessary.
706 while (Iter2 != RHS2.Elements.end()) {
707 if (Iter1 == RHS1.Elements.end())
710 if (Iter1->index() > Iter2->index()) {
712 } else if (Iter1->index() == Iter2->index()) {
713 bool BecameZero = false;
714 Elements.emplace_back(Iter1->index());
715 Elements.back().intersectWithComplement(*Iter1, *Iter2, BecameZero);
721 Elements.push_back(*Iter1++);
725 // copy the remaining elements
726 std::copy(Iter1, RHS1.Elements.end(), std::back_inserter(Elements));
729 void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
730 const SparseBitVector<ElementSize> *RHS2) {
731 intersectWithComplement(*RHS1, *RHS2);
734 bool intersects(const SparseBitVector<ElementSize> *RHS) const {
735 return intersects(*RHS);
738 // Return true if we share any bits in common with RHS
739 bool intersects(const SparseBitVector<ElementSize> &RHS) const {
740 ElementListConstIter Iter1 = Elements.begin();
741 ElementListConstIter Iter2 = RHS.Elements.begin();
743 // Check if both bitmaps are empty.
744 if (Elements.empty() && RHS.Elements.empty())
747 // Loop through, intersecting stopping when we hit bits in common.
748 while (Iter2 != RHS.Elements.end()) {
749 if (Iter1 == Elements.end())
752 if (Iter1->index() > Iter2->index()) {
754 } else if (Iter1->index() == Iter2->index()) {
755 if (Iter1->intersects(*Iter2))
766 // Return true iff all bits set in this SparseBitVector are
768 bool contains(const SparseBitVector<ElementSize> &RHS) const {
769 SparseBitVector<ElementSize> Result(*this);
771 return (Result == RHS);
774 // Return the first set bit in the bitmap. Return -1 if no bits are set.
775 int find_first() const {
776 if (Elements.empty())
778 const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
779 return (First.index() * ElementSize) + First.find_first();
782 // Return the last set bit in the bitmap. Return -1 if no bits are set.
783 int find_last() const {
784 if (Elements.empty())
786 const SparseBitVectorElement<ElementSize> &Last = *(Elements.rbegin());
787 return (Last.index() * ElementSize) + Last.find_last();
790 // Return true if the SparseBitVector is empty
792 return Elements.empty();
795 unsigned count() const {
796 unsigned BitCount = 0;
797 for (ElementListConstIter Iter = Elements.begin();
798 Iter != Elements.end();
800 BitCount += Iter->count();
805 iterator begin() const {
806 return iterator(this);
809 iterator end() const {
810 return iterator(this, true);
814 // Convenience functions to allow Or and And without dereferencing in the user
817 template <unsigned ElementSize>
818 inline bool operator |=(SparseBitVector<ElementSize> &LHS,
819 const SparseBitVector<ElementSize> *RHS) {
823 template <unsigned ElementSize>
824 inline bool operator |=(SparseBitVector<ElementSize> *LHS,
825 const SparseBitVector<ElementSize> &RHS) {
826 return LHS->operator|=(RHS);
829 template <unsigned ElementSize>
830 inline bool operator &=(SparseBitVector<ElementSize> *LHS,
831 const SparseBitVector<ElementSize> &RHS) {
832 return LHS->operator&=(RHS);
835 template <unsigned ElementSize>
836 inline bool operator &=(SparseBitVector<ElementSize> &LHS,
837 const SparseBitVector<ElementSize> *RHS) {
841 // Convenience functions for infix union, intersection, difference operators.
843 template <unsigned ElementSize>
844 inline SparseBitVector<ElementSize>
845 operator|(const SparseBitVector<ElementSize> &LHS,
846 const SparseBitVector<ElementSize> &RHS) {
847 SparseBitVector<ElementSize> Result(LHS);
852 template <unsigned ElementSize>
853 inline SparseBitVector<ElementSize>
854 operator&(const SparseBitVector<ElementSize> &LHS,
855 const SparseBitVector<ElementSize> &RHS) {
856 SparseBitVector<ElementSize> Result(LHS);
861 template <unsigned ElementSize>
862 inline SparseBitVector<ElementSize>
863 operator-(const SparseBitVector<ElementSize> &LHS,
864 const SparseBitVector<ElementSize> &RHS) {
865 SparseBitVector<ElementSize> Result;
866 Result.intersectWithComplement(LHS, RHS);
870 // Dump a SparseBitVector to a stream
871 template <unsigned ElementSize>
872 void dump(const SparseBitVector<ElementSize> &LHS, raw_ostream &out) {
875 typename SparseBitVector<ElementSize>::iterator bi = LHS.begin(),
879 for (++bi; bi != be; ++bi) {
886 } // end namespace llvm
888 #endif // LLVM_ADT_SPARSEBITVECTOR_H