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