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