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