Miscellaneous Fixes for SparseBitVector
[oota-llvm.git] / include / llvm / ADT / SparseBitVector.h
1 //===- llvm/ADT/SparseBitVector.h - Efficient Sparse BitVector -*- 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 SparseBitVector class.  See the doxygen comment for
11 // SparseBitVector for more details on the algorithm used.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ADT_SPARSEBITVECTOR_H
16 #define LLVM_ADT_SPARSEBITVECTOR_H
17
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <cassert>
25 #include <climits>
26
27 namespace llvm {
28
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.
41
42
43 template <unsigned ElementSize = 128>
44 struct SparseBitVectorElement
45   : public ilist_node<SparseBitVectorElement<ElementSize> > {
46 public:
47   typedef unsigned long BitWord;
48   typedef unsigned size_type;
49   enum {
50     BITWORD_SIZE = sizeof(BitWord) * CHAR_BIT,
51     BITWORDS_PER_ELEMENT = (ElementSize + BITWORD_SIZE - 1) / BITWORD_SIZE,
52     BITS_PER_ELEMENT = ElementSize
53   };
54
55 private:
56   // Index of Element in terms of where first bit starts.
57   unsigned ElementIndex;
58   BitWord Bits[BITWORDS_PER_ELEMENT];
59   // Needed for sentinels
60   friend struct ilist_sentinel_traits<SparseBitVectorElement>;
61   SparseBitVectorElement() {
62     ElementIndex = ~0U;
63     memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
64   }
65
66 public:
67   explicit SparseBitVectorElement(unsigned Idx) {
68     ElementIndex = Idx;
69     memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
70   }
71
72   // Comparison.
73   bool operator==(const SparseBitVectorElement &RHS) const {
74     if (ElementIndex != RHS.ElementIndex)
75       return false;
76     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
77       if (Bits[i] != RHS.Bits[i])
78         return false;
79     return true;
80   }
81
82   bool operator!=(const SparseBitVectorElement &RHS) const {
83     return !(*this == RHS);
84   }
85
86   // Return the bits that make up word Idx in our element.
87   BitWord word(unsigned Idx) const {
88     assert (Idx < BITWORDS_PER_ELEMENT);
89     return Bits[Idx];
90   }
91
92   unsigned index() const {
93     return ElementIndex;
94   }
95
96   bool empty() const {
97     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
98       if (Bits[i])
99         return false;
100     return true;
101   }
102
103   void set(unsigned Idx) {
104     Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
105   }
106
107   bool test_and_set (unsigned Idx) {
108     bool old = test(Idx);
109     if (!old) {
110       set(Idx);
111       return true;
112     }
113     return false;
114   }
115
116   void reset(unsigned Idx) {
117     Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
118   }
119
120   bool test(unsigned Idx) const {
121     return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
122   }
123
124   size_type count() const {
125     unsigned NumBits = 0;
126     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
127       NumBits += countPopulation(Bits[i]);
128     return NumBits;
129   }
130
131   /// find_first - Returns the index of the first set bit.
132   int find_first() const {
133     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
134       if (Bits[i] != 0)
135         return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
136     llvm_unreachable("Illegal empty element");
137   }
138
139   /// find_next - Returns the index of the next set bit starting from the
140   /// "Curr" bit. Returns -1 if the next set bit is not found.
141   int find_next(unsigned Curr) const {
142     if (Curr >= BITS_PER_ELEMENT)
143       return -1;
144
145     unsigned WordPos = Curr / BITWORD_SIZE;
146     unsigned BitPos = Curr % BITWORD_SIZE;
147     BitWord Copy = Bits[WordPos];
148     assert (WordPos <= BITWORDS_PER_ELEMENT
149             && "Word Position outside of element");
150
151     // Mask off previous bits.
152     Copy &= ~0UL << BitPos;
153
154     if (Copy != 0)
155       return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
156
157     // Check subsequent words.
158     for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
159       if (Bits[i] != 0)
160         return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
161     return -1;
162   }
163
164   // Union this element with RHS and return true if this one changed.
165   bool unionWith(const SparseBitVectorElement &RHS) {
166     bool changed = false;
167     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
168       BitWord old = changed ? 0 : Bits[i];
169
170       Bits[i] |= RHS.Bits[i];
171       if (!changed && old != Bits[i])
172         changed = true;
173     }
174     return changed;
175   }
176
177   // Return true if we have any bits in common with RHS
178   bool intersects(const SparseBitVectorElement &RHS) const {
179     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
180       if (RHS.Bits[i] & Bits[i])
181         return true;
182     }
183     return false;
184   }
185
186   // Intersect this Element with RHS and return true if this one changed.
187   // BecameZero is set to true if this element became all-zero bits.
188   bool intersectWith(const SparseBitVectorElement &RHS,
189                      bool &BecameZero) {
190     bool changed = false;
191     bool allzero = true;
192
193     BecameZero = false;
194     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
195       BitWord old = changed ? 0 : Bits[i];
196
197       Bits[i] &= RHS.Bits[i];
198       if (Bits[i] != 0)
199         allzero = false;
200
201       if (!changed && old != Bits[i])
202         changed = true;
203     }
204     BecameZero = allzero;
205     return changed;
206   }
207   // Intersect this Element with the complement of RHS and return true if this
208   // one changed.  BecameZero is set to true if this element became all-zero
209   // bits.
210   bool intersectWithComplement(const SparseBitVectorElement &RHS,
211                                bool &BecameZero) {
212     bool changed = false;
213     bool allzero = true;
214
215     BecameZero = false;
216     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
217       BitWord old = changed ? 0 : Bits[i];
218
219       Bits[i] &= ~RHS.Bits[i];
220       if (Bits[i] != 0)
221         allzero = false;
222
223       if (!changed && old != Bits[i])
224         changed = true;
225     }
226     BecameZero = allzero;
227     return changed;
228   }
229   // Three argument version of intersectWithComplement that intersects
230   // RHS1 & ~RHS2 into this element
231   void intersectWithComplement(const SparseBitVectorElement &RHS1,
232                                const SparseBitVectorElement &RHS2,
233                                bool &BecameZero) {
234     bool allzero = true;
235
236     BecameZero = false;
237     for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
238       Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
239       if (Bits[i] != 0)
240         allzero = false;
241     }
242     BecameZero = allzero;
243   }
244 };
245
246 template <unsigned ElementSize>
247 struct ilist_traits<SparseBitVectorElement<ElementSize> >
248   : public ilist_default_traits<SparseBitVectorElement<ElementSize> > {
249   typedef SparseBitVectorElement<ElementSize> Element;
250
251   Element *createSentinel() const { return static_cast<Element *>(&Sentinel); }
252   static void destroySentinel(Element *) {}
253
254   Element *provideInitialHead() const { return createSentinel(); }
255   Element *ensureHead(Element *) const { return createSentinel(); }
256   static void noteHead(Element *, Element *) {}
257
258 private:
259   mutable ilist_half_node<Element> Sentinel;
260 };
261
262 template <unsigned ElementSize = 128>
263 class SparseBitVector {
264   typedef ilist<SparseBitVectorElement<ElementSize> > ElementList;
265   typedef typename ElementList::iterator ElementListIter;
266   typedef typename ElementList::const_iterator ElementListConstIter;
267   enum {
268     BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
269   };
270
271   // Pointer to our current Element.
272   ElementListIter CurrElementIter;
273   ElementList Elements;
274
275   // This is like std::lower_bound, except we do linear searching from the
276   // current position.
277   ElementListIter FindLowerBound(unsigned ElementIndex) {
278
279     if (Elements.empty()) {
280       CurrElementIter = Elements.begin();
281       return Elements.begin();
282     }
283
284     // Make sure our current iterator is valid.
285     if (CurrElementIter == Elements.end())
286       --CurrElementIter;
287
288     // Search from our current iterator, either backwards or forwards,
289     // depending on what element we are looking for.
290     ElementListIter ElementIter = CurrElementIter;
291     if (CurrElementIter->index() == ElementIndex) {
292       return ElementIter;
293     } else if (CurrElementIter->index() > ElementIndex) {
294       while (ElementIter != Elements.begin()
295              && ElementIter->index() > ElementIndex)
296         --ElementIter;
297     } else {
298       while (ElementIter != Elements.end() &&
299              ElementIter->index() < ElementIndex)
300         ++ElementIter;
301     }
302     CurrElementIter = ElementIter;
303     return ElementIter;
304   }
305
306   // Iterator to walk set bits in the bitmap.  This iterator is a lot uglier
307   // than it would be, in order to be efficient.
308   class SparseBitVectorIterator {
309   private:
310     bool AtEnd;
311
312     const SparseBitVector<ElementSize> *BitVector;
313
314     // Current element inside of bitmap.
315     ElementListConstIter Iter;
316
317     // Current bit number inside of our bitmap.
318     unsigned BitNumber;
319
320     // Current word number inside of our element.
321     unsigned WordNumber;
322
323     // Current bits from the element.
324     typename SparseBitVectorElement<ElementSize>::BitWord Bits;
325
326     // Move our iterator to the first non-zero bit in the bitmap.
327     void AdvanceToFirstNonZero() {
328       if (AtEnd)
329         return;
330       if (BitVector->Elements.empty()) {
331         AtEnd = true;
332         return;
333       }
334       Iter = BitVector->Elements.begin();
335       BitNumber = Iter->index() * ElementSize;
336       unsigned BitPos = Iter->find_first();
337       BitNumber += BitPos;
338       WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
339       Bits = Iter->word(WordNumber);
340       Bits >>= BitPos % BITWORD_SIZE;
341     }
342
343     // Move our iterator to the next non-zero bit.
344     void AdvanceToNextNonZero() {
345       if (AtEnd)
346         return;
347
348       while (Bits && !(Bits & 1)) {
349         Bits >>= 1;
350         BitNumber += 1;
351       }
352
353       // See if we ran out of Bits in this word.
354       if (!Bits) {
355         int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
356         // If we ran out of set bits in this element, move to next element.
357         if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
358           ++Iter;
359           WordNumber = 0;
360
361           // We may run out of elements in the bitmap.
362           if (Iter == BitVector->Elements.end()) {
363             AtEnd = true;
364             return;
365           }
366           // Set up for next non-zero word in bitmap.
367           BitNumber = Iter->index() * ElementSize;
368           NextSetBitNumber = Iter->find_first();
369           BitNumber += NextSetBitNumber;
370           WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
371           Bits = Iter->word(WordNumber);
372           Bits >>= NextSetBitNumber % BITWORD_SIZE;
373         } else {
374           WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
375           Bits = Iter->word(WordNumber);
376           Bits >>= NextSetBitNumber % BITWORD_SIZE;
377           BitNumber = Iter->index() * ElementSize;
378           BitNumber += NextSetBitNumber;
379         }
380       }
381     }
382   public:
383     // Preincrement.
384     inline SparseBitVectorIterator& operator++() {
385       ++BitNumber;
386       Bits >>= 1;
387       AdvanceToNextNonZero();
388       return *this;
389     }
390
391     // Postincrement.
392     inline SparseBitVectorIterator operator++(int) {
393       SparseBitVectorIterator tmp = *this;
394       ++*this;
395       return tmp;
396     }
397
398     // Return the current set bit number.
399     unsigned operator*() const {
400       return BitNumber;
401     }
402
403     bool operator==(const SparseBitVectorIterator &RHS) const {
404       // If they are both at the end, ignore the rest of the fields.
405       if (AtEnd && RHS.AtEnd)
406         return true;
407       // Otherwise they are the same if they have the same bit number and
408       // bitmap.
409       return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
410     }
411     bool operator!=(const SparseBitVectorIterator &RHS) const {
412       return !(*this == RHS);
413     }
414     SparseBitVectorIterator(): BitVector(NULL) {
415     }
416
417
418     SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
419                             bool end = false):BitVector(RHS) {
420       Iter = BitVector->Elements.begin();
421       BitNumber = 0;
422       Bits = 0;
423       WordNumber = ~0;
424       AtEnd = end;
425       AdvanceToFirstNonZero();
426     }
427   };
428 public:
429   typedef SparseBitVectorIterator iterator;
430
431   SparseBitVector () {
432     CurrElementIter = Elements.begin ();
433   }
434
435   ~SparseBitVector() {
436   }
437
438   // SparseBitVector copy ctor.
439   SparseBitVector(const SparseBitVector &RHS) {
440     ElementListConstIter ElementIter = RHS.Elements.begin();
441     while (ElementIter != RHS.Elements.end()) {
442       Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
443       ++ElementIter;
444     }
445
446     CurrElementIter = Elements.begin ();
447   }
448
449   // Clear.
450   void clear() {
451     Elements.clear();
452   }
453
454   // Assignment
455   SparseBitVector& operator=(const SparseBitVector& RHS) {
456     if (this == &RHS)
457       return *this;
458
459     Elements.clear();
460
461     ElementListConstIter ElementIter = RHS.Elements.begin();
462     while (ElementIter != RHS.Elements.end()) {
463       Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
464       ++ElementIter;
465     }
466
467     CurrElementIter = Elements.begin ();
468
469     return *this;
470   }
471
472   // Test, Reset, and Set a bit in the bitmap.
473   bool test(unsigned Idx) {
474     if (Elements.empty())
475       return false;
476
477     unsigned ElementIndex = Idx / ElementSize;
478     ElementListIter ElementIter = FindLowerBound(ElementIndex);
479
480     // If we can't find an element that is supposed to contain this bit, there
481     // is nothing more to do.
482     if (ElementIter == Elements.end() ||
483         ElementIter->index() != ElementIndex)
484       return false;
485     return ElementIter->test(Idx % ElementSize);
486   }
487
488   void reset(unsigned Idx) {
489     if (Elements.empty())
490       return;
491
492     unsigned ElementIndex = Idx / ElementSize;
493     ElementListIter ElementIter = FindLowerBound(ElementIndex);
494
495     // If we can't find an element that is supposed to contain this bit, there
496     // is nothing more to do.
497     if (ElementIter == Elements.end() ||
498         ElementIter->index() != ElementIndex)
499       return;
500     ElementIter->reset(Idx % ElementSize);
501
502     // When the element is zeroed out, delete it.
503     if (ElementIter->empty()) {
504       ++CurrElementIter;
505       Elements.erase(ElementIter);
506     }
507   }
508
509   void set(unsigned Idx) {
510     unsigned ElementIndex = Idx / ElementSize;
511     SparseBitVectorElement<ElementSize> *Element;
512     ElementListIter ElementIter;
513     if (Elements.empty()) {
514       Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
515       ElementIter = Elements.insert(Elements.end(), Element);
516
517     } else {
518       ElementIter = FindLowerBound(ElementIndex);
519
520       if (ElementIter == Elements.end() ||
521           ElementIter->index() != ElementIndex) {
522         Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
523         // We may have hit the beginning of our SparseBitVector, in which case,
524         // we may need to insert right after this element, which requires moving
525         // the current iterator forward one, because insert does insert before.
526         if (ElementIter != Elements.end() &&
527             ElementIter->index() < ElementIndex)
528           ElementIter = Elements.insert(++ElementIter, Element);
529         else
530           ElementIter = Elements.insert(ElementIter, Element);
531       }
532     }
533     CurrElementIter = ElementIter;
534
535     ElementIter->set(Idx % ElementSize);
536   }
537
538   bool test_and_set (unsigned Idx) {
539     bool old = test(Idx);
540     if (!old) {
541       set(Idx);
542       return true;
543     }
544     return false;
545   }
546
547   bool operator!=(const SparseBitVector &RHS) const {
548     return !(*this == RHS);
549   }
550
551   bool operator==(const SparseBitVector &RHS) const {
552     ElementListConstIter Iter1 = Elements.begin();
553     ElementListConstIter Iter2 = RHS.Elements.begin();
554
555     for (; Iter1 != Elements.end() && Iter2 != RHS.Elements.end();
556          ++Iter1, ++Iter2) {
557       if (*Iter1 != *Iter2)
558         return false;
559     }
560     return Iter1 == Elements.end() && Iter2 == RHS.Elements.end();
561   }
562
563   // Union our bitmap with the RHS and return true if we changed.
564   bool operator|=(const SparseBitVector &RHS) {
565     if (this == &RHS)
566       return false;
567
568     bool changed = false;
569     ElementListIter Iter1 = Elements.begin();
570     ElementListConstIter Iter2 = RHS.Elements.begin();
571
572     // If RHS is empty, we are done
573     if (RHS.Elements.empty())
574       return false;
575
576     while (Iter2 != RHS.Elements.end()) {
577       if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
578         Elements.insert(Iter1,
579                         new SparseBitVectorElement<ElementSize>(*Iter2));
580         ++Iter2;
581         changed = true;
582       } else if (Iter1->index() == Iter2->index()) {
583         changed |= Iter1->unionWith(*Iter2);
584         ++Iter1;
585         ++Iter2;
586       } else {
587         ++Iter1;
588       }
589     }
590     CurrElementIter = Elements.begin();
591     return changed;
592   }
593
594   // Intersect our bitmap with the RHS and return true if ours changed.
595   bool operator&=(const SparseBitVector &RHS) {
596     if (this == &RHS)
597       return false;
598
599     bool changed = false;
600     ElementListIter Iter1 = Elements.begin();
601     ElementListConstIter Iter2 = RHS.Elements.begin();
602
603     // Check if both bitmaps are empty.
604     if (Elements.empty() && RHS.Elements.empty())
605       return false;
606
607     // Loop through, intersecting as we go, erasing elements when necessary.
608     while (Iter2 != RHS.Elements.end()) {
609       if (Iter1 == Elements.end()) {
610         CurrElementIter = Elements.begin();
611         return changed;
612       }
613
614       if (Iter1->index() > Iter2->index()) {
615         ++Iter2;
616       } else if (Iter1->index() == Iter2->index()) {
617         bool BecameZero;
618         changed |= Iter1->intersectWith(*Iter2, BecameZero);
619         if (BecameZero) {
620           ElementListIter IterTmp = Iter1;
621           ++Iter1;
622           Elements.erase(IterTmp);
623         } else {
624           ++Iter1;
625         }
626         ++Iter2;
627       } else {
628         ElementListIter IterTmp = Iter1;
629         ++Iter1;
630         Elements.erase(IterTmp);
631         changed = true;
632       }
633     }
634     if (Iter1 != Elements.end()) {
635       Elements.erase(Iter1, Elements.end());
636       changed = true;
637     }
638     CurrElementIter = Elements.begin();
639     return changed;
640   }
641
642   // Intersect our bitmap with the complement of the RHS and return true
643   // if ours changed.
644   bool intersectWithComplement(const SparseBitVector &RHS) {
645     if (this == &RHS) {
646       if (!empty()) {
647         clear();
648         return true;
649       }
650       return false;
651     }
652
653     bool changed = false;
654     ElementListIter Iter1 = Elements.begin();
655     ElementListConstIter Iter2 = RHS.Elements.begin();
656
657     // If either our bitmap or RHS is empty, we are done
658     if (Elements.empty() || RHS.Elements.empty())
659       return false;
660
661     // Loop through, intersecting as we go, erasing elements when necessary.
662     while (Iter2 != RHS.Elements.end()) {
663       if (Iter1 == Elements.end()) {
664         CurrElementIter = Elements.begin();
665         return changed;
666       }
667
668       if (Iter1->index() > Iter2->index()) {
669         ++Iter2;
670       } else if (Iter1->index() == Iter2->index()) {
671         bool BecameZero;
672         changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
673         if (BecameZero) {
674           ElementListIter IterTmp = Iter1;
675           ++Iter1;
676           Elements.erase(IterTmp);
677         } else {
678           ++Iter1;
679         }
680         ++Iter2;
681       } else {
682         ++Iter1;
683       }
684     }
685     CurrElementIter = Elements.begin();
686     return changed;
687   }
688
689   bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
690     return intersectWithComplement(*RHS);
691   }
692
693
694   //  Three argument version of intersectWithComplement.
695   //  Result of RHS1 & ~RHS2 is stored into this bitmap.
696   void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
697                                const SparseBitVector<ElementSize> &RHS2)
698   {
699     if (this == &RHS1) {
700       intersectWithComplement(RHS2);
701       return;
702     } else if (this == &RHS2) {
703       SparseBitVector RHS2Copy(RHS2);
704       intersectWithComplement(RHS1, RHS2Copy);
705       return;
706     }
707
708     Elements.clear();
709     CurrElementIter = Elements.begin();
710     ElementListConstIter Iter1 = RHS1.Elements.begin();
711     ElementListConstIter Iter2 = RHS2.Elements.begin();
712
713     // If RHS1 is empty, we are done
714     // If RHS2 is empty, we still have to copy RHS1
715     if (RHS1.Elements.empty())
716       return;
717
718     // Loop through, intersecting as we go, erasing elements when necessary.
719     while (Iter2 != RHS2.Elements.end()) {
720       if (Iter1 == RHS1.Elements.end())
721         return;
722
723       if (Iter1->index() > Iter2->index()) {
724         ++Iter2;
725       } else if (Iter1->index() == Iter2->index()) {
726         bool BecameZero = false;
727         SparseBitVectorElement<ElementSize> *NewElement =
728           new SparseBitVectorElement<ElementSize>(Iter1->index());
729         NewElement->intersectWithComplement(*Iter1, *Iter2, BecameZero);
730         if (!BecameZero) {
731           Elements.push_back(NewElement);
732         }
733         else
734           delete NewElement;
735         ++Iter1;
736         ++Iter2;
737       } else {
738         SparseBitVectorElement<ElementSize> *NewElement =
739           new SparseBitVectorElement<ElementSize>(*Iter1);
740         Elements.push_back(NewElement);
741         ++Iter1;
742       }
743     }
744
745     // copy the remaining elements
746     while (Iter1 != RHS1.Elements.end()) {
747         SparseBitVectorElement<ElementSize> *NewElement =
748           new SparseBitVectorElement<ElementSize>(*Iter1);
749         Elements.push_back(NewElement);
750         ++Iter1;
751       }
752
753     return;
754   }
755
756   void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
757                                const SparseBitVector<ElementSize> *RHS2) {
758     intersectWithComplement(*RHS1, *RHS2);
759   }
760
761   bool intersects(const SparseBitVector<ElementSize> *RHS) const {
762     return intersects(*RHS);
763   }
764
765   // Return true if we share any bits in common with RHS
766   bool intersects(const SparseBitVector<ElementSize> &RHS) const {
767     ElementListConstIter Iter1 = Elements.begin();
768     ElementListConstIter Iter2 = RHS.Elements.begin();
769
770     // Check if both bitmaps are empty.
771     if (Elements.empty() && RHS.Elements.empty())
772       return false;
773
774     // Loop through, intersecting stopping when we hit bits in common.
775     while (Iter2 != RHS.Elements.end()) {
776       if (Iter1 == Elements.end())
777         return false;
778
779       if (Iter1->index() > Iter2->index()) {
780         ++Iter2;
781       } else if (Iter1->index() == Iter2->index()) {
782         if (Iter1->intersects(*Iter2))
783           return true;
784         ++Iter1;
785         ++Iter2;
786       } else {
787         ++Iter1;
788       }
789     }
790     return false;
791   }
792
793   // Return true iff all bits set in this SparseBitVector are
794   // also set in RHS.
795   bool contains(const SparseBitVector<ElementSize> &RHS) const {
796     SparseBitVector<ElementSize> Result(*this);
797     Result &= RHS;
798     return (Result == RHS);
799   }
800
801   // Return the first set bit in the bitmap.  Return -1 if no bits are set.
802   int find_first() const {
803     if (Elements.empty())
804       return -1;
805     const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
806     return (First.index() * ElementSize) + First.find_first();
807   }
808
809   // Return true if the SparseBitVector is empty
810   bool empty() const {
811     return Elements.empty();
812   }
813
814   unsigned count() const {
815     unsigned BitCount = 0;
816     for (ElementListConstIter Iter = Elements.begin();
817          Iter != Elements.end();
818          ++Iter)
819       BitCount += Iter->count();
820
821     return BitCount;
822   }
823   iterator begin() const {
824     return iterator(this);
825   }
826
827   iterator end() const {
828     return iterator(this, true);
829   }
830 };
831
832 // Convenience functions to allow Or and And without dereferencing in the user
833 // code.
834
835 template <unsigned ElementSize>
836 inline bool operator |=(SparseBitVector<ElementSize> &LHS,
837                         const SparseBitVector<ElementSize> *RHS) {
838   return LHS |= *RHS;
839 }
840
841 template <unsigned ElementSize>
842 inline bool operator |=(SparseBitVector<ElementSize> *LHS,
843                         const SparseBitVector<ElementSize> &RHS) {
844   return LHS->operator|=(RHS);
845 }
846
847 template <unsigned ElementSize>
848 inline bool operator &=(SparseBitVector<ElementSize> *LHS,
849                         const SparseBitVector<ElementSize> &RHS) {
850   return LHS->operator&=(RHS);
851 }
852
853 template <unsigned ElementSize>
854 inline bool operator &=(SparseBitVector<ElementSize> &LHS,
855                         const SparseBitVector<ElementSize> *RHS) {
856   return LHS &= *RHS;
857 }
858
859 // Convenience functions for infix union, intersection, difference operators.
860
861 template <unsigned ElementSize>
862 inline SparseBitVector<ElementSize>
863 operator|(const SparseBitVector<ElementSize> &LHS,
864           const SparseBitVector<ElementSize> &RHS) {
865   SparseBitVector<ElementSize> Result(LHS);
866   Result |= RHS;
867   return Result;
868 }
869
870 template <unsigned ElementSize>
871 inline SparseBitVector<ElementSize>
872 operator&(const SparseBitVector<ElementSize> &LHS,
873           const SparseBitVector<ElementSize> &RHS) {
874   SparseBitVector<ElementSize> Result(LHS);
875   Result &= RHS;
876   return Result;
877 }
878
879 template <unsigned ElementSize>
880 inline SparseBitVector<ElementSize>
881 operator-(const SparseBitVector<ElementSize> &LHS,
882           const SparseBitVector<ElementSize> &RHS) {
883   SparseBitVector<ElementSize> Result;
884   Result.intersectWithComplement(LHS, RHS);
885   return Result;
886 }
887
888
889
890
891 // Dump a SparseBitVector to a stream
892 template <unsigned ElementSize>
893 void dump(const SparseBitVector<ElementSize> &LHS, raw_ostream &out) {
894   out << "[";
895
896   typename SparseBitVector<ElementSize>::iterator bi = LHS.begin(),
897     be = LHS.end();
898   if (bi != be) {
899     out << *bi;
900     for (++bi; bi != be; ++bi) {
901       out << " " << *bi;
902     }
903   }
904   out << "]\n";
905 }
906 } // end namespace llvm
907
908 #endif