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