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