Per Chris' suggestion, get rid of the select canonicalization and just add
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineAndOrXor.cpp
1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitAnd, visitOr, and visitXor functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20
21
22 /// AddOne - Add one to a ConstantInt.
23 static Constant *AddOne(Constant *C) {
24   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
25 }
26 /// SubOne - Subtract one from a ConstantInt.
27 static Constant *SubOne(ConstantInt *C) {
28   return ConstantInt::get(C->getContext(), C->getValue()-1);
29 }
30
31 /// isFreeToInvert - Return true if the specified value is free to invert (apply
32 /// ~ to).  This happens in cases where the ~ can be eliminated.
33 static inline bool isFreeToInvert(Value *V) {
34   // ~(~(X)) -> X.
35   if (BinaryOperator::isNot(V))
36     return true;
37   
38   // Constants can be considered to be not'ed values.
39   if (isa<ConstantInt>(V))
40     return true;
41   
42   // Compares can be inverted if they have a single use.
43   if (CmpInst *CI = dyn_cast<CmpInst>(V))
44     return CI->hasOneUse();
45   
46   return false;
47 }
48
49 static inline Value *dyn_castNotVal(Value *V) {
50   // If this is not(not(x)) don't return that this is a not: we want the two
51   // not's to be folded first.
52   if (BinaryOperator::isNot(V)) {
53     Value *Operand = BinaryOperator::getNotArgument(V);
54     if (!isFreeToInvert(Operand))
55       return Operand;
56   }
57   
58   // Constants can be considered to be not'ed values...
59   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
60     return ConstantInt::get(C->getType(), ~C->getValue());
61   return 0;
62 }
63
64
65 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
66 /// are carefully arranged to allow folding of expressions such as:
67 ///
68 ///      (A < B) | (A > B) --> (A != B)
69 ///
70 /// Note that this is only valid if the first and second predicates have the
71 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
72 ///
73 /// Three bits are used to represent the condition, as follows:
74 ///   0  A > B
75 ///   1  A == B
76 ///   2  A < B
77 ///
78 /// <=>  Value  Definition
79 /// 000     0   Always false
80 /// 001     1   A >  B
81 /// 010     2   A == B
82 /// 011     3   A >= B
83 /// 100     4   A <  B
84 /// 101     5   A != B
85 /// 110     6   A <= B
86 /// 111     7   Always true
87 ///  
88 static unsigned getICmpCode(const ICmpInst *ICI) {
89   switch (ICI->getPredicate()) {
90     // False -> 0
91   case ICmpInst::ICMP_UGT: return 1;  // 001
92   case ICmpInst::ICMP_SGT: return 1;  // 001
93   case ICmpInst::ICMP_EQ:  return 2;  // 010
94   case ICmpInst::ICMP_UGE: return 3;  // 011
95   case ICmpInst::ICMP_SGE: return 3;  // 011
96   case ICmpInst::ICMP_ULT: return 4;  // 100
97   case ICmpInst::ICMP_SLT: return 4;  // 100
98   case ICmpInst::ICMP_NE:  return 5;  // 101
99   case ICmpInst::ICMP_ULE: return 6;  // 110
100   case ICmpInst::ICMP_SLE: return 6;  // 110
101     // True -> 7
102   default:
103     llvm_unreachable("Invalid ICmp predicate!");
104     return 0;
105   }
106 }
107
108 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
109 /// predicate into a three bit mask. It also returns whether it is an ordered
110 /// predicate by reference.
111 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
112   isOrdered = false;
113   switch (CC) {
114   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
115   case FCmpInst::FCMP_UNO:                   return 0;  // 000
116   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
117   case FCmpInst::FCMP_UGT:                   return 1;  // 001
118   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
119   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
120   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
121   case FCmpInst::FCMP_UGE:                   return 3;  // 011
122   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
123   case FCmpInst::FCMP_ULT:                   return 4;  // 100
124   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
125   case FCmpInst::FCMP_UNE:                   return 5;  // 101
126   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
127   case FCmpInst::FCMP_ULE:                   return 6;  // 110
128     // True -> 7
129   default:
130     // Not expecting FCMP_FALSE and FCMP_TRUE;
131     llvm_unreachable("Unexpected FCmp predicate!");
132     return 0;
133   }
134 }
135
136 /// getICmpValue - This is the complement of getICmpCode, which turns an
137 /// opcode and two operands into either a constant true or false, or a brand 
138 /// new ICmp instruction. The sign is passed in to determine which kind
139 /// of predicate to use in the new icmp instruction.
140 static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
141                            InstCombiner::BuilderTy *Builder) {
142   CmpInst::Predicate Pred;
143   switch (Code) {
144   default: assert(0 && "Illegal ICmp code!");
145   case 0: // False.
146     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
147   case 1: Pred = Sign ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
148   case 2: Pred = ICmpInst::ICMP_EQ; break;
149   case 3: Pred = Sign ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
150   case 4: Pred = Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
151   case 5: Pred = ICmpInst::ICMP_NE; break;
152   case 6: Pred = Sign ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
153   case 7: // True.
154     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
155   }
156   return Builder->CreateICmp(Pred, LHS, RHS);
157 }
158
159 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
160 /// opcode and two operands into either a FCmp instruction. isordered is passed
161 /// in to determine which kind of predicate to use in the new fcmp instruction.
162 static Value *getFCmpValue(bool isordered, unsigned code,
163                            Value *LHS, Value *RHS,
164                            InstCombiner::BuilderTy *Builder) {
165   CmpInst::Predicate Pred;
166   switch (code) {
167   default: assert(0 && "Illegal FCmp code!");
168   case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
169   case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
170   case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
171   case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
172   case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
173   case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
174   case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
175   case 7: return ConstantInt::getTrue(LHS->getContext());
176   }
177   return Builder->CreateFCmp(Pred, LHS, RHS);
178 }
179
180 /// PredicatesFoldable - Return true if both predicates match sign or if at
181 /// least one of them is an equality comparison (which is signless).
182 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
183   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
184          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
185          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
186 }
187
188 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
189 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
190 // guaranteed to be a binary operator.
191 Instruction *InstCombiner::OptAndOp(Instruction *Op,
192                                     ConstantInt *OpRHS,
193                                     ConstantInt *AndRHS,
194                                     BinaryOperator &TheAnd) {
195   Value *X = Op->getOperand(0);
196   Constant *Together = 0;
197   if (!Op->isShift())
198     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
199
200   switch (Op->getOpcode()) {
201   case Instruction::Xor:
202     if (Op->hasOneUse()) {
203       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
204       Value *And = Builder->CreateAnd(X, AndRHS);
205       And->takeName(Op);
206       return BinaryOperator::CreateXor(And, Together);
207     }
208     break;
209   case Instruction::Or:
210     if (Together == AndRHS) // (X | C) & C --> C
211       return ReplaceInstUsesWith(TheAnd, AndRHS);
212
213     if (Op->hasOneUse() && Together != OpRHS) {
214       // (X | C1) & C2 --> (X | (C1&C2)) & C2
215       Value *Or = Builder->CreateOr(X, Together);
216       Or->takeName(Op);
217       return BinaryOperator::CreateAnd(Or, AndRHS);
218     }
219     break;
220   case Instruction::Add:
221     if (Op->hasOneUse()) {
222       // Adding a one to a single bit bit-field should be turned into an XOR
223       // of the bit.  First thing to check is to see if this AND is with a
224       // single bit constant.
225       const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
226
227       // If there is only one bit set.
228       if (AndRHSV.isPowerOf2()) {
229         // Ok, at this point, we know that we are masking the result of the
230         // ADD down to exactly one bit.  If the constant we are adding has
231         // no bits set below this bit, then we can eliminate the ADD.
232         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
233
234         // Check to see if any bits below the one bit set in AndRHSV are set.
235         if ((AddRHS & (AndRHSV-1)) == 0) {
236           // If not, the only thing that can effect the output of the AND is
237           // the bit specified by AndRHSV.  If that bit is set, the effect of
238           // the XOR is to toggle the bit.  If it is clear, then the ADD has
239           // no effect.
240           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
241             TheAnd.setOperand(0, X);
242             return &TheAnd;
243           } else {
244             // Pull the XOR out of the AND.
245             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
246             NewAnd->takeName(Op);
247             return BinaryOperator::CreateXor(NewAnd, AndRHS);
248           }
249         }
250       }
251     }
252     break;
253
254   case Instruction::Shl: {
255     // We know that the AND will not produce any of the bits shifted in, so if
256     // the anded constant includes them, clear them now!
257     //
258     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
259     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
260     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
261     ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
262                                        AndRHS->getValue() & ShlMask);
263
264     if (CI->getValue() == ShlMask) { 
265     // Masking out bits that the shift already masks
266       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
267     } else if (CI != AndRHS) {                  // Reducing bits set in and.
268       TheAnd.setOperand(1, CI);
269       return &TheAnd;
270     }
271     break;
272   }
273   case Instruction::LShr: {
274     // We know that the AND will not produce any of the bits shifted in, so if
275     // the anded constant includes them, clear them now!  This only applies to
276     // unsigned shifts, because a signed shr may bring in set bits!
277     //
278     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
279     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
280     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
281     ConstantInt *CI = ConstantInt::get(Op->getContext(),
282                                        AndRHS->getValue() & ShrMask);
283
284     if (CI->getValue() == ShrMask) {   
285     // Masking out bits that the shift already masks.
286       return ReplaceInstUsesWith(TheAnd, Op);
287     } else if (CI != AndRHS) {
288       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
289       return &TheAnd;
290     }
291     break;
292   }
293   case Instruction::AShr:
294     // Signed shr.
295     // See if this is shifting in some sign extension, then masking it out
296     // with an and.
297     if (Op->hasOneUse()) {
298       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
299       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
300       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
301       Constant *C = ConstantInt::get(Op->getContext(),
302                                      AndRHS->getValue() & ShrMask);
303       if (C == AndRHS) {          // Masking out bits shifted in.
304         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
305         // Make the argument unsigned.
306         Value *ShVal = Op->getOperand(0);
307         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
308         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
309       }
310     }
311     break;
312   }
313   return 0;
314 }
315
316
317 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
318 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
319 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
320 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
321 /// insert new instructions.
322 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
323                                      bool isSigned, bool Inside) {
324   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
325             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
326          "Lo is not <= Hi in range emission code!");
327     
328   if (Inside) {
329     if (Lo == Hi)  // Trivially false.
330       return ConstantInt::getFalse(V->getContext());
331
332     // V >= Min && V < Hi --> V < Hi
333     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
334       ICmpInst::Predicate pred = (isSigned ? 
335         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
336       return Builder->CreateICmp(pred, V, Hi);
337     }
338
339     // Emit V-Lo <u Hi-Lo
340     Constant *NegLo = ConstantExpr::getNeg(Lo);
341     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
342     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
343     return Builder->CreateICmpULT(Add, UpperBound);
344   }
345
346   if (Lo == Hi)  // Trivially true.
347     return ConstantInt::getTrue(V->getContext());
348
349   // V < Min || V >= Hi -> V > Hi-1
350   Hi = SubOne(cast<ConstantInt>(Hi));
351   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
352     ICmpInst::Predicate pred = (isSigned ? 
353         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
354     return Builder->CreateICmp(pred, V, Hi);
355   }
356
357   // Emit V-Lo >u Hi-1-Lo
358   // Note that Hi has already had one subtracted from it, above.
359   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
360   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
361   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
362   return Builder->CreateICmpUGT(Add, LowerBound);
363 }
364
365 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
366 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
367 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
368 // not, since all 1s are not contiguous.
369 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
370   const APInt& V = Val->getValue();
371   uint32_t BitWidth = Val->getType()->getBitWidth();
372   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
373
374   // look for the first zero bit after the run of ones
375   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
376   // look for the first non-zero bit
377   ME = V.getActiveBits(); 
378   return true;
379 }
380
381 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
382 /// where isSub determines whether the operator is a sub.  If we can fold one of
383 /// the following xforms:
384 /// 
385 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
386 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
387 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
388 ///
389 /// return (A +/- B).
390 ///
391 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
392                                         ConstantInt *Mask, bool isSub,
393                                         Instruction &I) {
394   Instruction *LHSI = dyn_cast<Instruction>(LHS);
395   if (!LHSI || LHSI->getNumOperands() != 2 ||
396       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
397
398   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
399
400   switch (LHSI->getOpcode()) {
401   default: return 0;
402   case Instruction::And:
403     if (ConstantExpr::getAnd(N, Mask) == Mask) {
404       // If the AndRHS is a power of two minus one (0+1+), this is simple.
405       if ((Mask->getValue().countLeadingZeros() + 
406            Mask->getValue().countPopulation()) == 
407           Mask->getValue().getBitWidth())
408         break;
409
410       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
411       // part, we don't need any explicit masks to take them out of A.  If that
412       // is all N is, ignore it.
413       uint32_t MB = 0, ME = 0;
414       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
415         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
416         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
417         if (MaskedValueIsZero(RHS, Mask))
418           break;
419       }
420     }
421     return 0;
422   case Instruction::Or:
423   case Instruction::Xor:
424     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
425     if ((Mask->getValue().countLeadingZeros() + 
426          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
427         && ConstantExpr::getAnd(N, Mask)->isNullValue())
428       break;
429     return 0;
430   }
431   
432   if (isSub)
433     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
434   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
435 }
436
437 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
438 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
439   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
440
441   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
442   if (PredicatesFoldable(LHSCC, RHSCC)) {
443     if (LHS->getOperand(0) == RHS->getOperand(1) &&
444         LHS->getOperand(1) == RHS->getOperand(0))
445       LHS->swapOperands();
446     if (LHS->getOperand(0) == RHS->getOperand(0) &&
447         LHS->getOperand(1) == RHS->getOperand(1)) {
448       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
449       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
450       bool isSigned = LHS->isSigned() || RHS->isSigned();
451       return getICmpValue(isSigned, Code, Op0, Op1, Builder);
452     }
453   }
454   
455   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
456   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
457   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
458   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
459   if (LHSCst == 0 || RHSCst == 0) return 0;
460   
461   if (LHSCst == RHSCst && LHSCC == RHSCC) {
462     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
463     // where C is a power of 2
464     if (LHSCC == ICmpInst::ICMP_ULT &&
465         LHSCst->getValue().isPowerOf2()) {
466       Value *NewOr = Builder->CreateOr(Val, Val2);
467       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
468     }
469     
470     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
471     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
472       Value *NewOr = Builder->CreateOr(Val, Val2);
473       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
474     }
475     
476     // (icmp ne (A & C1), 0) & (icmp ne (A & C2), 0) -->
477     // (icmp eq (A & (C1|C2)), (C1|C2))
478     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
479       Instruction *I1 = dyn_cast<Instruction>(Val);
480       Instruction *I2 = dyn_cast<Instruction>(Val2);
481       if (I1 && I1->getOpcode() == Instruction::And &&
482           I2 && I2->getOpcode() == Instruction::And &&
483           I1->getOperand(0) == I1->getOperand(0)) {
484         ConstantInt *CI1 = dyn_cast<ConstantInt>(I1->getOperand(1));
485         ConstantInt *CI2 = dyn_cast<ConstantInt>(I2->getOperand(1));
486         if (CI1 && !CI1->isZero() && CI2 && !CI2->isZero() &&
487             CI1->getValue().operator&(CI2->getValue()) == 0) {
488           Constant *ConstOr = ConstantExpr::getOr(CI1, CI2);
489           Value *NewAnd = Builder->CreateAnd(I1->getOperand(0), ConstOr);
490           return Builder->CreateICmp(ICmpInst::ICMP_EQ, NewAnd, ConstOr);
491         }
492       }
493     }
494   }
495   
496   // From here on, we only handle:
497   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
498   if (Val != Val2) return 0;
499   
500   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
501   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
502       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
503       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
504       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
505     return 0;
506   
507   // We can't fold (ugt x, C) & (sgt x, C2).
508   if (!PredicatesFoldable(LHSCC, RHSCC))
509     return 0;
510     
511   // Ensure that the larger constant is on the RHS.
512   bool ShouldSwap;
513   if (CmpInst::isSigned(LHSCC) ||
514       (ICmpInst::isEquality(LHSCC) && 
515        CmpInst::isSigned(RHSCC)))
516     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
517   else
518     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
519     
520   if (ShouldSwap) {
521     std::swap(LHS, RHS);
522     std::swap(LHSCst, RHSCst);
523     std::swap(LHSCC, RHSCC);
524   }
525
526   // At this point, we know we have two icmp instructions
527   // comparing a value against two constants and and'ing the result
528   // together.  Because of the above check, we know that we only have
529   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
530   // (from the icmp folding check above), that the two constants 
531   // are not equal and that the larger constant is on the RHS
532   assert(LHSCst != RHSCst && "Compares not folded above?");
533
534   switch (LHSCC) {
535   default: llvm_unreachable("Unknown integer condition code!");
536   case ICmpInst::ICMP_EQ:
537     switch (RHSCC) {
538     default: llvm_unreachable("Unknown integer condition code!");
539     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
540     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
541     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
542       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
543     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
544     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
545     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
546       return LHS;
547     }
548   case ICmpInst::ICMP_NE:
549     switch (RHSCC) {
550     default: llvm_unreachable("Unknown integer condition code!");
551     case ICmpInst::ICMP_ULT:
552       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
553         return Builder->CreateICmpULT(Val, LHSCst);
554       break;                        // (X != 13 & X u< 15) -> no change
555     case ICmpInst::ICMP_SLT:
556       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
557         return Builder->CreateICmpSLT(Val, LHSCst);
558       break;                        // (X != 13 & X s< 15) -> no change
559     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
560     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
561     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
562       return RHS;
563     case ICmpInst::ICMP_NE:
564       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
565         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
566         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
567         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
568       }
569       break;                        // (X != 13 & X != 15) -> no change
570     }
571     break;
572   case ICmpInst::ICMP_ULT:
573     switch (RHSCC) {
574     default: llvm_unreachable("Unknown integer condition code!");
575     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
576     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
577       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
578     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
579       break;
580     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
581     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
582       return LHS;
583     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
584       break;
585     }
586     break;
587   case ICmpInst::ICMP_SLT:
588     switch (RHSCC) {
589     default: llvm_unreachable("Unknown integer condition code!");
590     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
591     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
592       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
593     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
594       break;
595     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
596     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
597       return LHS;
598     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
599       break;
600     }
601     break;
602   case ICmpInst::ICMP_UGT:
603     switch (RHSCC) {
604     default: llvm_unreachable("Unknown integer condition code!");
605     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
606     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
607       return RHS;
608     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
609       break;
610     case ICmpInst::ICMP_NE:
611       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
612         return Builder->CreateICmp(LHSCC, Val, RHSCst);
613       break;                        // (X u> 13 & X != 15) -> no change
614     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
615       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
616     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
617       break;
618     }
619     break;
620   case ICmpInst::ICMP_SGT:
621     switch (RHSCC) {
622     default: llvm_unreachable("Unknown integer condition code!");
623     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
624     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
625       return RHS;
626     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
627       break;
628     case ICmpInst::ICMP_NE:
629       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
630         return Builder->CreateICmp(LHSCC, Val, RHSCst);
631       break;                        // (X s> 13 & X != 15) -> no change
632     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
633       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
634     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
635       break;
636     }
637     break;
638   }
639  
640   return 0;
641 }
642
643 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
644 /// instcombine, this returns a Value which should already be inserted into the
645 /// function.
646 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
647   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
648       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
649     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
650     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
651       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
652         // If either of the constants are nans, then the whole thing returns
653         // false.
654         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
655           return ConstantInt::getFalse(LHS->getContext());
656         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
657       }
658     
659     // Handle vector zeros.  This occurs because the canonical form of
660     // "fcmp ord x,x" is "fcmp ord x, 0".
661     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
662         isa<ConstantAggregateZero>(RHS->getOperand(1)))
663       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
664     return 0;
665   }
666   
667   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
668   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
669   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
670   
671   
672   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
673     // Swap RHS operands to match LHS.
674     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
675     std::swap(Op1LHS, Op1RHS);
676   }
677   
678   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
679     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
680     if (Op0CC == Op1CC)
681       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
682     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
683       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
684     if (Op0CC == FCmpInst::FCMP_TRUE)
685       return RHS;
686     if (Op1CC == FCmpInst::FCMP_TRUE)
687       return LHS;
688     
689     bool Op0Ordered;
690     bool Op1Ordered;
691     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
692     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
693     if (Op1Pred == 0) {
694       std::swap(LHS, RHS);
695       std::swap(Op0Pred, Op1Pred);
696       std::swap(Op0Ordered, Op1Ordered);
697     }
698     if (Op0Pred == 0) {
699       // uno && ueq -> uno && (uno || eq) -> ueq
700       // ord && olt -> ord && (ord && lt) -> olt
701       if (Op0Ordered == Op1Ordered)
702         return RHS;
703       
704       // uno && oeq -> uno && (ord && eq) -> false
705       // uno && ord -> false
706       if (!Op0Ordered)
707         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
708       // ord && ueq -> ord && (uno || eq) -> oeq
709       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
710     }
711   }
712
713   return 0;
714 }
715
716
717 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
718   bool Changed = SimplifyCommutative(I);
719   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
720
721   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
722     return ReplaceInstUsesWith(I, V);
723
724   // See if we can simplify any instructions used by the instruction whose sole 
725   // purpose is to compute bits we don't care about.
726   if (SimplifyDemandedInstructionBits(I))
727     return &I;  
728
729   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
730     const APInt &AndRHSMask = AndRHS->getValue();
731     APInt NotAndRHS(~AndRHSMask);
732
733     // Optimize a variety of ((val OP C1) & C2) combinations...
734     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
735       Value *Op0LHS = Op0I->getOperand(0);
736       Value *Op0RHS = Op0I->getOperand(1);
737       switch (Op0I->getOpcode()) {
738       default: break;
739       case Instruction::Xor:
740       case Instruction::Or:
741         // If the mask is only needed on one incoming arm, push it up.
742         if (!Op0I->hasOneUse()) break;
743           
744         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
745           // Not masking anything out for the LHS, move to RHS.
746           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
747                                              Op0RHS->getName()+".masked");
748           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
749         }
750         if (!isa<Constant>(Op0RHS) &&
751             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
752           // Not masking anything out for the RHS, move to LHS.
753           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
754                                              Op0LHS->getName()+".masked");
755           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
756         }
757
758         break;
759       case Instruction::Add:
760         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
761         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
762         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
763         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
764           return BinaryOperator::CreateAnd(V, AndRHS);
765         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
766           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
767         break;
768
769       case Instruction::Sub:
770         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
771         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
772         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
773         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
774           return BinaryOperator::CreateAnd(V, AndRHS);
775
776         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
777         // has 1's for all bits that the subtraction with A might affect.
778         if (Op0I->hasOneUse()) {
779           uint32_t BitWidth = AndRHSMask.getBitWidth();
780           uint32_t Zeros = AndRHSMask.countLeadingZeros();
781           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
782
783           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
784           if (!(A && A->isZero()) &&               // avoid infinite recursion.
785               MaskedValueIsZero(Op0LHS, Mask)) {
786             Value *NewNeg = Builder->CreateNeg(Op0RHS);
787             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
788           }
789         }
790         break;
791
792       case Instruction::Shl:
793       case Instruction::LShr:
794         // (1 << x) & 1 --> zext(x == 0)
795         // (1 >> x) & 1 --> zext(x == 0)
796         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
797           Value *NewICmp =
798             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
799           return new ZExtInst(NewICmp, I.getType());
800         }
801         break;
802       }
803
804       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
805         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
806           return Res;
807     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
808       // If this is an integer truncation or change from signed-to-unsigned, and
809       // if the source is an and/or with immediate, transform it.  This
810       // frequently occurs for bitfield accesses.
811       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
812         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
813             CastOp->getNumOperands() == 2)
814           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
815             if (CastOp->getOpcode() == Instruction::And) {
816               // Change: and (cast (and X, C1) to T), C2
817               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
818               // This will fold the two constants together, which may allow 
819               // other simplifications.
820               Value *NewCast = Builder->CreateTruncOrBitCast(
821                 CastOp->getOperand(0), I.getType(), 
822                 CastOp->getName()+".shrunk");
823               // trunc_or_bitcast(C1)&C2
824               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
825               C3 = ConstantExpr::getAnd(C3, AndRHS);
826               return BinaryOperator::CreateAnd(NewCast, C3);
827             } else if (CastOp->getOpcode() == Instruction::Or) {
828               // Change: and (cast (or X, C1) to T), C2
829               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
830               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
831               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
832                 // trunc(C1)&C2
833                 return ReplaceInstUsesWith(I, AndRHS);
834             }
835           }
836       }
837     }
838
839     // Try to fold constant and into select arguments.
840     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
841       if (Instruction *R = FoldOpIntoSelect(I, SI))
842         return R;
843     if (isa<PHINode>(Op0))
844       if (Instruction *NV = FoldOpIntoPhi(I))
845         return NV;
846   }
847
848
849   // (~A & ~B) == (~(A | B)) - De Morgan's Law
850   if (Value *Op0NotVal = dyn_castNotVal(Op0))
851     if (Value *Op1NotVal = dyn_castNotVal(Op1))
852       if (Op0->hasOneUse() && Op1->hasOneUse()) {
853         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
854                                       I.getName()+".demorgan");
855         return BinaryOperator::CreateNot(Or);
856       }
857
858   {
859     Value *A = 0, *B = 0, *C = 0, *D = 0;
860     // (A|B) & ~(A&B) -> A^B
861     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
862         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
863         ((A == C && B == D) || (A == D && B == C)))
864       return BinaryOperator::CreateXor(A, B);
865     
866     // ~(A&B) & (A|B) -> A^B
867     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
868         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
869         ((A == C && B == D) || (A == D && B == C)))
870       return BinaryOperator::CreateXor(A, B);
871     
872     if (Op0->hasOneUse() &&
873         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
874       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
875         I.swapOperands();     // Simplify below
876         std::swap(Op0, Op1);
877       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
878         cast<BinaryOperator>(Op0)->swapOperands();
879         I.swapOperands();     // Simplify below
880         std::swap(Op0, Op1);
881       }
882     }
883
884     if (Op1->hasOneUse() &&
885         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
886       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
887         cast<BinaryOperator>(Op1)->swapOperands();
888         std::swap(A, B);
889       }
890       if (A == Op0)                                // A&(A^B) -> A & ~B
891         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
892     }
893
894     // (A&((~A)|B)) -> A&B
895     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
896         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
897       return BinaryOperator::CreateAnd(A, Op1);
898     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
899         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
900       return BinaryOperator::CreateAnd(A, Op0);
901   }
902   
903   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
904     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
905       if (Value *Res = FoldAndOfICmps(LHS, RHS))
906         return ReplaceInstUsesWith(I, Res);
907   
908   // If and'ing two fcmp, try combine them into one.
909   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
910     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
911       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
912         return ReplaceInstUsesWith(I, Res);
913   
914   
915   // fold (and (cast A), (cast B)) -> (cast (and A, B))
916   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
917     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
918       const Type *SrcTy = Op0C->getOperand(0)->getType();
919       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
920           SrcTy == Op1C->getOperand(0)->getType() &&
921           SrcTy->isIntOrIntVectorTy()) {
922         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
923         
924         // Only do this if the casts both really cause code to be generated.
925         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
926             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
927           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
928           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
929         }
930         
931         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
932         // cast is otherwise not optimizable.  This happens for vector sexts.
933         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
934           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
935             if (Value *Res = FoldAndOfICmps(LHS, RHS))
936               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
937         
938         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
939         // cast is otherwise not optimizable.  This happens for vector sexts.
940         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
941           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
942             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
943               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
944       }
945     }
946     
947   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
948   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
949     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
950       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
951           SI0->getOperand(1) == SI1->getOperand(1) &&
952           (SI0->hasOneUse() || SI1->hasOneUse())) {
953         Value *NewOp =
954           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
955                              SI0->getName());
956         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
957                                       SI1->getOperand(1));
958       }
959   }
960
961   return Changed ? &I : 0;
962 }
963
964 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
965 /// capable of providing pieces of a bswap.  The subexpression provides pieces
966 /// of a bswap if it is proven that each of the non-zero bytes in the output of
967 /// the expression came from the corresponding "byte swapped" byte in some other
968 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
969 /// we know that the expression deposits the low byte of %X into the high byte
970 /// of the bswap result and that all other bytes are zero.  This expression is
971 /// accepted, the high byte of ByteValues is set to X to indicate a correct
972 /// match.
973 ///
974 /// This function returns true if the match was unsuccessful and false if so.
975 /// On entry to the function the "OverallLeftShift" is a signed integer value
976 /// indicating the number of bytes that the subexpression is later shifted.  For
977 /// example, if the expression is later right shifted by 16 bits, the
978 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
979 /// byte of ByteValues is actually being set.
980 ///
981 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
982 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
983 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
984 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
985 /// always in the local (OverallLeftShift) coordinate space.
986 ///
987 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
988                               SmallVector<Value*, 8> &ByteValues) {
989   if (Instruction *I = dyn_cast<Instruction>(V)) {
990     // If this is an or instruction, it may be an inner node of the bswap.
991     if (I->getOpcode() == Instruction::Or) {
992       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
993                                ByteValues) ||
994              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
995                                ByteValues);
996     }
997   
998     // If this is a logical shift by a constant multiple of 8, recurse with
999     // OverallLeftShift and ByteMask adjusted.
1000     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1001       unsigned ShAmt = 
1002         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1003       // Ensure the shift amount is defined and of a byte value.
1004       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1005         return true;
1006
1007       unsigned ByteShift = ShAmt >> 3;
1008       if (I->getOpcode() == Instruction::Shl) {
1009         // X << 2 -> collect(X, +2)
1010         OverallLeftShift += ByteShift;
1011         ByteMask >>= ByteShift;
1012       } else {
1013         // X >>u 2 -> collect(X, -2)
1014         OverallLeftShift -= ByteShift;
1015         ByteMask <<= ByteShift;
1016         ByteMask &= (~0U >> (32-ByteValues.size()));
1017       }
1018
1019       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1020       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1021
1022       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1023                                ByteValues);
1024     }
1025
1026     // If this is a logical 'and' with a mask that clears bytes, clear the
1027     // corresponding bytes in ByteMask.
1028     if (I->getOpcode() == Instruction::And &&
1029         isa<ConstantInt>(I->getOperand(1))) {
1030       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1031       unsigned NumBytes = ByteValues.size();
1032       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1033       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1034       
1035       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1036         // If this byte is masked out by a later operation, we don't care what
1037         // the and mask is.
1038         if ((ByteMask & (1 << i)) == 0)
1039           continue;
1040         
1041         // If the AndMask is all zeros for this byte, clear the bit.
1042         APInt MaskB = AndMask & Byte;
1043         if (MaskB == 0) {
1044           ByteMask &= ~(1U << i);
1045           continue;
1046         }
1047         
1048         // If the AndMask is not all ones for this byte, it's not a bytezap.
1049         if (MaskB != Byte)
1050           return true;
1051
1052         // Otherwise, this byte is kept.
1053       }
1054
1055       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1056                                ByteValues);
1057     }
1058   }
1059   
1060   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1061   // the input value to the bswap.  Some observations: 1) if more than one byte
1062   // is demanded from this input, then it could not be successfully assembled
1063   // into a byteswap.  At least one of the two bytes would not be aligned with
1064   // their ultimate destination.
1065   if (!isPowerOf2_32(ByteMask)) return true;
1066   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1067   
1068   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1069   // is demanded, it needs to go into byte 0 of the result.  This means that the
1070   // byte needs to be shifted until it lands in the right byte bucket.  The
1071   // shift amount depends on the position: if the byte is coming from the high
1072   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1073   // low part, it must be shifted left.
1074   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1075   if (InputByteNo < ByteValues.size()/2) {
1076     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1077       return true;
1078   } else {
1079     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1080       return true;
1081   }
1082   
1083   // If the destination byte value is already defined, the values are or'd
1084   // together, which isn't a bswap (unless it's an or of the same bits).
1085   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1086     return true;
1087   ByteValues[DestByteNo] = V;
1088   return false;
1089 }
1090
1091 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1092 /// If so, insert the new bswap intrinsic and return it.
1093 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1094   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1095   if (!ITy || ITy->getBitWidth() % 16 || 
1096       // ByteMask only allows up to 32-byte values.
1097       ITy->getBitWidth() > 32*8) 
1098     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1099   
1100   /// ByteValues - For each byte of the result, we keep track of which value
1101   /// defines each byte.
1102   SmallVector<Value*, 8> ByteValues;
1103   ByteValues.resize(ITy->getBitWidth()/8);
1104     
1105   // Try to find all the pieces corresponding to the bswap.
1106   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1107   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1108     return 0;
1109   
1110   // Check to see if all of the bytes come from the same value.
1111   Value *V = ByteValues[0];
1112   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1113   
1114   // Check to make sure that all of the bytes come from the same value.
1115   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1116     if (ByteValues[i] != V)
1117       return 0;
1118   const Type *Tys[] = { ITy };
1119   Module *M = I.getParent()->getParent()->getParent();
1120   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1121   return CallInst::Create(F, V);
1122 }
1123
1124 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1125 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1126 /// we can simplify this expression to "cond ? C : D or B".
1127 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1128                                          Value *C, Value *D) {
1129   // If A is not a select of -1/0, this cannot match.
1130   Value *Cond = 0;
1131   if (!match(A, m_SExt(m_Value(Cond))) ||
1132       !Cond->getType()->isIntegerTy(1))
1133     return 0;
1134
1135   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1136   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1137     return SelectInst::Create(Cond, C, B);
1138   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1139     return SelectInst::Create(Cond, C, B);
1140   
1141   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1142   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1143     return SelectInst::Create(Cond, C, D);
1144   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1145     return SelectInst::Create(Cond, C, D);
1146   return 0;
1147 }
1148
1149 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1150 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1151   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1152
1153   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1154   if (PredicatesFoldable(LHSCC, RHSCC)) {
1155     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1156         LHS->getOperand(1) == RHS->getOperand(0))
1157       LHS->swapOperands();
1158     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1159         LHS->getOperand(1) == RHS->getOperand(1)) {
1160       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1161       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1162       bool isSigned = LHS->isSigned() || RHS->isSigned();
1163       return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1164     }
1165   }
1166   
1167   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1168   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1169   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1170   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1171   if (LHSCst == 0 || RHSCst == 0) return 0;
1172
1173   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1174   if (LHSCst == RHSCst && LHSCC == RHSCC &&
1175       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1176     Value *NewOr = Builder->CreateOr(Val, Val2);
1177     return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1178   }
1179   
1180   // (icmp eq (A & C1), 0) | (icmp eq (A & C2), 0) -->
1181   // (icmp ne (A & (C1|C2)), (C1|C2))
1182   if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1183     Instruction *I1 = dyn_cast<Instruction>(Val);
1184     Instruction *I2 = dyn_cast<Instruction>(Val2);
1185     if (I1 && I1->getOpcode() == Instruction::And &&
1186         I2 && I2->getOpcode() == Instruction::And &&
1187         I1->getOperand(0) == I1->getOperand(0)) {
1188       ConstantInt *CI1 = dyn_cast<ConstantInt>(I1->getOperand(1));
1189       ConstantInt *CI2 = dyn_cast<ConstantInt>(I2->getOperand(1));
1190       if (CI1 && !CI1->isZero() && CI2 && !CI2->isZero() &&
1191           CI1->getValue().operator&(CI2->getValue()) == 0) {
1192         Constant *ConstOr = ConstantExpr::getOr(CI1, CI2);
1193         Value *NewAnd = Builder->CreateAnd(I1->getOperand(0), ConstOr);
1194         return Builder->CreateICmp(ICmpInst::ICMP_NE, NewAnd, ConstOr);
1195       }
1196     }
1197   }
1198   
1199   // From here on, we only handle:
1200   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1201   if (Val != Val2) return 0;
1202   
1203   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1204   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1205       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1206       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1207       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1208     return 0;
1209   
1210   // We can't fold (ugt x, C) | (sgt x, C2).
1211   if (!PredicatesFoldable(LHSCC, RHSCC))
1212     return 0;
1213   
1214   // Ensure that the larger constant is on the RHS.
1215   bool ShouldSwap;
1216   if (CmpInst::isSigned(LHSCC) ||
1217       (ICmpInst::isEquality(LHSCC) && 
1218        CmpInst::isSigned(RHSCC)))
1219     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1220   else
1221     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1222   
1223   if (ShouldSwap) {
1224     std::swap(LHS, RHS);
1225     std::swap(LHSCst, RHSCst);
1226     std::swap(LHSCC, RHSCC);
1227   }
1228   
1229   // At this point, we know we have two icmp instructions
1230   // comparing a value against two constants and or'ing the result
1231   // together.  Because of the above check, we know that we only have
1232   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1233   // icmp folding check above), that the two constants are not
1234   // equal.
1235   assert(LHSCst != RHSCst && "Compares not folded above?");
1236
1237   switch (LHSCC) {
1238   default: llvm_unreachable("Unknown integer condition code!");
1239   case ICmpInst::ICMP_EQ:
1240     switch (RHSCC) {
1241     default: llvm_unreachable("Unknown integer condition code!");
1242     case ICmpInst::ICMP_EQ:
1243       if (LHSCst == SubOne(RHSCst)) {
1244         // (X == 13 | X == 14) -> X-13 <u 2
1245         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1246         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1247         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1248         return Builder->CreateICmpULT(Add, AddCST);
1249       }
1250       break;                         // (X == 13 | X == 15) -> no change
1251     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1252     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1253       break;
1254     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1255     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1256     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1257       return RHS;
1258     }
1259     break;
1260   case ICmpInst::ICMP_NE:
1261     switch (RHSCC) {
1262     default: llvm_unreachable("Unknown integer condition code!");
1263     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1264     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1265     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1266       return LHS;
1267     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1268     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1269     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1270       return ConstantInt::getTrue(LHS->getContext());
1271     }
1272     break;
1273   case ICmpInst::ICMP_ULT:
1274     switch (RHSCC) {
1275     default: llvm_unreachable("Unknown integer condition code!");
1276     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1277       break;
1278     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1279       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1280       // this can cause overflow.
1281       if (RHSCst->isMaxValue(false))
1282         return LHS;
1283       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1284     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1285       break;
1286     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1287     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1288       return RHS;
1289     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1290       break;
1291     }
1292     break;
1293   case ICmpInst::ICMP_SLT:
1294     switch (RHSCC) {
1295     default: llvm_unreachable("Unknown integer condition code!");
1296     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1297       break;
1298     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1299       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1300       // this can cause overflow.
1301       if (RHSCst->isMaxValue(true))
1302         return LHS;
1303       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1304     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1305       break;
1306     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1307     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1308       return RHS;
1309     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1310       break;
1311     }
1312     break;
1313   case ICmpInst::ICMP_UGT:
1314     switch (RHSCC) {
1315     default: llvm_unreachable("Unknown integer condition code!");
1316     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1317     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1318       return LHS;
1319     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1320       break;
1321     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1322     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1323       return ConstantInt::getTrue(LHS->getContext());
1324     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1325       break;
1326     }
1327     break;
1328   case ICmpInst::ICMP_SGT:
1329     switch (RHSCC) {
1330     default: llvm_unreachable("Unknown integer condition code!");
1331     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1332     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1333       return LHS;
1334     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1335       break;
1336     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1337     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1338       return ConstantInt::getTrue(LHS->getContext());
1339     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1340       break;
1341     }
1342     break;
1343   }
1344   return 0;
1345 }
1346
1347 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1348 /// instcombine, this returns a Value which should already be inserted into the
1349 /// function.
1350 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1351   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1352       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
1353       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1354     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1355       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1356         // If either of the constants are nans, then the whole thing returns
1357         // true.
1358         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1359           return ConstantInt::getTrue(LHS->getContext());
1360         
1361         // Otherwise, no need to compare the two constants, compare the
1362         // rest.
1363         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1364       }
1365     
1366     // Handle vector zeros.  This occurs because the canonical form of
1367     // "fcmp uno x,x" is "fcmp uno x, 0".
1368     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1369         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1370       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1371     
1372     return 0;
1373   }
1374   
1375   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1376   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1377   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1378   
1379   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1380     // Swap RHS operands to match LHS.
1381     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1382     std::swap(Op1LHS, Op1RHS);
1383   }
1384   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1385     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1386     if (Op0CC == Op1CC)
1387       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1388     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1389       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1390     if (Op0CC == FCmpInst::FCMP_FALSE)
1391       return RHS;
1392     if (Op1CC == FCmpInst::FCMP_FALSE)
1393       return LHS;
1394     bool Op0Ordered;
1395     bool Op1Ordered;
1396     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1397     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1398     if (Op0Ordered == Op1Ordered) {
1399       // If both are ordered or unordered, return a new fcmp with
1400       // or'ed predicates.
1401       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1402     }
1403   }
1404   return 0;
1405 }
1406
1407 /// FoldOrWithConstants - This helper function folds:
1408 ///
1409 ///     ((A | B) & C1) | (B & C2)
1410 ///
1411 /// into:
1412 /// 
1413 ///     (A & C1) | B
1414 ///
1415 /// when the XOR of the two constants is "all ones" (-1).
1416 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1417                                                Value *A, Value *B, Value *C) {
1418   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1419   if (!CI1) return 0;
1420
1421   Value *V1 = 0;
1422   ConstantInt *CI2 = 0;
1423   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1424
1425   APInt Xor = CI1->getValue() ^ CI2->getValue();
1426   if (!Xor.isAllOnesValue()) return 0;
1427
1428   if (V1 == A || V1 == B) {
1429     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1430     return BinaryOperator::CreateOr(NewOp, V1);
1431   }
1432
1433   return 0;
1434 }
1435
1436 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1437   bool Changed = SimplifyCommutative(I);
1438   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1439
1440   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1441     return ReplaceInstUsesWith(I, V);
1442
1443   // See if we can simplify any instructions used by the instruction whose sole 
1444   // purpose is to compute bits we don't care about.
1445   if (SimplifyDemandedInstructionBits(I))
1446     return &I;
1447
1448   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1449     ConstantInt *C1 = 0; Value *X = 0;
1450     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1451     // iff (C1 & C2) == 0.
1452     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1453         (RHS->getValue() & C1->getValue()) != 0 &&
1454         Op0->hasOneUse()) {
1455       Value *Or = Builder->CreateOr(X, RHS);
1456       Or->takeName(Op0);
1457       return BinaryOperator::CreateAnd(Or, 
1458                          ConstantInt::get(I.getContext(),
1459                                           RHS->getValue() | C1->getValue()));
1460     }
1461
1462     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1463     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1464         Op0->hasOneUse()) {
1465       Value *Or = Builder->CreateOr(X, RHS);
1466       Or->takeName(Op0);
1467       return BinaryOperator::CreateXor(Or,
1468                  ConstantInt::get(I.getContext(),
1469                                   C1->getValue() & ~RHS->getValue()));
1470     }
1471
1472     // Try to fold constant and into select arguments.
1473     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1474       if (Instruction *R = FoldOpIntoSelect(I, SI))
1475         return R;
1476
1477     if (isa<PHINode>(Op0))
1478       if (Instruction *NV = FoldOpIntoPhi(I))
1479         return NV;
1480   }
1481
1482   Value *A = 0, *B = 0;
1483   ConstantInt *C1 = 0, *C2 = 0;
1484
1485   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1486   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1487   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1488       match(Op1, m_Or(m_Value(), m_Value())) ||
1489       (match(Op0, m_Shift(m_Value(), m_Value())) &&
1490        match(Op1, m_Shift(m_Value(), m_Value())))) {
1491     if (Instruction *BSwap = MatchBSwap(I))
1492       return BSwap;
1493   }
1494   
1495   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1496   if (Op0->hasOneUse() &&
1497       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1498       MaskedValueIsZero(Op1, C1->getValue())) {
1499     Value *NOr = Builder->CreateOr(A, Op1);
1500     NOr->takeName(Op0);
1501     return BinaryOperator::CreateXor(NOr, C1);
1502   }
1503
1504   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1505   if (Op1->hasOneUse() &&
1506       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1507       MaskedValueIsZero(Op0, C1->getValue())) {
1508     Value *NOr = Builder->CreateOr(A, Op0);
1509     NOr->takeName(Op0);
1510     return BinaryOperator::CreateXor(NOr, C1);
1511   }
1512
1513   // (A & C)|(B & D)
1514   Value *C = 0, *D = 0;
1515   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1516       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1517     Value *V1 = 0, *V2 = 0, *V3 = 0;
1518     C1 = dyn_cast<ConstantInt>(C);
1519     C2 = dyn_cast<ConstantInt>(D);
1520     if (C1 && C2) {  // (A & C1)|(B & C2)
1521       // If we have: ((V + N) & C1) | (V & C2)
1522       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1523       // replace with V+N.
1524       if (C1->getValue() == ~C2->getValue()) {
1525         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1526             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1527           // Add commutes, try both ways.
1528           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1529             return ReplaceInstUsesWith(I, A);
1530           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1531             return ReplaceInstUsesWith(I, A);
1532         }
1533         // Or commutes, try both ways.
1534         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1535             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1536           // Add commutes, try both ways.
1537           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1538             return ReplaceInstUsesWith(I, B);
1539           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1540             return ReplaceInstUsesWith(I, B);
1541         }
1542       }
1543       
1544       if ((C1->getValue() & C2->getValue()) == 0) {
1545         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1546         // iff (C1&C2) == 0 and (N&~C1) == 0
1547         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1548             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1549              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1550           return BinaryOperator::CreateAnd(A,
1551                                ConstantInt::get(A->getContext(),
1552                                                 C1->getValue()|C2->getValue()));
1553         // Or commutes, try both ways.
1554         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1555             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1556              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1557           return BinaryOperator::CreateAnd(B,
1558                                ConstantInt::get(B->getContext(),
1559                                                 C1->getValue()|C2->getValue()));
1560         
1561         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1562         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1563         ConstantInt *C3 = 0, *C4 = 0;
1564         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1565             (C3->getValue() & ~C1->getValue()) == 0 &&
1566             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1567             (C4->getValue() & ~C2->getValue()) == 0) {
1568           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1569           return BinaryOperator::CreateAnd(V2,
1570                                ConstantInt::get(B->getContext(),
1571                                                 C1->getValue()|C2->getValue()));
1572         }
1573       }
1574     }
1575     
1576     // Check to see if we have any common things being and'ed.  If so, find the
1577     // terms for V1 & (V2|V3).
1578     if (Op0->hasOneUse() || Op1->hasOneUse()) {
1579       V1 = 0;
1580       if (A == B)      // (A & C)|(A & D) == A & (C|D)
1581         V1 = A, V2 = C, V3 = D;
1582       else if (A == D) // (A & C)|(B & A) == A & (B|C)
1583         V1 = A, V2 = B, V3 = C;
1584       else if (C == B) // (A & C)|(C & D) == C & (A|D)
1585         V1 = C, V2 = A, V3 = D;
1586       else if (C == D) // (A & C)|(B & C) == C & (A|B)
1587         V1 = C, V2 = A, V3 = B;
1588       
1589       if (V1) {
1590         Value *Or = Builder->CreateOr(V2, V3, "tmp");
1591         return BinaryOperator::CreateAnd(V1, Or);
1592       }
1593     }
1594
1595     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
1596     // Don't do this for vector select idioms, the code generator doesn't handle
1597     // them well yet.
1598     if (!I.getType()->isVectorTy()) {
1599       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1600         return Match;
1601       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1602         return Match;
1603       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1604         return Match;
1605       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1606         return Match;
1607     }
1608
1609     // ((A&~B)|(~A&B)) -> A^B
1610     if ((match(C, m_Not(m_Specific(D))) &&
1611          match(B, m_Not(m_Specific(A)))))
1612       return BinaryOperator::CreateXor(A, D);
1613     // ((~B&A)|(~A&B)) -> A^B
1614     if ((match(A, m_Not(m_Specific(D))) &&
1615          match(B, m_Not(m_Specific(C)))))
1616       return BinaryOperator::CreateXor(C, D);
1617     // ((A&~B)|(B&~A)) -> A^B
1618     if ((match(C, m_Not(m_Specific(B))) &&
1619          match(D, m_Not(m_Specific(A)))))
1620       return BinaryOperator::CreateXor(A, B);
1621     // ((~B&A)|(B&~A)) -> A^B
1622     if ((match(A, m_Not(m_Specific(B))) &&
1623          match(D, m_Not(m_Specific(C)))))
1624       return BinaryOperator::CreateXor(C, B);
1625
1626     // ((A|B)&1)|(B&-2) -> (A&1) | B
1627     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1628         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1629       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1630       if (Ret) return Ret;
1631     }
1632     // (B&-2)|((A|B)&1) -> (A&1) | B
1633     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1634         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1635       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1636       if (Ret) return Ret;
1637     }
1638   }
1639   
1640   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1641   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1642     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1643       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1644           SI0->getOperand(1) == SI1->getOperand(1) &&
1645           (SI0->hasOneUse() || SI1->hasOneUse())) {
1646         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1647                                          SI0->getName());
1648         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1649                                       SI1->getOperand(1));
1650       }
1651   }
1652
1653   // (~A | ~B) == (~(A & B)) - De Morgan's Law
1654   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1655     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1656       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1657         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1658                                         I.getName()+".demorgan");
1659         return BinaryOperator::CreateNot(And);
1660       }
1661
1662   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1663     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1664       if (Value *Res = FoldOrOfICmps(LHS, RHS))
1665         return ReplaceInstUsesWith(I, Res);
1666     
1667   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
1668   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1669     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1670       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1671         return ReplaceInstUsesWith(I, Res);
1672   
1673   // fold (or (cast A), (cast B)) -> (cast (or A, B))
1674   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1675     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1676       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1677         const Type *SrcTy = Op0C->getOperand(0)->getType();
1678         if (SrcTy == Op1C->getOperand(0)->getType() &&
1679             SrcTy->isIntOrIntVectorTy()) {
1680           Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1681
1682           if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1683               // Only do this if the casts both really cause code to be
1684               // generated.
1685               ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1686               ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1687             Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1688             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1689           }
1690           
1691           // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1692           // cast is otherwise not optimizable.  This happens for vector sexts.
1693           if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1694             if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1695               if (Value *Res = FoldOrOfICmps(LHS, RHS))
1696                 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1697           
1698           // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1699           // cast is otherwise not optimizable.  This happens for vector sexts.
1700           if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1701             if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1702               if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1703                 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1704         }
1705       }
1706   }
1707   
1708   return Changed ? &I : 0;
1709 }
1710
1711 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1712   bool Changed = SimplifyCommutative(I);
1713   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1714
1715   if (isa<UndefValue>(Op1)) {
1716     if (isa<UndefValue>(Op0))
1717       // Handle undef ^ undef -> 0 special case. This is a common
1718       // idiom (misuse).
1719       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1720     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
1721   }
1722
1723   // xor X, X = 0
1724   if (Op0 == Op1)
1725     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1726   
1727   // See if we can simplify any instructions used by the instruction whose sole 
1728   // purpose is to compute bits we don't care about.
1729   if (SimplifyDemandedInstructionBits(I))
1730     return &I;
1731   if (I.getType()->isVectorTy())
1732     if (isa<ConstantAggregateZero>(Op1))
1733       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
1734
1735   // Is this a ~ operation?
1736   if (Value *NotOp = dyn_castNotVal(&I)) {
1737     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1738       if (Op0I->getOpcode() == Instruction::And || 
1739           Op0I->getOpcode() == Instruction::Or) {
1740         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1741         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1742         if (dyn_castNotVal(Op0I->getOperand(1)))
1743           Op0I->swapOperands();
1744         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1745           Value *NotY =
1746             Builder->CreateNot(Op0I->getOperand(1),
1747                                Op0I->getOperand(1)->getName()+".not");
1748           if (Op0I->getOpcode() == Instruction::And)
1749             return BinaryOperator::CreateOr(Op0NotVal, NotY);
1750           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1751         }
1752         
1753         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1754         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1755         if (isFreeToInvert(Op0I->getOperand(0)) && 
1756             isFreeToInvert(Op0I->getOperand(1))) {
1757           Value *NotX =
1758             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1759           Value *NotY =
1760             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1761           if (Op0I->getOpcode() == Instruction::And)
1762             return BinaryOperator::CreateOr(NotX, NotY);
1763           return BinaryOperator::CreateAnd(NotX, NotY);
1764         }
1765
1766       } else if (Op0I->getOpcode() == Instruction::AShr) {
1767         // ~(~X >>s Y) --> (X >>s Y)
1768         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1769           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
1770       }
1771     }
1772   }
1773   
1774   
1775   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1776     if (RHS->isOne() && Op0->hasOneUse())
1777       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
1778       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
1779         return CmpInst::Create(CI->getOpcode(),
1780                                CI->getInversePredicate(),
1781                                CI->getOperand(0), CI->getOperand(1));
1782
1783     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1784     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1785       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1786         if (CI->hasOneUse() && Op0C->hasOneUse()) {
1787           Instruction::CastOps Opcode = Op0C->getOpcode();
1788           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1789               (RHS == ConstantExpr::getCast(Opcode, 
1790                                            ConstantInt::getTrue(I.getContext()),
1791                                             Op0C->getDestTy()))) {
1792             CI->setPredicate(CI->getInversePredicate());
1793             return CastInst::Create(Opcode, CI, Op0C->getType());
1794           }
1795         }
1796       }
1797     }
1798
1799     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1800       // ~(c-X) == X-c-1 == X+(-c-1)
1801       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1802         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1803           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1804           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1805                                       ConstantInt::get(I.getType(), 1));
1806           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1807         }
1808           
1809       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1810         if (Op0I->getOpcode() == Instruction::Add) {
1811           // ~(X-c) --> (-c-1)-X
1812           if (RHS->isAllOnesValue()) {
1813             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1814             return BinaryOperator::CreateSub(
1815                            ConstantExpr::getSub(NegOp0CI,
1816                                       ConstantInt::get(I.getType(), 1)),
1817                                       Op0I->getOperand(0));
1818           } else if (RHS->getValue().isSignBit()) {
1819             // (X + C) ^ signbit -> (X + C + signbit)
1820             Constant *C = ConstantInt::get(I.getContext(),
1821                                            RHS->getValue() + Op0CI->getValue());
1822             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1823
1824           }
1825         } else if (Op0I->getOpcode() == Instruction::Or) {
1826           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1827           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1828             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1829             // Anything in both C1 and C2 is known to be zero, remove it from
1830             // NewRHS.
1831             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1832             NewRHS = ConstantExpr::getAnd(NewRHS, 
1833                                        ConstantExpr::getNot(CommonBits));
1834             Worklist.Add(Op0I);
1835             I.setOperand(0, Op0I->getOperand(0));
1836             I.setOperand(1, NewRHS);
1837             return &I;
1838           }
1839         }
1840       }
1841     }
1842
1843     // Try to fold constant and into select arguments.
1844     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1845       if (Instruction *R = FoldOpIntoSelect(I, SI))
1846         return R;
1847     if (isa<PHINode>(Op0))
1848       if (Instruction *NV = FoldOpIntoPhi(I))
1849         return NV;
1850   }
1851
1852   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1853     if (X == Op1)
1854       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1855
1856   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1857     if (X == Op0)
1858       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1859
1860   
1861   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1862   if (Op1I) {
1863     Value *A, *B;
1864     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1865       if (A == Op0) {              // B^(B|A) == (A|B)^B
1866         Op1I->swapOperands();
1867         I.swapOperands();
1868         std::swap(Op0, Op1);
1869       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
1870         I.swapOperands();     // Simplified below.
1871         std::swap(Op0, Op1);
1872       }
1873     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1874       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
1875     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1876       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
1877     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
1878                Op1I->hasOneUse()){
1879       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
1880         Op1I->swapOperands();
1881         std::swap(A, B);
1882       }
1883       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
1884         I.swapOperands();     // Simplified below.
1885         std::swap(Op0, Op1);
1886       }
1887     }
1888   }
1889   
1890   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1891   if (Op0I) {
1892     Value *A, *B;
1893     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1894         Op0I->hasOneUse()) {
1895       if (A == Op1)                                  // (B|A)^B == (A|B)^B
1896         std::swap(A, B);
1897       if (B == Op1)                                  // (A|B)^B == A & ~B
1898         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1899     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1900       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
1901     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1902       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
1903     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
1904                Op0I->hasOneUse()){
1905       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
1906         std::swap(A, B);
1907       if (B == Op1 &&                                      // (B&A)^A == ~B & A
1908           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
1909         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1910       }
1911     }
1912   }
1913   
1914   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
1915   if (Op0I && Op1I && Op0I->isShift() && 
1916       Op0I->getOpcode() == Op1I->getOpcode() && 
1917       Op0I->getOperand(1) == Op1I->getOperand(1) &&
1918       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
1919     Value *NewOp =
1920       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1921                          Op0I->getName());
1922     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
1923                                   Op1I->getOperand(1));
1924   }
1925     
1926   if (Op0I && Op1I) {
1927     Value *A, *B, *C, *D;
1928     // (A & B)^(A | B) -> A ^ B
1929     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1930         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1931       if ((A == C && B == D) || (A == D && B == C)) 
1932         return BinaryOperator::CreateXor(A, B);
1933     }
1934     // (A | B)^(A & B) -> A ^ B
1935     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1936         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1937       if ((A == C && B == D) || (A == D && B == C)) 
1938         return BinaryOperator::CreateXor(A, B);
1939     }
1940     
1941     // (A & B)^(C & D)
1942     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1943         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1944         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1945       // (X & Y)^(X & Y) -> (Y^Z) & X
1946       Value *X = 0, *Y = 0, *Z = 0;
1947       if (A == C)
1948         X = A, Y = B, Z = D;
1949       else if (A == D)
1950         X = A, Y = B, Z = C;
1951       else if (B == C)
1952         X = B, Y = A, Z = D;
1953       else if (B == D)
1954         X = B, Y = A, Z = C;
1955       
1956       if (X) {
1957         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1958         return BinaryOperator::CreateAnd(NewOp, X);
1959       }
1960     }
1961   }
1962     
1963   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1964   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1965     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1966       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1967         if (LHS->getOperand(0) == RHS->getOperand(1) &&
1968             LHS->getOperand(1) == RHS->getOperand(0))
1969           LHS->swapOperands();
1970         if (LHS->getOperand(0) == RHS->getOperand(0) &&
1971             LHS->getOperand(1) == RHS->getOperand(1)) {
1972           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1973           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1974           bool isSigned = LHS->isSigned() || RHS->isSigned();
1975           return ReplaceInstUsesWith(I, 
1976                                getICmpValue(isSigned, Code, Op0, Op1, Builder));
1977         }
1978       }
1979
1980   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1981   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1982     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1983       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1984         const Type *SrcTy = Op0C->getOperand(0)->getType();
1985         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
1986             // Only do this if the casts both really cause code to be generated.
1987             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0), 
1988                                I.getType()) &&
1989             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0), 
1990                                I.getType())) {
1991           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1992                                             Op1C->getOperand(0), I.getName());
1993           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1994         }
1995       }
1996   }
1997
1998   return Changed ? &I : 0;
1999 }