llvm.org GIT mirror llvm / 3a54b3d
Removed trailing whitespace. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@62000 91177308-0d34-0410-b5e6-96231b3b80d8 Misha Brukman 11 years ago
30 changed file(s) with 942 addition(s) and 942 deletion(s). Raw diff Collapse all Expand all
190190 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false) {
191191 return APFloat(Sem, fcNaN, Negative);
192192 }
193
193
194194 /// Profile - Used to insert APFloat objects, or objects that contain
195195 /// APFloat objects, into FoldingSets.
196196 void Profile(FoldingSetNodeID& NID) const;
197
197
198198 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
199199 void Emit(Serializer& S) const;
200
200
201201 /// @brief Used by the Bitcode deserializer to deserialize APInts.
202202 static APFloat ReadVal(Deserializer& D);
203203
2525 class Deserializer;
2626 class FoldingSetNodeID;
2727 class raw_ostream;
28
28
2929 template
3030 class SmallVectorImpl;
31
31
3232 /* An unsigned host type used as a single part of a multi-part
3333 bignum. */
3434 typedef uint64_t integerPart;
4242 //===----------------------------------------------------------------------===//
4343
4444 /// APInt - This class represents arbitrary precision constant integral values.
45 /// It is a functional replacement for common case unsigned integer type like
46 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
45 /// It is a functional replacement for common case unsigned integer type like
46 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
4747 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
48 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
48 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
4949 /// and methods to manipulate integer values of any bit-width. It supports both
5050 /// the typical integer arithmetic and comparison operations as well as bitwise
5151 /// manipulation.
5252 ///
5353 /// The class has several invariants worth noting:
5454 /// * All bit, byte, and word positions are zero-based.
55 /// * Once the bit width is set, it doesn't change except by the Truncate,
55 /// * Once the bit width is set, it doesn't change except by the Truncate,
5656 /// SignExtend, or ZeroExtend operations.
5757 /// * All binary operators must be on APInt instances of the same bit width.
58 /// Attempting to use these operators on instances with different bit
58 /// Attempting to use these operators on instances with different bit
5959 /// widths will yield an assertion.
6060 /// * The value is stored canonically as an unsigned value. For operations
6161 /// where it makes a difference, there are both signed and unsigned variants
9292
9393 /// @returns true if the number of bits <= 64, false otherwise.
9494 /// @brief Determine if this APInt just has one word to store value.
95 bool isSingleWord() const {
96 return BitWidth <= APINT_BITS_PER_WORD;
95 bool isSingleWord() const {
96 return BitWidth <= APINT_BITS_PER_WORD;
9797 }
9898
9999 /// @returns the word position for the specified bit position.
100100 /// @brief Determine which word a bit is in.
101 static uint32_t whichWord(uint32_t bitPosition) {
102 return bitPosition / APINT_BITS_PER_WORD;
103 }
104
105 /// @returns the bit position in a word for the specified bit position
101 static uint32_t whichWord(uint32_t bitPosition) {
102 return bitPosition / APINT_BITS_PER_WORD;
103 }
104
105 /// @returns the bit position in a word for the specified bit position
106106 /// in the APInt.
107107 /// @brief Determine which bit in a word a bit is in.
108 static uint32_t whichBit(uint32_t bitPosition) {
109 return bitPosition % APINT_BITS_PER_WORD;
110 }
111
112 /// This method generates and returns a uint64_t (word) mask for a single
113 /// bit at a specific bit position. This is used to mask the bit in the
108 static uint32_t whichBit(uint32_t bitPosition) {
109 return bitPosition % APINT_BITS_PER_WORD;
110 }
111
112 /// This method generates and returns a uint64_t (word) mask for a single
113 /// bit at a specific bit position. This is used to mask the bit in the
114114 /// corresponding word.
115115 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
116116 /// @brief Get a single bit mask.
117 static uint64_t maskBit(uint32_t bitPosition) {
118 return 1ULL << whichBit(bitPosition);
117 static uint64_t maskBit(uint32_t bitPosition) {
118 return 1ULL << whichBit(bitPosition);
119119 }
120120
121121 /// This method is used internally to clear the to "N" bits in the high order
122 /// word that are not used by the APInt. This is needed after the most
123 /// significant word is assigned a value to ensure that those bits are
122 /// word that are not used by the APInt. This is needed after the most
123 /// significant word is assigned a value to ensure that those bits are
124124 /// zero'd out.
125125 /// @brief Clear unused high order bits
126126 APInt& clearUnusedBits() {
143143
144144 /// @returns the corresponding word for the specified bit position.
145145 /// @brief Get the word corresponding to a bit position
146 uint64_t getWord(uint32_t bitPosition) const {
147 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
146 uint64_t getWord(uint32_t bitPosition) const {
147 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
148148 }
149149
150150 /// This is used by the constructors that take string arguments.
151151 /// @brief Convert a char array into an APInt
152 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
152 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
153153 uint8_t radix);
154154
155155 /// This is used by the toString method to divide by the radix. It simply
157157 /// has specific constraints on its inputs. If those constraints are not met
158158 /// then it provides a simpler form of divide.
159159 /// @brief An internal division function for dividing APInts.
160 static void divide(const APInt LHS, uint32_t lhsWords,
160 static void divide(const APInt LHS, uint32_t lhsWords,
161161 const APInt &RHS, uint32_t rhsWords,
162162 APInt *Quotient, APInt *Remainder);
163163
227227 APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[]);
228228
229229 /// This constructor interprets the slen characters starting at StrStart as
230 /// a string in the given radix. The interpretation stops when the first
230 /// a string in the given radix. The interpretation stops when the first
231231 /// character that is not suitable for the radix is encountered. Acceptable
232232 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
233233 /// the string to require more bits than numBits.
243243 APInt(const APInt& that)
244244 : BitWidth(that.BitWidth), VAL(0) {
245245 assert(BitWidth && "bitwidth too small");
246 if (isSingleWord())
246 if (isSingleWord())
247247 VAL = that.VAL;
248248 else
249249 initSlowCase(that);
251251
252252 /// @brief Destructor.
253253 ~APInt() {
254 if (!isSingleWord())
254 if (!isSingleWord())
255255 delete [] pVal;
256256 }
257257
258258 /// Default constructor that creates an uninitialized APInt. This is useful
259259 /// for object deserialization (pair this with the static method Read).
260260 explicit APInt() : BitWidth(1) {}
261
262 /// Profile - Used to insert APInt objects, or objects that contain APInt
261
262 /// Profile - Used to insert APInt objects, or objects that contain APInt
263263 /// objects, into FoldingSets.
264264 void Profile(FoldingSetNodeID& id) const;
265
265
266266 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
267267 void Emit(Serializer& S) const;
268
268
269269 /// @brief Used by the Bitcode deserializer to deserialize APInts.
270270 void Read(Deserializer& D);
271271
334334 assert(N && "N == 0 ???");
335335 if (N >= getBitWidth())
336336 return true;
337
337
338338 if (isSingleWord())
339339 return VAL == (VAL & (~0ULL >> (64 - N)));
340340 APInt Tmp(N, getNumWords(), pVal);
349349 }
350350
351351 /// @returns true if the argument APInt value is a power of two > 0.
352 bool isPowerOf2() const;
352 bool isPowerOf2() const;
353353
354354 /// isSignBit - Return true if this is the value returned by getSignBit.
355355 bool isSignBit() const { return isMinSignedValue(); }
356
356
357357 /// This converts the APInt to a boolean value as a test against zero.
358 /// @brief Boolean conversion function.
358 /// @brief Boolean conversion function.
359359 bool getBoolValue() const {
360360 return *this != 0;
361361 }
424424 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
425425 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
426426 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
427 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
427 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
428428 /// @param numBits the intended bit width of the result
429429 /// @param loBit the index of the lowest bit set.
430430 /// @param hiBit the index of the highest bit set.
477477 /// @brief Get a hash value based on this APInt
478478 uint64_t getHashValue() const;
479479
480 /// This function returns a pointer to the internal storage of the APInt.
480 /// This function returns a pointer to the internal storage of the APInt.
481481 /// This is useful for writing out the APInt in binary form without any
482482 /// conversions.
483483 const uint64_t* getRawData() const {
502502 APInt& operator++();
503503
504504 /// @returns a new APInt representing *this decremented by one.
505 /// @brief Postfix decrement operator.
505 /// @brief Postfix decrement operator.
506506 const APInt operator--(int) {
507507 APInt API(*this);
508508 --(*this);
510510 }
511511
512512 /// @returns *this decremented by one.
513 /// @brief Prefix decrement operator.
513 /// @brief Prefix decrement operator.
514514 APInt& operator--();
515515
516 /// Performs a bitwise complement operation on this APInt.
516 /// Performs a bitwise complement operation on this APInt.
517517 /// @returns an APInt that is the bitwise complement of *this
518 /// @brief Unary bitwise complement operator.
518 /// @brief Unary bitwise complement operator.
519519 APInt operator~() const {
520520 APInt Result(*this);
521521 Result.flip();
531531
532532 /// Performs logical negation operation on this APInt.
533533 /// @returns true if *this is zero, false otherwise.
534 /// @brief Logical negation operator.
534 /// @brief Logical negation operator.
535535 bool operator!() const;
536536
537537 /// @}
538538 /// @name Assignment Operators
539539 /// @{
540540 /// @returns *this after assignment of RHS.
541 /// @brief Copy assignment operator.
541 /// @brief Copy assignment operator.
542542 APInt& operator=(const APInt& RHS) {
543543 // If the bitwidths are the same, we can avoid mucking with memory
544544 if (isSingleWord() && RHS.isSingleWord()) {
554554 /// the bit width, the excess bits are truncated. If the bit width is larger
555555 /// than 64, the value is zero filled in the unspecified high order bits.
556556 /// @returns *this after assignment of RHS value.
557 /// @brief Assignment operator.
557 /// @brief Assignment operator.
558558 APInt& operator=(uint64_t RHS);
559559
560560 /// Performs a bitwise AND operation on this APInt and RHS. The result is
561 /// assigned to *this.
561 /// assigned to *this.
562562 /// @returns *this after ANDing with RHS.
563 /// @brief Bitwise AND assignment operator.
563 /// @brief Bitwise AND assignment operator.
564564 APInt& operator&=(const APInt& RHS);
565565
566 /// Performs a bitwise OR operation on this APInt and RHS. The result is
566 /// Performs a bitwise OR operation on this APInt and RHS. The result is
567567 /// assigned *this;
568568 /// @returns *this after ORing with RHS.
569 /// @brief Bitwise OR assignment operator.
569 /// @brief Bitwise OR assignment operator.
570570 APInt& operator|=(const APInt& RHS);
571571
572572 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
573573 /// assigned to *this.
574574 /// @returns *this after XORing with RHS.
575 /// @brief Bitwise XOR assignment operator.
575 /// @brief Bitwise XOR assignment operator.
576576 APInt& operator^=(const APInt& RHS);
577577
578578 /// Multiplies this APInt by RHS and assigns the result to *this.
579579 /// @returns *this
580 /// @brief Multiplication assignment operator.
580 /// @brief Multiplication assignment operator.
581581 APInt& operator*=(const APInt& RHS);
582582
583583 /// Adds RHS to *this and assigns the result to *this.
584584 /// @returns *this
585 /// @brief Addition assignment operator.
585 /// @brief Addition assignment operator.
586586 APInt& operator+=(const APInt& RHS);
587587
588588 /// Subtracts RHS from *this and assigns the result to *this.
589589 /// @returns *this
590 /// @brief Subtraction assignment operator.
590 /// @brief Subtraction assignment operator.
591591 APInt& operator-=(const APInt& RHS);
592592
593593 /// Shifts *this left by shiftAmt and assigns the result to *this.
603603 /// @{
604604 /// Performs a bitwise AND operation on *this and RHS.
605605 /// @returns An APInt value representing the bitwise AND of *this and RHS.
606 /// @brief Bitwise AND operator.
606 /// @brief Bitwise AND operator.
607607 APInt operator&(const APInt& RHS) const {
608608 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
609609 if (isSingleWord())
616616
617617 /// Performs a bitwise OR operation on *this and RHS.
618618 /// @returns An APInt value representing the bitwise OR of *this and RHS.
619 /// @brief Bitwise OR operator.
619 /// @brief Bitwise OR operator.
620620 APInt operator|(const APInt& RHS) const {
621621 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
622622 if (isSingleWord())
629629
630630 /// Performs a bitwise XOR operation on *this and RHS.
631631 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
632 /// @brief Bitwise XOR operator.
632 /// @brief Bitwise XOR operator.
633633 APInt operator^(const APInt& RHS) const {
634634 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
635635 if (isSingleWord())
641641 }
642642
643643 /// Multiplies this APInt by RHS and returns the result.
644 /// @brief Multiplication operator.
644 /// @brief Multiplication operator.
645645 APInt operator*(const APInt& RHS) const;
646646
647647 /// Adds RHS to this APInt and returns the result.
648 /// @brief Addition operator.
648 /// @brief Addition operator.
649649 APInt operator+(const APInt& RHS) const;
650650 APInt operator+(uint64_t RHS) const {
651651 return (*this) + APInt(BitWidth, RHS);
652652 }
653653
654654 /// Subtracts RHS from this APInt and returns the result.
655 /// @brief Subtraction operator.
655 /// @brief Subtraction operator.
656656 APInt operator-(const APInt& RHS) const;
657657 APInt operator-(uint64_t RHS) const {
658658 return (*this) - APInt(BitWidth, RHS);
659659 }
660
660
661661 APInt operator<<(unsigned Bits) const {
662662 return shl(Bits);
663663 }
757757 /// may overlap with the pair of output arguments. It is safe to call
758758 /// udivrem(X, Y, X, Y), for example.
759759 /// @brief Dual division/remainder interface.
760 static void udivrem(const APInt &LHS, const APInt &RHS,
760 static void udivrem(const APInt &LHS, const APInt &RHS,
761761 APInt &Quotient, APInt &Remainder);
762762
763763 static void sdivrem(const APInt &LHS, const APInt &RHS,
787787 /// @{
788788 /// Compares this APInt with RHS for the validity of the equality
789789 /// relationship.
790 /// @brief Equality operator.
790 /// @brief Equality operator.
791791 bool operator==(const APInt& RHS) const {
792792 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
793793 if (isSingleWord())
795795 return EqualSlowCase(RHS);
796796 }
797797
798 /// Compares this APInt with a uint64_t for the validity of the equality
798 /// Compares this APInt with a uint64_t for the validity of the equality
799799 /// relationship.
800800 /// @returns true if *this == Val
801801 /// @brief Equality operator.
810810 /// @returns true if *this == Val
811811 /// @brief Equality comparison.
812812 bool eq(const APInt &RHS) const {
813 return (*this) == RHS;
813 return (*this) == RHS;
814814 }
815815
816816 /// Compares this APInt with RHS for the validity of the inequality
817817 /// relationship.
818818 /// @returns true if *this != Val
819 /// @brief Inequality operator.
819 /// @brief Inequality operator.
820820 bool operator!=(const APInt& RHS) const {
821821 return !((*this) == RHS);
822822 }
823823
824 /// Compares this APInt with a uint64_t for the validity of the inequality
824 /// Compares this APInt with a uint64_t for the validity of the inequality
825825 /// relationship.
826826 /// @returns true if *this != Val
827 /// @brief Inequality operator.
827 /// @brief Inequality operator.
828828 bool operator!=(uint64_t Val) const {
829829 return !((*this) == Val);
830830 }
831
831
832832 /// Compares this APInt with RHS for the validity of the inequality
833833 /// relationship.
834834 /// @returns true if *this != Val
907907 /// @name Resizing Operators
908908 /// @{
909909 /// Truncate the APInt to a specified width. It is an error to specify a width
910 /// that is greater than or equal to the current width.
910 /// that is greater than or equal to the current width.
911911 /// @brief Truncate to new width.
912912 APInt &trunc(uint32_t width);
913913
914914 /// This operation sign extends the APInt to a new width. If the high order
915915 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
916 /// It is an error to specify a width that is less than or equal to the
916 /// It is an error to specify a width that is less than or equal to the
917917 /// current width.
918918 /// @brief Sign extend to a new width.
919919 APInt &sext(uint32_t width);
920920
921921 /// This operation zero extends the APInt to a new width. The high order bits
922 /// are filled with 0 bits. It is an error to specify a width that is less
922 /// are filled with 0 bits. It is an error to specify a width that is less
923923 /// than or equal to the current width.
924924 /// @brief Zero extend to a new width.
925925 APInt &zext(uint32_t width);
957957
958958 /// @brief Set every bit to 0.
959959 APInt& clear() {
960 if (isSingleWord())
960 if (isSingleWord())
961961 VAL = 0;
962 else
962 else
963963 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
964964 return *this;
965965 }
979979 return clearUnusedBits();
980980 }
981981
982 /// Toggle a given bit to its opposite value whose position is given
982 /// Toggle a given bit to its opposite value whose position is given
983983 /// as "bitPosition".
984984 /// @brief Toggles a given bit to its opposite value.
985985 APInt& flip(uint32_t bitPosition);
989989 /// @{
990990
991991 /// @returns the total number of bits.
992 uint32_t getBitWidth() const {
993 return BitWidth;
992 uint32_t getBitWidth() const {
993 return BitWidth;
994994 }
995995
996996 /// Here one word's bitwidth equals to that of uint64_t.
10161016 }
10171017
10181018 /// Computes the minimum bit width for this APInt while considering it to be
1019 /// a signed (and probably negative) value. If the value is not negative,
1019 /// a signed (and probably negative) value. If the value is not negative,
10201020 /// this function returns the same value as getActiveBits()+1. Otherwise, it
10211021 /// returns the smallest bit width that will retain the negative value. For
10221022 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
10231023 /// for -1, this function will always return 1.
1024 /// @brief Get the minimum bit size for this signed APInt
1024 /// @brief Get the minimum bit size for this signed APInt
10251025 uint32_t getMinSignedBits() const {
10261026 if (isNegative())
10271027 return BitWidth - countLeadingOnes() + 1;
10451045 /// @brief Get sign extended value
10461046 int64_t getSExtValue() const {
10471047 if (isSingleWord())
1048 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1048 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
10491049 (APINT_BITS_PER_WORD - BitWidth);
10501050 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
10511051 return int64_t(pVal[0]);
10781078 /// @brief Count the number of leading one bits.
10791079 uint32_t countLeadingOnes() const;
10801080
1081 /// countTrailingZeros - This function is an APInt version of the
1082 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1081 /// countTrailingZeros - This function is an APInt version of the
1082 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
10831083 /// the number of zeros from the least significant bit to the first set bit.
10841084 /// @returns BitWidth if the value is zero.
10851085 /// @returns the number of zeros from the least significant bit to the first
10871087 /// @brief Count the number of trailing zero bits.
10881088 uint32_t countTrailingZeros() const;
10891089
1090 /// countTrailingOnes - This function is an APInt version of the
1091 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1090 /// countTrailingOnes - This function is an APInt version of the
1091 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
10921092 /// the number of ones from the least significant bit to the first zero bit.
10931093 /// @returns BitWidth if the value is all ones.
10941094 /// @returns the number of ones from the least significant bit to the first
11021102
11031103 /// countPopulation - This function is an APInt version of the
11041104 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1105 /// of 1 bits in the APInt value.
1105 /// of 1 bits in the APInt value.
11061106 /// @returns 0 if the value is zero.
11071107 /// @returns the number of set bits.
11081108 /// @brief Count the number of bits set.
11161116 /// @name Conversion Functions
11171117 /// @{
11181118 void print(raw_ostream &OS, bool isSigned) const;
1119
1119
11201120 /// toString - Converts an APInt to a string and append it to Str. Str is
11211121 /// commonly a SmallString.
11221122 void toString(SmallVectorImpl &Str, unsigned Radix, bool Signed) const;
11321132 void toStringSigned(SmallVectorImpl &Str, unsigned Radix = 10) const {
11331133 return toString(Str, Radix, true);
11341134 }
1135
1135
11361136 /// toString - This returns the APInt as a std::string. Note that this is an
11371137 /// inefficient method. It is better to pass in a SmallVector/SmallString
11381138 /// to the methods above to avoid thrashing the heap for the string.
11391139 std::string toString(unsigned Radix, bool Signed) const;
1140
1140
11411141
11421142 /// @returns a byte-swapped representation of this APInt Value.
11431143 APInt byteSwap() const;
13581358 static void tcOr(integerPart *, const integerPart *, unsigned int);
13591359 static void tcXor(integerPart *, const integerPart *, unsigned int);
13601360 static void tcComplement(integerPart *, unsigned int);
1361
1361
13621362 /// Comparison (unsigned) of two bignums.
13631363 static int tcCompare(const integerPart *, const integerPart *,
13641364 unsigned int);
13881388 I.print(OS, true);
13891389 return OS;
13901390 }
1391
1391
13921392 namespace APIntOps {
13931393
13941394 /// @brief Determine the smaller of two APInts considered to be signed.
14411441
14421442 /// @returns the floor log base 2 of the specified APInt value.
14431443 inline uint32_t logBase2(const APInt& APIVal) {
1444 return APIVal.logBase2();
1444 return APIVal.logBase2();
14451445 }
14461446
14471447 /// GreatestCommonDivisor - This function returns the greatest common
15431543 return LHS - RHS;
15441544 }
15451545
1546 /// Performs bitwise AND operation on APInt LHS and
1546 /// Performs bitwise AND operation on APInt LHS and
15471547 /// APInt RHS.
15481548 /// @brief Bitwise AND function for APInt.
15491549 inline APInt And(const APInt& LHS, const APInt& RHS) {
15511551 }
15521552
15531553 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1554 /// @brief Bitwise OR function for APInt.
1554 /// @brief Bitwise OR function for APInt.
15551555 inline APInt Or(const APInt& LHS, const APInt& RHS) {
15561556 return LHS | RHS;
15571557 }
15601560 /// @brief Bitwise XOR function for APInt.
15611561 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
15621562 return LHS ^ RHS;
1563 }
1563 }
15641564
15651565 /// Performs a bitwise complement operation on APInt.
1566 /// @brief Bitwise complement function.
1566 /// @brief Bitwise complement function.
15671567 inline APInt Not(const APInt& APIVal) {
15681568 return ~APIVal;
15691569 }
1717 #include "llvm/ADT/APInt.h"
1818
1919 namespace llvm {
20
20
2121 class APSInt : public APInt {
2222 bool IsUnsigned;
2323 public:
2626
2727 /// APSInt ctor - Create an APSInt with the specified width, default to
2828 /// unsigned.
29 explicit APSInt(uint32_t BitWidth, bool isUnsigned = true)
29 explicit APSInt(uint32_t BitWidth, bool isUnsigned = true)
3030 : APInt(BitWidth, 0), IsUnsigned(isUnsigned) {}
3131
32 explicit APSInt(const APInt &I, bool isUnsigned = true)
32 explicit APSInt(const APInt &I, bool isUnsigned = true)
3333 : APInt(I), IsUnsigned(isUnsigned) {}
3434
3535 APSInt &operator=(const APSInt &RHS) {
36 APInt::operator=(RHS);
36 APInt::operator=(RHS);
3737 IsUnsigned = RHS.IsUnsigned;
3838 return *this;
3939 }
4040
4141 APSInt &operator=(const APInt &RHS) {
4242 // Retain our current sign.
43 APInt::operator=(RHS);
43 APInt::operator=(RHS);
4444 return *this;
4545 }
4646
4747 APSInt &operator=(uint64_t RHS) {
4848 // Retain our current sign.
49 APInt::operator=(RHS);
49 APInt::operator=(RHS);
5050 return *this;
5151 }
5252
5555 bool isUnsigned() const { return IsUnsigned; }
5656 void setIsUnsigned(bool Val) { IsUnsigned = Val; }
5757 void setIsSigned(bool Val) { IsUnsigned = !Val; }
58
58
5959 /// toString - Append this APSInt to the specified SmallString.
6060 void toString(SmallVectorImpl &Str, unsigned Radix = 10) const {
6161 return APInt::toString(Str, Radix, isSigned());
6666 return APInt::toString(Radix, isSigned());
6767 }
6868 using APInt::toString;
69
69
7070 APSInt& extend(uint32_t width) {
7171 if (IsUnsigned)
7272 zext(width);
7474 sext(width);
7575 return *this;
7676 }
77
77
7878 APSInt& extOrTrunc(uint32_t width) {
7979 if (IsUnsigned)
8080 zextOrTrunc(width);
8282 sextOrTrunc(width);
8383 return *this;
8484 }
85
85
8686 const APSInt &operator%=(const APSInt &RHS) {
8787 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
8888 if (IsUnsigned)
107107 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
108108 return IsUnsigned ? APSInt(udiv(RHS), true) : APSInt(sdiv(RHS), false);
109109 }
110
110
111111 APSInt operator>>(unsigned Amt) const {
112112 return IsUnsigned ? APSInt(lshr(Amt), true) : APSInt(ashr(Amt), false);
113113 }
115115 *this = *this >> Amt;
116116 return *this;
117117 }
118
118
119119 inline bool operator<(const APSInt& RHS) const {
120120 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
121121 return IsUnsigned ? ult(RHS) : slt(RHS);
132132 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
133133 return IsUnsigned ? uge(RHS) : sge(RHS);
134134 }
135
135
136136 // The remaining operators just wrap the logic of APInt, but retain the
137137 // signedness information.
138
138
139139 APSInt operator<<(unsigned Bits) const {
140140 return APSInt(static_cast(*this) << Bits, IsUnsigned);
141 }
141 }
142142 APSInt& operator<<=(unsigned Amt) {
143143 *this = *this << Amt;
144144 return *this;
145145 }
146
146
147147 APSInt& operator++() {
148148 static_cast(*this)++;
149149 return *this;
157157 }
158158 APSInt operator--(int) {
159159 return APSInt(--static_cast(*this), IsUnsigned);
160 }
160 }
161161 APSInt operator-() const {
162162 return APSInt(-static_cast(*this), IsUnsigned);
163 }
163 }
164164 APSInt& operator+=(const APSInt& RHS) {
165165 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
166166 static_cast(*this) += RHS;
167167 return *this;
168 }
168 }
169169 APSInt& operator-=(const APSInt& RHS) {
170170 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
171171 static_cast(*this) -= RHS;
172172 return *this;
173 }
173 }
174174 APSInt& operator*=(const APSInt& RHS) {
175175 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
176176 static_cast(*this) *= RHS;
192192 return *this;
193193 }
194194
195 APSInt operator&(const APSInt& RHS) const {
195 APSInt operator&(const APSInt& RHS) const {
196196 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
197197 return APSInt(static_cast(*this) & RHS, IsUnsigned);
198198 }
199199 APSInt And(const APSInt& RHS) const {
200200 return this->operator&(RHS);
201201 }
202
203 APSInt operator|(const APSInt& RHS) const {
202
203 APSInt operator|(const APSInt& RHS) const {
204204 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
205205 return APSInt(static_cast(*this) | RHS, IsUnsigned);
206206 }
207207 APSInt Or(const APSInt& RHS) const {
208208 return this->operator|(RHS);
209209 }
210
211
212 APSInt operator^(const APSInt& RHS) const {
210
211
212 APSInt operator^(const APSInt& RHS) const {
213213 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
214214 return APSInt(static_cast(*this) ^ RHS, IsUnsigned);
215215 }
216216 APSInt Xor(const APSInt& RHS) const {
217217 return this->operator^(RHS);
218 }
219
218 }
219
220220 APSInt operator*(const APSInt& RHS) const {
221221 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
222222 return APSInt(static_cast(*this) * RHS, IsUnsigned);
223223 }
224 APSInt operator+(const APSInt& RHS) const {
224 APSInt operator+(const APSInt& RHS) const {
225225 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
226226 return APSInt(static_cast(*this) + RHS, IsUnsigned);
227227 }
229229 assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
230230 return APSInt(static_cast(*this) - RHS, IsUnsigned);
231231 }
232 APSInt operator~() const {
232 APSInt operator~() const {
233233 return APSInt(~static_cast(*this), IsUnsigned);
234234 }
235
235
236236 /// getMaxValue - Return the APSInt representing the maximum integer value
237237 /// with the given bit width and signedness.
238238 static APSInt getMaxValue(uint32_t numBits, bool Signed) {
239239 return APSInt(Signed ? APInt::getSignedMaxValue(numBits)
240240 : APInt::getMaxValue(numBits), Signed);
241241 }
242
242
243243 /// getMinValue - Return the APSInt representing the minimum integer value
244244 /// with the given bit width and signedness.
245245 static APSInt getMinValue(uint32_t numBits, bool Signed) {
246246 return APSInt(Signed ? APInt::getSignedMinValue(numBits)
247247 : APInt::getMinValue(numBits), Signed);
248248 }
249
249
250250 /// Profile - Used to insert APSInt objects, or objects that contain APSInt
251251 /// objects, into FoldingSets.
252252 void Profile(FoldingSetNodeID& ID) const;
253253 };
254
254
255255 inline raw_ostream &operator<<(raw_ostream &OS, const APSInt &I) {
256256 I.print(OS, I.isSigned());
257257 return OS;
258258 }
259
260
259
260
261261 } // end namespace llvm
262262
263263 #endif
2525
2626 enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * 8 };
2727
28 BitWord *Bits; // Actual bits.
28 BitWord *Bits; // Actual bits.
2929 unsigned Size; // Size of bitvector in bits.
3030 unsigned Capacity; // Size of allocated memory in BitWord.
3131
8888 Bits = new BitWord[Capacity];
8989 std::copy(RHS.Bits, &RHS.Bits[Capacity], Bits);
9090 }
91
91
9292 ~BitVector() {
9393 delete[] Bits;
9494 }
184184 grow(N);
185185 init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
186186 }
187
188 // Set any old unused bits that are now included in the BitVector. This
189 // may set bits that are not included in the new vector, but we will clear
187
188 // Set any old unused bits that are now included in the BitVector. This
189 // may set bits that are not included in the new vector, but we will clear
190190 // them back out below.
191191 if (N > Size)
192192 set_unused_bits(t);
193
193
194194 // Update the size, and clear out any bits that are now unused
195195 unsigned OldSize = Size;
196196 Size = N;
249249 }
250250
251251 bool operator[](unsigned Idx) const {
252 assert (Idx < Size && "Out-of-bounds Bit access.");
252 assert (Idx < Size && "Out-of-bounds Bit access.");
253253 BitWord Mask = 1L << (Idx % BITWORD_SIZE);
254254 return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
255255 }
266266 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
267267 if (Bits[i] != RHS.Bits[i])
268268 return false;
269
269
270270 // Verify that any extra words are all zeros.
271271 if (i != ThisWords) {
272272 for (; i != ThisWords; ++i)
291291 unsigned i;
292292 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
293293 Bits[i] &= RHS.Bits[i];
294
294
295295 // Any bits that are just in this bitvector become zero, because they aren't
296296 // in the RHS bit vector. Any words only in RHS are ignored because they
297297 // are already zero in the LHS.
298298 for (; i != ThisWords; ++i)
299299 Bits[i] = 0;
300
300
301301 return *this;
302302 }
303303
314314 Bits[i] ^= RHS.Bits[i];
315315 return *this;
316316 }
317
317
318318 // Assignment operator.
319319 const BitVector &operator=(const BitVector &RHS) {
320320 if (this == &RHS) return *this;
326326 clear_unused_bits();
327327 return *this;
328328 }
329
329
330330 // Grow the bitvector to have enough elements.
331331 Capacity = RHSWords;
332332 BitWord *NewBits = new BitWord[Capacity];
343343 unsigned NumBitWords(unsigned S) const {
344344 return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
345345 }
346
346
347347 // Set the unused bits in the high words.
348348 void set_unused_bits(bool t = true) {
349349 // Set high words first.
350350 unsigned UsedWords = NumBitWords(Size);
351351 if (Capacity > UsedWords)
352352 init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
353
353
354354 // Then set any stray high bits of the last used word.
355355 unsigned ExtraBits = Size % BITWORD_SIZE;
356356 if (ExtraBits) {
376376 // Destroy the old bits.
377377 delete[] Bits;
378378 Bits = NewBits;
379
379
380380 clear_unused_bits();
381381 }
382382
383383 void init_words(BitWord *B, unsigned NumWords, bool t) {
384384 memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
385 }
385 }
386386 };
387387
388388 inline BitVector operator&(const BitVector &LHS, const BitVector &RHS) {
402402 Result ^= RHS;
403403 return Result;
404404 }
405
405
406406 } // End llvm namespace
407407 #endif
1919 #include
2020
2121 namespace llvm {
22
22
2323 template
2424 struct DenseMapInfo {
2525 //static inline T getEmptyKey();
3535 static inline T* getEmptyKey() { return reinterpret_cast(-1); }
3636 static inline T* getTombstoneKey() { return reinterpret_cast(-2); }
3737 static unsigned getHashValue(const T *PtrVal) {
38 return (unsigned((uintptr_t)PtrVal) >> 4) ^
38 return (unsigned((uintptr_t)PtrVal) >> 4) ^
3939 (unsigned((uintptr_t)PtrVal) >> 9);
4040 }
4141 static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
6060 typedef DenseMapInfo FirstInfo;
6161 typedef DenseMapInfo SecondInfo;
6262
63 static inline Pair getEmptyKey() {
64 return std::make_pair(FirstInfo::getEmptyKey(),
65 SecondInfo::getEmptyKey());
66 }
67 static inline Pair getTombstoneKey() {
68 return std::make_pair(FirstInfo::getTombstoneKey(),
63 static inline Pair getEmptyKey() {
64 return std::make_pair(FirstInfo::getEmptyKey(),
65 SecondInfo::getEmptyKey());
66 }
67 static inline Pair getTombstoneKey() {
68 return std::make_pair(FirstInfo::getTombstoneKey(),
6969 SecondInfo::getEmptyKey());
7070 }
7171 static unsigned getHashValue(const Pair& PairVal) {
8585 static bool isPod() { return FirstInfo::isPod() && SecondInfo::isPod(); }
8686 };
8787
88 template
88 template
8989 typename KeyInfoT = DenseMapInfo,
9090 typename ValueInfoT = DenseMapInfo >
9191 class DenseMapIterator;
101101 typedef std::pair BucketT;
102102 unsigned NumBuckets;
103103 BucketT *Buckets;
104
104
105105 unsigned NumEntries;
106106 unsigned NumTombstones;
107107 public:
108108 typedef KeyT key_type;
109109 typedef ValueT mapped_type;
110110 typedef BucketT value_type;
111
111
112112 DenseMap(const DenseMap& other) {
113113 NumBuckets = 0;
114114 CopyFrom(other);
115115 }
116
116
117117 explicit DenseMap(unsigned NumInitBuckets = 64) {
118118 init(NumInitBuckets);
119119 }
120
120
121121 ~DenseMap() {
122122 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
123123 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
128128 }
129129 operator delete(Buckets);
130130 }
131
131
132132 typedef DenseMapIterator iterator;
133133 typedef DenseMapConstIterator const_iterator;
134134 inline iterator begin() {
143143 inline const_iterator end() const {
144144 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
145145 }
146
146
147147 bool empty() const { return NumEntries == 0; }
148148 unsigned size() const { return NumEntries; }
149149
150150 /// Grow the densemap so that it has at least Size buckets. Does not shrink
151151 void resize(size_t Size) { grow(Size); }
152
152
153153 void clear() {
154154 // If the capacity of the array is huge, and the # elements used is small,
155155 // shrink the array.
157157 shrink_and_clear();
158158 return;
159159 }
160
160
161161 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
162162 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
163163 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
177177 BucketT *TheBucket;
178178 return LookupBucketFor(Val, TheBucket);
179179 }
180
180
181181 iterator find(const KeyT &Val) {
182182 BucketT *TheBucket;
183183 if (LookupBucketFor(Val, TheBucket))
190190 return const_iterator(TheBucket, Buckets+NumBuckets);
191191 return end();
192192 }
193
193
194194 /// lookup - Return the entry for the specified key, or a default
195195 /// constructed value if no such entry exists.
196196 ValueT lookup(const KeyT &Val) const {
205205 if (LookupBucketFor(KV.first, TheBucket))
206206 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
207207 false); // Already in map.
208
208
209209 // Otherwise, insert the new element.
210210 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
211211 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
212212 true);
213213 }
214
214
215215 /// insert - Range insertion of pairs.
216216 template
217217 void insert(InputIt I, InputIt E) {
219219 insert(*I);
220220 }
221221
222
222
223223 bool erase(const KeyT &Val) {
224224 BucketT *TheBucket;
225225 if (!LookupBucketFor(Val, TheBucket))
244244 BucketT *TheBucket;
245245 if (LookupBucketFor(Key, TheBucket))
246246 return *TheBucket;
247
247
248248 return *InsertIntoBucket(Key, ValueT(), TheBucket);
249249 }
250
250
251251 ValueT &operator[](const KeyT &Key) {
252252 return FindAndConstruct(Key).second;
253253 }
254
254
255255 DenseMap& operator=(const DenseMap& other) {
256256 CopyFrom(other);
257257 return *this;
258258 }
259
259
260260 private:
261261 void CopyFrom(const DenseMap& other) {
262262 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
268268 P->first.~KeyT();
269269 }
270270 }
271
271
272272 NumEntries = other.NumEntries;
273273 NumTombstones = other.NumTombstones;
274
274
275275 if (NumBuckets)
276276 operator delete(Buckets);
277277 Buckets = static_cast(operator new(sizeof(BucketT) *
278278 other.NumBuckets));
279
279
280280 if (KeyInfoT::isPod() && ValueInfoT::isPod())
281281 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
282282 else
288288 }
289289 NumBuckets = other.NumBuckets;
290290 }
291
291
292292 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
293293 BucketT *TheBucket) {
294294 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
301301 // table completely filled with tombstones, no lookup would ever succeed,
302302 // causing infinite loops in lookup.
303303 if (NumEntries*4 >= NumBuckets*3 ||
304 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
304 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
305305 this->grow(NumBuckets * 2);
306306 LookupBucketFor(Key, TheBucket);
307307 }
308308 ++NumEntries;
309
309
310310 // If we are writing over a tombstone, remember this.
311311 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
312312 --NumTombstones;
313
313
314314 TheBucket->first = Key;
315315 new (&TheBucket->second) ValueT(Value);
316316 return TheBucket;
325325 static const KeyT getTombstoneKey() {
326326 return KeyInfoT::getTombstoneKey();
327327 }
328
328
329329 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
330330 /// FoundBucket. If the bucket contains the key and a value, this returns
331331 /// true, otherwise it returns a bucket with an empty marker or tombstone and
334334 unsigned BucketNo = getHashValue(Val);
335335 unsigned ProbeAmt = 1;
336336 BucketT *BucketsPtr = Buckets;
337
337
338338 // FoundTombstone - Keep track of whether we find a tombstone while probing.
339339 BucketT *FoundTombstone = 0;
340340 const KeyT EmptyKey = getEmptyKey();
342342 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
343343 !KeyInfoT::isEqual(Val, TombstoneKey) &&
344344 "Empty/Tombstone value shouldn't be inserted into map!");
345
345
346346 while (1) {
347347 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
348348 // Found Val's bucket? If so, return it.
350350 FoundBucket = ThisBucket;
351351 return true;
352352 }
353
353
354354 // If we found an empty bucket, the key doesn't exist in the set.
355355 // Insert it and return the default value.
356356 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
360360 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
361361 return false;
362362 }
363
363
364364 // If this is a tombstone, remember it. If Val ends up not in the map, we
365365 // prefer to return it than something that would require more probing.
366366 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
367367 FoundTombstone = ThisBucket; // Remember the first tombstone found.
368
368
369369 // Otherwise, it's a hash collision or a tombstone, continue quadratic
370370 // probing.
371371 BucketNo += ProbeAmt++;
384384 for (unsigned i = 0; i != InitBuckets; ++i)
385385 new (&Buckets[i].first) KeyT(EmptyKey);
386386 }
387
387
388388 void grow(unsigned AtLeast) {
389389 unsigned OldNumBuckets = NumBuckets;
390390 BucketT *OldBuckets = Buckets;
391
391
392392 // Double the number of buckets.
393393 while (NumBuckets <= AtLeast)
394394 NumBuckets <<= 1;
412412 assert(!FoundVal && "Key already in new map?");
413413 DestBucket->first = B->first;
414414 new (&DestBucket->second) ValueT(B->second);
415
415
416416 // Free the value.
417417 B->second.~ValueT();
418418 }
419419 B->first.~KeyT();
420420 }
421
421
422422 // Free the old table.
423423 operator delete(OldBuckets);
424424 }
425
425
426426 void shrink_and_clear() {
427427 unsigned OldNumBuckets = NumBuckets;
428428 BucketT *OldBuckets = Buckets;
429
429
430430 // Reduce the number of buckets.
431431 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
432432 : 64;
448448 }
449449 B->first.~KeyT();
450450 }
451
451
452452 // Free the old table.
453453 operator delete(OldBuckets);
454
454
455455 NumEntries = 0;
456456 }
457457 };
467467 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
468468 AdvancePastEmptyBuckets();
469469 }
470
470
471471 std::pair &operator*() const {
472472 return *const_cast(Ptr);
473473 }
474474 std::pair *operator->() const {
475475 return const_cast(Ptr);
476476 }
477
477
478478 bool operator==(const DenseMapIterator &RHS) const {
479479 return Ptr == RHS.Ptr;
480480 }
481481 bool operator!=(const DenseMapIterator &RHS) const {
482482 return Ptr != RHS.Ptr;
483483 }
484
484
485485 inline DenseMapIterator& operator++() { // Preincrement
486486 ++Ptr;
487487 AdvancePastEmptyBuckets();
490490 DenseMapIterator operator++(int) { // Postincrement
491491 DenseMapIterator tmp = *this; ++*this; return tmp;
492492 }
493
493
494494 private:
495495 void AdvancePastEmptyBuckets() {
496496 const KeyT Empty = KeyInfoT::getEmptyKey();
497497 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
498498
499 while (Ptr != End &&
499 while (Ptr != End &&
500500 (KeyInfoT::isEqual(Ptr->first, Empty) ||
501501 KeyInfoT::isEqual(Ptr->first, Tombstone)))
502502 ++Ptr;
2828 public:
2929 DenseSet(const DenseSet &Other) : TheMap(Other.TheMap) {}
3030 explicit DenseSet(unsigned NumInitBuckets = 64) : TheMap(NumInitBuckets) {}
31
31
3232 bool empty() const { return TheMap.empty(); }
33 unsigned size() const { return TheMap.size(); }
34
33 unsigned size() const { return TheMap.size(); }
34
3535 void clear() {
3636 TheMap.clear();
3737 }
38
38
3939 bool count(const ValueT &V) const {
4040 return TheMap.count(V);
4141 }
42
42
4343 void erase(const ValueT &V) {
4444 TheMap.erase(V);
4545 }
46
46
4747 DenseSet &operator=(const DenseSet &RHS) {
4848 TheMap = RHS.TheMap;
4949 return *this;
5050 }
51
51
5252 // Iterators.
53
53
5454 class Iterator {
5555 typename MapTy::iterator I;
5656 public:
5757 Iterator(const typename MapTy::iterator &i) : I(i) {}
58
58
5959 ValueT& operator*() { return I->first; }
6060 ValueT* operator->() { return &I->first; }
61
61
6262 Iterator& operator++() { ++I; return *this; };
6363 bool operator==(const Iterator& X) const { return I == X.I; }
6464 bool operator!=(const Iterator& X) const { return I != X.I; }
6565 };
66
66
6767 class ConstIterator {
6868 typename MapTy::const_iterator I;
6969 public:
7070 ConstIterator(const typename MapTy::const_iterator &i) : I(i) {}
71
71
7272 const ValueT& operator*() { return I->first; }
7373 const ValueT* operator->() { return &I->first; }
74
74
7575 ConstIterator& operator++() { ++I; return *this; };
7676 bool operator==(const ConstIterator& X) const { return I == X.I; }
7777 bool operator!=(const ConstIterator& X) const { return I != X.I; }
7878 };
79
79
8080 typedef Iterator iterator;
8181 typedef ConstIterator const_iterator;
82
82
8383 iterator begin() { return Iterator(TheMap.begin()); }
8484 iterator end() { return Iterator(TheMap.end()); }
85
85
8686 const_iterator begin() const { return ConstIterator(TheMap.begin()); }
8787 const_iterator end() const { return ConstIterator(TheMap.end()); }
8888
2828 /// instance of the node in the set. If the node already exists, return
2929 /// it, otherwise return the bucket it should be inserted into.
3030 /// 2. Given a node that has already been created, remove it from the set.
31 ///
31 ///
3232 /// This class is implemented as a single-link chained hash table, where the
3333 /// "buckets" are actually the nodes themselves (the next pointer is in the
3434 /// node). The last node points back to the bucket to simplify node removal.
3636 /// Any node that is to be included in the folding set must be a subclass of
3737 /// FoldingSetNode. The node class must also define a Profile method used to
3838 /// establish the unique bits of data for the node. The Profile method is
39 /// passed a FoldingSetNodeID object which is used to gather the bits. Just
39 /// passed a FoldingSetNodeID object which is used to gather the bits. Just
4040 /// call one of the Add* functions defined in the FoldingSetImpl::NodeID class.
4141 /// NOTE: That the folding set does not own the nodes and it is the
4242 /// responsibility of the user to dispose of the nodes.
6161 /// Eg.
6262 /// FoldingSet MyFoldingSet;
6363 ///
64 /// Four public methods are available to manipulate the folding set;
64 /// Four public methods are available to manipulate the folding set;
6565 ///
6666 /// 1) If you have an existing node that you want add to the set but unsure
6767 /// that the node might already exist then call;
9696 /// bool WasRemoved = RemoveNode(N);
9797 ///
9898 /// The result indicates whether the node existed in the folding set.
99
99
100100 class FoldingSetNodeID;
101
101
102102 //===----------------------------------------------------------------------===//
103103 /// FoldingSetImpl - Implements the folding set functionality. The main
104104 /// structure is an array of buckets. Each bucket is indexed by the hash of
105105 /// the nodes it contains. The bucket itself points to the nodes contained
106106 /// in the bucket via a singly linked list. The last node in the list points
107107 /// back to the bucket to facilitate node removal.
108 ///
108 ///
109109 class FoldingSetImpl {
110110 protected:
111111 /// Buckets - Array of bucket chains.
112112 ///
113113 void **Buckets;
114
114
115115 /// NumBuckets - Length of the Buckets array. Always a power of 2.
116116 ///
117117 unsigned NumBuckets;
118
118
119119 /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
120120 /// is greater than twice the number of buckets.
121121 unsigned NumNodes;
122
122
123123 public:
124124 explicit FoldingSetImpl(unsigned Log2InitSize = 6);
125125 virtual ~FoldingSetImpl();
126
126
127127 //===--------------------------------------------------------------------===//
128128 /// Node - This class is used to maintain the singly linked bucket list in
129129 /// a folding set.
132132 private:
133133 // NextInFoldingSetBucket - next link in the bucket list.
134134 void *NextInFoldingSetBucket;
135
135
136136 public:
137137
138138 Node() : NextInFoldingSetBucket(0) {}
139
139
140140 // Accessors
141141 void *getNextInBucket() const { return NextInFoldingSetBucket; }
142142 void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
148148 /// RemoveNode - Remove a node from the folding set, returning true if one
149149 /// was removed or false if the node was not in the folding set.
150150 bool RemoveNode(Node *N);
151
151
152152 /// GetOrInsertNode - If there is an existing simple Node exactly
153153 /// equal to the specified node, return it. Otherwise, insert 'N' and return
154154 /// it instead.
155155 Node *GetOrInsertNode(Node *N);
156
156
157157 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
158158 /// return it. If not, return the insertion token that will make insertion
159159 /// faster.
160160 Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
161
161
162162 /// InsertNode - Insert the specified node into the folding set, knowing that
163 /// it is not already in the folding set. InsertPos must be obtained from
163 /// it is not already in the folding set. InsertPos must be obtained from
164164 /// FindNodeOrInsertPos.
165165 void InsertNode(Node *N, void *InsertPos);
166
166
167167 /// size - Returns the number of nodes in the folding set.
168168 unsigned size() const { return NumNodes; }
169169
170170 /// empty - Returns true if there are no nodes in the folding set.
171171 bool empty() const { return NumNodes == 0; }
172
172
173173 private:
174174
175175 /// GrowHashTable - Double the size of the hash table and rehash everything.
176176 ///
177177 void GrowHashTable();
178
178
179179 protected:
180180
181181 /// GetNodeProfile - Instantiations of the FoldingSet template implement
195195 static inline void Profile(const T& X, FoldingSetNodeID& ID) { X.Profile(ID);}
196196 static inline void Profile(T& X, FoldingSetNodeID& ID) { X.Profile(ID); }
197197 };
198
198
199199 //===--------------------------------------------------------------------===//
200200 /// FoldingSetNodeID - This class is used to gather all the unique data bits of
201201 /// a node. When all the bits are gathered this class is used to produce a
202 /// hash value for the node.
202 /// hash value for the node.
203203 ///
204204 class FoldingSetNodeID {
205205 /// Bits - Vector of all the data bits that make the node unique.
206206 /// Use a SmallVector to avoid a heap allocation in the common case.
207207 SmallVector Bits;
208
208
209209 public:
210210 FoldingSetNodeID() {}
211
211
212212 /// getRawData - Return the ith entry in the Bits data.
213213 ///
214214 unsigned getRawData(unsigned i) const {
215215 return Bits[i];
216216 }
217
217
218218 /// Add* - Add various data types to Bit data.
219219 ///
220220 void AddPointer(const void *Ptr);
228228 void AddDouble(double D);
229229 void AddString(const std::string &String);
230230 void AddString(const char* String);
231
231
232232 template
233233 inline void Add(const T& x) { FoldingSetTrait::Profile(x, *this); }
234
234
235235 /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
236236 /// object to be used to compute a new profile.
237237 inline void clear() { Bits.clear(); }
238
238
239239 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
240240 /// to lookup the node in the FoldingSetImpl.
241241 unsigned ComputeHash() const;
242
242
243243 /// operator== - Used to compare two nodes to each other.
244244 ///
245245 bool operator==(const FoldingSetNodeID &RHS) const;
246 };
246 };
247247
248248 // Convenience type to hide the implementation of the folding set.
249249 typedef FoldingSetImpl::Node FoldingSetNode;
250250 template class FoldingSetIterator;
251251 template class FoldingSetBucketIterator;
252
252
253253 //===----------------------------------------------------------------------===//
254254 /// FoldingSet - This template class is used to instantiate a specialized
255 /// implementation of the folding set to the node class T. T must be a
255 /// implementation of the folding set to the node class T. T must be a
256256 /// subclass of FoldingSetNode and implement a Profile function.
257257 ///
258258 template class FoldingSet : public FoldingSetImpl {
263263 T *TN = static_cast(N);
264264 FoldingSetTrait::Profile(*TN,ID);
265265 }
266
266
267267 public:
268268 explicit FoldingSet(unsigned Log2InitSize = 6)
269269 : FoldingSetImpl(Log2InitSize)
270270 {}
271
271
272272 typedef FoldingSetIterator iterator;
273273 iterator begin() { return iterator(Buckets); }
274274 iterator end() { return iterator(Buckets+NumBuckets); }
277277 const_iterator begin() const { return const_iterator(Buckets); }
278278 const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
279279
280 typedef FoldingSetBucketIterator bucket_iterator;
280 typedef FoldingSetBucketIterator bucket_iterator;
281281
282282 bucket_iterator bucket_begin(unsigned hash) {
283283 return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
284284 }
285
285
286286 bucket_iterator bucket_end(unsigned hash) {
287287 return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
288288 }
289
289
290290 /// GetOrInsertNode - If there is an existing simple Node exactly
291291 /// equal to the specified node, return it. Otherwise, insert 'N' and
292292 /// return it instead.
293293 T *GetOrInsertNode(Node *N) {
294294 return static_cast(FoldingSetImpl::GetOrInsertNode(N));
295295 }
296
296
297297 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
298298 /// return it. If not, return the insertion token that will make insertion
299299 /// faster.
310310 FoldingSetNode *NodePtr;
311311 FoldingSetIteratorImpl(void **Bucket);
312312 void advance();
313
313
314314 public:
315315 bool operator==(const FoldingSetIteratorImpl &RHS) const {
316316 return NodePtr == RHS.NodePtr;
325325 class FoldingSetIterator : public FoldingSetIteratorImpl {
326326 public:
327327 explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
328
328
329329 T &operator*() const {
330330 return *static_cast(NodePtr);
331331 }
332
332
333333 T *operator->() const {
334334 return static_cast(NodePtr);
335335 }
336
336
337337 inline FoldingSetIterator& operator++() { // Preincrement
338338 advance();
339339 return *this;
342342 FoldingSetIterator tmp = *this; ++*this; return tmp;
343343 }
344344 };
345
345
346346 //===----------------------------------------------------------------------===//
347347 /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
348348 /// shared by all folding sets, which knows how to walk a particular bucket
349349 /// of a folding set hash table.
350
350
351351 class FoldingSetBucketIteratorImpl {
352352 protected:
353353 void *Ptr;
354354
355355 explicit FoldingSetBucketIteratorImpl(void **Bucket);
356
356
357357 FoldingSetBucketIteratorImpl(void **Bucket, bool)
358358 : Ptr(Bucket) {}
359359
362362 uintptr_t x = reinterpret_cast(Probe) & ~0x1;
363363 Ptr = reinterpret_cast(x);
364364 }
365
365
366366 public:
367367 bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
368368 return Ptr == RHS.Ptr;
371371 return Ptr != RHS.Ptr;
372372 }
373373 };
374
375
374
375
376376 template
377377 class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
378378 public:
379 explicit FoldingSetBucketIterator(void **Bucket) :
379 explicit FoldingSetBucketIterator(void **Bucket) :
380380 FoldingSetBucketIteratorImpl(Bucket) {}
381
382 FoldingSetBucketIterator(void **Bucket, bool) :
381
382 FoldingSetBucketIterator(void **Bucket, bool) :
383383 FoldingSetBucketIteratorImpl(Bucket, true) {}
384
385 T& operator*() const { return *static_cast(Ptr); }
384
385 T& operator*() const { return *static_cast(Ptr); }
386386 T* operator->() const { return static_cast(Ptr); }
387
387
388388 inline FoldingSetBucketIterator& operator++() { // Preincrement
389389 advance();
390390 return *this;
391 }
391 }
392392 FoldingSetBucketIterator operator++(int) { // Postincrement
393393 FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
394394 }
395395 };
396
396
397397 //===----------------------------------------------------------------------===//
398398 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
399399 /// types in an enclosing object so that they can be inserted into FoldingSets.
403403 public:
404404 explicit FoldingSetNodeWrapper(const T& x) : data(x) {}
405405 virtual ~FoldingSetNodeWrapper() {}
406
406
407407 template
408408 explicit FoldingSetNodeWrapper(const A1& a1)
409409 : data(a1) {}
410
410
411411 template
412412 explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2)
413413 : data(a1,a2) {}
414
414
415415 template
416416 explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3)
417417 : data(a1,a2,a3) {}
418
418
419419 template
420420 explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3,
421421 const A4& a4)
422422 : data(a1,a2,a3,a4) {}
423
423
424424 template
425425 explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3,
426426 const A4& a4, const A5& a5)
427427 : data(a1,a2,a3,a4,a5) {}
428428
429
429
430430 void Profile(FoldingSetNodeID& ID) { FoldingSetTrait::Profile(data, ID); }
431431
432432 T& getValue() { return data; }
434434
435435 operator T&() { return data; }
436436 operator const T&() const { return data; }
437 };
438
437 };
438
439439 //===----------------------------------------------------------------------===//
440440 // Partial specializations of FoldingSetTrait.
441441
8383 struct GraphTraits > > {
8484 typedef typename GraphTraits::NodeType NodeType;
8585 typedef typename GraphTraits::ChildIteratorType ChildIteratorType;
86
86
8787 static NodeType *getEntryNode(Inverse > *G) {
8888 return GraphTraits::getEntryNode(G->Graph.Graph);
8989 }
90
90
9191 static ChildIteratorType child_begin(NodeType* N) {
9292 return GraphTraits::child_begin(N);
9393 }
94
94
9595 static ChildIteratorType child_end(NodeType* N) {
9696 return GraphTraits::child_end(N);
9797 }
2121 namespace llvm {
2222
2323 template class ImmutableListFactory;
24
24
2525 template
2626 class ImmutableListImpl : public FoldingSetNode {
2727 T Head;
2929
3030 ImmutableListImpl(const T& head, const ImmutableListImpl* tail = 0)
3131 : Head(head), Tail(tail) {}
32
32
3333 friend class ImmutableListFactory;
34
34
3535 // Do not implement.
3636 void operator=(const ImmutableListImpl&);
3737 ImmutableListImpl(const ImmutableListImpl&);
38
38
3939 public:
4040 const T& getHead() const { return Head; }
4141 const ImmutableListImpl* getTail() const { return Tail; }
42
42
4343 static inline void Profile(FoldingSetNodeID& ID, const T& H,
4444 const ImmutableListImpl* L){
4545 ID.AddPointer(L);
4646 ID.Add(H);
4747 }
48
48
4949 void Profile(FoldingSetNodeID& ID) {
5050 Profile(ID, Head, Tail);
5151 }
5252 };
53
53
5454 /// ImmutableList - This class represents an immutable (functional) list.
5555 /// It is implemented as a smart pointer (wraps ImmutableListImpl), so it
5656 /// it is intended to always be copied by value as if it were a pointer.
7777 const ImmutableListImpl* getInternalPointer() const {
7878 return X;
7979 }
80
80
8181 class iterator {
8282 const ImmutableListImpl* L;
8383 public:
8484 iterator() : L(0) {}
8585 iterator(ImmutableList l) : L(l.getInternalPointer()) {}
86
86
8787 iterator& operator++() { L = L->getTail(); return *this; }
8888 bool operator==(const iterator& I) const { return L == I.L; }
8989 bool operator!=(const iterator& I) const { return L != I.L; }
90 const value_type& operator*() const { return L->getHead(); }
91 ImmutableList getList() const { return L; }
90 const value_type& operator*() const { return L->getHead(); }
91 ImmutableList getList() const { return L; }
9292 };
9393
9494 /// begin - Returns an iterator referring to the head of the list, or
9595 /// an iterator denoting the end of the list if the list is empty.
9696 iterator begin() const { return iterator(X); }
97
97
9898 /// end - Returns an iterator denoting the end of the list. This iterator
9999 /// does not refer to a valid list element.
100100 iterator end() const { return iterator(); }
101101
102102 /// isEmpty - Returns true if the list is empty.
103103 bool isEmpty() const { return !X; }
104
104
105105 /// isEqual - Returns true if two lists are equal. Because all lists created
106106 /// from the same ImmutableListFactory are uniqued, this has O(1) complexity
107107 /// because it the contents of the list do not need to be compared. Note
108108 /// that you should only compare two lists created from the same
109109 /// ImmutableListFactory.
110 bool isEqual(const ImmutableList& L) const { return X == L.X; }
110 bool isEqual(const ImmutableList& L) const { return X == L.X; }
111111
112112 bool operator==(const ImmutableList& L) const { return isEqual(L); }
113113
116116 assert (!isEmpty() && "Cannot get the head of an empty list.");
117117 return X->getHead();
118118 }
119
119
120120 /// getTail - Returns the tail of the list, which is another (possibly empty)
121121 /// ImmutableList.
122122 ImmutableList getTail() {
123123 return X ? X->getTail() : 0;
124 }
124 }
125125
126126 void Profile(FoldingSetNodeID& ID) const {
127127 ID.AddPointer(X);
128128 }
129129 };
130
130
131131 template
132132 class ImmutableListFactory {
133 typedef ImmutableListImpl ListTy;
133 typedef ImmutableListImpl ListTy;
134134 typedef FoldingSet CacheTy;
135
135
136136 CacheTy Cache;
137137 uintptr_t Allocator;
138
138
139139 bool ownsAllocator() const {
140140 return Allocator & 0x1 ? false : true;
141141 }
142
143 BumpPtrAllocator& getAllocator() const {
142
143 BumpPtrAllocator& getAllocator() const {
144144 return *reinterpret_cast(Allocator & ~0x1);
145 }
145 }
146146
147147 public:
148148 ImmutableListFactory()
149149 : Allocator(reinterpret_cast(new BumpPtrAllocator())) {}
150
150
151151 ImmutableListFactory(BumpPtrAllocator& Alloc)
152152 : Allocator(reinterpret_cast(&Alloc) | 0x1) {}
153
153
154154 ~ImmutableListFactory() {
155155 if (ownsAllocator()) delete &getAllocator();
156156 }
157
157
158158 ImmutableList Concat(const T& Head, ImmutableList Tail) {
159159 // Profile the new list to see if it already exists in our cache.
160160 FoldingSetNodeID ID;
161161 void* InsertPos;
162
162
163163 const ListTy* TailImpl = Tail.getInternalPointer();
164164 ListTy::Profile(ID, Head, TailImpl);
165165 ListTy* L = Cache.FindNodeOrInsertPos(ID, InsertPos);
166
166
167167 if (!L) {
168168 // The list does not exist in our cache. Create it.
169169 BumpPtrAllocator& A = getAllocator();
170170 L = (ListTy*) A.Allocate();
171171 new (L) ListTy(Head, TailImpl);
172
172
173173 // Insert the new list into the cache.
174174 Cache.InsertNode(L, InsertPos);
175175 }
176
176
177177 return L;
178178 }
179
179
180180 ImmutableList Add(const T& D, ImmutableList L) {
181181 return Concat(D, L);
182182 }
183
183
184184 ImmutableList GetEmptyList() const {
185185 return ImmutableList(0);
186186 }
187
187
188188 ImmutableList Create(const T& X) {
189189 return Concat(X, GetEmptyList());
190190 }
191191 };
192
192
193193 //===----------------------------------------------------------------------===//
194194 // Partially-specialized Traits.
195195 //===----------------------------------------------------------------------===//
204204 }
205205 static unsigned getHashValue(ImmutableList X) {
206206 uintptr_t PtrVal = reinterpret_cast(X.getInternalPointer());
207 return (unsigned((uintptr_t)PtrVal) >> 4) ^
207 return (unsigned((uintptr_t)PtrVal) >> 4) ^
208208 (unsigned((uintptr_t)PtrVal) >> 9);
209209 }
210210 static bool isEqual(ImmutableList X1, ImmutableList X2) {
212212 }
213213 static bool isPod() { return true; }
214214 };
215
215
216216 } // end llvm namespace
217217
218218 #endif
2828 typedef const T& key_type_ref;
2929 typedef const S data_type;
3030 typedef const S& data_type_ref;
31
31
3232 static inline key_type_ref KeyOfValue(value_type_ref V) {
3333 return V.first;
3434 }
35
35
3636 static inline data_type_ref DataOfValue(value_type_ref V) {
3737 return V.second;
3838 }
39
39
4040 static inline bool isEqual(key_type_ref L, key_type_ref R) {
4141 return ImutContainerInfo::isEqual(L,R);
42 }
42 }
4343 static inline bool isLess(key_type_ref L, key_type_ref R) {
4444 return ImutContainerInfo::isLess(L,R);
4545 }
46
46
4747 static inline bool isDataEqual(data_type_ref L, data_type_ref R) {
4848 return ImutContainerInfo::isEqual(L,R);
4949 }
50
50
5151 static inline void Profile(FoldingSetNodeID& ID, value_type_ref V) {
5252 ImutContainerInfo::Profile(ID, V.first);
5353 ImutContainerInfo::Profile(ID, V.second);
5454 }
55 };
56
57
58 template
55 };
56
57
58 template
5959 typename ValInfo = ImutKeyValueInfo >
6060 class ImmutableMap {
6161 public:
6666 typedef typename ValInfo::data_type data_type;
6767 typedef typename ValInfo::data_type_ref data_type_ref;
6868 typedef ImutAVLTree TreeTy;
69
69
7070 private:
7171 TreeTy* Root;
72
72
7373 public:
7474 /// Constructs a map from a pointer to a tree root. In general one
7575 /// should use a Factory object to create maps instead of directly
7676 /// invoking the constructor, but there are cases where make this
7777 /// constructor public is useful.
7878 explicit ImmutableMap(const TreeTy* R) : Root(const_cast(R)) {}
79
79
8080 class Factory {
8181 typename TreeTy::Factory F;
82
82
8383 public:
8484 Factory() {}
85
85
8686 Factory(BumpPtrAllocator& Alloc)
8787 : F(Alloc) {}
88
88
8989 ImmutableMap GetEmptyMap() { return ImmutableMap(F.GetEmptyTree()); }
90
90
9191 ImmutableMap Add(ImmutableMap Old, key_type_ref K, data_type_ref D) {
9292 return ImmutableMap(F.Add(Old.Root,
9393 std::make_pair(K,D)));
9494 }
95
95
9696 ImmutableMap Remove(ImmutableMap Old, key_type_ref K) {
9797 return ImmutableMap(F.Remove(Old.Root,K));
98 }
99
98 }
99
100100 private:
101101 Factory(const Factory& RHS) {};
102 void operator=(const Factory& RHS) {};
103 };
104
105 friend class Factory;
106
102 void operator=(const Factory& RHS) {};
103 };
104
105 friend class Factory;
106
107107 bool contains(key_type_ref K) const {
108108 return Root ? Root->contains(K) : false;
109109 }
110110
111
111
112112 bool operator==(ImmutableMap RHS) const {
113113 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
114114 }
115
115
116116 bool operator!=(ImmutableMap RHS) const {
117117 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
118118 }
119
119
120120 TreeTy* getRoot() const { return Root; }
121
121
122122 bool isEmpty() const { return !Root; }
123123
124 //===--------------------------------------------------===//
124 //===--------------------------------------------------===//
125125 // Foreach - A limited form of map iteration.
126126 //===--------------------------------------------------===//
127127
129129 template
130130 struct CBWrapper {
131131 Callback C;
132 void operator()(value_type_ref V) { C(V.first,V.second); }
133 };
134
132 void operator()(value_type_ref V) { C(V.first,V.second); }
133 };
134
135135 template
136136 struct CBWrapperRef {
137137 Callback &C;
138138 CBWrapperRef(Callback& c) : C(c) {}
139
140 void operator()(value_type_ref V) { C(V.first,V.second); }
141 };
142
143 public:
144 template
145 void foreach(Callback& C) {
146 if (Root) {
139
140 void operator()(value_type_ref V) { C(V.first,V.second); }
141 };
142
143 public:
144 template
145 void foreach(Callback& C) {
146 if (Root) {
147147 CBWrapperRef CB(C);
148148 Root->foreach(CB);
149149 }
150150 }
151
152 template
153 void foreach() {
151
152 template
153 void foreach() {
154154 if (Root) {
155155 CBWrapper CB;
156156 Root->foreach(CB);
157157 }
158158 }
159
160 //===--------------------------------------------------===//
159
160 //===--------------------------------------------------===//
161161 // For testing.
162 //===--------------------------------------------------===//
163
162 //===--------------------------------------------------===//
163
164164 void verify() const { if (Root) Root->verify(); }
165
166 //===--------------------------------------------------===//
165
166 //===--------------------------------------------------===//
167167 // Iterators.
168 //===--------------------------------------------------===//
169
168 //===--------------------------------------------------===//
169
170170 class iterator {
171171 typename TreeTy::iterator itr;
172
172
173173 iterator() {}
174174 iterator(TreeTy* t) : itr(t) {}
175175 friend class ImmutableMap;
177177 public:
178178 value_type_ref operator*() const { return itr->getValue(); }
179179 value_type* operator->() const { return &itr->getValue(); }
180
180
181181 key_type_ref getKey() const { return itr->getValue().first; }
182182 data_type_ref getData() const { return itr->getValue().second; }
183
184
183
184
185185 iterator& operator++() { ++itr; return *this; }
186186 iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
187187 iterator& operator--() { --itr; return *this; }
188188 iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
189189 bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
190 bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
191 };
192
190 bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
191 };
192
193193 iterator begin() const { return iterator(Root); }
194 iterator end() const { return iterator(); }
195
194 iterator end() const { return iterator(); }
195
196196 data_type* lookup(key_type_ref K) const {
197197 if (Root) {
198198 TreeTy* T = Root->find(K);
199199 if (T) return &T->getValue().second;
200200 }
201
201
202202 return 0;
203203 }
204
205 //===--------------------------------------------------===//
204
205 //===--------------------------------------------------===//
206206 // Utility methods.
207 //===--------------------------------------------------===//
208
207 //===--------------------------------------------------===//
208
209209 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
210210
211211 static inline void Profile(FoldingSetNodeID& ID, const ImmutableMap& M) {
212212 ID.AddPointer(M.Root);
213213 }
214
214
215215 inline void Profile(FoldingSetNodeID& ID) const {
216216 return Profile(ID,*this);
217 }
217 }
218218 };
219
219
220220 } // end namespace llvm
221221
222222 #endif
2020 #include
2121
2222 namespace llvm {
23
24 //===----------------------------------------------------------------------===//
23
24 //===----------------------------------------------------------------------===//
2525 // Immutable AVL-Tree Definition.
2626 //===----------------------------------------------------------------------===//
2727
2828 template class ImutAVLFactory;
2929 template class ImutAVLTreeInOrderIterator;
3030 template class ImutAVLTreeGenericIterator;
31
31
3232 template
3333 class ImutAVLTree : public FoldingSetNode {
3434 public:
3838
3939 typedef ImutAVLFactory Factory;
4040 friend class ImutAVLFactory;
41
41
4242 friend class ImutAVLTreeGenericIterator;
4343 friend class FoldingSet;
44
44
4545 typedef ImutAVLTreeInOrderIterator iterator;
46
47 //===----------------------------------------------------===//
46
47 //===----------------------------------------------------===//
4848 // Public Interface.
49 //===----------------------------------------------------===//
50
49 //===----------------------------------------------------===//
50
5151 /// getLeft - Returns a pointer to the left subtree. This value
5252 /// is NULL if there is no left subtree.
53 ImutAVLTree* getLeft() const {
53 ImutAVLTree* getLeft() const {
5454 assert (!isMutable() && "Node is incorrectly marked mutable.");
55
55
5656 return reinterpret_cast(Left);
5757 }
58
58
5959 /// getRight - Returns a pointer to the right subtree. This value is
6060 /// NULL if there is no right subtree.
61 ImutAVLTree* getRight() const { return Right; }
62
63
61 ImutAVLTree* getRight() const { return Right; }
62
63
6464 /// getHeight - Returns the height of the tree. A tree with no subtrees
6565 /// has a height of 1.
66 unsigned getHeight() const { return Height; }
67
66 unsigned getHeight() const { return Height; }
67
6868 /// getValue - Returns the data value associated with the tree node.
6969 const value_type& getValue() const { return Value; }
70
70
7171 /// find - Finds the subtree associated with the specified key value.
7272 /// This method returns NULL if no matching subtree is found.
7373 ImutAVLTree* find(key_type_ref K) {
7474 ImutAVLTree *T = this;
75
75
7676 while (T) {
7777 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
78
78
7979 if (ImutInfo::isEqual(K,CurrentKey))
8080 return T;
8181 else if (ImutInfo::isLess(K,CurrentKey))
8383 else
8484 T = T->getRight();
8585 }
86
86
8787 return NULL;
8888 }
89
89
9090 /// size - Returns the number of nodes in the tree, which includes
9191 /// both leaves and non-leaf nodes.
9292 unsigned size() const {
9393 unsigned n = 1;
94
94
9595 if (const ImutAVLTree* L = getLeft()) n += L->size();
9696 if (const ImutAVLTree* R = getRight()) n += R->size();
97
97
9898 return n;
9999 }
100
100
101101 /// begin - Returns an iterator that iterates over the nodes of the tree
102102 /// in an inorder traversal. The returned iterator thus refers to the
103103 /// the tree node with the minimum data element.
104104 iterator begin() const { return iterator(this); }
105
105
106106 /// end - Returns an iterator for the tree that denotes the end of an
107107 /// inorder traversal.
108108 iterator end() const { return iterator(); }
109
109
110110 bool ElementEqual(value_type_ref V) const {
111111 // Compare the keys.
112112 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
113113 ImutInfo::KeyOfValue(V)))
114114 return false;
115
115
116116 // Also compare the data values.
117117 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
118118 ImutInfo::DataOfValue(V)))
119119 return false;
120
120
121121 return true;
122122 }
123
123
124124 bool ElementEqual(const ImutAVLTree* RHS) const {
125125 return ElementEqual(RHS->getValue());
126126 }
127
127
128128 /// isEqual - Compares two trees for structural equality and returns true
129129 /// if they are equal. This worst case performance of this operation is
130130 // linear in the sizes of the trees.
131131 bool isEqual(const ImutAVLTree& RHS) const {
132132 if (&RHS == this)
133133 return true;
134
134
135135 iterator LItr = begin(), LEnd = end();
136136 iterator RItr = RHS.begin(), REnd = RHS.end();
137
137
138138 while (LItr != LEnd && RItr != REnd) {
139139 if (*LItr == *RItr) {
140140 LItr.SkipSubTree();
141141 RItr.SkipSubTree();
142142 continue;
143143 }
144
144
145145 if (!LItr->ElementEqual(*RItr))
146146 return false;
147
147
148148 ++LItr;
149149 ++RItr;
150150 }
151
151
152152 return LItr == LEnd && RItr == REnd;
153153 }
154154
155155 /// isNotEqual - Compares two trees for structural inequality. Performance
156156 /// is the same is isEqual.
157157 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
158
158
159159 /// contains - Returns true if this tree contains a subtree (node) that
160160 /// has an data element that matches the specified key. Complexity
161161 /// is logarithmic in the size of the tree.
162162 bool contains(const key_type_ref K) { return (bool) find(K); }
163
163
164164 /// foreach - A member template the accepts invokes operator() on a functor
165165 /// object (specifed by Callback) for every node/subtree in the tree.
166166 /// Nodes are visited using an inorder traversal.
167167 template
168168 void foreach(Callback& C) {
169169 if (ImutAVLTree* L = getLeft()) L->foreach(C);
170
171 C(Value);
172
170
171 C(Value);
172
173173 if (ImutAVLTree* R = getRight()) R->foreach(C);
174174 }
175
175
176176 /// verify - A utility method that checks that the balancing and
177177 /// ordering invariants of the tree are satisifed. It is a recursive
178178 /// method that returns the height of the tree, which is then consumed
182182 unsigned verify() const {
183183 unsigned HL = getLeft() ? getLeft()->verify() : 0;
184184 unsigned HR = getRight() ? getRight()->verify() : 0;
185
186 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
185
186 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
187187 && "Height calculation wrong.");
188
188
189189 assert ((HL > HR ? HL-HR : HR-HL) <= 2
190190 && "Balancing invariant violated.");
191
192
191
192
193193 assert (!getLeft()
194194 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
195195 ImutInfo::KeyOfValue(getValue()))
196196 && "Value in left child is not less that current value.");
197
198
197
198
199199 assert (!getRight()
200200 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
201201 ImutInfo::KeyOfValue(getRight()->getValue()))
202202 && "Current value is not less that value of right child.");
203
203
204204 return getHeight();
205205 }
206
206
207207 /// Profile - Profiling for ImutAVLTree.
208208 void Profile(llvm::FoldingSetNodeID& ID) {
209209 ID.AddInteger(ComputeDigest());
210210 }
211
212 //===----------------------------------------------------===//
211
212 //===----------------------------------------------------===//
213213 // Internal Values.
214214 //===----------------------------------------------------===//
215
215
216216 private:
217217 uintptr_t Left;
218218 ImutAVLTree* Right;
219219 unsigned Height;
220220 value_type Value;
221221 unsigned Digest;
222
223 //===----------------------------------------------------===//
222
223 //===----------------------------------------------------===//
224224 // Internal methods (node manipulation; used by Factory).
225225 //===----------------------------------------------------===//
226226
227227 private:
228
228
229229 enum { Mutable = 0x1 };
230230
231231 /// ImutAVLTree - Internal constructor that is only called by
233233 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
234234 : Left(reinterpret_cast(l) | Mutable),
235235 Right(r), Height(height), Value(v), Digest(0) {}
236
237
236
237
238238 /// isMutable - Returns true if the left and right subtree references
239239 /// (as well as height) can be changed. If this method returns false,
240240 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
242242 /// method returns false for an instance of ImutAVLTree, all subtrees
243243 /// will also have this method return false. The converse is not true.
244244 bool isMutable() const { return Left & Mutable; }
245
245
246246 /// getSafeLeft - Returns the pointer to the left tree by always masking
247247 /// out the mutable bit. This is used internally by ImutAVLFactory,
248248 /// as no trees returned to the client should have the mutable flag set.
249 ImutAVLTree* getSafeLeft() const {
249 ImutAVLTree* getSafeLeft() const {
250250 return reinterpret_cast(Left & ~Mutable);
251251 }
252
253 //===----------------------------------------------------===//
252
253 //===----------------------------------------------------===//
254254 // Mutating operations. A tree root can be manipulated as
255 // long as its reference has not "escaped" from internal
255 // long as its reference has not "escaped" from internal
256256 // methods of a factory object (see below). When a tree
257 // pointer is externally viewable by client code, the
258 // internal "mutable bit" is cleared to mark the tree
257 // pointer is externally viewable by client code, the
258 // internal "mutable bit" is cleared to mark the tree
259259 // immutable. Note that a tree that still has its mutable
260260 // bit set may have children (subtrees) that are themselves
261261 // immutable.
262262 //===----------------------------------------------------===//
263
264
263
264
265265 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
266266 /// it is an error to call setLeft(), setRight(), and setHeight(). It
267 /// is also then safe to call getLeft() instead of getSafeLeft().
267 /// is also then safe to call getLeft() instead of getSafeLeft().
268268 void MarkImmutable() {
269269 assert (isMutable() && "Mutable flag already removed.");
270270 Left &= ~Mutable;
271271 }
272
272
273273 /// setLeft - Changes the reference of the left subtree. Used internally
274274 /// by ImutAVLFactory.
275275 void setLeft(ImutAVLTree* NewLeft) {
276 assert (isMutable() &&
276 assert (isMutable() &&
277277 "Only a mutable tree can have its left subtree changed.");
278
278
279279 Left = reinterpret_cast(NewLeft) | Mutable;
280280 }
281
281
282282 /// setRight - Changes the reference of the right subtree. Used internally
283283 /// by ImutAVLFactory.
284284 void setRight(ImutAVLTree* NewRight) {
285285 assert (isMutable() &&
286286 "Only a mutable tree can have its right subtree changed.");
287
287
288288 Right = NewRight;
289289 }
290
290
291291 /// setHeight - Changes the height of the tree. Used internally by
292292 /// ImutAVLFactory.
293293 void setHeight(unsigned h) {
294294 assert (isMutable() && "Only a mutable tree can have its height changed.");
295295 Height = h;
296296 }
297
298
297
298
299299 static inline
300300 unsigned ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
301301 unsigned digest = 0;
302
302
303303 if (L) digest += L->ComputeDigest();
304
304
305305 { // Compute digest of stored data.
306306 FoldingSetNodeID ID;
307307 ImutInfo::Profile(ID,V);
308308 digest += ID.ComputeHash();
309309 }
310
310
311311 if (R) digest += R->ComputeDigest();
312
312
313313 return digest;
314314 }
315
315
316316 inline unsigned ComputeDigest() {
317317 if (Digest) return Digest;
318
318
319319 unsigned X = ComputeDigest(getSafeLeft(), getRight(), getValue());
320320 if (!isMutable()) Digest = X;
321
321
322322 return X;
323323 }
324324 };
325325
326 //===----------------------------------------------------------------------===//
326 //===----------------------------------------------------------------------===//
327327 // Immutable AVL-Tree Factory class.
328328 //===----------------------------------------------------------------------===//
329329
330 template
330 template
331331 class ImutAVLFactory {
332332 typedef ImutAVLTree TreeTy;
333333 typedef typename TreeTy::value_type_ref value_type_ref;
334334 typedef typename TreeTy::key_type_ref key_type_ref;
335
335
336336 typedef FoldingSet CacheTy;
337
337
338338 CacheTy Cache;
339339 uintptr_t Allocator;
340
340
341341 bool ownsAllocator() const {
342342 return Allocator & 0x1 ? false : true;
343343 }
344344
345 BumpPtrAllocator& getAllocator() const {
345 BumpPtrAllocator& getAllocator() const {
346346 return *reinterpret_cast(Allocator & ~0x1);
347347 }
348
349 //===--------------------------------------------------===//
348
349 //===--------------------------------------------------===//
350350 // Public interface.
351351 //===--------------------------------------------------===//
352
352
353353 public:
354354 ImutAVLFactory()
355355 : Allocator(reinterpret_cast(new BumpPtrAllocator())) {}
356
356
357357 ImutAVLFactory(BumpPtrAllocator& Alloc)
358358 : Allocator(reinterpret_cast(&Alloc) | 0x1) {}
359
359
360360 ~ImutAVLFactory() {
361361 if (ownsAllocator()) delete &getAllocator();
362362 }
363
363
364364 TreeTy* Add(TreeTy* T, value_type_ref V) {
365365 T = Add_internal(V,T);
366366 MarkImmutable(T);
367367 return T;
368368 }
369
369
370370 TreeTy* Remove(TreeTy* T, key_type_ref V) {
371371 T = Remove_internal(V,T);
372372 MarkImmutable(T);
373373 return T;
374374 }
375
375
376376 TreeTy* GetEmptyTree() const { return NULL; }
377
378 //===--------------------------------------------------===//
377
378 //===--------------------------------------------------===//
379379 // A bunch of quick helper functions used for reasoning
380380 // about the properties of trees and their children.
381381 // These have succinct names so that the balancing code
382382 // is as terse (and readable) as possible.
383383 //===--------------------------------------------------===//
384384 private:
385
385
386386 bool isEmpty(TreeTy* T) const { return !T; }
387 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
387 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
388388 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
389 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
389 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
390390 value_type_ref Value(TreeTy* T) const { return T->Value; }
391
391
392392 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
393393 unsigned hl = Height(L);
394394 unsigned hr = Height(R);
395395 return ( hl > hr ? hl : hr ) + 1;
396396 }
397
398
397
398
399399 static bool CompareTreeWithSection(TreeTy* T,
400400 typename TreeTy::iterator& TI,
401401 typename TreeTy::iterator& TE) {
402
402
403403 typename TreeTy::iterator I = T->begin(), E = T->end();
404
404
405405 for ( ; I!=E ; ++I, ++TI)
406406 if (TI == TE || !I->ElementEqual(*TI))
407407 return false;
408408
409409 return true;
410 }
411
412 //===--------------------------------------------------===//
410 }
411
412 //===--------------------------------------------------===//
413413 // "CreateNode" is used to generate new tree roots that link
414414 // to other trees. The functon may also simply move links
415415 // in an existing root if that root is still marked mutable.
418418 // then discarded later before the finished tree is
419419 // returned to the caller.
420420 //===--------------------------------------------------===//
421
421
422422 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
423423 // Search the FoldingSet bucket for a Tree with the same digest.
424424 FoldingSetNodeID ID;
425425 unsigned digest = TreeTy::ComputeDigest(L, R, V);
426426 ID.AddInteger(digest);
427427 unsigned hash = ID.ComputeHash();
428
428
429429 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
430430 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
431
431
432432 for (; I != E; ++I) {
433433 TreeTy* T = &*I;
434434
435435 if (T->ComputeDigest() != digest)
436436 continue;
437
437
438438 // We found a collision. Perform a comparison of Contents('T')
439439 // with Contents('L')+'V'+Contents('R').
440
440
441441 typename TreeTy::iterator TI = T->begin(), TE = T->end();
442
442
443443 // First compare Contents('L') with the (initial) contents of T.
444444 if (!CompareTreeWithSection(L, TI, TE))
445445 continue;
446
446
447447 // Now compare the new data element.
448448 if (TI == TE || !TI->ElementEqual(V))
449449 continue;
450
450
451451 ++TI;
452452
453453 // Now compare the remainder of 'T' with 'R'.
454454 if (!CompareTreeWithSection(R, TI, TE))
455455 continue;
456
456
457457 if (TI != TE) // Contents('R') did not match suffix of 'T'.
458458 continue;
459
459
460460 // Trees did match! Return 'T'.
461461 return T;
462462 }
463
463
464464 // No tree with the contents: Contents('L')+'V'+Contents('R').
465465 // Create it.
466466
477477
478478 return T;
479479 }
480
481 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
480
481 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
482482 assert (!isEmpty(OldTree));
483
483
484484 if (OldTree->isMutable()) {
485485 OldTree->setLeft(L);
486486 OldTree->setRight(R);
489489 }
490490 else return CreateNode(L, Value(OldTree), R);
491491 }
492
492
493493 /// Balance - Used by Add_internal and Remove_internal to
494494 /// balance a newly created tree.
495495 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
496
496
497497 unsigned hl = Height(L);
498498 unsigned hr = Height(R);
499
499
500500 if (hl > hr + 2) {
501501 assert (!isEmpty(L) &&
502502 "Left tree cannot be empty to have a height >= 2.");
503
503
504504 TreeTy* LL = Left(L);
505505 TreeTy* LR = Right(L);
506
506
507507 if (Height(LL) >= Height(LR))
508508 return CreateNode(LL, L, CreateNode(LR,V,R));
509
509
510510 assert (!isEmpty(LR) &&
511511 "LR cannot be empty because it has a height >= 1.");
512
512
513513 TreeTy* LRL = Left(LR);
514514 TreeTy* LRR = Right(LR);
515
516 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
515
516 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
517517 }
518518 else if (hr > hl + 2) {
519519 assert (!isEmpty(R) &&
520520 "Right tree cannot be empty to have a height >= 2.");
521
521
522522 TreeTy* RL = Left(R);
523523 TreeTy* RR = Right(R);
524
524
525525 if (Height(RR) >= Height(RL))
526526 return CreateNode(CreateNode(L,V,RL), R, RR);
527
527
528528 assert (!isEmpty(RL) &&
529529 "RL cannot be empty because it has a height >= 1.");
530
530
531531 TreeTy* RLL = Left(RL);
532532 TreeTy* RLR = Right(RL);
533
533
534534 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
535535 }
536536 else
537537 return CreateNode(L,V,R);
538538 }
539
539
540540 /// Add_internal - Creates a new tree that includes the specified
541541 /// data and the data from the original tree. If the original tree
542542 /// already contained the data item, the original tree is returned.
543543 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
544544 if (isEmpty(T))
545545 return CreateNode(T, V, T);
546
546
547547 assert (!T->isMutable());
548
548
549549 key_type_ref K = ImutInfo::KeyOfValue(V);
550550 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
551
551
552552 if (ImutInfo::isEqual(K,KCurrent))
553553 return CreateNode(Left(T), V, Right(T));
554554 else if (ImutInfo::isLess(K,KCurrent))
556556 else
557557 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
558558 }
559
559
560560 /// Remove_internal - Creates a new tree that includes all the data
561561 /// from the original tree except the specified data. If the
562562 /// specified data did not exist in the original tree, the original
564564 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
565565 if (isEmpty(T))
566566 return T;
567
567
568568 assert (!T->isMutable());
569
569
570570 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
571
571
572572 if (ImutInfo::isEqual(K,KCurrent))
573573 return CombineLeftRightTrees(Left(T),Right(T));
574574 else if (ImutInfo::isLess(K,KCurrent))
576576 else
577577 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
578578 }
579
579
580580 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
581 if (isEmpty(L)) return R;
581 if (isEmpty(L)) return R;
582582 if (isEmpty(R)) return L;
583
584 TreeTy* OldNode;
583
584 TreeTy* OldNode;
585585 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
586586 return Balance(L,Value(OldNode),NewRight);
587587 }
588
588
589589 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
590590 assert (!isEmpty(T));
591
591
592592 if (isEmpty(Left(T))) {
593593 NodeRemoved = T;
594594 return Right(T);
595595 }
596
596
597597 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
598 }
599
598 }
599
600600 /// MarkImmutable - Clears the mutable bits of a root and all of its
601601 /// descendants.
602602 void MarkImmutable(TreeTy* T) {
603603 if (!T || !T->isMutable())
604604 return;
605
605
606606 T->MarkImmutable();
607607 MarkImmutable(Left(T));
608608 MarkImmutable(Right(T));
609
609
610610 // Now that the node is immutable it can safely be inserted
611611 // into the node cache.
612612 llvm::FoldingSetNodeID ID;
614614 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
615615 }
616616 };
617
618
619 //===----------------------------------------------------------------------===//
617
618
619 //===----------------------------------------------------------------------===//
620620 // Immutable AVL-Tree Iterators.
621 //===----------------------------------------------------------------------===//
621 //===----------------------------------------------------------------------===//
622622
623623 template
624624 class ImutAVLTreeGenericIterator {
625625 SmallVector stack;
626626 public:
627 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
627 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
628628 Flags=0x3 };
629
630 typedef ImutAVLTree TreeTy;
629
630 typedef ImutAVLTree TreeTy;
631631 typedef ImutAVLTreeGenericIterator _Self;
632632
633633 inline ImutAVLTreeGenericIterator() {}
634634 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
635635 if (Root) stack.push_back(reinterpret_cast(Root));
636 }
637
636 }
637
638638 TreeTy* operator*() const {
639 assert (!stack.empty());
639 assert (!stack.empty());
640640 return reinterpret_cast(stack.back() & ~Flags);
641641 }
642
642
643643 uintptr_t getVisitState() {
644644 assert (!stack.empty());
645645 return stack.back() & Flags;
646646 }
647
648
647
648
649649 bool AtEnd() const { return stack.empty(); }
650650
651 bool AtBeginning() const {
651 bool AtBeginning() const {
652652 return stack.size() == 1 && getVisitState() == VisitedNone;
653653 }
654
654
655655 void SkipToParent() {
656656 assert (!stack.empty());
657657 stack.pop_back();
658
658
659659 if (stack.empty())
660660 return;
661
661
662662 switch (getVisitState()) {
663663 case VisitedNone:
664664 stack.back() |= VisitedLeft;
667667 stack.back() |= VisitedRight;
668668 break;
669669 default:
670 assert (false && "Unreachable.");
671 }
672 }
673
670 assert (false && "Unreachable.");
671 }
672 }
673
674674 inline bool operator==(const _Self& x) const {
675675 if (stack.size() != x.stack.size())
676676 return false;
677
677
678678 for (unsigned i = 0 ; i < stack.size(); i++)
679679 if (stack[i] != x.stack[i])
680680 return false;
681
681
682682 return true;
683683 }
684
685 inline bool operator!=(const _Self& x) const { return !operator==(x); }
686
684
685 inline bool operator!=(const _Self& x) const { return !operator==(x); }
686
687687 _Self& operator++() {
688688 assert (!stack.empty());
689
689
690690 TreeTy* Current = reinterpret_cast(stack.back() & ~Flags);
691691 assert (Current);
692
692
693693 switch (getVisitState()) {
694694 case VisitedNone:
695695 if (TreeTy* L = Current->getSafeLeft())
696696 stack.push_back(reinterpret_cast(L));
697697 else
698698 stack.back() |= VisitedLeft;
699
699
700700 break;
701
701
702702 case VisitedLeft:
703703 if (TreeTy* R = Current->getRight())
704704 stack.push_back(reinterpret_cast(R));
705705 else
706706 stack.back() |= VisitedRight;
707
707
708708 break;
709
709
710710 case VisitedRight:
711 SkipToParent();
711 SkipToParent();
712712 break;
713
713
714714 default:
715715 assert (false && "Unreachable.");
716716 }
717
717
718718 return *this;
719719 }
720
720
721721 _Self& operator--() {
722722 assert (!stack.empty());
723
723
724724 TreeTy* Current = reinterpret_cast(stack.back() & ~Flags);
725725 assert (Current);
726
726
727727 switch (getVisitState()) {
728728 case VisitedNone:
729729 stack.pop_back();
730730 break;
731
732 case VisitedLeft:
731
732 case VisitedLeft:
733733 stack.back() &= ~Flags; // Set state to "VisitedNone."
734
734
735735 if (TreeTy* L = Current->getLeft())
736736 stack.push_back(reinterpret_cast(L) | VisitedRight);
737
737
738738 break;
739
740 case VisitedRight:
739
740 case VisitedRight:
741741 stack.back() &= ~Flags;
742742 stack.back() |= VisitedLeft;
743
743
744744 if (TreeTy* R = Current->getRight())
745745 stack.push_back(reinterpret_cast(R) | VisitedRight);
746
746
747747 break;
748
748
749749 default:
750750 assert (false && "Unreachable.");
751751 }
752
752
753753 return *this;
754754 }
755755 };
756
756
757757 template
758758 class ImutAVLTreeInOrderIterator {
759759 typedef ImutAVLTreeGenericIterator InternalIteratorTy;
763763 typedef ImutAVLTree TreeTy;
764764 typedef ImutAVLTreeInOrderIterator _Self;
765765
766 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
766 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
767767 if (Root) operator++(); // Advance to first element.
768768 }
769
769
770770 ImutAVLTreeInOrderIterator() : InternalItr() {}
771771
772772 inline bool operator==(const _Self& x) const {
773773 return InternalItr == x.InternalItr;
774774 }
775
776 inline bool operator!=(const _Self& x) const { return !operator==(x); }
777
775
776 inline bool operator!=(const _Self& x) const { return !operator==(x); }
777
778778 inline TreeTy* operator*() const { return *InternalItr; }
779779 inline TreeTy* operator->() const { return *InternalItr; }
780
781 inline _Self& operator++() {
780
781 inline _Self& operator++() {
782782 do ++InternalItr;
783 while (!InternalItr.AtEnd() &&
783 while (!InternalItr.AtEnd() &&
784784 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
785785
786786 return *this;
787787 }
788
789 inline _Self& operator--() {
788
789 inline _Self& operator--() {
790790 do --InternalItr;
791 while (!InternalItr.AtBeginning() &&
791 while (!InternalItr.AtBeginning() &&
792792 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
793
793
794794 return *this;
795795 }
796
796
797797 inline void SkipSubTree() {
798798 InternalItr.SkipToParent();
799
799
800800 while (!InternalItr.AtEnd() &&
801801 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
802 ++InternalItr;