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