InstCombine: Add a combine that turns (2^n)-1 ^ x back into (2^n)-1 - x iff x is...
[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   // From here on, we only handle:
748   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
749   if (Val != Val2) return 0;
750   
751   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
752   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
753       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
754       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
755       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
756     return 0;
757
758   // Make a constant range that's the intersection of the two icmp ranges.
759   // If the intersection is empty, we know that the result is false.
760   ConstantRange LHSRange = 
761     ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
762   ConstantRange RHSRange = 
763     ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
764
765   if (LHSRange.intersectWith(RHSRange).isEmptySet())
766     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
767
768   // We can't fold (ugt x, C) & (sgt x, C2).
769   if (!PredicatesFoldable(LHSCC, RHSCC))
770     return 0;
771     
772   // Ensure that the larger constant is on the RHS.
773   bool ShouldSwap;
774   if (CmpInst::isSigned(LHSCC) ||
775       (ICmpInst::isEquality(LHSCC) && 
776        CmpInst::isSigned(RHSCC)))
777     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
778   else
779     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
780     
781   if (ShouldSwap) {
782     std::swap(LHS, RHS);
783     std::swap(LHSCst, RHSCst);
784     std::swap(LHSCC, RHSCC);
785   }
786
787   // At this point, we know we have two icmp instructions
788   // comparing a value against two constants and and'ing the result
789   // together.  Because of the above check, we know that we only have
790   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
791   // (from the icmp folding check above), that the two constants 
792   // are not equal and that the larger constant is on the RHS
793   assert(LHSCst != RHSCst && "Compares not folded above?");
794
795   switch (LHSCC) {
796   default: llvm_unreachable("Unknown integer condition code!");
797   case ICmpInst::ICMP_EQ:
798     switch (RHSCC) {
799     default: llvm_unreachable("Unknown integer condition code!");
800     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
801     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
802     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
803       return LHS;
804     }
805   case ICmpInst::ICMP_NE:
806     switch (RHSCC) {
807     default: llvm_unreachable("Unknown integer condition code!");
808     case ICmpInst::ICMP_ULT:
809       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
810         return Builder->CreateICmpULT(Val, LHSCst);
811       break;                        // (X != 13 & X u< 15) -> no change
812     case ICmpInst::ICMP_SLT:
813       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
814         return Builder->CreateICmpSLT(Val, LHSCst);
815       break;                        // (X != 13 & X s< 15) -> no change
816     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
817     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
818     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
819       return RHS;
820     case ICmpInst::ICMP_NE:
821       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
822         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
823         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
824         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
825       }
826       break;                        // (X != 13 & X != 15) -> no change
827     }
828     break;
829   case ICmpInst::ICMP_ULT:
830     switch (RHSCC) {
831     default: llvm_unreachable("Unknown integer condition code!");
832     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
833     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
834       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
835     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
836       break;
837     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
838     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
839       return LHS;
840     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
841       break;
842     }
843     break;
844   case ICmpInst::ICMP_SLT:
845     switch (RHSCC) {
846     default: llvm_unreachable("Unknown integer condition code!");
847     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
848       break;
849     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
850     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
851       return LHS;
852     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
853       break;
854     }
855     break;
856   case ICmpInst::ICMP_UGT:
857     switch (RHSCC) {
858     default: llvm_unreachable("Unknown integer condition code!");
859     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
860     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
861       return RHS;
862     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
863       break;
864     case ICmpInst::ICMP_NE:
865       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
866         return Builder->CreateICmp(LHSCC, Val, RHSCst);
867       break;                        // (X u> 13 & X != 15) -> no change
868     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
869       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
870     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
871       break;
872     }
873     break;
874   case ICmpInst::ICMP_SGT:
875     switch (RHSCC) {
876     default: llvm_unreachable("Unknown integer condition code!");
877     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
878     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
879       return RHS;
880     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
881       break;
882     case ICmpInst::ICMP_NE:
883       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
884         return Builder->CreateICmp(LHSCC, Val, RHSCst);
885       break;                        // (X s> 13 & X != 15) -> no change
886     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
887       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
888     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
889       break;
890     }
891     break;
892   }
893  
894   return 0;
895 }
896
897 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
898 /// instcombine, this returns a Value which should already be inserted into the
899 /// function.
900 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
901   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
902       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
903     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
904     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
905       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
906         // If either of the constants are nans, then the whole thing returns
907         // false.
908         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
909           return ConstantInt::getFalse(LHS->getContext());
910         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
911       }
912     
913     // Handle vector zeros.  This occurs because the canonical form of
914     // "fcmp ord x,x" is "fcmp ord x, 0".
915     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
916         isa<ConstantAggregateZero>(RHS->getOperand(1)))
917       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
918     return 0;
919   }
920   
921   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
922   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
923   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
924   
925   
926   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
927     // Swap RHS operands to match LHS.
928     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
929     std::swap(Op1LHS, Op1RHS);
930   }
931   
932   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
933     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
934     if (Op0CC == Op1CC)
935       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
936     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
937       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
938     if (Op0CC == FCmpInst::FCMP_TRUE)
939       return RHS;
940     if (Op1CC == FCmpInst::FCMP_TRUE)
941       return LHS;
942     
943     bool Op0Ordered;
944     bool Op1Ordered;
945     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
946     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
947     if (Op1Pred == 0) {
948       std::swap(LHS, RHS);
949       std::swap(Op0Pred, Op1Pred);
950       std::swap(Op0Ordered, Op1Ordered);
951     }
952     if (Op0Pred == 0) {
953       // uno && ueq -> uno && (uno || eq) -> ueq
954       // ord && olt -> ord && (ord && lt) -> olt
955       if (Op0Ordered == Op1Ordered)
956         return RHS;
957       
958       // uno && oeq -> uno && (ord && eq) -> false
959       // uno && ord -> false
960       if (!Op0Ordered)
961         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
962       // ord && ueq -> ord && (uno || eq) -> oeq
963       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
964     }
965   }
966
967   return 0;
968 }
969
970
971 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
972   bool Changed = SimplifyAssociativeOrCommutative(I);
973   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
974
975   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
976     return ReplaceInstUsesWith(I, V);
977
978   // (A|B)&(A|C) -> A|(B&C) etc
979   if (Value *V = SimplifyUsingDistributiveLaws(I))
980     return ReplaceInstUsesWith(I, V);
981
982   // See if we can simplify any instructions used by the instruction whose sole 
983   // purpose is to compute bits we don't care about.
984   if (SimplifyDemandedInstructionBits(I))
985     return &I;  
986
987   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
988     const APInt &AndRHSMask = AndRHS->getValue();
989
990     // Optimize a variety of ((val OP C1) & C2) combinations...
991     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
992       Value *Op0LHS = Op0I->getOperand(0);
993       Value *Op0RHS = Op0I->getOperand(1);
994       switch (Op0I->getOpcode()) {
995       default: break;
996       case Instruction::Xor:
997       case Instruction::Or: {
998         // If the mask is only needed on one incoming arm, push it up.
999         if (!Op0I->hasOneUse()) break;
1000           
1001         APInt NotAndRHS(~AndRHSMask);
1002         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1003           // Not masking anything out for the LHS, move to RHS.
1004           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1005                                              Op0RHS->getName()+".masked");
1006           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1007         }
1008         if (!isa<Constant>(Op0RHS) &&
1009             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1010           // Not masking anything out for the RHS, move to LHS.
1011           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1012                                              Op0LHS->getName()+".masked");
1013           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1014         }
1015
1016         break;
1017       }
1018       case Instruction::Add:
1019         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1020         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1021         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1022         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1023           return BinaryOperator::CreateAnd(V, AndRHS);
1024         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1025           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1026         break;
1027
1028       case Instruction::Sub:
1029         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1030         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1031         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1032         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1033           return BinaryOperator::CreateAnd(V, AndRHS);
1034
1035         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1036         // has 1's for all bits that the subtraction with A might affect.
1037         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1038           uint32_t BitWidth = AndRHSMask.getBitWidth();
1039           uint32_t Zeros = AndRHSMask.countLeadingZeros();
1040           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1041
1042           if (MaskedValueIsZero(Op0LHS, Mask)) {
1043             Value *NewNeg = Builder->CreateNeg(Op0RHS);
1044             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1045           }
1046         }
1047         break;
1048
1049       case Instruction::Shl:
1050       case Instruction::LShr:
1051         // (1 << x) & 1 --> zext(x == 0)
1052         // (1 >> x) & 1 --> zext(x == 0)
1053         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1054           Value *NewICmp =
1055             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1056           return new ZExtInst(NewICmp, I.getType());
1057         }
1058         break;
1059       }
1060           
1061       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1062         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1063           return Res;
1064     }
1065     
1066     // If this is an integer truncation, and if the source is an 'and' with
1067     // immediate, transform it.  This frequently occurs for bitfield accesses.
1068     {
1069       Value *X = 0; ConstantInt *YC = 0;
1070       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1071         // Change: and (trunc (and X, YC) to T), C2
1072         // into  : and (trunc X to T), trunc(YC) & C2
1073         // This will fold the two constants together, which may allow 
1074         // other simplifications.
1075         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1076         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1077         C3 = ConstantExpr::getAnd(C3, AndRHS);
1078         return BinaryOperator::CreateAnd(NewCast, C3);
1079       }
1080     }
1081
1082     // Try to fold constant and into select arguments.
1083     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1084       if (Instruction *R = FoldOpIntoSelect(I, SI))
1085         return R;
1086     if (isa<PHINode>(Op0))
1087       if (Instruction *NV = FoldOpIntoPhi(I))
1088         return NV;
1089   }
1090
1091
1092   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1093   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1094     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1095       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1096         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1097                                       I.getName()+".demorgan");
1098         return BinaryOperator::CreateNot(Or);
1099       }
1100   
1101   {
1102     Value *A = 0, *B = 0, *C = 0, *D = 0;
1103     // (A|B) & ~(A&B) -> A^B
1104     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1105         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1106         ((A == C && B == D) || (A == D && B == C)))
1107       return BinaryOperator::CreateXor(A, B);
1108     
1109     // ~(A&B) & (A|B) -> A^B
1110     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1111         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1112         ((A == C && B == D) || (A == D && B == C)))
1113       return BinaryOperator::CreateXor(A, B);
1114     
1115     // A&(A^B) => A & ~B
1116     {
1117       Value *tmpOp0 = Op0;
1118       Value *tmpOp1 = Op1;
1119       if (Op0->hasOneUse() &&
1120           match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1121         if (A == Op1 || B == Op1 ) {
1122           tmpOp1 = Op0;
1123           tmpOp0 = Op1;
1124           // Simplify below
1125         }
1126       }
1127
1128       if (tmpOp1->hasOneUse() &&
1129           match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1130         if (B == tmpOp0) {
1131           std::swap(A, B);
1132         }
1133         // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1134         // A is originally -1 (or a vector of -1 and undefs), then we enter
1135         // an endless loop. By checking that A is non-constant we ensure that
1136         // we will never get to the loop.
1137         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1138           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1139       }
1140     }
1141
1142     // (A&((~A)|B)) -> A&B
1143     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1144         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1145       return BinaryOperator::CreateAnd(A, Op1);
1146     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1147         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1148       return BinaryOperator::CreateAnd(A, Op0);
1149   }
1150   
1151   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1152     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1153       if (Value *Res = FoldAndOfICmps(LHS, RHS))
1154         return ReplaceInstUsesWith(I, Res);
1155   
1156   // If and'ing two fcmp, try combine them into one.
1157   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1158     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1159       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1160         return ReplaceInstUsesWith(I, Res);
1161   
1162   
1163   // fold (and (cast A), (cast B)) -> (cast (and A, B))
1164   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1165     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1166       Type *SrcTy = Op0C->getOperand(0)->getType();
1167       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1168           SrcTy == Op1C->getOperand(0)->getType() &&
1169           SrcTy->isIntOrIntVectorTy()) {
1170         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1171         
1172         // Only do this if the casts both really cause code to be generated.
1173         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1174             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1175           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1176           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1177         }
1178         
1179         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1180         // cast is otherwise not optimizable.  This happens for vector sexts.
1181         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1182           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1183             if (Value *Res = FoldAndOfICmps(LHS, RHS))
1184               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1185         
1186         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1187         // cast is otherwise not optimizable.  This happens for vector sexts.
1188         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1189           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1190             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1191               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1192       }
1193     }
1194     
1195   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
1196   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1197     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1198       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1199           SI0->getOperand(1) == SI1->getOperand(1) &&
1200           (SI0->hasOneUse() || SI1->hasOneUse())) {
1201         Value *NewOp =
1202           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1203                              SI0->getName());
1204         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1205                                       SI1->getOperand(1));
1206       }
1207   }
1208
1209   return Changed ? &I : 0;
1210 }
1211
1212 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1213 /// capable of providing pieces of a bswap.  The subexpression provides pieces
1214 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1215 /// the expression came from the corresponding "byte swapped" byte in some other
1216 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
1217 /// we know that the expression deposits the low byte of %X into the high byte
1218 /// of the bswap result and that all other bytes are zero.  This expression is
1219 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1220 /// match.
1221 ///
1222 /// This function returns true if the match was unsuccessful and false if so.
1223 /// On entry to the function the "OverallLeftShift" is a signed integer value
1224 /// indicating the number of bytes that the subexpression is later shifted.  For
1225 /// example, if the expression is later right shifted by 16 bits, the
1226 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
1227 /// byte of ByteValues is actually being set.
1228 ///
1229 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1230 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
1231 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
1232 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
1233 /// always in the local (OverallLeftShift) coordinate space.
1234 ///
1235 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1236                               SmallVector<Value*, 8> &ByteValues) {
1237   if (Instruction *I = dyn_cast<Instruction>(V)) {
1238     // If this is an or instruction, it may be an inner node of the bswap.
1239     if (I->getOpcode() == Instruction::Or) {
1240       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1241                                ByteValues) ||
1242              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1243                                ByteValues);
1244     }
1245   
1246     // If this is a logical shift by a constant multiple of 8, recurse with
1247     // OverallLeftShift and ByteMask adjusted.
1248     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1249       unsigned ShAmt = 
1250         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1251       // Ensure the shift amount is defined and of a byte value.
1252       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1253         return true;
1254
1255       unsigned ByteShift = ShAmt >> 3;
1256       if (I->getOpcode() == Instruction::Shl) {
1257         // X << 2 -> collect(X, +2)
1258         OverallLeftShift += ByteShift;
1259         ByteMask >>= ByteShift;
1260       } else {
1261         // X >>u 2 -> collect(X, -2)
1262         OverallLeftShift -= ByteShift;
1263         ByteMask <<= ByteShift;
1264         ByteMask &= (~0U >> (32-ByteValues.size()));
1265       }
1266
1267       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1268       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1269
1270       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1271                                ByteValues);
1272     }
1273
1274     // If this is a logical 'and' with a mask that clears bytes, clear the
1275     // corresponding bytes in ByteMask.
1276     if (I->getOpcode() == Instruction::And &&
1277         isa<ConstantInt>(I->getOperand(1))) {
1278       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1279       unsigned NumBytes = ByteValues.size();
1280       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1281       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1282       
1283       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1284         // If this byte is masked out by a later operation, we don't care what
1285         // the and mask is.
1286         if ((ByteMask & (1 << i)) == 0)
1287           continue;
1288         
1289         // If the AndMask is all zeros for this byte, clear the bit.
1290         APInt MaskB = AndMask & Byte;
1291         if (MaskB == 0) {
1292           ByteMask &= ~(1U << i);
1293           continue;
1294         }
1295         
1296         // If the AndMask is not all ones for this byte, it's not a bytezap.
1297         if (MaskB != Byte)
1298           return true;
1299
1300         // Otherwise, this byte is kept.
1301       }
1302
1303       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1304                                ByteValues);
1305     }
1306   }
1307   
1308   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1309   // the input value to the bswap.  Some observations: 1) if more than one byte
1310   // is demanded from this input, then it could not be successfully assembled
1311   // into a byteswap.  At least one of the two bytes would not be aligned with
1312   // their ultimate destination.
1313   if (!isPowerOf2_32(ByteMask)) return true;
1314   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1315   
1316   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1317   // is demanded, it needs to go into byte 0 of the result.  This means that the
1318   // byte needs to be shifted until it lands in the right byte bucket.  The
1319   // shift amount depends on the position: if the byte is coming from the high
1320   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1321   // low part, it must be shifted left.
1322   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1323   if (InputByteNo < ByteValues.size()/2) {
1324     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1325       return true;
1326   } else {
1327     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1328       return true;
1329   }
1330   
1331   // If the destination byte value is already defined, the values are or'd
1332   // together, which isn't a bswap (unless it's an or of the same bits).
1333   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1334     return true;
1335   ByteValues[DestByteNo] = V;
1336   return false;
1337 }
1338
1339 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1340 /// If so, insert the new bswap intrinsic and return it.
1341 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1342   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1343   if (!ITy || ITy->getBitWidth() % 16 || 
1344       // ByteMask only allows up to 32-byte values.
1345       ITy->getBitWidth() > 32*8) 
1346     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1347   
1348   /// ByteValues - For each byte of the result, we keep track of which value
1349   /// defines each byte.
1350   SmallVector<Value*, 8> ByteValues;
1351   ByteValues.resize(ITy->getBitWidth()/8);
1352     
1353   // Try to find all the pieces corresponding to the bswap.
1354   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1355   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1356     return 0;
1357   
1358   // Check to see if all of the bytes come from the same value.
1359   Value *V = ByteValues[0];
1360   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1361   
1362   // Check to make sure that all of the bytes come from the same value.
1363   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1364     if (ByteValues[i] != V)
1365       return 0;
1366   Module *M = I.getParent()->getParent()->getParent();
1367   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1368   return CallInst::Create(F, V);
1369 }
1370
1371 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1372 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1373 /// we can simplify this expression to "cond ? C : D or B".
1374 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1375                                          Value *C, Value *D) {
1376   // If A is not a select of -1/0, this cannot match.
1377   Value *Cond = 0;
1378   if (!match(A, m_SExt(m_Value(Cond))) ||
1379       !Cond->getType()->isIntegerTy(1))
1380     return 0;
1381
1382   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1383   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1384     return SelectInst::Create(Cond, C, B);
1385   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1386     return SelectInst::Create(Cond, C, B);
1387   
1388   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1389   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1390     return SelectInst::Create(Cond, C, D);
1391   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1392     return SelectInst::Create(Cond, C, D);
1393   return 0;
1394 }
1395
1396 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1397 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1398   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1399
1400   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1401   if (PredicatesFoldable(LHSCC, RHSCC)) {
1402     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1403         LHS->getOperand(1) == RHS->getOperand(0))
1404       LHS->swapOperands();
1405     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1406         LHS->getOperand(1) == RHS->getOperand(1)) {
1407       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1408       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1409       bool isSigned = LHS->isSigned() || RHS->isSigned();
1410       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1411     }
1412   }
1413
1414   // handle (roughly):
1415   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1416   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1417     return V;
1418
1419   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1420   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1421   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1422   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1423   if (LHSCst == 0 || RHSCst == 0) return 0;
1424
1425   if (LHSCst == RHSCst && LHSCC == RHSCC) {
1426     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1427     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1428       Value *NewOr = Builder->CreateOr(Val, Val2);
1429       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1430     }
1431
1432     // (icmp slt A, 0) | (icmp slt B, 0) --> (icmp slt (A|B), 0)
1433     if (LHSCC == ICmpInst::ICMP_SLT && LHSCst->isZero()) {
1434       Value *NewOr = Builder->CreateOr(Val, Val2);
1435       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1436     }
1437
1438     // (icmp sgt A, -1) | (icmp sgt B, -1) --> (icmp sgt (A&B), -1)
1439     if (LHSCC == ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
1440       Value *NewAnd = Builder->CreateAnd(Val, Val2);
1441       return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
1442     }
1443   }
1444
1445   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1446   //   iff C2 + CA == C1.
1447   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1448     ConstantInt *AddCst;
1449     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1450       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1451         return Builder->CreateICmpULE(Val, LHSCst);
1452   }
1453
1454   // From here on, we only handle:
1455   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1456   if (Val != Val2) return 0;
1457   
1458   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1459   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1460       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1461       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1462       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1463     return 0;
1464   
1465   // We can't fold (ugt x, C) | (sgt x, C2).
1466   if (!PredicatesFoldable(LHSCC, RHSCC))
1467     return 0;
1468   
1469   // Ensure that the larger constant is on the RHS.
1470   bool ShouldSwap;
1471   if (CmpInst::isSigned(LHSCC) ||
1472       (ICmpInst::isEquality(LHSCC) && 
1473        CmpInst::isSigned(RHSCC)))
1474     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1475   else
1476     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1477   
1478   if (ShouldSwap) {
1479     std::swap(LHS, RHS);
1480     std::swap(LHSCst, RHSCst);
1481     std::swap(LHSCC, RHSCC);
1482   }
1483   
1484   // At this point, we know we have two icmp instructions
1485   // comparing a value against two constants and or'ing the result
1486   // together.  Because of the above check, we know that we only have
1487   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1488   // icmp folding check above), that the two constants are not
1489   // equal.
1490   assert(LHSCst != RHSCst && "Compares not folded above?");
1491
1492   switch (LHSCC) {
1493   default: llvm_unreachable("Unknown integer condition code!");
1494   case ICmpInst::ICMP_EQ:
1495     switch (RHSCC) {
1496     default: llvm_unreachable("Unknown integer condition code!");
1497     case ICmpInst::ICMP_EQ:
1498       if (LHSCst == SubOne(RHSCst)) {
1499         // (X == 13 | X == 14) -> X-13 <u 2
1500         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1501         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1502         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1503         return Builder->CreateICmpULT(Add, AddCST);
1504       }
1505       break;                         // (X == 13 | X == 15) -> no change
1506     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1507     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1508       break;
1509     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1510     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1511     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1512       return RHS;
1513     }
1514     break;
1515   case ICmpInst::ICMP_NE:
1516     switch (RHSCC) {
1517     default: llvm_unreachable("Unknown integer condition code!");
1518     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1519     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1520     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1521       return LHS;
1522     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1523     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1524     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1525       return ConstantInt::getTrue(LHS->getContext());
1526     }
1527     break;
1528   case ICmpInst::ICMP_ULT:
1529     switch (RHSCC) {
1530     default: llvm_unreachable("Unknown integer condition code!");
1531     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1532       break;
1533     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1534       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1535       // this can cause overflow.
1536       if (RHSCst->isMaxValue(false))
1537         return LHS;
1538       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1539     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1540       break;
1541     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1542     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1543       return RHS;
1544     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1545       break;
1546     }
1547     break;
1548   case ICmpInst::ICMP_SLT:
1549     switch (RHSCC) {
1550     default: llvm_unreachable("Unknown integer condition code!");
1551     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1552       break;
1553     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1554       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1555       // this can cause overflow.
1556       if (RHSCst->isMaxValue(true))
1557         return LHS;
1558       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1559     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1560       break;
1561     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1562     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1563       return RHS;
1564     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1565       break;
1566     }
1567     break;
1568   case ICmpInst::ICMP_UGT:
1569     switch (RHSCC) {
1570     default: llvm_unreachable("Unknown integer condition code!");
1571     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1572     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1573       return LHS;
1574     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1575       break;
1576     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1577     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1578       return ConstantInt::getTrue(LHS->getContext());
1579     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1580       break;
1581     }
1582     break;
1583   case ICmpInst::ICMP_SGT:
1584     switch (RHSCC) {
1585     default: llvm_unreachable("Unknown integer condition code!");
1586     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1587     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1588       return LHS;
1589     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1590       break;
1591     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1592     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1593       return ConstantInt::getTrue(LHS->getContext());
1594     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1595       break;
1596     }
1597     break;
1598   }
1599   return 0;
1600 }
1601
1602 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1603 /// instcombine, this returns a Value which should already be inserted into the
1604 /// function.
1605 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1606   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1607       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
1608       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1609     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1610       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1611         // If either of the constants are nans, then the whole thing returns
1612         // true.
1613         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1614           return ConstantInt::getTrue(LHS->getContext());
1615         
1616         // Otherwise, no need to compare the two constants, compare the
1617         // rest.
1618         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1619       }
1620     
1621     // Handle vector zeros.  This occurs because the canonical form of
1622     // "fcmp uno x,x" is "fcmp uno x, 0".
1623     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1624         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1625       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1626     
1627     return 0;
1628   }
1629   
1630   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1631   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1632   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1633   
1634   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1635     // Swap RHS operands to match LHS.
1636     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1637     std::swap(Op1LHS, Op1RHS);
1638   }
1639   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1640     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1641     if (Op0CC == Op1CC)
1642       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1643     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1644       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1645     if (Op0CC == FCmpInst::FCMP_FALSE)
1646       return RHS;
1647     if (Op1CC == FCmpInst::FCMP_FALSE)
1648       return LHS;
1649     bool Op0Ordered;
1650     bool Op1Ordered;
1651     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1652     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1653     if (Op0Ordered == Op1Ordered) {
1654       // If both are ordered or unordered, return a new fcmp with
1655       // or'ed predicates.
1656       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1657     }
1658   }
1659   return 0;
1660 }
1661
1662 /// FoldOrWithConstants - This helper function folds:
1663 ///
1664 ///     ((A | B) & C1) | (B & C2)
1665 ///
1666 /// into:
1667 /// 
1668 ///     (A & C1) | B
1669 ///
1670 /// when the XOR of the two constants is "all ones" (-1).
1671 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1672                                                Value *A, Value *B, Value *C) {
1673   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1674   if (!CI1) return 0;
1675
1676   Value *V1 = 0;
1677   ConstantInt *CI2 = 0;
1678   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1679
1680   APInt Xor = CI1->getValue() ^ CI2->getValue();
1681   if (!Xor.isAllOnesValue()) return 0;
1682
1683   if (V1 == A || V1 == B) {
1684     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1685     return BinaryOperator::CreateOr(NewOp, V1);
1686   }
1687
1688   return 0;
1689 }
1690
1691 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1692   bool Changed = SimplifyAssociativeOrCommutative(I);
1693   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1694
1695   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1696     return ReplaceInstUsesWith(I, V);
1697
1698   // (A&B)|(A&C) -> A&(B|C) etc
1699   if (Value *V = SimplifyUsingDistributiveLaws(I))
1700     return ReplaceInstUsesWith(I, V);
1701
1702   // See if we can simplify any instructions used by the instruction whose sole 
1703   // purpose is to compute bits we don't care about.
1704   if (SimplifyDemandedInstructionBits(I))
1705     return &I;
1706
1707   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1708     ConstantInt *C1 = 0; Value *X = 0;
1709     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1710     // iff (C1 & C2) == 0.
1711     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1712         (RHS->getValue() & C1->getValue()) != 0 &&
1713         Op0->hasOneUse()) {
1714       Value *Or = Builder->CreateOr(X, RHS);
1715       Or->takeName(Op0);
1716       return BinaryOperator::CreateAnd(Or, 
1717                          ConstantInt::get(I.getContext(),
1718                                           RHS->getValue() | C1->getValue()));
1719     }
1720
1721     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1722     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1723         Op0->hasOneUse()) {
1724       Value *Or = Builder->CreateOr(X, RHS);
1725       Or->takeName(Op0);
1726       return BinaryOperator::CreateXor(Or,
1727                  ConstantInt::get(I.getContext(),
1728                                   C1->getValue() & ~RHS->getValue()));
1729     }
1730
1731     // Try to fold constant and into select arguments.
1732     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1733       if (Instruction *R = FoldOpIntoSelect(I, SI))
1734         return R;
1735
1736     if (isa<PHINode>(Op0))
1737       if (Instruction *NV = FoldOpIntoPhi(I))
1738         return NV;
1739   }
1740
1741   Value *A = 0, *B = 0;
1742   ConstantInt *C1 = 0, *C2 = 0;
1743
1744   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1745   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1746   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1747       match(Op1, m_Or(m_Value(), m_Value())) ||
1748       (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1749        match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1750     if (Instruction *BSwap = MatchBSwap(I))
1751       return BSwap;
1752   }
1753   
1754   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1755   if (Op0->hasOneUse() &&
1756       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1757       MaskedValueIsZero(Op1, C1->getValue())) {
1758     Value *NOr = Builder->CreateOr(A, Op1);
1759     NOr->takeName(Op0);
1760     return BinaryOperator::CreateXor(NOr, C1);
1761   }
1762
1763   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1764   if (Op1->hasOneUse() &&
1765       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1766       MaskedValueIsZero(Op0, C1->getValue())) {
1767     Value *NOr = Builder->CreateOr(A, Op0);
1768     NOr->takeName(Op0);
1769     return BinaryOperator::CreateXor(NOr, C1);
1770   }
1771
1772   // (A & C)|(B & D)
1773   Value *C = 0, *D = 0;
1774   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1775       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1776     Value *V1 = 0, *V2 = 0;
1777     C1 = dyn_cast<ConstantInt>(C);
1778     C2 = dyn_cast<ConstantInt>(D);
1779     if (C1 && C2) {  // (A & C1)|(B & C2)
1780       // If we have: ((V + N) & C1) | (V & C2)
1781       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1782       // replace with V+N.
1783       if (C1->getValue() == ~C2->getValue()) {
1784         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1785             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1786           // Add commutes, try both ways.
1787           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1788             return ReplaceInstUsesWith(I, A);
1789           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1790             return ReplaceInstUsesWith(I, A);
1791         }
1792         // Or commutes, try both ways.
1793         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1794             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1795           // Add commutes, try both ways.
1796           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1797             return ReplaceInstUsesWith(I, B);
1798           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1799             return ReplaceInstUsesWith(I, B);
1800         }
1801       }
1802       
1803       if ((C1->getValue() & C2->getValue()) == 0) {
1804         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1805         // iff (C1&C2) == 0 and (N&~C1) == 0
1806         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1807             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1808              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1809           return BinaryOperator::CreateAnd(A,
1810                                ConstantInt::get(A->getContext(),
1811                                                 C1->getValue()|C2->getValue()));
1812         // Or commutes, try both ways.
1813         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1814             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1815              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1816           return BinaryOperator::CreateAnd(B,
1817                                ConstantInt::get(B->getContext(),
1818                                                 C1->getValue()|C2->getValue()));
1819         
1820         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1821         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1822         ConstantInt *C3 = 0, *C4 = 0;
1823         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1824             (C3->getValue() & ~C1->getValue()) == 0 &&
1825             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1826             (C4->getValue() & ~C2->getValue()) == 0) {
1827           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1828           return BinaryOperator::CreateAnd(V2,
1829                                ConstantInt::get(B->getContext(),
1830                                                 C1->getValue()|C2->getValue()));
1831         }
1832       }
1833     }
1834
1835     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
1836     // Don't do this for vector select idioms, the code generator doesn't handle
1837     // them well yet.
1838     if (!I.getType()->isVectorTy()) {
1839       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1840         return Match;
1841       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1842         return Match;
1843       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1844         return Match;
1845       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1846         return Match;
1847     }
1848
1849     // ((A&~B)|(~A&B)) -> A^B
1850     if ((match(C, m_Not(m_Specific(D))) &&
1851          match(B, m_Not(m_Specific(A)))))
1852       return BinaryOperator::CreateXor(A, D);
1853     // ((~B&A)|(~A&B)) -> A^B
1854     if ((match(A, m_Not(m_Specific(D))) &&
1855          match(B, m_Not(m_Specific(C)))))
1856       return BinaryOperator::CreateXor(C, D);
1857     // ((A&~B)|(B&~A)) -> A^B
1858     if ((match(C, m_Not(m_Specific(B))) &&
1859          match(D, m_Not(m_Specific(A)))))
1860       return BinaryOperator::CreateXor(A, B);
1861     // ((~B&A)|(B&~A)) -> A^B
1862     if ((match(A, m_Not(m_Specific(B))) &&
1863          match(D, m_Not(m_Specific(C)))))
1864       return BinaryOperator::CreateXor(C, B);
1865
1866     // ((A|B)&1)|(B&-2) -> (A&1) | B
1867     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1868         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1869       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1870       if (Ret) return Ret;
1871     }
1872     // (B&-2)|((A|B)&1) -> (A&1) | B
1873     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1874         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1875       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1876       if (Ret) return Ret;
1877     }
1878   }
1879   
1880   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1881   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1882     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1883       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1884           SI0->getOperand(1) == SI1->getOperand(1) &&
1885           (SI0->hasOneUse() || SI1->hasOneUse())) {
1886         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1887                                          SI0->getName());
1888         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1889                                       SI1->getOperand(1));
1890       }
1891   }
1892
1893   // (~A | ~B) == (~(A & B)) - De Morgan's Law
1894   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1895     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1896       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1897         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1898                                         I.getName()+".demorgan");
1899         return BinaryOperator::CreateNot(And);
1900       }
1901
1902   // Canonicalize xor to the RHS.
1903   if (match(Op0, m_Xor(m_Value(), m_Value())))
1904     std::swap(Op0, Op1);
1905
1906   // A | ( A ^ B) -> A |  B
1907   // A | (~A ^ B) -> A | ~B
1908   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1909     if (Op0 == A || Op0 == B)
1910       return BinaryOperator::CreateOr(A, B);
1911
1912     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1913       Value *Not = Builder->CreateNot(B, B->getName()+".not");
1914       return BinaryOperator::CreateOr(Not, Op0);
1915     }
1916     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1917       Value *Not = Builder->CreateNot(A, A->getName()+".not");
1918       return BinaryOperator::CreateOr(Not, Op0);
1919     }
1920   }
1921
1922   // A | ~(A | B) -> A | ~B
1923   // A | ~(A ^ B) -> A | ~B
1924   if (match(Op1, m_Not(m_Value(A))))
1925     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
1926       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1927           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1928                                B->getOpcode() == Instruction::Xor)) {
1929         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1930                                                  B->getOperand(0);
1931         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
1932         return BinaryOperator::CreateOr(Not, Op0);
1933       }
1934
1935   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1936     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1937       if (Value *Res = FoldOrOfICmps(LHS, RHS))
1938         return ReplaceInstUsesWith(I, Res);
1939     
1940   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
1941   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1942     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1943       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1944         return ReplaceInstUsesWith(I, Res);
1945   
1946   // fold (or (cast A), (cast B)) -> (cast (or A, B))
1947   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1948     CastInst *Op1C = dyn_cast<CastInst>(Op1);
1949     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1950       Type *SrcTy = Op0C->getOperand(0)->getType();
1951       if (SrcTy == Op1C->getOperand(0)->getType() &&
1952           SrcTy->isIntOrIntVectorTy()) {
1953         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1954
1955         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1956             // Only do this if the casts both really cause code to be
1957             // generated.
1958             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1959             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1960           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1961           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1962         }
1963         
1964         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1965         // cast is otherwise not optimizable.  This happens for vector sexts.
1966         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1967           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1968             if (Value *Res = FoldOrOfICmps(LHS, RHS))
1969               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1970         
1971         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1972         // cast is otherwise not optimizable.  This happens for vector sexts.
1973         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1974           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1975             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1976               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1977       }
1978     }
1979   }
1980
1981   // or(sext(A), B) -> A ? -1 : B where A is an i1
1982   // or(A, sext(B)) -> B ? -1 : A where B is an i1
1983   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
1984     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
1985   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
1986     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
1987
1988   // Note: If we've gotten to the point of visiting the outer OR, then the
1989   // inner one couldn't be simplified.  If it was a constant, then it won't
1990   // be simplified by a later pass either, so we try swapping the inner/outer
1991   // ORs in the hopes that we'll be able to simplify it this way.
1992   // (X|C) | V --> (X|V) | C
1993   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
1994       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
1995     Value *Inner = Builder->CreateOr(A, Op1);
1996     Inner->takeName(Op0);
1997     return BinaryOperator::CreateOr(Inner, C1);
1998   }
1999   
2000   return Changed ? &I : 0;
2001 }
2002
2003 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2004   bool Changed = SimplifyAssociativeOrCommutative(I);
2005   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2006
2007   if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2008     return ReplaceInstUsesWith(I, V);
2009
2010   // (A&B)^(A&C) -> A&(B^C) etc
2011   if (Value *V = SimplifyUsingDistributiveLaws(I))
2012     return ReplaceInstUsesWith(I, V);
2013
2014   // See if we can simplify any instructions used by the instruction whose sole 
2015   // purpose is to compute bits we don't care about.
2016   if (SimplifyDemandedInstructionBits(I))
2017     return &I;
2018
2019   // Is this a ~ operation?
2020   if (Value *NotOp = dyn_castNotVal(&I)) {
2021     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2022       if (Op0I->getOpcode() == Instruction::And || 
2023           Op0I->getOpcode() == Instruction::Or) {
2024         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2025         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2026         if (dyn_castNotVal(Op0I->getOperand(1)))
2027           Op0I->swapOperands();
2028         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2029           Value *NotY =
2030             Builder->CreateNot(Op0I->getOperand(1),
2031                                Op0I->getOperand(1)->getName()+".not");
2032           if (Op0I->getOpcode() == Instruction::And)
2033             return BinaryOperator::CreateOr(Op0NotVal, NotY);
2034           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2035         }
2036         
2037         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2038         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2039         if (isFreeToInvert(Op0I->getOperand(0)) && 
2040             isFreeToInvert(Op0I->getOperand(1))) {
2041           Value *NotX =
2042             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2043           Value *NotY =
2044             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2045           if (Op0I->getOpcode() == Instruction::And)
2046             return BinaryOperator::CreateOr(NotX, NotY);
2047           return BinaryOperator::CreateAnd(NotX, NotY);
2048         }
2049
2050       } else if (Op0I->getOpcode() == Instruction::AShr) {
2051         // ~(~X >>s Y) --> (X >>s Y)
2052         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2053           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2054       }
2055     }
2056   }
2057   
2058   
2059   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2060     if (RHS->isOne() && Op0->hasOneUse())
2061       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2062       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2063         return CmpInst::Create(CI->getOpcode(),
2064                                CI->getInversePredicate(),
2065                                CI->getOperand(0), CI->getOperand(1));
2066
2067     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2068     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2069       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2070         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2071           Instruction::CastOps Opcode = Op0C->getOpcode();
2072           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2073               (RHS == ConstantExpr::getCast(Opcode, 
2074                                            ConstantInt::getTrue(I.getContext()),
2075                                             Op0C->getDestTy()))) {
2076             CI->setPredicate(CI->getInversePredicate());
2077             return CastInst::Create(Opcode, CI, Op0C->getType());
2078           }
2079         }
2080       }
2081     }
2082
2083     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2084       // ~(c-X) == X-c-1 == X+(-c-1)
2085       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2086         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2087           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2088           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2089                                       ConstantInt::get(I.getType(), 1));
2090           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2091         }
2092           
2093       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2094         if (Op0I->getOpcode() == Instruction::Add) {
2095           // ~(X-c) --> (-c-1)-X
2096           if (RHS->isAllOnesValue()) {
2097             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2098             return BinaryOperator::CreateSub(
2099                            ConstantExpr::getSub(NegOp0CI,
2100                                       ConstantInt::get(I.getType(), 1)),
2101                                       Op0I->getOperand(0));
2102           } else if (RHS->getValue().isSignBit()) {
2103             // (X + C) ^ signbit -> (X + C + signbit)
2104             Constant *C = ConstantInt::get(I.getContext(),
2105                                            RHS->getValue() + Op0CI->getValue());
2106             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2107
2108           }
2109         } else if (Op0I->getOpcode() == Instruction::Or) {
2110           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2111           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2112             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2113             // Anything in both C1 and C2 is known to be zero, remove it from
2114             // NewRHS.
2115             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2116             NewRHS = ConstantExpr::getAnd(NewRHS, 
2117                                        ConstantExpr::getNot(CommonBits));
2118             Worklist.Add(Op0I);
2119             I.setOperand(0, Op0I->getOperand(0));
2120             I.setOperand(1, NewRHS);
2121             return &I;
2122           }
2123         }
2124       }
2125     }
2126
2127     // Try to fold constant and into select arguments.
2128     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2129       if (Instruction *R = FoldOpIntoSelect(I, SI))
2130         return R;
2131     if (isa<PHINode>(Op0))
2132       if (Instruction *NV = FoldOpIntoPhi(I))
2133         return NV;
2134   }
2135
2136   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2137   if (Op1I) {
2138     Value *A, *B;
2139     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2140       if (A == Op0) {              // B^(B|A) == (A|B)^B
2141         Op1I->swapOperands();
2142         I.swapOperands();
2143         std::swap(Op0, Op1);
2144       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2145         I.swapOperands();     // Simplified below.
2146         std::swap(Op0, Op1);
2147       }
2148     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
2149                Op1I->hasOneUse()){
2150       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2151         Op1I->swapOperands();
2152         std::swap(A, B);
2153       }
2154       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2155         I.swapOperands();     // Simplified below.
2156         std::swap(Op0, Op1);
2157       }
2158     }
2159   }
2160   
2161   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2162   if (Op0I) {
2163     Value *A, *B;
2164     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2165         Op0I->hasOneUse()) {
2166       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2167         std::swap(A, B);
2168       if (B == Op1)                                  // (A|B)^B == A & ~B
2169         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2170     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
2171                Op0I->hasOneUse()){
2172       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2173         std::swap(A, B);
2174       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2175           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2176         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2177       }
2178     }
2179   }
2180   
2181   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
2182   if (Op0I && Op1I && Op0I->isShift() && 
2183       Op0I->getOpcode() == Op1I->getOpcode() && 
2184       Op0I->getOperand(1) == Op1I->getOperand(1) &&
2185       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2186     Value *NewOp =
2187       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2188                          Op0I->getName());
2189     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
2190                                   Op1I->getOperand(1));
2191   }
2192     
2193   if (Op0I && Op1I) {
2194     Value *A, *B, *C, *D;
2195     // (A & B)^(A | B) -> A ^ B
2196     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2197         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2198       if ((A == C && B == D) || (A == D && B == C)) 
2199         return BinaryOperator::CreateXor(A, B);
2200     }
2201     // (A | B)^(A & B) -> A ^ B
2202     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2203         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2204       if ((A == C && B == D) || (A == D && B == C)) 
2205         return BinaryOperator::CreateXor(A, B);
2206     }
2207   }
2208
2209   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2210   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2211     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2212       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2213         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2214             LHS->getOperand(1) == RHS->getOperand(0))
2215           LHS->swapOperands();
2216         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2217             LHS->getOperand(1) == RHS->getOperand(1)) {
2218           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2219           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2220           bool isSigned = LHS->isSigned() || RHS->isSigned();
2221           return ReplaceInstUsesWith(I, 
2222                                getNewICmpValue(isSigned, Code, Op0, Op1,
2223                                                Builder));
2224         }
2225       }
2226
2227   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2228   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2229     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2230       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2231         Type *SrcTy = Op0C->getOperand(0)->getType();
2232         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2233             // Only do this if the casts both really cause code to be generated.
2234             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0), 
2235                                I.getType()) &&
2236             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0), 
2237                                I.getType())) {
2238           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2239                                             Op1C->getOperand(0), I.getName());
2240           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2241         }
2242       }
2243   }
2244
2245   return Changed ? &I : 0;
2246 }