Another attempt at getting the clang self-host to like my instcombine patch.
[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)) where C1 and C2 are non-zero POT
478     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
479       Value *Op1 = 0, *Op2 = 0;
480       ConstantInt *CI1 = 0, *CI2 = 0;
481       if (match(LHS->getOperand(0), m_And(m_Value(Op1), m_ConstantInt(CI1))) &&
482           match(RHS->getOperand(0), m_And(m_Value(Op2), m_ConstantInt(CI2)))) {
483         if (Op1 == Op2 && !CI1->isZero() && !CI2->isZero() &&
484             CI1->getValue().isPowerOf2() && CI2->getValue().isPowerOf2()) {
485           Constant *ConstOr = ConstantExpr::getOr(CI1, CI2);
486           Value *NewAnd = Builder->CreateAnd(Op1, ConstOr);
487           return Builder->CreateICmp(ICmpInst::ICMP_EQ, NewAnd, ConstOr);
488         }
489       }
490     }
491   }
492   
493   // From here on, we only handle:
494   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
495   if (Val != Val2) return 0;
496   
497   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
498   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
499       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
500       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
501       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
502     return 0;
503   
504   // We can't fold (ugt x, C) & (sgt x, C2).
505   if (!PredicatesFoldable(LHSCC, RHSCC))
506     return 0;
507     
508   // Ensure that the larger constant is on the RHS.
509   bool ShouldSwap;
510   if (CmpInst::isSigned(LHSCC) ||
511       (ICmpInst::isEquality(LHSCC) && 
512        CmpInst::isSigned(RHSCC)))
513     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
514   else
515     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
516     
517   if (ShouldSwap) {
518     std::swap(LHS, RHS);
519     std::swap(LHSCst, RHSCst);
520     std::swap(LHSCC, RHSCC);
521   }
522
523   // At this point, we know we have two icmp instructions
524   // comparing a value against two constants and and'ing the result
525   // together.  Because of the above check, we know that we only have
526   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
527   // (from the icmp folding check above), that the two constants 
528   // are not equal and that the larger constant is on the RHS
529   assert(LHSCst != RHSCst && "Compares not folded above?");
530
531   switch (LHSCC) {
532   default: llvm_unreachable("Unknown integer condition code!");
533   case ICmpInst::ICMP_EQ:
534     switch (RHSCC) {
535     default: llvm_unreachable("Unknown integer condition code!");
536     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
537     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
538     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
539       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
540     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
541     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
542     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
543       return LHS;
544     }
545   case ICmpInst::ICMP_NE:
546     switch (RHSCC) {
547     default: llvm_unreachable("Unknown integer condition code!");
548     case ICmpInst::ICMP_ULT:
549       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
550         return Builder->CreateICmpULT(Val, LHSCst);
551       break;                        // (X != 13 & X u< 15) -> no change
552     case ICmpInst::ICMP_SLT:
553       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
554         return Builder->CreateICmpSLT(Val, LHSCst);
555       break;                        // (X != 13 & X s< 15) -> no change
556     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
557     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
558     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
559       return RHS;
560     case ICmpInst::ICMP_NE:
561       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
562         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
563         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
564         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
565       }
566       break;                        // (X != 13 & X != 15) -> no change
567     }
568     break;
569   case ICmpInst::ICMP_ULT:
570     switch (RHSCC) {
571     default: llvm_unreachable("Unknown integer condition code!");
572     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
573     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
574       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
575     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
576       break;
577     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
578     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
579       return LHS;
580     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
581       break;
582     }
583     break;
584   case ICmpInst::ICMP_SLT:
585     switch (RHSCC) {
586     default: llvm_unreachable("Unknown integer condition code!");
587     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
588     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
589       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
590     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
591       break;
592     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
593     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
594       return LHS;
595     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
596       break;
597     }
598     break;
599   case ICmpInst::ICMP_UGT:
600     switch (RHSCC) {
601     default: llvm_unreachable("Unknown integer condition code!");
602     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
603     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
604       return RHS;
605     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
606       break;
607     case ICmpInst::ICMP_NE:
608       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
609         return Builder->CreateICmp(LHSCC, Val, RHSCst);
610       break;                        // (X u> 13 & X != 15) -> no change
611     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
612       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
613     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
614       break;
615     }
616     break;
617   case ICmpInst::ICMP_SGT:
618     switch (RHSCC) {
619     default: llvm_unreachable("Unknown integer condition code!");
620     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
621     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
622       return RHS;
623     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
624       break;
625     case ICmpInst::ICMP_NE:
626       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
627         return Builder->CreateICmp(LHSCC, Val, RHSCst);
628       break;                        // (X s> 13 & X != 15) -> no change
629     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
630       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
631     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
632       break;
633     }
634     break;
635   }
636  
637   return 0;
638 }
639
640 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
641 /// instcombine, this returns a Value which should already be inserted into the
642 /// function.
643 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
644   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
645       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
646     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
647     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
648       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
649         // If either of the constants are nans, then the whole thing returns
650         // false.
651         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
652           return ConstantInt::getFalse(LHS->getContext());
653         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
654       }
655     
656     // Handle vector zeros.  This occurs because the canonical form of
657     // "fcmp ord x,x" is "fcmp ord x, 0".
658     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
659         isa<ConstantAggregateZero>(RHS->getOperand(1)))
660       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
661     return 0;
662   }
663   
664   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
665   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
666   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
667   
668   
669   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
670     // Swap RHS operands to match LHS.
671     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
672     std::swap(Op1LHS, Op1RHS);
673   }
674   
675   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
676     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
677     if (Op0CC == Op1CC)
678       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
679     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
680       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
681     if (Op0CC == FCmpInst::FCMP_TRUE)
682       return RHS;
683     if (Op1CC == FCmpInst::FCMP_TRUE)
684       return LHS;
685     
686     bool Op0Ordered;
687     bool Op1Ordered;
688     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
689     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
690     if (Op1Pred == 0) {
691       std::swap(LHS, RHS);
692       std::swap(Op0Pred, Op1Pred);
693       std::swap(Op0Ordered, Op1Ordered);
694     }
695     if (Op0Pred == 0) {
696       // uno && ueq -> uno && (uno || eq) -> ueq
697       // ord && olt -> ord && (ord && lt) -> olt
698       if (Op0Ordered == Op1Ordered)
699         return RHS;
700       
701       // uno && oeq -> uno && (ord && eq) -> false
702       // uno && ord -> false
703       if (!Op0Ordered)
704         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
705       // ord && ueq -> ord && (uno || eq) -> oeq
706       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
707     }
708   }
709
710   return 0;
711 }
712
713
714 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
715   bool Changed = SimplifyCommutative(I);
716   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
717
718   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
719     return ReplaceInstUsesWith(I, V);
720
721   // See if we can simplify any instructions used by the instruction whose sole 
722   // purpose is to compute bits we don't care about.
723   if (SimplifyDemandedInstructionBits(I))
724     return &I;  
725
726   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
727     const APInt &AndRHSMask = AndRHS->getValue();
728     APInt NotAndRHS(~AndRHSMask);
729
730     // Optimize a variety of ((val OP C1) & C2) combinations...
731     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
732       Value *Op0LHS = Op0I->getOperand(0);
733       Value *Op0RHS = Op0I->getOperand(1);
734       switch (Op0I->getOpcode()) {
735       default: break;
736       case Instruction::Xor:
737       case Instruction::Or:
738         // If the mask is only needed on one incoming arm, push it up.
739         if (!Op0I->hasOneUse()) break;
740           
741         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
742           // Not masking anything out for the LHS, move to RHS.
743           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
744                                              Op0RHS->getName()+".masked");
745           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
746         }
747         if (!isa<Constant>(Op0RHS) &&
748             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
749           // Not masking anything out for the RHS, move to LHS.
750           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
751                                              Op0LHS->getName()+".masked");
752           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
753         }
754
755         break;
756       case Instruction::Add:
757         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
758         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
759         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
760         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
761           return BinaryOperator::CreateAnd(V, AndRHS);
762         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
763           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
764         break;
765
766       case Instruction::Sub:
767         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
768         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
769         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
770         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
771           return BinaryOperator::CreateAnd(V, AndRHS);
772
773         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
774         // has 1's for all bits that the subtraction with A might affect.
775         if (Op0I->hasOneUse()) {
776           uint32_t BitWidth = AndRHSMask.getBitWidth();
777           uint32_t Zeros = AndRHSMask.countLeadingZeros();
778           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
779
780           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
781           if (!(A && A->isZero()) &&               // avoid infinite recursion.
782               MaskedValueIsZero(Op0LHS, Mask)) {
783             Value *NewNeg = Builder->CreateNeg(Op0RHS);
784             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
785           }
786         }
787         break;
788
789       case Instruction::Shl:
790       case Instruction::LShr:
791         // (1 << x) & 1 --> zext(x == 0)
792         // (1 >> x) & 1 --> zext(x == 0)
793         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
794           Value *NewICmp =
795             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
796           return new ZExtInst(NewICmp, I.getType());
797         }
798         break;
799       }
800
801       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
802         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
803           return Res;
804     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
805       // If this is an integer truncation or change from signed-to-unsigned, and
806       // if the source is an and/or with immediate, transform it.  This
807       // frequently occurs for bitfield accesses.
808       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
809         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
810             CastOp->getNumOperands() == 2)
811           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
812             if (CastOp->getOpcode() == Instruction::And) {
813               // Change: and (cast (and X, C1) to T), C2
814               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
815               // This will fold the two constants together, which may allow 
816               // other simplifications.
817               Value *NewCast = Builder->CreateTruncOrBitCast(
818                 CastOp->getOperand(0), I.getType(), 
819                 CastOp->getName()+".shrunk");
820               // trunc_or_bitcast(C1)&C2
821               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
822               C3 = ConstantExpr::getAnd(C3, AndRHS);
823               return BinaryOperator::CreateAnd(NewCast, C3);
824             } else if (CastOp->getOpcode() == Instruction::Or) {
825               // Change: and (cast (or X, C1) to T), C2
826               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
827               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
828               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
829                 // trunc(C1)&C2
830                 return ReplaceInstUsesWith(I, AndRHS);
831             }
832           }
833       }
834     }
835
836     // Try to fold constant and into select arguments.
837     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
838       if (Instruction *R = FoldOpIntoSelect(I, SI))
839         return R;
840     if (isa<PHINode>(Op0))
841       if (Instruction *NV = FoldOpIntoPhi(I))
842         return NV;
843   }
844
845
846   // (~A & ~B) == (~(A | B)) - De Morgan's Law
847   if (Value *Op0NotVal = dyn_castNotVal(Op0))
848     if (Value *Op1NotVal = dyn_castNotVal(Op1))
849       if (Op0->hasOneUse() && Op1->hasOneUse()) {
850         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
851                                       I.getName()+".demorgan");
852         return BinaryOperator::CreateNot(Or);
853       }
854
855   {
856     Value *A = 0, *B = 0, *C = 0, *D = 0;
857     // (A|B) & ~(A&B) -> A^B
858     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
859         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
860         ((A == C && B == D) || (A == D && B == C)))
861       return BinaryOperator::CreateXor(A, B);
862     
863     // ~(A&B) & (A|B) -> A^B
864     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
865         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
866         ((A == C && B == D) || (A == D && B == C)))
867       return BinaryOperator::CreateXor(A, B);
868     
869     if (Op0->hasOneUse() &&
870         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
871       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
872         I.swapOperands();     // Simplify below
873         std::swap(Op0, Op1);
874       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
875         cast<BinaryOperator>(Op0)->swapOperands();
876         I.swapOperands();     // Simplify below
877         std::swap(Op0, Op1);
878       }
879     }
880
881     if (Op1->hasOneUse() &&
882         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
883       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
884         cast<BinaryOperator>(Op1)->swapOperands();
885         std::swap(A, B);
886       }
887       if (A == Op0)                                // A&(A^B) -> A & ~B
888         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
889     }
890
891     // (A&((~A)|B)) -> A&B
892     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
893         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
894       return BinaryOperator::CreateAnd(A, Op1);
895     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
896         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
897       return BinaryOperator::CreateAnd(A, Op0);
898   }
899   
900   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
901     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
902       if (Value *Res = FoldAndOfICmps(LHS, RHS))
903         return ReplaceInstUsesWith(I, Res);
904   
905   // If and'ing two fcmp, try combine them into one.
906   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
907     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
908       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
909         return ReplaceInstUsesWith(I, Res);
910   
911   
912   // fold (and (cast A), (cast B)) -> (cast (and A, B))
913   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
914     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
915       const Type *SrcTy = Op0C->getOperand(0)->getType();
916       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
917           SrcTy == Op1C->getOperand(0)->getType() &&
918           SrcTy->isIntOrIntVectorTy()) {
919         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
920         
921         // Only do this if the casts both really cause code to be generated.
922         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
923             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
924           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
925           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
926         }
927         
928         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
929         // cast is otherwise not optimizable.  This happens for vector sexts.
930         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
931           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
932             if (Value *Res = FoldAndOfICmps(LHS, RHS))
933               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
934         
935         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
936         // cast is otherwise not optimizable.  This happens for vector sexts.
937         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
938           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
939             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
940               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
941       }
942     }
943     
944   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
945   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
946     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
947       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
948           SI0->getOperand(1) == SI1->getOperand(1) &&
949           (SI0->hasOneUse() || SI1->hasOneUse())) {
950         Value *NewOp =
951           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
952                              SI0->getName());
953         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
954                                       SI1->getOperand(1));
955       }
956   }
957
958   return Changed ? &I : 0;
959 }
960
961 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
962 /// capable of providing pieces of a bswap.  The subexpression provides pieces
963 /// of a bswap if it is proven that each of the non-zero bytes in the output of
964 /// the expression came from the corresponding "byte swapped" byte in some other
965 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
966 /// we know that the expression deposits the low byte of %X into the high byte
967 /// of the bswap result and that all other bytes are zero.  This expression is
968 /// accepted, the high byte of ByteValues is set to X to indicate a correct
969 /// match.
970 ///
971 /// This function returns true if the match was unsuccessful and false if so.
972 /// On entry to the function the "OverallLeftShift" is a signed integer value
973 /// indicating the number of bytes that the subexpression is later shifted.  For
974 /// example, if the expression is later right shifted by 16 bits, the
975 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
976 /// byte of ByteValues is actually being set.
977 ///
978 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
979 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
980 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
981 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
982 /// always in the local (OverallLeftShift) coordinate space.
983 ///
984 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
985                               SmallVector<Value*, 8> &ByteValues) {
986   if (Instruction *I = dyn_cast<Instruction>(V)) {
987     // If this is an or instruction, it may be an inner node of the bswap.
988     if (I->getOpcode() == Instruction::Or) {
989       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
990                                ByteValues) ||
991              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
992                                ByteValues);
993     }
994   
995     // If this is a logical shift by a constant multiple of 8, recurse with
996     // OverallLeftShift and ByteMask adjusted.
997     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
998       unsigned ShAmt = 
999         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1000       // Ensure the shift amount is defined and of a byte value.
1001       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1002         return true;
1003
1004       unsigned ByteShift = ShAmt >> 3;
1005       if (I->getOpcode() == Instruction::Shl) {
1006         // X << 2 -> collect(X, +2)
1007         OverallLeftShift += ByteShift;
1008         ByteMask >>= ByteShift;
1009       } else {
1010         // X >>u 2 -> collect(X, -2)
1011         OverallLeftShift -= ByteShift;
1012         ByteMask <<= ByteShift;
1013         ByteMask &= (~0U >> (32-ByteValues.size()));
1014       }
1015
1016       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1017       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1018
1019       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1020                                ByteValues);
1021     }
1022
1023     // If this is a logical 'and' with a mask that clears bytes, clear the
1024     // corresponding bytes in ByteMask.
1025     if (I->getOpcode() == Instruction::And &&
1026         isa<ConstantInt>(I->getOperand(1))) {
1027       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1028       unsigned NumBytes = ByteValues.size();
1029       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1030       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1031       
1032       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1033         // If this byte is masked out by a later operation, we don't care what
1034         // the and mask is.
1035         if ((ByteMask & (1 << i)) == 0)
1036           continue;
1037         
1038         // If the AndMask is all zeros for this byte, clear the bit.
1039         APInt MaskB = AndMask & Byte;
1040         if (MaskB == 0) {
1041           ByteMask &= ~(1U << i);
1042           continue;
1043         }
1044         
1045         // If the AndMask is not all ones for this byte, it's not a bytezap.
1046         if (MaskB != Byte)
1047           return true;
1048
1049         // Otherwise, this byte is kept.
1050       }
1051
1052       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1053                                ByteValues);
1054     }
1055   }
1056   
1057   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1058   // the input value to the bswap.  Some observations: 1) if more than one byte
1059   // is demanded from this input, then it could not be successfully assembled
1060   // into a byteswap.  At least one of the two bytes would not be aligned with
1061   // their ultimate destination.
1062   if (!isPowerOf2_32(ByteMask)) return true;
1063   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1064   
1065   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1066   // is demanded, it needs to go into byte 0 of the result.  This means that the
1067   // byte needs to be shifted until it lands in the right byte bucket.  The
1068   // shift amount depends on the position: if the byte is coming from the high
1069   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1070   // low part, it must be shifted left.
1071   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1072   if (InputByteNo < ByteValues.size()/2) {
1073     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1074       return true;
1075   } else {
1076     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1077       return true;
1078   }
1079   
1080   // If the destination byte value is already defined, the values are or'd
1081   // together, which isn't a bswap (unless it's an or of the same bits).
1082   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1083     return true;
1084   ByteValues[DestByteNo] = V;
1085   return false;
1086 }
1087
1088 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1089 /// If so, insert the new bswap intrinsic and return it.
1090 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1091   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1092   if (!ITy || ITy->getBitWidth() % 16 || 
1093       // ByteMask only allows up to 32-byte values.
1094       ITy->getBitWidth() > 32*8) 
1095     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1096   
1097   /// ByteValues - For each byte of the result, we keep track of which value
1098   /// defines each byte.
1099   SmallVector<Value*, 8> ByteValues;
1100   ByteValues.resize(ITy->getBitWidth()/8);
1101     
1102   // Try to find all the pieces corresponding to the bswap.
1103   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1104   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1105     return 0;
1106   
1107   // Check to see if all of the bytes come from the same value.
1108   Value *V = ByteValues[0];
1109   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1110   
1111   // Check to make sure that all of the bytes come from the same value.
1112   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1113     if (ByteValues[i] != V)
1114       return 0;
1115   const Type *Tys[] = { ITy };
1116   Module *M = I.getParent()->getParent()->getParent();
1117   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1118   return CallInst::Create(F, V);
1119 }
1120
1121 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1122 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1123 /// we can simplify this expression to "cond ? C : D or B".
1124 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1125                                          Value *C, Value *D) {
1126   // If A is not a select of -1/0, this cannot match.
1127   Value *Cond = 0;
1128   if (!match(A, m_SExt(m_Value(Cond))) ||
1129       !Cond->getType()->isIntegerTy(1))
1130     return 0;
1131
1132   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1133   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1134     return SelectInst::Create(Cond, C, B);
1135   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1136     return SelectInst::Create(Cond, C, B);
1137   
1138   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1139   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1140     return SelectInst::Create(Cond, C, D);
1141   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1142     return SelectInst::Create(Cond, C, D);
1143   return 0;
1144 }
1145
1146 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1147 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1148   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1149
1150   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1151   if (PredicatesFoldable(LHSCC, RHSCC)) {
1152     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1153         LHS->getOperand(1) == RHS->getOperand(0))
1154       LHS->swapOperands();
1155     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1156         LHS->getOperand(1) == RHS->getOperand(1)) {
1157       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1158       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1159       bool isSigned = LHS->isSigned() || RHS->isSigned();
1160       return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1161     }
1162   }
1163   
1164   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1165   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1166   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1167   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1168   if (LHSCst == 0 || RHSCst == 0) return 0;
1169
1170   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1171   if (LHSCst == RHSCst && LHSCC == RHSCC &&
1172       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1173     Value *NewOr = Builder->CreateOr(Val, Val2);
1174     return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1175   }
1176   
1177   // (icmp eq (A & C1), 0) | (icmp eq (A & C2), 0) -->
1178   // (icmp ne (A & (C1|C2)), (C1|C2)) where C1 and C2 are non-zero POT
1179   if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1180     Value *Op1 = 0, *Op2 = 0;
1181     ConstantInt *CI1 = 0, *CI2 = 0;
1182     if (match(LHS->getOperand(0), m_And(m_Value(Op1), m_ConstantInt(CI1))) &&
1183         match(RHS->getOperand(0), m_And(m_Value(Op2), m_ConstantInt(CI2)))) {
1184       if (Op1 == Op2 && !CI1->isZero() && !CI2->isZero() &&
1185           CI1->getValue().isPowerOf2() && CI2->getValue().isPowerOf2()) {
1186         Constant *ConstOr = ConstantExpr::getOr(CI1, CI2);
1187         Value *NewAnd = Builder->CreateAnd(Op1, ConstOr);
1188         return Builder->CreateICmp(ICmpInst::ICMP_NE, NewAnd, ConstOr);
1189       }
1190     }
1191   }
1192   
1193   // From here on, we only handle:
1194   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1195   if (Val != Val2) return 0;
1196   
1197   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1198   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1199       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1200       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1201       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1202     return 0;
1203   
1204   // We can't fold (ugt x, C) | (sgt x, C2).
1205   if (!PredicatesFoldable(LHSCC, RHSCC))
1206     return 0;
1207   
1208   // Ensure that the larger constant is on the RHS.
1209   bool ShouldSwap;
1210   if (CmpInst::isSigned(LHSCC) ||
1211       (ICmpInst::isEquality(LHSCC) && 
1212        CmpInst::isSigned(RHSCC)))
1213     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1214   else
1215     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1216   
1217   if (ShouldSwap) {
1218     std::swap(LHS, RHS);
1219     std::swap(LHSCst, RHSCst);
1220     std::swap(LHSCC, RHSCC);
1221   }
1222   
1223   // At this point, we know we have two icmp instructions
1224   // comparing a value against two constants and or'ing the result
1225   // together.  Because of the above check, we know that we only have
1226   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1227   // icmp folding check above), that the two constants are not
1228   // equal.
1229   assert(LHSCst != RHSCst && "Compares not folded above?");
1230
1231   switch (LHSCC) {
1232   default: llvm_unreachable("Unknown integer condition code!");
1233   case ICmpInst::ICMP_EQ:
1234     switch (RHSCC) {
1235     default: llvm_unreachable("Unknown integer condition code!");
1236     case ICmpInst::ICMP_EQ:
1237       if (LHSCst == SubOne(RHSCst)) {
1238         // (X == 13 | X == 14) -> X-13 <u 2
1239         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1240         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1241         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1242         return Builder->CreateICmpULT(Add, AddCST);
1243       }
1244       break;                         // (X == 13 | X == 15) -> no change
1245     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1246     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1247       break;
1248     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1249     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1250     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1251       return RHS;
1252     }
1253     break;
1254   case ICmpInst::ICMP_NE:
1255     switch (RHSCC) {
1256     default: llvm_unreachable("Unknown integer condition code!");
1257     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1258     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1259     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1260       return LHS;
1261     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1262     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1263     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1264       return ConstantInt::getTrue(LHS->getContext());
1265     }
1266     break;
1267   case ICmpInst::ICMP_ULT:
1268     switch (RHSCC) {
1269     default: llvm_unreachable("Unknown integer condition code!");
1270     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1271       break;
1272     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1273       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1274       // this can cause overflow.
1275       if (RHSCst->isMaxValue(false))
1276         return LHS;
1277       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1278     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1279       break;
1280     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1281     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1282       return RHS;
1283     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1284       break;
1285     }
1286     break;
1287   case ICmpInst::ICMP_SLT:
1288     switch (RHSCC) {
1289     default: llvm_unreachable("Unknown integer condition code!");
1290     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1291       break;
1292     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1293       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1294       // this can cause overflow.
1295       if (RHSCst->isMaxValue(true))
1296         return LHS;
1297       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1298     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1299       break;
1300     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1301     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1302       return RHS;
1303     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1304       break;
1305     }
1306     break;
1307   case ICmpInst::ICMP_UGT:
1308     switch (RHSCC) {
1309     default: llvm_unreachable("Unknown integer condition code!");
1310     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1311     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1312       return LHS;
1313     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1314       break;
1315     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1316     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1317       return ConstantInt::getTrue(LHS->getContext());
1318     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1319       break;
1320     }
1321     break;
1322   case ICmpInst::ICMP_SGT:
1323     switch (RHSCC) {
1324     default: llvm_unreachable("Unknown integer condition code!");
1325     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1326     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1327       return LHS;
1328     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1329       break;
1330     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1331     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1332       return ConstantInt::getTrue(LHS->getContext());
1333     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1334       break;
1335     }
1336     break;
1337   }
1338   return 0;
1339 }
1340
1341 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1342 /// instcombine, this returns a Value which should already be inserted into the
1343 /// function.
1344 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1345   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1346       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
1347       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1348     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1349       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1350         // If either of the constants are nans, then the whole thing returns
1351         // true.
1352         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1353           return ConstantInt::getTrue(LHS->getContext());
1354         
1355         // Otherwise, no need to compare the two constants, compare the
1356         // rest.
1357         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1358       }
1359     
1360     // Handle vector zeros.  This occurs because the canonical form of
1361     // "fcmp uno x,x" is "fcmp uno x, 0".
1362     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1363         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1364       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1365     
1366     return 0;
1367   }
1368   
1369   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1370   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1371   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1372   
1373   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1374     // Swap RHS operands to match LHS.
1375     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1376     std::swap(Op1LHS, Op1RHS);
1377   }
1378   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1379     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1380     if (Op0CC == Op1CC)
1381       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1382     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1383       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1384     if (Op0CC == FCmpInst::FCMP_FALSE)
1385       return RHS;
1386     if (Op1CC == FCmpInst::FCMP_FALSE)
1387       return LHS;
1388     bool Op0Ordered;
1389     bool Op1Ordered;
1390     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1391     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1392     if (Op0Ordered == Op1Ordered) {
1393       // If both are ordered or unordered, return a new fcmp with
1394       // or'ed predicates.
1395       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1396     }
1397   }
1398   return 0;
1399 }
1400
1401 /// FoldOrWithConstants - This helper function folds:
1402 ///
1403 ///     ((A | B) & C1) | (B & C2)
1404 ///
1405 /// into:
1406 /// 
1407 ///     (A & C1) | B
1408 ///
1409 /// when the XOR of the two constants is "all ones" (-1).
1410 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1411                                                Value *A, Value *B, Value *C) {
1412   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1413   if (!CI1) return 0;
1414
1415   Value *V1 = 0;
1416   ConstantInt *CI2 = 0;
1417   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1418
1419   APInt Xor = CI1->getValue() ^ CI2->getValue();
1420   if (!Xor.isAllOnesValue()) return 0;
1421
1422   if (V1 == A || V1 == B) {
1423     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1424     return BinaryOperator::CreateOr(NewOp, V1);
1425   }
1426
1427   return 0;
1428 }
1429
1430 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1431   bool Changed = SimplifyCommutative(I);
1432   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1433
1434   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1435     return ReplaceInstUsesWith(I, V);
1436
1437   // See if we can simplify any instructions used by the instruction whose sole 
1438   // purpose is to compute bits we don't care about.
1439   if (SimplifyDemandedInstructionBits(I))
1440     return &I;
1441
1442   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1443     ConstantInt *C1 = 0; Value *X = 0;
1444     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1445     // iff (C1 & C2) == 0.
1446     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1447         (RHS->getValue() & C1->getValue()) != 0 &&
1448         Op0->hasOneUse()) {
1449       Value *Or = Builder->CreateOr(X, RHS);
1450       Or->takeName(Op0);
1451       return BinaryOperator::CreateAnd(Or, 
1452                          ConstantInt::get(I.getContext(),
1453                                           RHS->getValue() | C1->getValue()));
1454     }
1455
1456     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1457     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1458         Op0->hasOneUse()) {
1459       Value *Or = Builder->CreateOr(X, RHS);
1460       Or->takeName(Op0);
1461       return BinaryOperator::CreateXor(Or,
1462                  ConstantInt::get(I.getContext(),
1463                                   C1->getValue() & ~RHS->getValue()));
1464     }
1465
1466     // Try to fold constant and into select arguments.
1467     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1468       if (Instruction *R = FoldOpIntoSelect(I, SI))
1469         return R;
1470
1471     if (isa<PHINode>(Op0))
1472       if (Instruction *NV = FoldOpIntoPhi(I))
1473         return NV;
1474   }
1475
1476   Value *A = 0, *B = 0;
1477   ConstantInt *C1 = 0, *C2 = 0;
1478
1479   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1480   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1481   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1482       match(Op1, m_Or(m_Value(), m_Value())) ||
1483       (match(Op0, m_Shift(m_Value(), m_Value())) &&
1484        match(Op1, m_Shift(m_Value(), m_Value())))) {
1485     if (Instruction *BSwap = MatchBSwap(I))
1486       return BSwap;
1487   }
1488   
1489   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1490   if (Op0->hasOneUse() &&
1491       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1492       MaskedValueIsZero(Op1, C1->getValue())) {
1493     Value *NOr = Builder->CreateOr(A, Op1);
1494     NOr->takeName(Op0);
1495     return BinaryOperator::CreateXor(NOr, C1);
1496   }
1497
1498   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1499   if (Op1->hasOneUse() &&
1500       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1501       MaskedValueIsZero(Op0, C1->getValue())) {
1502     Value *NOr = Builder->CreateOr(A, Op0);
1503     NOr->takeName(Op0);
1504     return BinaryOperator::CreateXor(NOr, C1);
1505   }
1506
1507   // (A & C)|(B & D)
1508   Value *C = 0, *D = 0;
1509   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1510       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1511     Value *V1 = 0, *V2 = 0, *V3 = 0;
1512     C1 = dyn_cast<ConstantInt>(C);
1513     C2 = dyn_cast<ConstantInt>(D);
1514     if (C1 && C2) {  // (A & C1)|(B & C2)
1515       // If we have: ((V + N) & C1) | (V & C2)
1516       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1517       // replace with V+N.
1518       if (C1->getValue() == ~C2->getValue()) {
1519         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1520             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1521           // Add commutes, try both ways.
1522           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1523             return ReplaceInstUsesWith(I, A);
1524           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1525             return ReplaceInstUsesWith(I, A);
1526         }
1527         // Or commutes, try both ways.
1528         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1529             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1530           // Add commutes, try both ways.
1531           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1532             return ReplaceInstUsesWith(I, B);
1533           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1534             return ReplaceInstUsesWith(I, B);
1535         }
1536       }
1537       
1538       if ((C1->getValue() & C2->getValue()) == 0) {
1539         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1540         // iff (C1&C2) == 0 and (N&~C1) == 0
1541         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1542             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1543              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1544           return BinaryOperator::CreateAnd(A,
1545                                ConstantInt::get(A->getContext(),
1546                                                 C1->getValue()|C2->getValue()));
1547         // Or commutes, try both ways.
1548         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1549             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1550              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1551           return BinaryOperator::CreateAnd(B,
1552                                ConstantInt::get(B->getContext(),
1553                                                 C1->getValue()|C2->getValue()));
1554         
1555         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1556         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1557         ConstantInt *C3 = 0, *C4 = 0;
1558         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1559             (C3->getValue() & ~C1->getValue()) == 0 &&
1560             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1561             (C4->getValue() & ~C2->getValue()) == 0) {
1562           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1563           return BinaryOperator::CreateAnd(V2,
1564                                ConstantInt::get(B->getContext(),
1565                                                 C1->getValue()|C2->getValue()));
1566         }
1567       }
1568     }
1569     
1570     // Check to see if we have any common things being and'ed.  If so, find the
1571     // terms for V1 & (V2|V3).
1572     if (Op0->hasOneUse() || Op1->hasOneUse()) {
1573       V1 = 0;
1574       if (A == B)      // (A & C)|(A & D) == A & (C|D)
1575         V1 = A, V2 = C, V3 = D;
1576       else if (A == D) // (A & C)|(B & A) == A & (B|C)
1577         V1 = A, V2 = B, V3 = C;
1578       else if (C == B) // (A & C)|(C & D) == C & (A|D)
1579         V1 = C, V2 = A, V3 = D;
1580       else if (C == D) // (A & C)|(B & C) == C & (A|B)
1581         V1 = C, V2 = A, V3 = B;
1582       
1583       if (V1) {
1584         Value *Or = Builder->CreateOr(V2, V3, "tmp");
1585         return BinaryOperator::CreateAnd(V1, Or);
1586       }
1587     }
1588
1589     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
1590     // Don't do this for vector select idioms, the code generator doesn't handle
1591     // them well yet.
1592     if (!I.getType()->isVectorTy()) {
1593       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1594         return Match;
1595       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1596         return Match;
1597       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1598         return Match;
1599       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1600         return Match;
1601     }
1602
1603     // ((A&~B)|(~A&B)) -> A^B
1604     if ((match(C, m_Not(m_Specific(D))) &&
1605          match(B, m_Not(m_Specific(A)))))
1606       return BinaryOperator::CreateXor(A, D);
1607     // ((~B&A)|(~A&B)) -> A^B
1608     if ((match(A, m_Not(m_Specific(D))) &&
1609          match(B, m_Not(m_Specific(C)))))
1610       return BinaryOperator::CreateXor(C, D);
1611     // ((A&~B)|(B&~A)) -> A^B
1612     if ((match(C, m_Not(m_Specific(B))) &&
1613          match(D, m_Not(m_Specific(A)))))
1614       return BinaryOperator::CreateXor(A, B);
1615     // ((~B&A)|(B&~A)) -> A^B
1616     if ((match(A, m_Not(m_Specific(B))) &&
1617          match(D, m_Not(m_Specific(C)))))
1618       return BinaryOperator::CreateXor(C, B);
1619
1620     // ((A|B)&1)|(B&-2) -> (A&1) | B
1621     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1622         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1623       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1624       if (Ret) return Ret;
1625     }
1626     // (B&-2)|((A|B)&1) -> (A&1) | B
1627     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1628         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1629       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1630       if (Ret) return Ret;
1631     }
1632   }
1633   
1634   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1635   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1636     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1637       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1638           SI0->getOperand(1) == SI1->getOperand(1) &&
1639           (SI0->hasOneUse() || SI1->hasOneUse())) {
1640         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1641                                          SI0->getName());
1642         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1643                                       SI1->getOperand(1));
1644       }
1645   }
1646
1647   // (~A | ~B) == (~(A & B)) - De Morgan's Law
1648   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1649     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1650       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1651         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1652                                         I.getName()+".demorgan");
1653         return BinaryOperator::CreateNot(And);
1654       }
1655
1656   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1657     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1658       if (Value *Res = FoldOrOfICmps(LHS, RHS))
1659         return ReplaceInstUsesWith(I, Res);
1660     
1661   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
1662   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1663     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1664       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1665         return ReplaceInstUsesWith(I, Res);
1666   
1667   // fold (or (cast A), (cast B)) -> (cast (or A, B))
1668   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1669     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1670       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1671         const Type *SrcTy = Op0C->getOperand(0)->getType();
1672         if (SrcTy == Op1C->getOperand(0)->getType() &&
1673             SrcTy->isIntOrIntVectorTy()) {
1674           Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1675
1676           if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1677               // Only do this if the casts both really cause code to be
1678               // generated.
1679               ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1680               ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1681             Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1682             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1683           }
1684           
1685           // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1686           // cast is otherwise not optimizable.  This happens for vector sexts.
1687           if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1688             if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1689               if (Value *Res = FoldOrOfICmps(LHS, RHS))
1690                 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1691           
1692           // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1693           // cast is otherwise not optimizable.  This happens for vector sexts.
1694           if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1695             if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1696               if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1697                 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1698         }
1699       }
1700   }
1701   
1702   return Changed ? &I : 0;
1703 }
1704
1705 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1706   bool Changed = SimplifyCommutative(I);
1707   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1708
1709   if (isa<UndefValue>(Op1)) {
1710     if (isa<UndefValue>(Op0))
1711       // Handle undef ^ undef -> 0 special case. This is a common
1712       // idiom (misuse).
1713       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1714     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
1715   }
1716
1717   // xor X, X = 0
1718   if (Op0 == Op1)
1719     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1720   
1721   // See if we can simplify any instructions used by the instruction whose sole 
1722   // purpose is to compute bits we don't care about.
1723   if (SimplifyDemandedInstructionBits(I))
1724     return &I;
1725   if (I.getType()->isVectorTy())
1726     if (isa<ConstantAggregateZero>(Op1))
1727       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
1728
1729   // Is this a ~ operation?
1730   if (Value *NotOp = dyn_castNotVal(&I)) {
1731     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1732       if (Op0I->getOpcode() == Instruction::And || 
1733           Op0I->getOpcode() == Instruction::Or) {
1734         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1735         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1736         if (dyn_castNotVal(Op0I->getOperand(1)))
1737           Op0I->swapOperands();
1738         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1739           Value *NotY =
1740             Builder->CreateNot(Op0I->getOperand(1),
1741                                Op0I->getOperand(1)->getName()+".not");
1742           if (Op0I->getOpcode() == Instruction::And)
1743             return BinaryOperator::CreateOr(Op0NotVal, NotY);
1744           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1745         }
1746         
1747         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1748         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1749         if (isFreeToInvert(Op0I->getOperand(0)) && 
1750             isFreeToInvert(Op0I->getOperand(1))) {
1751           Value *NotX =
1752             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1753           Value *NotY =
1754             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1755           if (Op0I->getOpcode() == Instruction::And)
1756             return BinaryOperator::CreateOr(NotX, NotY);
1757           return BinaryOperator::CreateAnd(NotX, NotY);
1758         }
1759
1760       } else if (Op0I->getOpcode() == Instruction::AShr) {
1761         // ~(~X >>s Y) --> (X >>s Y)
1762         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1763           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
1764       }
1765     }
1766   }
1767   
1768   
1769   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1770     if (RHS->isOne() && Op0->hasOneUse())
1771       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
1772       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
1773         return CmpInst::Create(CI->getOpcode(),
1774                                CI->getInversePredicate(),
1775                                CI->getOperand(0), CI->getOperand(1));
1776
1777     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1778     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1779       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1780         if (CI->hasOneUse() && Op0C->hasOneUse()) {
1781           Instruction::CastOps Opcode = Op0C->getOpcode();
1782           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1783               (RHS == ConstantExpr::getCast(Opcode, 
1784                                            ConstantInt::getTrue(I.getContext()),
1785                                             Op0C->getDestTy()))) {
1786             CI->setPredicate(CI->getInversePredicate());
1787             return CastInst::Create(Opcode, CI, Op0C->getType());
1788           }
1789         }
1790       }
1791     }
1792
1793     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1794       // ~(c-X) == X-c-1 == X+(-c-1)
1795       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1796         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1797           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1798           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1799                                       ConstantInt::get(I.getType(), 1));
1800           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1801         }
1802           
1803       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1804         if (Op0I->getOpcode() == Instruction::Add) {
1805           // ~(X-c) --> (-c-1)-X
1806           if (RHS->isAllOnesValue()) {
1807             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1808             return BinaryOperator::CreateSub(
1809                            ConstantExpr::getSub(NegOp0CI,
1810                                       ConstantInt::get(I.getType(), 1)),
1811                                       Op0I->getOperand(0));
1812           } else if (RHS->getValue().isSignBit()) {
1813             // (X + C) ^ signbit -> (X + C + signbit)
1814             Constant *C = ConstantInt::get(I.getContext(),
1815                                            RHS->getValue() + Op0CI->getValue());
1816             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1817
1818           }
1819         } else if (Op0I->getOpcode() == Instruction::Or) {
1820           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1821           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1822             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1823             // Anything in both C1 and C2 is known to be zero, remove it from
1824             // NewRHS.
1825             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1826             NewRHS = ConstantExpr::getAnd(NewRHS, 
1827                                        ConstantExpr::getNot(CommonBits));
1828             Worklist.Add(Op0I);
1829             I.setOperand(0, Op0I->getOperand(0));
1830             I.setOperand(1, NewRHS);
1831             return &I;
1832           }
1833         }
1834       }
1835     }
1836
1837     // Try to fold constant and into select arguments.
1838     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1839       if (Instruction *R = FoldOpIntoSelect(I, SI))
1840         return R;
1841     if (isa<PHINode>(Op0))
1842       if (Instruction *NV = FoldOpIntoPhi(I))
1843         return NV;
1844   }
1845
1846   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1847     if (X == Op1)
1848       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1849
1850   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1851     if (X == Op0)
1852       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1853
1854   
1855   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1856   if (Op1I) {
1857     Value *A, *B;
1858     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1859       if (A == Op0) {              // B^(B|A) == (A|B)^B
1860         Op1I->swapOperands();
1861         I.swapOperands();
1862         std::swap(Op0, Op1);
1863       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
1864         I.swapOperands();     // Simplified below.
1865         std::swap(Op0, Op1);
1866       }
1867     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1868       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
1869     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1870       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
1871     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
1872                Op1I->hasOneUse()){
1873       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
1874         Op1I->swapOperands();
1875         std::swap(A, B);
1876       }
1877       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
1878         I.swapOperands();     // Simplified below.
1879         std::swap(Op0, Op1);
1880       }
1881     }
1882   }
1883   
1884   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1885   if (Op0I) {
1886     Value *A, *B;
1887     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1888         Op0I->hasOneUse()) {
1889       if (A == Op1)                                  // (B|A)^B == (A|B)^B
1890         std::swap(A, B);
1891       if (B == Op1)                                  // (A|B)^B == A & ~B
1892         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1893     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1894       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
1895     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1896       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
1897     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
1898                Op0I->hasOneUse()){
1899       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
1900         std::swap(A, B);
1901       if (B == Op1 &&                                      // (B&A)^A == ~B & A
1902           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
1903         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1904       }
1905     }
1906   }
1907   
1908   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
1909   if (Op0I && Op1I && Op0I->isShift() && 
1910       Op0I->getOpcode() == Op1I->getOpcode() && 
1911       Op0I->getOperand(1) == Op1I->getOperand(1) &&
1912       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
1913     Value *NewOp =
1914       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1915                          Op0I->getName());
1916     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
1917                                   Op1I->getOperand(1));
1918   }
1919     
1920   if (Op0I && Op1I) {
1921     Value *A, *B, *C, *D;
1922     // (A & B)^(A | B) -> A ^ B
1923     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1924         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1925       if ((A == C && B == D) || (A == D && B == C)) 
1926         return BinaryOperator::CreateXor(A, B);
1927     }
1928     // (A | B)^(A & B) -> A ^ B
1929     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1930         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1931       if ((A == C && B == D) || (A == D && B == C)) 
1932         return BinaryOperator::CreateXor(A, B);
1933     }
1934     
1935     // (A & B)^(C & D)
1936     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1937         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1938         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1939       // (X & Y)^(X & Y) -> (Y^Z) & X
1940       Value *X = 0, *Y = 0, *Z = 0;
1941       if (A == C)
1942         X = A, Y = B, Z = D;
1943       else if (A == D)
1944         X = A, Y = B, Z = C;
1945       else if (B == C)
1946         X = B, Y = A, Z = D;
1947       else if (B == D)
1948         X = B, Y = A, Z = C;
1949       
1950       if (X) {
1951         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1952         return BinaryOperator::CreateAnd(NewOp, X);
1953       }
1954     }
1955   }
1956     
1957   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1958   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1959     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1960       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1961         if (LHS->getOperand(0) == RHS->getOperand(1) &&
1962             LHS->getOperand(1) == RHS->getOperand(0))
1963           LHS->swapOperands();
1964         if (LHS->getOperand(0) == RHS->getOperand(0) &&
1965             LHS->getOperand(1) == RHS->getOperand(1)) {
1966           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1967           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1968           bool isSigned = LHS->isSigned() || RHS->isSigned();
1969           return ReplaceInstUsesWith(I, 
1970                                getICmpValue(isSigned, Code, Op0, Op1, Builder));
1971         }
1972       }
1973
1974   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1975   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1976     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1977       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1978         const Type *SrcTy = Op0C->getOperand(0)->getType();
1979         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
1980             // Only do this if the casts both really cause code to be generated.
1981             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0), 
1982                                I.getType()) &&
1983             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0), 
1984                                I.getType())) {
1985           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1986                                             Op1C->getOperand(0), I.getName());
1987           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1988         }
1989       }
1990   }
1991
1992   return Changed ? &I : 0;
1993 }