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