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