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 "InstCombineInternal.h"
15#include "llvm/Analysis/InstructionSimplify.h"
16#include "llvm/IR/ConstantRange.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/PatternMatch.h"
19#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
20using namespace llvm;
21using namespace PatternMatch;
22
23#define DEBUG_TYPE "instcombine"
24
25static inline Value *dyn_castNotVal(Value *V) {
26  // If this is not(not(x)) don't return that this is a not: we want the two
27  // not's to be folded first.
28  if (BinaryOperator::isNot(V)) {
29    Value *Operand = BinaryOperator::getNotArgument(V);
30    if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
31      return Operand;
32  }
33
34  // Constants can be considered to be not'ed values...
35  if (ConstantInt *C = dyn_cast<ConstantInt>(V))
36    return ConstantInt::get(C->getType(), ~C->getValue());
37  return nullptr;
38}
39
40/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
41/// a three bit mask. It also returns whether it is an ordered predicate by
42/// reference.
43static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
44  isOrdered = false;
45  switch (CC) {
46  case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
47  case FCmpInst::FCMP_UNO:                   return 0;  // 000
48  case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
49  case FCmpInst::FCMP_UGT:                   return 1;  // 001
50  case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
51  case FCmpInst::FCMP_UEQ:                   return 2;  // 010
52  case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
53  case FCmpInst::FCMP_UGE:                   return 3;  // 011
54  case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
55  case FCmpInst::FCMP_ULT:                   return 4;  // 100
56  case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
57  case FCmpInst::FCMP_UNE:                   return 5;  // 101
58  case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
59  case FCmpInst::FCMP_ULE:                   return 6;  // 110
60    // True -> 7
61  default:
62    // Not expecting FCMP_FALSE and FCMP_TRUE;
63    llvm_unreachable("Unexpected FCmp predicate!");
64  }
65}
66
67/// This is the complement of getICmpCode, which turns an opcode and two
68/// operands into either a constant true or false, or a brand new ICmp
69/// instruction. The sign is passed in to determine which kind of predicate to
70/// use in the new icmp instruction.
71static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72                              InstCombiner::BuilderTy *Builder) {
73  ICmpInst::Predicate NewPred;
74  if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75    return NewConstant;
76  return Builder->CreateICmp(NewPred, LHS, RHS);
77}
78
79/// This is the complement of getFCmpCode, which turns an opcode and two
80/// operands into either a FCmp instruction. isordered is passed in to determine
81/// which kind of predicate to use in the new fcmp instruction.
82static Value *getFCmpValue(bool isordered, unsigned code,
83                           Value *LHS, Value *RHS,
84                           InstCombiner::BuilderTy *Builder) {
85  CmpInst::Predicate Pred;
86  switch (code) {
87  default: llvm_unreachable("Illegal FCmp code!");
88  case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
89  case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
90  case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
91  case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
92  case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
93  case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
94  case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
95  case 7:
96    if (!isordered)
97      return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
98    Pred = FCmpInst::FCMP_ORD; break;
99  }
100  return Builder->CreateFCmp(Pred, LHS, RHS);
101}
102
103/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
104/// \param I Binary operator to transform.
105/// \return Pointer to node that must replace the original binary operator, or
106///         null pointer if no transformation was made.
107Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
108  IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
109
110  // Can't do vectors.
111  if (I.getType()->isVectorTy()) return nullptr;
112
113  // Can only do bitwise ops.
114  unsigned Op = I.getOpcode();
115  if (Op != Instruction::And && Op != Instruction::Or &&
116      Op != Instruction::Xor)
117    return nullptr;
118
119  Value *OldLHS = I.getOperand(0);
120  Value *OldRHS = I.getOperand(1);
121  ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
122  ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
123  IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
124  IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
125  bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
126  bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
127
128  if (!IsBswapLHS && !IsBswapRHS)
129    return nullptr;
130
131  if (!IsBswapLHS && !ConstLHS)
132    return nullptr;
133
134  if (!IsBswapRHS && !ConstRHS)
135    return nullptr;
136
137  /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
138  /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
139  Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
140                  Builder->getInt(ConstLHS->getValue().byteSwap());
141
142  Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
143                  Builder->getInt(ConstRHS->getValue().byteSwap());
144
145  Value *BinOp = nullptr;
146  if (Op == Instruction::And)
147    BinOp = Builder->CreateAnd(NewLHS, NewRHS);
148  else if (Op == Instruction::Or)
149    BinOp = Builder->CreateOr(NewLHS, NewRHS);
150  else //if (Op == Instruction::Xor)
151    BinOp = Builder->CreateXor(NewLHS, NewRHS);
152
153  Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
154  return Builder->CreateCall(F, BinOp);
155}
156
157/// This handles expressions of the form ((val OP C1) & C2).  Where
158/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
159/// guaranteed to be a binary operator.
160Instruction *InstCombiner::OptAndOp(Instruction *Op,
161                                    ConstantInt *OpRHS,
162                                    ConstantInt *AndRHS,
163                                    BinaryOperator &TheAnd) {
164  Value *X = Op->getOperand(0);
165  Constant *Together = nullptr;
166  if (!Op->isShift())
167    Together = ConstantExpr::getAnd(AndRHS, OpRHS);
168
169  switch (Op->getOpcode()) {
170  case Instruction::Xor:
171    if (Op->hasOneUse()) {
172      // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
173      Value *And = Builder->CreateAnd(X, AndRHS);
174      And->takeName(Op);
175      return BinaryOperator::CreateXor(And, Together);
176    }
177    break;
178  case Instruction::Or:
179    if (Op->hasOneUse()){
180      if (Together != OpRHS) {
181        // (X | C1) & C2 --> (X | (C1&C2)) & C2
182        Value *Or = Builder->CreateOr(X, Together);
183        Or->takeName(Op);
184        return BinaryOperator::CreateAnd(Or, AndRHS);
185      }
186
187      ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
188      if (TogetherCI && !TogetherCI->isZero()){
189        // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
190        // NOTE: This reduces the number of bits set in the & mask, which
191        // can expose opportunities for store narrowing.
192        Together = ConstantExpr::getXor(AndRHS, Together);
193        Value *And = Builder->CreateAnd(X, Together);
194        And->takeName(Op);
195        return BinaryOperator::CreateOr(And, OpRHS);
196      }
197    }
198
199    break;
200  case Instruction::Add:
201    if (Op->hasOneUse()) {
202      // Adding a one to a single bit bit-field should be turned into an XOR
203      // of the bit.  First thing to check is to see if this AND is with a
204      // single bit constant.
205      const APInt &AndRHSV = AndRHS->getValue();
206
207      // If there is only one bit set.
208      if (AndRHSV.isPowerOf2()) {
209        // Ok, at this point, we know that we are masking the result of the
210        // ADD down to exactly one bit.  If the constant we are adding has
211        // no bits set below this bit, then we can eliminate the ADD.
212        const APInt& AddRHS = OpRHS->getValue();
213
214        // Check to see if any bits below the one bit set in AndRHSV are set.
215        if ((AddRHS & (AndRHSV-1)) == 0) {
216          // If not, the only thing that can effect the output of the AND is
217          // the bit specified by AndRHSV.  If that bit is set, the effect of
218          // the XOR is to toggle the bit.  If it is clear, then the ADD has
219          // no effect.
220          if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
221            TheAnd.setOperand(0, X);
222            return &TheAnd;
223          } else {
224            // Pull the XOR out of the AND.
225            Value *NewAnd = Builder->CreateAnd(X, AndRHS);
226            NewAnd->takeName(Op);
227            return BinaryOperator::CreateXor(NewAnd, AndRHS);
228          }
229        }
230      }
231    }
232    break;
233
234  case Instruction::Shl: {
235    // We know that the AND will not produce any of the bits shifted in, so if
236    // the anded constant includes them, clear them now!
237    //
238    uint32_t BitWidth = AndRHS->getType()->getBitWidth();
239    uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
240    APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
241    ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
242
243    if (CI->getValue() == ShlMask)
244      // Masking out bits that the shift already masks.
245      return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
246
247    if (CI != AndRHS) {                  // Reducing bits set in and.
248      TheAnd.setOperand(1, CI);
249      return &TheAnd;
250    }
251    break;
252  }
253  case Instruction::LShr: {
254    // We know that the AND will not produce any of the bits shifted in, so if
255    // the anded constant includes them, clear them now!  This only applies to
256    // unsigned shifts, because a signed shr may bring in set bits!
257    //
258    uint32_t BitWidth = AndRHS->getType()->getBitWidth();
259    uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
260    APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
261    ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
262
263    if (CI->getValue() == ShrMask)
264      // Masking out bits that the shift already masks.
265      return ReplaceInstUsesWith(TheAnd, Op);
266
267    if (CI != AndRHS) {
268      TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
269      return &TheAnd;
270    }
271    break;
272  }
273  case Instruction::AShr:
274    // Signed shr.
275    // See if this is shifting in some sign extension, then masking it out
276    // with an and.
277    if (Op->hasOneUse()) {
278      uint32_t BitWidth = AndRHS->getType()->getBitWidth();
279      uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
280      APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
281      Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
282      if (C == AndRHS) {          // Masking out bits shifted in.
283        // (Val ashr C1) & C2 -> (Val lshr C1) & C2
284        // Make the argument unsigned.
285        Value *ShVal = Op->getOperand(0);
286        ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
287        return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
288      }
289    }
290    break;
291  }
292  return nullptr;
293}
294
295/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
296/// (V < Lo || V >= Hi).  In practice, we emit the more efficient
297/// (V-Lo) \<u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
298/// whether to treat the V, Lo and HI as signed or not. IB is the location to
299/// insert new instructions.
300Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
301                                     bool isSigned, bool Inside) {
302  assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
303            ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
304         "Lo is not <= Hi in range emission code!");
305
306  if (Inside) {
307    if (Lo == Hi)  // Trivially false.
308      return Builder->getFalse();
309
310    // V >= Min && V < Hi --> V < Hi
311    if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
312      ICmpInst::Predicate pred = (isSigned ?
313        ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
314      return Builder->CreateICmp(pred, V, Hi);
315    }
316
317    // Emit V-Lo <u Hi-Lo
318    Constant *NegLo = ConstantExpr::getNeg(Lo);
319    Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
320    Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
321    return Builder->CreateICmpULT(Add, UpperBound);
322  }
323
324  if (Lo == Hi)  // Trivially true.
325    return Builder->getTrue();
326
327  // V < Min || V >= Hi -> V > Hi-1
328  Hi = SubOne(cast<ConstantInt>(Hi));
329  if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
330    ICmpInst::Predicate pred = (isSigned ?
331        ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
332    return Builder->CreateICmp(pred, V, Hi);
333  }
334
335  // Emit V-Lo >u Hi-1-Lo
336  // Note that Hi has already had one subtracted from it, above.
337  ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
338  Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
339  Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
340  return Builder->CreateICmpUGT(Add, LowerBound);
341}
342
343/// Returns true iff Val consists of one contiguous run of 1s with any number
344/// of 0s on either side.  The 1s are allowed to wrap from LSB to MSB,
345/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
346/// not, since all 1s are not contiguous.
347static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
348  const APInt& V = Val->getValue();
349  uint32_t BitWidth = Val->getType()->getBitWidth();
350  if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
351
352  // look for the first zero bit after the run of ones
353  MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
354  // look for the first non-zero bit
355  ME = V.getActiveBits();
356  return true;
357}
358
359/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
360/// whether the operator is a sub. If we can fold one of the following xforms:
361///
362/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
363/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
364/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
365///
366/// return (A +/- B).
367///
368Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
369                                        ConstantInt *Mask, bool isSub,
370                                        Instruction &I) {
371  Instruction *LHSI = dyn_cast<Instruction>(LHS);
372  if (!LHSI || LHSI->getNumOperands() != 2 ||
373      !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
374
375  ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
376
377  switch (LHSI->getOpcode()) {
378  default: return nullptr;
379  case Instruction::And:
380    if (ConstantExpr::getAnd(N, Mask) == Mask) {
381      // If the AndRHS is a power of two minus one (0+1+), this is simple.
382      if ((Mask->getValue().countLeadingZeros() +
383           Mask->getValue().countPopulation()) ==
384          Mask->getValue().getBitWidth())
385        break;
386
387      // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
388      // part, we don't need any explicit masks to take them out of A.  If that
389      // is all N is, ignore it.
390      uint32_t MB = 0, ME = 0;
391      if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
392        uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
393        APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
394        if (MaskedValueIsZero(RHS, Mask, 0, &I))
395          break;
396      }
397    }
398    return nullptr;
399  case Instruction::Or:
400  case Instruction::Xor:
401    // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
402    if ((Mask->getValue().countLeadingZeros() +
403         Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
404        && ConstantExpr::getAnd(N, Mask)->isNullValue())
405      break;
406    return nullptr;
407  }
408
409  if (isSub)
410    return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
411  return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
412}
413
414/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
415/// One of A and B is considered the mask, the other the value. This is
416/// described as the "AMask" or "BMask" part of the enum. If the enum
417/// contains only "Mask", then both A and B can be considered masks.
418/// If A is the mask, then it was proven, that (A & C) == C. This
419/// is trivial if C == A, or C == 0. If both A and C are constants, this
420/// proof is also easy.
421/// For the following explanations we assume that A is the mask.
422/// The part "AllOnes" declares, that the comparison is true only
423/// if (A & B) == A, or all bits of A are set in B.
424///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
425/// The part "AllZeroes" declares, that the comparison is true only
426/// if (A & B) == 0, or all bits of A are cleared in B.
427///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
428/// The part "Mixed" declares, that (A & B) == C and C might or might not
429/// contain any number of one bits and zero bits.
430///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
431/// The Part "Not" means, that in above descriptions "==" should be replaced
432/// by "!=".
433///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
434/// If the mask A contains a single bit, then the following is equivalent:
435///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
436///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
437enum MaskedICmpType {
438  FoldMskICmp_AMask_AllOnes           =     1,
439  FoldMskICmp_AMask_NotAllOnes        =     2,
440  FoldMskICmp_BMask_AllOnes           =     4,
441  FoldMskICmp_BMask_NotAllOnes        =     8,
442  FoldMskICmp_Mask_AllZeroes          =    16,
443  FoldMskICmp_Mask_NotAllZeroes       =    32,
444  FoldMskICmp_AMask_Mixed             =    64,
445  FoldMskICmp_AMask_NotMixed          =   128,
446  FoldMskICmp_BMask_Mixed             =   256,
447  FoldMskICmp_BMask_NotMixed          =   512
448};
449
450/// Return the set of pattern classes (from MaskedICmpType)
451/// that (icmp SCC (A & B), C) satisfies.
452static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
453                                    ICmpInst::Predicate SCC)
454{
455  ConstantInt *ACst = dyn_cast<ConstantInt>(A);
456  ConstantInt *BCst = dyn_cast<ConstantInt>(B);
457  ConstantInt *CCst = dyn_cast<ConstantInt>(C);
458  bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
459  bool icmp_abit = (ACst && !ACst->isZero() &&
460                    ACst->getValue().isPowerOf2());
461  bool icmp_bbit = (BCst && !BCst->isZero() &&
462                    BCst->getValue().isPowerOf2());
463  unsigned result = 0;
464  if (CCst && CCst->isZero()) {
465    // if C is zero, then both A and B qualify as mask
466    result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
467                          FoldMskICmp_Mask_AllZeroes |
468                          FoldMskICmp_AMask_Mixed |
469                          FoldMskICmp_BMask_Mixed)
470                       : (FoldMskICmp_Mask_NotAllZeroes |
471                          FoldMskICmp_Mask_NotAllZeroes |
472                          FoldMskICmp_AMask_NotMixed |
473                          FoldMskICmp_BMask_NotMixed));
474    if (icmp_abit)
475      result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
476                            FoldMskICmp_AMask_NotMixed)
477                         : (FoldMskICmp_AMask_AllOnes |
478                            FoldMskICmp_AMask_Mixed));
479    if (icmp_bbit)
480      result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
481                            FoldMskICmp_BMask_NotMixed)
482                         : (FoldMskICmp_BMask_AllOnes |
483                            FoldMskICmp_BMask_Mixed));
484    return result;
485  }
486  if (A == C) {
487    result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
488                          FoldMskICmp_AMask_Mixed)
489                       : (FoldMskICmp_AMask_NotAllOnes |
490                          FoldMskICmp_AMask_NotMixed));
491    if (icmp_abit)
492      result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
493                            FoldMskICmp_AMask_NotMixed)
494                         : (FoldMskICmp_Mask_AllZeroes |
495                            FoldMskICmp_AMask_Mixed));
496  } else if (ACst && CCst &&
497             ConstantExpr::getAnd(ACst, CCst) == CCst) {
498    result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
499                       : FoldMskICmp_AMask_NotMixed);
500  }
501  if (B == C) {
502    result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
503                          FoldMskICmp_BMask_Mixed)
504                       : (FoldMskICmp_BMask_NotAllOnes |
505                          FoldMskICmp_BMask_NotMixed));
506    if (icmp_bbit)
507      result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
508                            FoldMskICmp_BMask_NotMixed)
509                         : (FoldMskICmp_Mask_AllZeroes |
510                            FoldMskICmp_BMask_Mixed));
511  } else if (BCst && CCst &&
512             ConstantExpr::getAnd(BCst, CCst) == CCst) {
513    result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
514                       : FoldMskICmp_BMask_NotMixed);
515  }
516  return result;
517}
518
519/// Convert an analysis of a masked ICmp into its equivalent if all boolean
520/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
521/// is adjacent to the corresponding normal flag (recording ==), this just
522/// involves swapping those bits over.
523static unsigned conjugateICmpMask(unsigned Mask) {
524  unsigned NewMask;
525  NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
526                     FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
527                     FoldMskICmp_BMask_Mixed))
528            << 1;
529
530  NewMask |=
531      (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
532               FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
533               FoldMskICmp_BMask_NotMixed))
534      >> 1;
535
536  return NewMask;
537}
538
539/// Decompose an icmp into the form ((X & Y) pred Z) if possible.
540/// The returned predicate is either == or !=. Returns false if
541/// decomposition fails.
542static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
543                                 Value *&X, Value *&Y, Value *&Z) {
544  ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
545  if (!C)
546    return false;
547
548  switch (I->getPredicate()) {
549  default:
550    return false;
551  case ICmpInst::ICMP_SLT:
552    // X < 0 is equivalent to (X & SignBit) != 0.
553    if (!C->isZero())
554      return false;
555    Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
556    Pred = ICmpInst::ICMP_NE;
557    break;
558  case ICmpInst::ICMP_SGT:
559    // X > -1 is equivalent to (X & SignBit) == 0.
560    if (!C->isAllOnesValue())
561      return false;
562    Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
563    Pred = ICmpInst::ICMP_EQ;
564    break;
565  case ICmpInst::ICMP_ULT:
566    // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
567    if (!C->getValue().isPowerOf2())
568      return false;
569    Y = ConstantInt::get(I->getContext(), -C->getValue());
570    Pred = ICmpInst::ICMP_EQ;
571    break;
572  case ICmpInst::ICMP_UGT:
573    // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
574    if (!(C->getValue() + 1).isPowerOf2())
575      return false;
576    Y = ConstantInt::get(I->getContext(), ~C->getValue());
577    Pred = ICmpInst::ICMP_NE;
578    break;
579  }
580
581  X = I->getOperand(0);
582  Z = ConstantInt::getNullValue(C->getType());
583  return true;
584}
585
586/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
587/// Return the set of pattern classes (from MaskedICmpType)
588/// that both LHS and RHS satisfy.
589static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
590                                             Value*& B, Value*& C,
591                                             Value*& D, Value*& E,
592                                             ICmpInst *LHS, ICmpInst *RHS,
593                                             ICmpInst::Predicate &LHSCC,
594                                             ICmpInst::Predicate &RHSCC) {
595  if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
596  // vectors are not (yet?) supported
597  if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
598
599  // Here comes the tricky part:
600  // LHS might be of the form L11 & L12 == X, X == L21 & L22,
601  // and L11 & L12 == L21 & L22. The same goes for RHS.
602  // Now we must find those components L** and R**, that are equal, so
603  // that we can extract the parameters A, B, C, D, and E for the canonical
604  // above.
605  Value *L1 = LHS->getOperand(0);
606  Value *L2 = LHS->getOperand(1);
607  Value *L11,*L12,*L21,*L22;
608  // Check whether the icmp can be decomposed into a bit test.
609  if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
610    L21 = L22 = L1 = nullptr;
611  } else {
612    // Look for ANDs in the LHS icmp.
613    if (!L1->getType()->isIntegerTy()) {
614      // You can icmp pointers, for example. They really aren't masks.
615      L11 = L12 = nullptr;
616    } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
617      // Any icmp can be viewed as being trivially masked; if it allows us to
618      // remove one, it's worth it.
619      L11 = L1;
620      L12 = Constant::getAllOnesValue(L1->getType());
621    }
622
623    if (!L2->getType()->isIntegerTy()) {
624      // You can icmp pointers, for example. They really aren't masks.
625      L21 = L22 = nullptr;
626    } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
627      L21 = L2;
628      L22 = Constant::getAllOnesValue(L2->getType());
629    }
630  }
631
632  // Bail if LHS was a icmp that can't be decomposed into an equality.
633  if (!ICmpInst::isEquality(LHSCC))
634    return 0;
635
636  Value *R1 = RHS->getOperand(0);
637  Value *R2 = RHS->getOperand(1);
638  Value *R11,*R12;
639  bool ok = false;
640  if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
641    if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
642      A = R11; D = R12;
643    } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
644      A = R12; D = R11;
645    } else {
646      return 0;
647    }
648    E = R2; R1 = nullptr; ok = true;
649  } else if (R1->getType()->isIntegerTy()) {
650    if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
651      // As before, model no mask as a trivial mask if it'll let us do an
652      // optimization.
653      R11 = R1;
654      R12 = Constant::getAllOnesValue(R1->getType());
655    }
656
657    if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
658      A = R11; D = R12; E = R2; ok = true;
659    } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
660      A = R12; D = R11; E = R2; ok = true;
661    }
662  }
663
664  // Bail if RHS was a icmp that can't be decomposed into an equality.
665  if (!ICmpInst::isEquality(RHSCC))
666    return 0;
667
668  // Look for ANDs in on the right side of the RHS icmp.
669  if (!ok && R2->getType()->isIntegerTy()) {
670    if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
671      R11 = R2;
672      R12 = Constant::getAllOnesValue(R2->getType());
673    }
674
675    if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
676      A = R11; D = R12; E = R1; ok = true;
677    } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
678      A = R12; D = R11; E = R1; ok = true;
679    } else {
680      return 0;
681    }
682  }
683  if (!ok)
684    return 0;
685
686  if (L11 == A) {
687    B = L12; C = L2;
688  } else if (L12 == A) {
689    B = L11; C = L2;
690  } else if (L21 == A) {
691    B = L22; C = L1;
692  } else if (L22 == A) {
693    B = L21; C = L1;
694  }
695
696  unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
697  unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
698  return left_type & right_type;
699}
700
701/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
702/// into a single (icmp(A & X) ==/!= Y).
703static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
704                                     llvm::InstCombiner::BuilderTy *Builder) {
705  Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
706  ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
707  unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
708                                               LHSCC, RHSCC);
709  if (mask == 0) return nullptr;
710  assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
711         "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
712
713  // In full generality:
714  //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
715  // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
716  //
717  // If the latter can be converted into (icmp (A & X) Op Y) then the former is
718  // equivalent to (icmp (A & X) !Op Y).
719  //
720  // Therefore, we can pretend for the rest of this function that we're dealing
721  // with the conjunction, provided we flip the sense of any comparisons (both
722  // input and output).
723
724  // In most cases we're going to produce an EQ for the "&&" case.
725  ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
726  if (!IsAnd) {
727    // Convert the masking analysis into its equivalent with negated
728    // comparisons.
729    mask = conjugateICmpMask(mask);
730  }
731
732  if (mask & FoldMskICmp_Mask_AllZeroes) {
733    // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
734    // -> (icmp eq (A & (B|D)), 0)
735    Value *newOr = Builder->CreateOr(B, D);
736    Value *newAnd = Builder->CreateAnd(A, newOr);
737    // we can't use C as zero, because we might actually handle
738    //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
739    // with B and D, having a single bit set
740    Value *zero = Constant::getNullValue(A->getType());
741    return Builder->CreateICmp(NEWCC, newAnd, zero);
742  }
743  if (mask & FoldMskICmp_BMask_AllOnes) {
744    // (icmp eq (A & B), B) & (icmp eq (A & D), D)
745    // -> (icmp eq (A & (B|D)), (B|D))
746    Value *newOr = Builder->CreateOr(B, D);
747    Value *newAnd = Builder->CreateAnd(A, newOr);
748    return Builder->CreateICmp(NEWCC, newAnd, newOr);
749  }
750  if (mask & FoldMskICmp_AMask_AllOnes) {
751    // (icmp eq (A & B), A) & (icmp eq (A & D), A)
752    // -> (icmp eq (A & (B&D)), A)
753    Value *newAnd1 = Builder->CreateAnd(B, D);
754    Value *newAnd = Builder->CreateAnd(A, newAnd1);
755    return Builder->CreateICmp(NEWCC, newAnd, A);
756  }
757
758  // Remaining cases assume at least that B and D are constant, and depend on
759  // their actual values. This isn't strictly, necessary, just a "handle the
760  // easy cases for now" decision.
761  ConstantInt *BCst = dyn_cast<ConstantInt>(B);
762  if (!BCst) return nullptr;
763  ConstantInt *DCst = dyn_cast<ConstantInt>(D);
764  if (!DCst) return nullptr;
765
766  if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
767    // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
768    // (icmp ne (A & B), B) & (icmp ne (A & D), D)
769    //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
770    // Only valid if one of the masks is a superset of the other (check "B&D" is
771    // the same as either B or D).
772    APInt NewMask = BCst->getValue() & DCst->getValue();
773
774    if (NewMask == BCst->getValue())
775      return LHS;
776    else if (NewMask == DCst->getValue())
777      return RHS;
778  }
779  if (mask & FoldMskICmp_AMask_NotAllOnes) {
780    // (icmp ne (A & B), B) & (icmp ne (A & D), D)
781    //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
782    // Only valid if one of the masks is a superset of the other (check "B|D" is
783    // the same as either B or D).
784    APInt NewMask = BCst->getValue() | DCst->getValue();
785
786    if (NewMask == BCst->getValue())
787      return LHS;
788    else if (NewMask == DCst->getValue())
789      return RHS;
790  }
791  if (mask & FoldMskICmp_BMask_Mixed) {
792    // (icmp eq (A & B), C) & (icmp eq (A & D), E)
793    // We already know that B & C == C && D & E == E.
794    // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
795    // C and E, which are shared by both the mask B and the mask D, don't
796    // contradict, then we can transform to
797    // -> (icmp eq (A & (B|D)), (C|E))
798    // Currently, we only handle the case of B, C, D, and E being constant.
799    // we can't simply use C and E, because we might actually handle
800    //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
801    // with B and D, having a single bit set
802    ConstantInt *CCst = dyn_cast<ConstantInt>(C);
803    if (!CCst) return nullptr;
804    ConstantInt *ECst = dyn_cast<ConstantInt>(E);
805    if (!ECst) return nullptr;
806    if (LHSCC != NEWCC)
807      CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
808    if (RHSCC != NEWCC)
809      ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
810    // if there is a conflict we should actually return a false for the
811    // whole construct
812    if (((BCst->getValue() & DCst->getValue()) &
813         (CCst->getValue() ^ ECst->getValue())) != 0)
814      return ConstantInt::get(LHS->getType(), !IsAnd);
815    Value *newOr1 = Builder->CreateOr(B, D);
816    Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
817    Value *newAnd = Builder->CreateAnd(A, newOr1);
818    return Builder->CreateICmp(NEWCC, newAnd, newOr2);
819  }
820  return nullptr;
821}
822
823/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
824/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
825/// If \p Inverted is true then the check is for the inverted range, e.g.
826/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
827Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
828                                        bool Inverted) {
829  // Check the lower range comparison, e.g. x >= 0
830  // InstCombine already ensured that if there is a constant it's on the RHS.
831  ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
832  if (!RangeStart)
833    return nullptr;
834
835  ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
836                               Cmp0->getPredicate());
837
838  // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
839  if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
840        (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
841    return nullptr;
842
843  ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
844                               Cmp1->getPredicate());
845
846  Value *Input = Cmp0->getOperand(0);
847  Value *RangeEnd;
848  if (Cmp1->getOperand(0) == Input) {
849    // For the upper range compare we have: icmp x, n
850    RangeEnd = Cmp1->getOperand(1);
851  } else if (Cmp1->getOperand(1) == Input) {
852    // For the upper range compare we have: icmp n, x
853    RangeEnd = Cmp1->getOperand(0);
854    Pred1 = ICmpInst::getSwappedPredicate(Pred1);
855  } else {
856    return nullptr;
857  }
858
859  // Check the upper range comparison, e.g. x < n
860  ICmpInst::Predicate NewPred;
861  switch (Pred1) {
862    case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
863    case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
864    default: return nullptr;
865  }
866
867  // This simplification is only valid if the upper range is not negative.
868  bool IsNegative, IsNotNegative;
869  ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
870  if (!IsNotNegative)
871    return nullptr;
872
873  if (Inverted)
874    NewPred = ICmpInst::getInversePredicate(NewPred);
875
876  return Builder->CreateICmp(NewPred, Input, RangeEnd);
877}
878
879/// Fold (icmp)&(icmp) if possible.
880Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
881  ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
882
883  // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
884  if (PredicatesFoldable(LHSCC, RHSCC)) {
885    if (LHS->getOperand(0) == RHS->getOperand(1) &&
886        LHS->getOperand(1) == RHS->getOperand(0))
887      LHS->swapOperands();
888    if (LHS->getOperand(0) == RHS->getOperand(0) &&
889        LHS->getOperand(1) == RHS->getOperand(1)) {
890      Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
891      unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
892      bool isSigned = LHS->isSigned() || RHS->isSigned();
893      return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
894    }
895  }
896
897  // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
898  if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
899    return V;
900
901  // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
902  if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
903    return V;
904
905  // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
906  if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
907    return V;
908
909  // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
910  Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
911  ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
912  ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
913  if (!LHSCst || !RHSCst) return nullptr;
914
915  if (LHSCst == RHSCst && LHSCC == RHSCC) {
916    // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
917    // where C is a power of 2
918    if (LHSCC == ICmpInst::ICMP_ULT &&
919        LHSCst->getValue().isPowerOf2()) {
920      Value *NewOr = Builder->CreateOr(Val, Val2);
921      return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
922    }
923
924    // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
925    if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
926      Value *NewOr = Builder->CreateOr(Val, Val2);
927      return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
928    }
929  }
930
931  // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
932  // where CMAX is the all ones value for the truncated type,
933  // iff the lower bits of C2 and CA are zero.
934  if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
935      LHS->hasOneUse() && RHS->hasOneUse()) {
936    Value *V;
937    ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
938
939    // (trunc x) == C1 & (and x, CA) == C2
940    // (and x, CA) == C2 & (trunc x) == C1
941    if (match(Val2, m_Trunc(m_Value(V))) &&
942        match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
943      SmallCst = RHSCst;
944      BigCst = LHSCst;
945    } else if (match(Val, m_Trunc(m_Value(V))) &&
946               match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
947      SmallCst = LHSCst;
948      BigCst = RHSCst;
949    }
950
951    if (SmallCst && BigCst) {
952      unsigned BigBitSize = BigCst->getType()->getBitWidth();
953      unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
954
955      // Check that the low bits are zero.
956      APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
957      if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
958        Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
959        APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
960        Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
961        return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
962      }
963    }
964  }
965
966  // From here on, we only handle:
967  //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
968  if (Val != Val2) return nullptr;
969
970  // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
971  if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
972      RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
973      LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
974      RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
975    return nullptr;
976
977  // Make a constant range that's the intersection of the two icmp ranges.
978  // If the intersection is empty, we know that the result is false.
979  ConstantRange LHSRange =
980      ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
981  ConstantRange RHSRange =
982      ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
983
984  if (LHSRange.intersectWith(RHSRange).isEmptySet())
985    return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
986
987  // We can't fold (ugt x, C) & (sgt x, C2).
988  if (!PredicatesFoldable(LHSCC, RHSCC))
989    return nullptr;
990
991  // Ensure that the larger constant is on the RHS.
992  bool ShouldSwap;
993  if (CmpInst::isSigned(LHSCC) ||
994      (ICmpInst::isEquality(LHSCC) &&
995       CmpInst::isSigned(RHSCC)))
996    ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
997  else
998    ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
999
1000  if (ShouldSwap) {
1001    std::swap(LHS, RHS);
1002    std::swap(LHSCst, RHSCst);
1003    std::swap(LHSCC, RHSCC);
1004  }
1005
1006  // At this point, we know we have two icmp instructions
1007  // comparing a value against two constants and and'ing the result
1008  // together.  Because of the above check, we know that we only have
1009  // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1010  // (from the icmp folding check above), that the two constants
1011  // are not equal and that the larger constant is on the RHS
1012  assert(LHSCst != RHSCst && "Compares not folded above?");
1013
1014  switch (LHSCC) {
1015  default: llvm_unreachable("Unknown integer condition code!");
1016  case ICmpInst::ICMP_EQ:
1017    switch (RHSCC) {
1018    default: llvm_unreachable("Unknown integer condition code!");
1019    case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
1020    case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
1021    case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
1022      return LHS;
1023    }
1024  case ICmpInst::ICMP_NE:
1025    switch (RHSCC) {
1026    default: llvm_unreachable("Unknown integer condition code!");
1027    case ICmpInst::ICMP_ULT:
1028      if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
1029        return Builder->CreateICmpULT(Val, LHSCst);
1030      if (LHSCst->isNullValue())    // (X !=  0 & X u< 14) -> X-1 u< 13
1031        return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1032      break;                        // (X != 13 & X u< 15) -> no change
1033    case ICmpInst::ICMP_SLT:
1034      if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
1035        return Builder->CreateICmpSLT(Val, LHSCst);
1036      break;                        // (X != 13 & X s< 15) -> no change
1037    case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
1038    case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
1039    case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
1040      return RHS;
1041    case ICmpInst::ICMP_NE:
1042      // Special case to get the ordering right when the values wrap around
1043      // zero.
1044      if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
1045        std::swap(LHSCst, RHSCst);
1046      if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1047        Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1048        Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1049        return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1050                                      Val->getName()+".cmp");
1051      }
1052      break;                        // (X != 13 & X != 15) -> no change
1053    }
1054    break;
1055  case ICmpInst::ICMP_ULT:
1056    switch (RHSCC) {
1057    default: llvm_unreachable("Unknown integer condition code!");
1058    case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
1059    case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
1060      return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1061    case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
1062      break;
1063    case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
1064    case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
1065      return LHS;
1066    case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
1067      break;
1068    }
1069    break;
1070  case ICmpInst::ICMP_SLT:
1071    switch (RHSCC) {
1072    default: llvm_unreachable("Unknown integer condition code!");
1073    case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
1074      break;
1075    case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
1076    case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
1077      return LHS;
1078    case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
1079      break;
1080    }
1081    break;
1082  case ICmpInst::ICMP_UGT:
1083    switch (RHSCC) {
1084    default: llvm_unreachable("Unknown integer condition code!");
1085    case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
1086    case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
1087      return RHS;
1088    case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
1089      break;
1090    case ICmpInst::ICMP_NE:
1091      if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
1092        return Builder->CreateICmp(LHSCC, Val, RHSCst);
1093      break;                        // (X u> 13 & X != 15) -> no change
1094    case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
1095      return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1096    case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
1097      break;
1098    }
1099    break;
1100  case ICmpInst::ICMP_SGT:
1101    switch (RHSCC) {
1102    default: llvm_unreachable("Unknown integer condition code!");
1103    case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
1104    case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
1105      return RHS;
1106    case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
1107      break;
1108    case ICmpInst::ICMP_NE:
1109      if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1110        return Builder->CreateICmp(LHSCC, Val, RHSCst);
1111      break;                        // (X s> 13 & X != 15) -> no change
1112    case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
1113      return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1114    case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
1115      break;
1116    }
1117    break;
1118  }
1119
1120  return nullptr;
1121}
1122
1123/// Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of instcombine, this returns
1124/// a Value which should already be inserted into the function.
1125Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1126  if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1127      RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1128    if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1129      return nullptr;
1130
1131    // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
1132    if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1133      if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1134        // If either of the constants are nans, then the whole thing returns
1135        // false.
1136        if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1137          return Builder->getFalse();
1138        return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1139      }
1140
1141    // Handle vector zeros.  This occurs because the canonical form of
1142    // "fcmp ord x,x" is "fcmp ord x, 0".
1143    if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1144        isa<ConstantAggregateZero>(RHS->getOperand(1)))
1145      return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1146    return nullptr;
1147  }
1148
1149  Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1150  Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1151  FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1152
1153
1154  if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1155    // Swap RHS operands to match LHS.
1156    Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1157    std::swap(Op1LHS, Op1RHS);
1158  }
1159
1160  if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1161    // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1162    if (Op0CC == Op1CC)
1163      return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1164    if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1165      return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1166    if (Op0CC == FCmpInst::FCMP_TRUE)
1167      return RHS;
1168    if (Op1CC == FCmpInst::FCMP_TRUE)
1169      return LHS;
1170
1171    bool Op0Ordered;
1172    bool Op1Ordered;
1173    unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1174    unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1175    // uno && ord -> false
1176    if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1177        return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1178    if (Op1Pred == 0) {
1179      std::swap(LHS, RHS);
1180      std::swap(Op0Pred, Op1Pred);
1181      std::swap(Op0Ordered, Op1Ordered);
1182    }
1183    if (Op0Pred == 0) {
1184      // uno && ueq -> uno && (uno || eq) -> uno
1185      // ord && olt -> ord && (ord && lt) -> olt
1186      if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1187        return LHS;
1188      if (Op0Ordered && (Op0Ordered == Op1Ordered))
1189        return RHS;
1190
1191      // uno && oeq -> uno && (ord && eq) -> false
1192      if (!Op0Ordered)
1193        return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1194      // ord && ueq -> ord && (uno || eq) -> oeq
1195      return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1196    }
1197  }
1198
1199  return nullptr;
1200}
1201
1202/// Match De Morgan's Laws:
1203/// (~A & ~B) == (~(A | B))
1204/// (~A | ~B) == (~(A & B))
1205static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1206                                       InstCombiner::BuilderTy *Builder) {
1207  auto Opcode = I.getOpcode();
1208  assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1209         "Trying to match De Morgan's Laws with something other than and/or");
1210  // Flip the logic operation.
1211  if (Opcode == Instruction::And)
1212    Opcode = Instruction::Or;
1213  else
1214    Opcode = Instruction::And;
1215
1216  Value *Op0 = I.getOperand(0);
1217  Value *Op1 = I.getOperand(1);
1218  // TODO: Use pattern matchers instead of dyn_cast.
1219  if (Value *Op0NotVal = dyn_castNotVal(Op0))
1220    if (Value *Op1NotVal = dyn_castNotVal(Op1))
1221      if (Op0->hasOneUse() && Op1->hasOneUse()) {
1222        Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1223                                              I.getName() + ".demorgan");
1224        return BinaryOperator::CreateNot(LogicOp);
1225      }
1226
1227  // De Morgan's Law in disguise:
1228  // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1229  // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1230  Value *A = nullptr;
1231  Value *B = nullptr;
1232  ConstantInt *C1 = nullptr;
1233  if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1234      match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1235    // TODO: This check could be loosened to handle different type sizes.
1236    // Alternatively, we could fix the definition of m_Not to recognize a not
1237    // operation hidden by a zext?
1238    if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1239        C1->isOne()) {
1240      Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1241                                            I.getName() + ".demorgan");
1242      Value *Not = Builder->CreateNot(LogicOp);
1243      return CastInst::CreateZExtOrBitCast(Not, I.getType());
1244    }
1245  }
1246
1247  return nullptr;
1248}
1249
1250Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1251  bool Changed = SimplifyAssociativeOrCommutative(I);
1252  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1253
1254  if (Value *V = SimplifyVectorOp(I))
1255    return ReplaceInstUsesWith(I, V);
1256
1257  if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
1258    return ReplaceInstUsesWith(I, V);
1259
1260  // (A|B)&(A|C) -> A|(B&C) etc
1261  if (Value *V = SimplifyUsingDistributiveLaws(I))
1262    return ReplaceInstUsesWith(I, V);
1263
1264  // See if we can simplify any instructions used by the instruction whose sole
1265  // purpose is to compute bits we don't care about.
1266  if (SimplifyDemandedInstructionBits(I))
1267    return &I;
1268
1269  if (Value *V = SimplifyBSwap(I))
1270    return ReplaceInstUsesWith(I, V);
1271
1272  if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1273    const APInt &AndRHSMask = AndRHS->getValue();
1274
1275    // Optimize a variety of ((val OP C1) & C2) combinations...
1276    if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1277      Value *Op0LHS = Op0I->getOperand(0);
1278      Value *Op0RHS = Op0I->getOperand(1);
1279      switch (Op0I->getOpcode()) {
1280      default: break;
1281      case Instruction::Xor:
1282      case Instruction::Or: {
1283        // If the mask is only needed on one incoming arm, push it up.
1284        if (!Op0I->hasOneUse()) break;
1285
1286        APInt NotAndRHS(~AndRHSMask);
1287        if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1288          // Not masking anything out for the LHS, move to RHS.
1289          Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1290                                             Op0RHS->getName()+".masked");
1291          return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1292        }
1293        if (!isa<Constant>(Op0RHS) &&
1294            MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1295          // Not masking anything out for the RHS, move to LHS.
1296          Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1297                                             Op0LHS->getName()+".masked");
1298          return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1299        }
1300
1301        break;
1302      }
1303      case Instruction::Add:
1304        // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1305        // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1306        // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1307        if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1308          return BinaryOperator::CreateAnd(V, AndRHS);
1309        if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1310          return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1311        break;
1312
1313      case Instruction::Sub:
1314        // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1315        // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1316        // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1317        if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1318          return BinaryOperator::CreateAnd(V, AndRHS);
1319
1320        // -x & 1 -> x & 1
1321        if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1322          return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1323
1324        // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1325        // has 1's for all bits that the subtraction with A might affect.
1326        if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1327          uint32_t BitWidth = AndRHSMask.getBitWidth();
1328          uint32_t Zeros = AndRHSMask.countLeadingZeros();
1329          APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1330
1331          if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
1332            Value *NewNeg = Builder->CreateNeg(Op0RHS);
1333            return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1334          }
1335        }
1336        break;
1337
1338      case Instruction::Shl:
1339      case Instruction::LShr:
1340        // (1 << x) & 1 --> zext(x == 0)
1341        // (1 >> x) & 1 --> zext(x == 0)
1342        if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1343          Value *NewICmp =
1344            Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1345          return new ZExtInst(NewICmp, I.getType());
1346        }
1347        break;
1348      }
1349
1350      if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1351        if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1352          return Res;
1353    }
1354
1355    // If this is an integer truncation, and if the source is an 'and' with
1356    // immediate, transform it.  This frequently occurs for bitfield accesses.
1357    {
1358      Value *X = nullptr; ConstantInt *YC = nullptr;
1359      if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1360        // Change: and (trunc (and X, YC) to T), C2
1361        // into  : and (trunc X to T), trunc(YC) & C2
1362        // This will fold the two constants together, which may allow
1363        // other simplifications.
1364        Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1365        Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1366        C3 = ConstantExpr::getAnd(C3, AndRHS);
1367        return BinaryOperator::CreateAnd(NewCast, C3);
1368      }
1369    }
1370
1371    // Try to fold constant and into select arguments.
1372    if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1373      if (Instruction *R = FoldOpIntoSelect(I, SI))
1374        return R;
1375    if (isa<PHINode>(Op0))
1376      if (Instruction *NV = FoldOpIntoPhi(I))
1377        return NV;
1378  }
1379
1380  if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1381    return DeMorgan;
1382
1383  {
1384    Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
1385    // (A|B) & ~(A&B) -> A^B
1386    if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1387        match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1388        ((A == C && B == D) || (A == D && B == C)))
1389      return BinaryOperator::CreateXor(A, B);
1390
1391    // ~(A&B) & (A|B) -> A^B
1392    if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1393        match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1394        ((A == C && B == D) || (A == D && B == C)))
1395      return BinaryOperator::CreateXor(A, B);
1396
1397    // A&(A^B) => A & ~B
1398    {
1399      Value *tmpOp0 = Op0;
1400      Value *tmpOp1 = Op1;
1401      if (Op0->hasOneUse() &&
1402          match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1403        if (A == Op1 || B == Op1 ) {
1404          tmpOp1 = Op0;
1405          tmpOp0 = Op1;
1406          // Simplify below
1407        }
1408      }
1409
1410      if (tmpOp1->hasOneUse() &&
1411          match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1412        if (B == tmpOp0) {
1413          std::swap(A, B);
1414        }
1415        // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1416        // A is originally -1 (or a vector of -1 and undefs), then we enter
1417        // an endless loop. By checking that A is non-constant we ensure that
1418        // we will never get to the loop.
1419        if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1420          return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1421      }
1422    }
1423
1424    // (A&((~A)|B)) -> A&B
1425    if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1426        match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1427      return BinaryOperator::CreateAnd(A, Op1);
1428    if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1429        match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1430      return BinaryOperator::CreateAnd(A, Op0);
1431
1432    // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1433    if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1434      if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1435        if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1436          return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1437
1438    // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1439    if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1440      if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1441        if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1442          return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1443
1444    // (A | B) & ((~A) ^ B) -> (A & B)
1445    if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1446        match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1447      return BinaryOperator::CreateAnd(A, B);
1448
1449    // ((~A) ^ B) & (A | B) -> (A & B)
1450    if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1451        match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1452      return BinaryOperator::CreateAnd(A, B);
1453  }
1454
1455  {
1456    ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1457    ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1458    if (LHS && RHS)
1459      if (Value *Res = FoldAndOfICmps(LHS, RHS))
1460        return ReplaceInstUsesWith(I, Res);
1461
1462    // TODO: Make this recursive; it's a little tricky because an arbitrary
1463    // number of 'and' instructions might have to be created.
1464    Value *X, *Y;
1465    if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1466      if (auto *Cmp = dyn_cast<ICmpInst>(X))
1467        if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1468          return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1469      if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1470        if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1471          return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1472    }
1473    if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1474      if (auto *Cmp = dyn_cast<ICmpInst>(X))
1475        if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1476          return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1477      if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1478        if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1479          return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1480    }
1481  }
1482
1483  // If and'ing two fcmp, try combine them into one.
1484  if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1485    if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1486      if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1487        return ReplaceInstUsesWith(I, Res);
1488
1489
1490  if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1491    Value *Op0COp = Op0C->getOperand(0);
1492    Type *SrcTy = Op0COp->getType();
1493    // fold (and (cast A), (cast B)) -> (cast (and A, B))
1494    if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1495      if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1496          SrcTy == Op1C->getOperand(0)->getType() &&
1497          SrcTy->isIntOrIntVectorTy()) {
1498        Value *Op1COp = Op1C->getOperand(0);
1499
1500        // Only do this if the casts both really cause code to be generated.
1501        if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1502            ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1503          Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1504          return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1505        }
1506
1507        // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1508        // cast is otherwise not optimizable.  This happens for vector sexts.
1509        if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1510          if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1511            if (Value *Res = FoldAndOfICmps(LHS, RHS))
1512              return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1513
1514        // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1515        // cast is otherwise not optimizable.  This happens for vector sexts.
1516        if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1517          if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1518            if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1519              return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1520      }
1521    }
1522
1523    // If we are masking off the sign bit of a floating-point value, convert
1524    // this to the canonical fabs intrinsic call and cast back to integer.
1525    // The backend should know how to optimize fabs().
1526    // TODO: This transform should also apply to vectors.
1527    ConstantInt *CI;
1528    if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
1529        match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
1530      Module *M = I.getModule();
1531      Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
1532      Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
1533      return CastInst::CreateBitOrPointerCast(Call, I.getType());
1534    }
1535  }
1536
1537  {
1538    Value *X = nullptr;
1539    bool OpsSwapped = false;
1540    // Canonicalize SExt or Not to the LHS
1541    if (match(Op1, m_SExt(m_Value())) ||
1542        match(Op1, m_Not(m_Value()))) {
1543      std::swap(Op0, Op1);
1544      OpsSwapped = true;
1545    }
1546
1547    // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1548    if (match(Op0, m_SExt(m_Value(X))) &&
1549        X->getType()->getScalarType()->isIntegerTy(1)) {
1550      Value *Zero = Constant::getNullValue(Op1->getType());
1551      return SelectInst::Create(X, Op1, Zero);
1552    }
1553
1554    // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1555    if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1556        X->getType()->getScalarType()->isIntegerTy(1)) {
1557      Value *Zero = Constant::getNullValue(Op0->getType());
1558      return SelectInst::Create(X, Zero, Op1);
1559    }
1560
1561    if (OpsSwapped)
1562      std::swap(Op0, Op1);
1563  }
1564
1565  return Changed ? &I : nullptr;
1566}
1567
1568
1569/// Analyze the specified subexpression and see if it is capable of providing
1570/// pieces of a bswap or bitreverse. The subexpression provides a potential
1571/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
1572/// the output of the expression came from a corresponding bit in some other
1573/// value. This function is recursive, and the end result is a mapping of
1574/// (value, bitnumber) to bitnumber. It is the caller's responsibility to
1575/// validate that all `value`s are identical and that the bitnumber to bitnumber
1576/// mapping is correct for a bswap or bitreverse.
1577///
1578/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
1579/// that the expression deposits the low byte of %X into the high byte of the
1580/// result and that all other bits are zero. This expression is accepted,
1581/// BitValues[24-31] are set to %X and BitProvenance[24-31] are set to [0-7].
1582///
1583/// This function returns true if the match was unsuccessful and false if so.
1584/// On entry to the function the "OverallLeftShift" is a signed integer value
1585/// indicating the number of bits that the subexpression is later shifted.  For
1586/// example, if the expression is later right shifted by 16 bits, the
1587/// OverallLeftShift value would be -16 on entry.  This is used to specify which
1588/// bits of BitValues are actually being set.
1589///
1590/// Similarly, BitMask is a bitmask where a bit is clear if its corresponding
1591/// bit is masked to zero by a user.  For example, in (X & 255), X will be
1592/// processed with a bytemask of 255. BitMask is always in the local
1593/// (OverallLeftShift) coordinate space.
1594///
1595static bool CollectBitParts(Value *V, int OverallLeftShift, APInt BitMask,
1596                            SmallVectorImpl<Value *> &BitValues,
1597                            SmallVectorImpl<int> &BitProvenance) {
1598  if (Instruction *I = dyn_cast<Instruction>(V)) {
1599    // If this is an or instruction, it may be an inner node of the bswap.
1600    if (I->getOpcode() == Instruction::Or)
1601      return CollectBitParts(I->getOperand(0), OverallLeftShift, BitMask,
1602                             BitValues, BitProvenance) ||
1603             CollectBitParts(I->getOperand(1), OverallLeftShift, BitMask,
1604                             BitValues, BitProvenance);
1605
1606    // If this is a logical shift by a constant, recurse with OverallLeftShift
1607    // and BitMask adjusted.
1608    if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1609      unsigned ShAmt =
1610          cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1611      // Ensure the shift amount is defined.
1612      if (ShAmt > BitValues.size())
1613        return true;
1614
1615      unsigned BitShift = ShAmt;
1616      if (I->getOpcode() == Instruction::Shl) {
1617        // X << C -> collect(X, +C)
1618        OverallLeftShift += BitShift;
1619        BitMask = BitMask.lshr(BitShift);
1620      } else {
1621        // X >>u C -> collect(X, -C)
1622        OverallLeftShift -= BitShift;
1623        BitMask = BitMask.shl(BitShift);
1624      }
1625
1626      if (OverallLeftShift >= (int)BitValues.size())
1627        return true;
1628      if (OverallLeftShift <= -(int)BitValues.size())
1629        return true;
1630
1631      return CollectBitParts(I->getOperand(0), OverallLeftShift, BitMask,
1632                             BitValues, BitProvenance);
1633    }
1634
1635    // If this is a logical 'and' with a mask that clears bits, clear the
1636    // corresponding bits in BitMask.
1637    if (I->getOpcode() == Instruction::And &&
1638        isa<ConstantInt>(I->getOperand(1))) {
1639      unsigned NumBits = BitValues.size();
1640      APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
1641      const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1642
1643      for (unsigned i = 0; i != NumBits; ++i, Bit <<= 1) {
1644        // If this bit is masked out by a later operation, we don't care what
1645        // the and mask is.
1646        if (BitMask[i] == 0)
1647          continue;
1648
1649        // If the AndMask is zero for this bit, clear the bit.
1650        APInt MaskB = AndMask & Bit;
1651        if (MaskB == 0) {
1652          BitMask.clearBit(i);
1653          continue;
1654        }
1655
1656        // Otherwise, this bit is kept.
1657      }
1658
1659      return CollectBitParts(I->getOperand(0), OverallLeftShift, BitMask,
1660                             BitValues, BitProvenance);
1661    }
1662  }
1663
1664  // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1665  // the input value to the bswap/bitreverse. To be part of a bswap or
1666  // bitreverse we must be demanding a contiguous range of bits from it.
1667  unsigned InputBitLen = BitMask.countPopulation();
1668  unsigned InputBitNo = BitMask.countTrailingZeros();
1669  if (BitMask.getBitWidth() - BitMask.countLeadingZeros() - InputBitNo !=
1670      InputBitLen)
1671    // Not a contiguous set range of bits!
1672    return true;
1673
1674  // We know we're moving a contiguous range of bits from the input to the
1675  // output. Record which bits in the output came from which bits in the input.
1676  unsigned DestBitNo = InputBitNo + OverallLeftShift;
1677  for (unsigned I = 0; I < InputBitLen; ++I)
1678    BitProvenance[DestBitNo + I] = InputBitNo + I;
1679
1680  // If the destination bit value is already defined, the values are or'd
1681  // together, which isn't a bswap/bitreverse (unless it's an or of the same
1682  // bits).
1683  if (BitValues[DestBitNo] && BitValues[DestBitNo] != V)
1684    return true;
1685  for (unsigned I = 0; I < InputBitLen; ++I)
1686    BitValues[DestBitNo + I] = V;
1687
1688  return false;
1689}
1690
1691static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
1692                                          unsigned BitWidth) {
1693  if (From % 8 != To % 8)
1694    return false;
1695  // Convert from bit indices to byte indices and check for a byte reversal.
1696  From >>= 3;
1697  To >>= 3;
1698  BitWidth >>= 3;
1699  return From == BitWidth - To - 1;
1700}
1701
1702static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
1703                                               unsigned BitWidth) {
1704  return From == BitWidth - To - 1;
1705}
1706
1707/// Given an OR instruction, check to see if this is a bswap or bitreverse
1708/// idiom. If so, insert the new intrinsic and return it.
1709Instruction *InstCombiner::MatchBSwapOrBitReverse(BinaryOperator &I) {
1710  IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1711  if (!ITy)
1712    return nullptr;   // Can't do vectors.
1713  unsigned BW = ITy->getBitWidth();
1714
1715  /// We keep track of which bit (BitProvenance) inside which value (BitValues)
1716  /// defines each bit in the result.
1717  SmallVector<Value *, 8> BitValues(BW, nullptr);
1718  SmallVector<int, 8> BitProvenance(BW, -1);
1719
1720  // Try to find all the pieces corresponding to the bswap.
1721  APInt BitMask = APInt::getAllOnesValue(BitValues.size());
1722  if (CollectBitParts(&I, 0, BitMask, BitValues, BitProvenance))
1723    return nullptr;
1724
1725  // Check to see if all of the bits come from the same value.
1726  Value *V = BitValues[0];
1727  if (!V) return nullptr;  // Didn't find a bit?  Must be zero.
1728
1729  if (!std::all_of(BitValues.begin(), BitValues.end(),
1730                   [&](const Value *X) { return X == V; }))
1731    return nullptr;
1732
1733  // Now, is the bit permutation correct for a bswap or a bitreverse? We can
1734  // only byteswap values with an even number of bytes.
1735  bool OKForBSwap = BW % 16 == 0, OKForBitReverse = true;;
1736  for (unsigned i = 0, e = BitValues.size(); i != e; ++i) {
1737    OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[i], i, BW);
1738    OKForBitReverse &=
1739        bitTransformIsCorrectForBitReverse(BitProvenance[i], i, BW);
1740  }
1741
1742  Intrinsic::ID Intrin;
1743  if (OKForBSwap)
1744    Intrin = Intrinsic::bswap;
1745  else if (OKForBitReverse)
1746    Intrin = Intrinsic::bitreverse;
1747  else
1748    return nullptr;
1749
1750  Function *F = Intrinsic::getDeclaration(I.getModule(), Intrin, ITy);
1751  return CallInst::Create(F, V);
1752}
1753
1754/// We have an expression of the form (A&C)|(B&D).  Check if A is (cond?-1:0)
1755/// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
1756/// expression to "cond ? C : D or B".
1757static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1758                                         Value *C, Value *D) {
1759  // If A is not a select of -1/0, this cannot match.
1760  Value *Cond = nullptr;
1761  if (!match(A, m_SExt(m_Value(Cond))) ||
1762      !Cond->getType()->isIntegerTy(1))
1763    return nullptr;
1764
1765  // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1766  if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1767    return SelectInst::Create(Cond, C, B);
1768  if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1769    return SelectInst::Create(Cond, C, B);
1770
1771  // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1772  if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1773    return SelectInst::Create(Cond, C, D);
1774  if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1775    return SelectInst::Create(Cond, C, D);
1776  return nullptr;
1777}
1778
1779/// Fold (icmp)|(icmp) if possible.
1780Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1781                                   Instruction *CxtI) {
1782  ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1783
1784  // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
1785  // if K1 and K2 are a one-bit mask.
1786  ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1787  ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1788
1789  if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1790      RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1791
1792    BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1793    BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1794    if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1795        LAnd->getOpcode() == Instruction::And &&
1796        RAnd->getOpcode() == Instruction::And) {
1797
1798      Value *Mask = nullptr;
1799      Value *Masked = nullptr;
1800      if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1801          isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1802                                 DT) &&
1803          isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1804                                 DT)) {
1805        Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1806        Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1807      } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1808                 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1809                                        CxtI, DT) &&
1810                 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1811                                        CxtI, DT)) {
1812        Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1813        Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1814      }
1815
1816      if (Masked)
1817        return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1818    }
1819  }
1820
1821  // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1822  //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1823  // The original condition actually refers to the following two ranges:
1824  // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1825  // We can fold these two ranges if:
1826  // 1) C1 and C2 is unsigned greater than C3.
1827  // 2) The two ranges are separated.
1828  // 3) C1 ^ C2 is one-bit mask.
1829  // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1830  // This implies all values in the two ranges differ by exactly one bit.
1831
1832  if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1833      LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1834      RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1835      LHSCst->getValue() == (RHSCst->getValue())) {
1836
1837    Value *LAdd = LHS->getOperand(0);
1838    Value *RAdd = RHS->getOperand(0);
1839
1840    Value *LAddOpnd, *RAddOpnd;
1841    ConstantInt *LAddCst, *RAddCst;
1842    if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1843        match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1844        LAddCst->getValue().ugt(LHSCst->getValue()) &&
1845        RAddCst->getValue().ugt(LHSCst->getValue())) {
1846
1847      APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1848      if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1849        ConstantInt *MaxAddCst = nullptr;
1850        if (LAddCst->getValue().ult(RAddCst->getValue()))
1851          MaxAddCst = RAddCst;
1852        else
1853          MaxAddCst = LAddCst;
1854
1855        APInt RRangeLow = -RAddCst->getValue();
1856        APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1857        APInt LRangeLow = -LAddCst->getValue();
1858        APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1859        APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1860        APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1861        APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1862                                                   : RRangeLow - LRangeLow;
1863
1864        if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1865            RangeDiff.ugt(LHSCst->getValue())) {
1866          Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1867
1868          Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1869          Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1870          return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1871        }
1872      }
1873    }
1874  }
1875
1876  // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1877  if (PredicatesFoldable(LHSCC, RHSCC)) {
1878    if (LHS->getOperand(0) == RHS->getOperand(1) &&
1879        LHS->getOperand(1) == RHS->getOperand(0))
1880      LHS->swapOperands();
1881    if (LHS->getOperand(0) == RHS->getOperand(0) &&
1882        LHS->getOperand(1) == RHS->getOperand(1)) {
1883      Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1884      unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1885      bool isSigned = LHS->isSigned() || RHS->isSigned();
1886      return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1887    }
1888  }
1889
1890  // handle (roughly):
1891  // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1892  if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1893    return V;
1894
1895  Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1896  if (LHS->hasOneUse() || RHS->hasOneUse()) {
1897    // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1898    // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1899    Value *A = nullptr, *B = nullptr;
1900    if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1901      B = Val;
1902      if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1903        A = Val2;
1904      else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1905        A = RHS->getOperand(1);
1906    }
1907    // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1908    // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1909    else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1910      B = Val2;
1911      if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1912        A = Val;
1913      else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1914        A = LHS->getOperand(1);
1915    }
1916    if (A && B)
1917      return Builder->CreateICmp(
1918          ICmpInst::ICMP_UGE,
1919          Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1920  }
1921
1922  // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1923  if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1924    return V;
1925
1926  // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1927  if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1928    return V;
1929
1930  // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1931  if (!LHSCst || !RHSCst) return nullptr;
1932
1933  if (LHSCst == RHSCst && LHSCC == RHSCC) {
1934    // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1935    if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1936      Value *NewOr = Builder->CreateOr(Val, Val2);
1937      return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1938    }
1939  }
1940
1941  // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1942  //   iff C2 + CA == C1.
1943  if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1944    ConstantInt *AddCst;
1945    if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1946      if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1947        return Builder->CreateICmpULE(Val, LHSCst);
1948  }
1949
1950  // From here on, we only handle:
1951  //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1952  if (Val != Val2) return nullptr;
1953
1954  // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1955  if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1956      RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1957      LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1958      RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1959    return nullptr;
1960
1961  // We can't fold (ugt x, C) | (sgt x, C2).
1962  if (!PredicatesFoldable(LHSCC, RHSCC))
1963    return nullptr;
1964
1965  // Ensure that the larger constant is on the RHS.
1966  bool ShouldSwap;
1967  if (CmpInst::isSigned(LHSCC) ||
1968      (ICmpInst::isEquality(LHSCC) &&
1969       CmpInst::isSigned(RHSCC)))
1970    ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1971  else
1972    ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1973
1974  if (ShouldSwap) {
1975    std::swap(LHS, RHS);
1976    std::swap(LHSCst, RHSCst);
1977    std::swap(LHSCC, RHSCC);
1978  }
1979
1980  // At this point, we know we have two icmp instructions
1981  // comparing a value against two constants and or'ing the result
1982  // together.  Because of the above check, we know that we only have
1983  // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1984  // icmp folding check above), that the two constants are not
1985  // equal.
1986  assert(LHSCst != RHSCst && "Compares not folded above?");
1987
1988  switch (LHSCC) {
1989  default: llvm_unreachable("Unknown integer condition code!");
1990  case ICmpInst::ICMP_EQ:
1991    switch (RHSCC) {
1992    default: llvm_unreachable("Unknown integer condition code!");
1993    case ICmpInst::ICMP_EQ:
1994      if (LHS->getOperand(0) == RHS->getOperand(0)) {
1995        // if LHSCst and RHSCst differ only by one bit:
1996        // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
1997        assert(LHSCst->getValue().ule(LHSCst->getValue()));
1998
1999        APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
2000        if (Xor.isPowerOf2()) {
2001          Value *Cst = Builder->getInt(Xor);
2002          Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
2003          return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
2004        }
2005      }
2006
2007      if (LHSCst == SubOne(RHSCst)) {
2008        // (X == 13 | X == 14) -> X-13 <u 2
2009        Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2010        Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
2011        AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2012        return Builder->CreateICmpULT(Add, AddCST);
2013      }
2014
2015      break;                         // (X == 13 | X == 15) -> no change
2016    case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
2017    case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
2018      break;
2019    case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
2020    case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
2021    case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
2022      return RHS;
2023    }
2024    break;
2025  case ICmpInst::ICMP_NE:
2026    switch (RHSCC) {
2027    default: llvm_unreachable("Unknown integer condition code!");
2028    case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
2029    case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
2030    case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
2031      return LHS;
2032    case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
2033    case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
2034    case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
2035      return Builder->getTrue();
2036    }
2037  case ICmpInst::ICMP_ULT:
2038    switch (RHSCC) {
2039    default: llvm_unreachable("Unknown integer condition code!");
2040    case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
2041      break;
2042    case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
2043      // If RHSCst is [us]MAXINT, it is always false.  Not handling
2044      // this can cause overflow.
2045      if (RHSCst->isMaxValue(false))
2046        return LHS;
2047      return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
2048    case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
2049      break;
2050    case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
2051    case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
2052      return RHS;
2053    case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
2054      break;
2055    }
2056    break;
2057  case ICmpInst::ICMP_SLT:
2058    switch (RHSCC) {
2059    default: llvm_unreachable("Unknown integer condition code!");
2060    case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
2061      break;
2062    case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
2063      // If RHSCst is [us]MAXINT, it is always false.  Not handling
2064      // this can cause overflow.
2065      if (RHSCst->isMaxValue(true))
2066        return LHS;
2067      return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
2068    case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
2069      break;
2070    case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
2071    case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
2072      return RHS;
2073    case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
2074      break;
2075    }
2076    break;
2077  case ICmpInst::ICMP_UGT:
2078    switch (RHSCC) {
2079    default: llvm_unreachable("Unknown integer condition code!");
2080    case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
2081    case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
2082      return LHS;
2083    case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
2084      break;
2085    case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
2086    case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
2087      return Builder->getTrue();
2088    case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
2089      break;
2090    }
2091    break;
2092  case ICmpInst::ICMP_SGT:
2093    switch (RHSCC) {
2094    default: llvm_unreachable("Unknown integer condition code!");
2095    case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
2096    case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
2097      return LHS;
2098    case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
2099      break;
2100    case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
2101    case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
2102      return Builder->getTrue();
2103    case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
2104      break;
2105    }
2106    break;
2107  }
2108  return nullptr;
2109}
2110
2111/// Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of instcombine, this returns
2112/// a Value which should already be inserted into the function.
2113Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
2114  if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2115      RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2116      LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2117    if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2118      if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2119        // If either of the constants are nans, then the whole thing returns
2120        // true.
2121        if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
2122          return Builder->getTrue();
2123
2124        // Otherwise, no need to compare the two constants, compare the
2125        // rest.
2126        return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2127      }
2128
2129    // Handle vector zeros.  This occurs because the canonical form of
2130    // "fcmp uno x,x" is "fcmp uno x, 0".
2131    if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2132        isa<ConstantAggregateZero>(RHS->getOperand(1)))
2133      return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2134
2135    return nullptr;
2136  }
2137
2138  Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2139  Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2140  FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2141
2142  if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2143    // Swap RHS operands to match LHS.
2144    Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2145    std::swap(Op1LHS, Op1RHS);
2146  }
2147  if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2148    // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2149    if (Op0CC == Op1CC)
2150      return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
2151    if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
2152      return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
2153    if (Op0CC == FCmpInst::FCMP_FALSE)
2154      return RHS;
2155    if (Op1CC == FCmpInst::FCMP_FALSE)
2156      return LHS;
2157    bool Op0Ordered;
2158    bool Op1Ordered;
2159    unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2160    unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2161    if (Op0Ordered == Op1Ordered) {
2162      // If both are ordered or unordered, return a new fcmp with
2163      // or'ed predicates.
2164      return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
2165    }
2166  }
2167  return nullptr;
2168}
2169
2170/// This helper function folds:
2171///
2172///     ((A | B) & C1) | (B & C2)
2173///
2174/// into:
2175///
2176///     (A & C1) | B
2177///
2178/// when the XOR of the two constants is "all ones" (-1).
2179Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2180                                               Value *A, Value *B, Value *C) {
2181  ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2182  if (!CI1) return nullptr;
2183
2184  Value *V1 = nullptr;
2185  ConstantInt *CI2 = nullptr;
2186  if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
2187
2188  APInt Xor = CI1->getValue() ^ CI2->getValue();
2189  if (!Xor.isAllOnesValue()) return nullptr;
2190
2191  if (V1 == A || V1 == B) {
2192    Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2193    return BinaryOperator::CreateOr(NewOp, V1);
2194  }
2195
2196  return nullptr;
2197}
2198
2199/// \brief This helper function folds:
2200///
2201///     ((A | B) & C1) ^ (B & C2)
2202///
2203/// into:
2204///
2205///     (A & C1) ^ B
2206///
2207/// when the XOR of the two constants is "all ones" (-1).
2208Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2209                                                Value *A, Value *B, Value *C) {
2210  ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2211  if (!CI1)
2212    return nullptr;
2213
2214  Value *V1 = nullptr;
2215  ConstantInt *CI2 = nullptr;
2216  if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2217    return nullptr;
2218
2219  APInt Xor = CI1->getValue() ^ CI2->getValue();
2220  if (!Xor.isAllOnesValue())
2221    return nullptr;
2222
2223  if (V1 == A || V1 == B) {
2224    Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2225    return BinaryOperator::CreateXor(NewOp, V1);
2226  }
2227
2228  return nullptr;
2229}
2230
2231Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2232  bool Changed = SimplifyAssociativeOrCommutative(I);
2233  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2234
2235  if (Value *V = SimplifyVectorOp(I))
2236    return ReplaceInstUsesWith(I, V);
2237
2238  if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
2239    return ReplaceInstUsesWith(I, V);
2240
2241  // (A&B)|(A&C) -> A&(B|C) etc
2242  if (Value *V = SimplifyUsingDistributiveLaws(I))
2243    return ReplaceInstUsesWith(I, V);
2244
2245  // See if we can simplify any instructions used by the instruction whose sole
2246  // purpose is to compute bits we don't care about.
2247  if (SimplifyDemandedInstructionBits(I))
2248    return &I;
2249
2250  if (Value *V = SimplifyBSwap(I))
2251    return ReplaceInstUsesWith(I, V);
2252
2253  if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2254    ConstantInt *C1 = nullptr; Value *X = nullptr;
2255    // (X & C1) | C2 --> (X | C2) & (C1|C2)
2256    // iff (C1 & C2) == 0.
2257    if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
2258        (RHS->getValue() & C1->getValue()) != 0 &&
2259        Op0->hasOneUse()) {
2260      Value *Or = Builder->CreateOr(X, RHS);
2261      Or->takeName(Op0);
2262      return BinaryOperator::CreateAnd(Or,
2263                             Builder->getInt(RHS->getValue() | C1->getValue()));
2264    }
2265
2266    // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2267    if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2268        Op0->hasOneUse()) {
2269      Value *Or = Builder->CreateOr(X, RHS);
2270      Or->takeName(Op0);
2271      return BinaryOperator::CreateXor(Or,
2272                            Builder->getInt(C1->getValue() & ~RHS->getValue()));
2273    }
2274
2275    // Try to fold constant and into select arguments.
2276    if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2277      if (Instruction *R = FoldOpIntoSelect(I, SI))
2278        return R;
2279
2280    if (isa<PHINode>(Op0))
2281      if (Instruction *NV = FoldOpIntoPhi(I))
2282        return NV;
2283  }
2284
2285  Value *A = nullptr, *B = nullptr;
2286  ConstantInt *C1 = nullptr, *C2 = nullptr;
2287
2288  // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
2289  bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
2290                 match(Op1, m_Or(m_Value(), m_Value()));
2291  // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
2292  bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2293                    match(Op1, m_LogicalShift(m_Value(), m_Value()));
2294  // (A & B) | (C & D)                              -> bswap if possible.
2295  bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
2296                  match(Op1, m_And(m_Value(), m_Value()));
2297
2298  if (OrOfOrs || OrOfShifts || OrOfAnds)
2299    if (Instruction *BSwap = MatchBSwapOrBitReverse(I))
2300      return BSwap;
2301
2302  // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2303  if (Op0->hasOneUse() &&
2304      match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2305      MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
2306    Value *NOr = Builder->CreateOr(A, Op1);
2307    NOr->takeName(Op0);
2308    return BinaryOperator::CreateXor(NOr, C1);
2309  }
2310
2311  // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2312  if (Op1->hasOneUse() &&
2313      match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2314      MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
2315    Value *NOr = Builder->CreateOr(A, Op0);
2316    NOr->takeName(Op0);
2317    return BinaryOperator::CreateXor(NOr, C1);
2318  }
2319
2320  // ((~A & B) | A) -> (A | B)
2321  if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2322      match(Op1, m_Specific(A)))
2323    return BinaryOperator::CreateOr(A, B);
2324
2325  // ((A & B) | ~A) -> (~A | B)
2326  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2327      match(Op1, m_Not(m_Specific(A))))
2328    return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2329
2330  // (A & (~B)) | (A ^ B) -> (A ^ B)
2331  if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2332      match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2333    return BinaryOperator::CreateXor(A, B);
2334
2335  // (A ^ B) | ( A & (~B)) -> (A ^ B)
2336  if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2337      match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2338    return BinaryOperator::CreateXor(A, B);
2339
2340  // (A & C)|(B & D)
2341  Value *C = nullptr, *D = nullptr;
2342  if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2343      match(Op1, m_And(m_Value(B), m_Value(D)))) {
2344    Value *V1 = nullptr, *V2 = nullptr;
2345    C1 = dyn_cast<ConstantInt>(C);
2346    C2 = dyn_cast<ConstantInt>(D);
2347    if (C1 && C2) {  // (A & C1)|(B & C2)
2348      if ((C1->getValue() & C2->getValue()) == 0) {
2349        // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2350        // iff (C1&C2) == 0 and (N&~C1) == 0
2351        if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2352            ((V1 == B &&
2353              MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2354             (V2 == B &&
2355              MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
2356          return BinaryOperator::CreateAnd(A,
2357                                Builder->getInt(C1->getValue()|C2->getValue()));
2358        // Or commutes, try both ways.
2359        if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2360            ((V1 == A &&
2361              MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2362             (V2 == A &&
2363              MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
2364          return BinaryOperator::CreateAnd(B,
2365                                Builder->getInt(C1->getValue()|C2->getValue()));
2366
2367        // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2368        // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2369        ConstantInt *C3 = nullptr, *C4 = nullptr;
2370        if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2371            (C3->getValue() & ~C1->getValue()) == 0 &&
2372            match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2373            (C4->getValue() & ~C2->getValue()) == 0) {
2374          V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2375          return BinaryOperator::CreateAnd(V2,
2376                                Builder->getInt(C1->getValue()|C2->getValue()));
2377        }
2378      }
2379    }
2380
2381    // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
2382    // Don't do this for vector select idioms, the code generator doesn't handle
2383    // them well yet.
2384    if (!I.getType()->isVectorTy()) {
2385      if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2386        return Match;
2387      if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2388        return Match;
2389      if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2390        return Match;
2391      if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2392        return Match;
2393    }
2394
2395    // ((A&~B)|(~A&B)) -> A^B
2396    if ((match(C, m_Not(m_Specific(D))) &&
2397         match(B, m_Not(m_Specific(A)))))
2398      return BinaryOperator::CreateXor(A, D);
2399    // ((~B&A)|(~A&B)) -> A^B
2400    if ((match(A, m_Not(m_Specific(D))) &&
2401         match(B, m_Not(m_Specific(C)))))
2402      return BinaryOperator::CreateXor(C, D);
2403    // ((A&~B)|(B&~A)) -> A^B
2404    if ((match(C, m_Not(m_Specific(B))) &&
2405         match(D, m_Not(m_Specific(A)))))
2406      return BinaryOperator::CreateXor(A, B);
2407    // ((~B&A)|(B&~A)) -> A^B
2408    if ((match(A, m_Not(m_Specific(B))) &&
2409         match(D, m_Not(m_Specific(C)))))
2410      return BinaryOperator::CreateXor(C, B);
2411
2412    // ((A|B)&1)|(B&-2) -> (A&1) | B
2413    if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2414        match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2415      Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2416      if (Ret) return Ret;
2417    }
2418    // (B&-2)|((A|B)&1) -> (A&1) | B
2419    if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2420        match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2421      Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2422      if (Ret) return Ret;
2423    }
2424    // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2425    if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2426        match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2427      Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2428      if (Ret) return Ret;
2429    }
2430    // (B&-2)|((A^B)&1) -> (A&1) ^ B
2431    if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2432        match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2433      Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2434      if (Ret) return Ret;
2435    }
2436  }
2437
2438  // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2439  if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2440    if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2441      if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2442        return BinaryOperator::CreateOr(Op0, C);
2443
2444  // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2445  if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2446    if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2447      if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2448        return BinaryOperator::CreateOr(Op1, C);
2449
2450  // ((B | C) & A) | B -> B | (A & C)
2451  if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2452    return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2453
2454  if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2455    return DeMorgan;
2456
2457  // Canonicalize xor to the RHS.
2458  bool SwappedForXor = false;
2459  if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2460    std::swap(Op0, Op1);
2461    SwappedForXor = true;
2462  }
2463
2464  // A | ( A ^ B) -> A |  B
2465  // A | (~A ^ B) -> A | ~B
2466  // (A & B) | (A ^ B)
2467  if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2468    if (Op0 == A || Op0 == B)
2469      return BinaryOperator::CreateOr(A, B);
2470
2471    if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2472        match(Op0, m_And(m_Specific(B), m_Specific(A))))
2473      return BinaryOperator::CreateOr(A, B);
2474
2475    if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2476      Value *Not = Builder->CreateNot(B, B->getName()+".not");
2477      return BinaryOperator::CreateOr(Not, Op0);
2478    }
2479    if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2480      Value *Not = Builder->CreateNot(A, A->getName()+".not");
2481      return BinaryOperator::CreateOr(Not, Op0);
2482    }
2483  }
2484
2485  // A | ~(A | B) -> A | ~B
2486  // A | ~(A ^ B) -> A | ~B
2487  if (match(Op1, m_Not(m_Value(A))))
2488    if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2489      if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2490          Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2491                               B->getOpcode() == Instruction::Xor)) {
2492        Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2493                                                 B->getOperand(0);
2494        Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2495        return BinaryOperator::CreateOr(Not, Op0);
2496      }
2497
2498  // (A & B) | ((~A) ^ B) -> (~A ^ B)
2499  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2500      match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2501    return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2502
2503  // ((~A) ^ B) | (A & B) -> (~A ^ B)
2504  if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2505      match(Op1, m_And(m_Specific(A), m_Specific(B))))
2506    return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2507
2508  if (SwappedForXor)
2509    std::swap(Op0, Op1);
2510
2511  {
2512    ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2513    ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2514    if (LHS && RHS)
2515      if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2516        return ReplaceInstUsesWith(I, Res);
2517
2518    // TODO: Make this recursive; it's a little tricky because an arbitrary
2519    // number of 'or' instructions might have to be created.
2520    Value *X, *Y;
2521    if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2522      if (auto *Cmp = dyn_cast<ICmpInst>(X))
2523        if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2524          return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2525      if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2526        if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2527          return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2528    }
2529    if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2530      if (auto *Cmp = dyn_cast<ICmpInst>(X))
2531        if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2532          return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2533      if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2534        if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2535          return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2536    }
2537  }
2538
2539  // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
2540  if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2541    if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2542      if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2543        return ReplaceInstUsesWith(I, Res);
2544
2545  // fold (or (cast A), (cast B)) -> (cast (or A, B))
2546  if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2547    CastInst *Op1C = dyn_cast<CastInst>(Op1);
2548    if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2549      Type *SrcTy = Op0C->getOperand(0)->getType();
2550      if (SrcTy == Op1C->getOperand(0)->getType() &&
2551          SrcTy->isIntOrIntVectorTy()) {
2552        Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2553
2554        if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2555            // Only do this if the casts both really cause code to be
2556            // generated.
2557            ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2558            ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2559          Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2560          return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2561        }
2562
2563        // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2564        // cast is otherwise not optimizable.  This happens for vector sexts.
2565        if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2566          if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2567            if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2568              return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2569
2570        // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2571        // cast is otherwise not optimizable.  This happens for vector sexts.
2572        if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2573          if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2574            if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2575              return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2576      }
2577    }
2578  }
2579
2580  // or(sext(A), B) -> A ? -1 : B where A is an i1
2581  // or(A, sext(B)) -> B ? -1 : A where B is an i1
2582  if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2583    return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2584  if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2585    return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2586
2587  // Note: If we've gotten to the point of visiting the outer OR, then the
2588  // inner one couldn't be simplified.  If it was a constant, then it won't
2589  // be simplified by a later pass either, so we try swapping the inner/outer
2590  // ORs in the hopes that we'll be able to simplify it this way.
2591  // (X|C) | V --> (X|V) | C
2592  if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2593      match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2594    Value *Inner = Builder->CreateOr(A, Op1);
2595    Inner->takeName(Op0);
2596    return BinaryOperator::CreateOr(Inner, C1);
2597  }
2598
2599  // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2600  // Since this OR statement hasn't been optimized further yet, we hope
2601  // that this transformation will allow the new ORs to be optimized.
2602  {
2603    Value *X = nullptr, *Y = nullptr;
2604    if (Op0->hasOneUse() && Op1->hasOneUse() &&
2605        match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2606        match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2607      Value *orTrue = Builder->CreateOr(A, C);
2608      Value *orFalse = Builder->CreateOr(B, D);
2609      return SelectInst::Create(X, orTrue, orFalse);
2610    }
2611  }
2612
2613  return Changed ? &I : nullptr;
2614}
2615
2616Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2617  bool Changed = SimplifyAssociativeOrCommutative(I);
2618  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2619
2620  if (Value *V = SimplifyVectorOp(I))
2621    return ReplaceInstUsesWith(I, V);
2622
2623  if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
2624    return ReplaceInstUsesWith(I, V);
2625
2626  // (A&B)^(A&C) -> A&(B^C) etc
2627  if (Value *V = SimplifyUsingDistributiveLaws(I))
2628    return ReplaceInstUsesWith(I, V);
2629
2630  // See if we can simplify any instructions used by the instruction whose sole
2631  // purpose is to compute bits we don't care about.
2632  if (SimplifyDemandedInstructionBits(I))
2633    return &I;
2634
2635  if (Value *V = SimplifyBSwap(I))
2636    return ReplaceInstUsesWith(I, V);
2637
2638  // Is this a ~ operation?
2639  if (Value *NotOp = dyn_castNotVal(&I)) {
2640    if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2641      if (Op0I->getOpcode() == Instruction::And ||
2642          Op0I->getOpcode() == Instruction::Or) {
2643        // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2644        // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2645        if (dyn_castNotVal(Op0I->getOperand(1)))
2646          Op0I->swapOperands();
2647        if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2648          Value *NotY =
2649            Builder->CreateNot(Op0I->getOperand(1),
2650                               Op0I->getOperand(1)->getName()+".not");
2651          if (Op0I->getOpcode() == Instruction::And)
2652            return BinaryOperator::CreateOr(Op0NotVal, NotY);
2653          return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2654        }
2655
2656        // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2657        // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2658        if (IsFreeToInvert(Op0I->getOperand(0),
2659                           Op0I->getOperand(0)->hasOneUse()) &&
2660            IsFreeToInvert(Op0I->getOperand(1),
2661                           Op0I->getOperand(1)->hasOneUse())) {
2662          Value *NotX =
2663            Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2664          Value *NotY =
2665            Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2666          if (Op0I->getOpcode() == Instruction::And)
2667            return BinaryOperator::CreateOr(NotX, NotY);
2668          return BinaryOperator::CreateAnd(NotX, NotY);
2669        }
2670
2671      } else if (Op0I->getOpcode() == Instruction::AShr) {
2672        // ~(~X >>s Y) --> (X >>s Y)
2673        if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2674          return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2675      }
2676    }
2677  }
2678
2679  if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2680    if (RHS->isAllOnesValue() && Op0->hasOneUse())
2681      // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2682      if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2683        return CmpInst::Create(CI->getOpcode(),
2684                               CI->getInversePredicate(),
2685                               CI->getOperand(0), CI->getOperand(1));
2686  }
2687
2688  if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2689    // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2690    if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2691      if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2692        if (CI->hasOneUse() && Op0C->hasOneUse()) {
2693          Instruction::CastOps Opcode = Op0C->getOpcode();
2694          if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2695              (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2696                                            Op0C->getDestTy()))) {
2697            CI->setPredicate(CI->getInversePredicate());
2698            return CastInst::Create(Opcode, CI, Op0C->getType());
2699          }
2700        }
2701      }
2702    }
2703
2704    if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2705      // ~(c-X) == X-c-1 == X+(-c-1)
2706      if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2707        if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2708          Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2709          Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2710                                      ConstantInt::get(I.getType(), 1));
2711          return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2712        }
2713
2714      if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2715        if (Op0I->getOpcode() == Instruction::Add) {
2716          // ~(X-c) --> (-c-1)-X
2717          if (RHS->isAllOnesValue()) {
2718            Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2719            return BinaryOperator::CreateSub(
2720                           ConstantExpr::getSub(NegOp0CI,
2721                                      ConstantInt::get(I.getType(), 1)),
2722                                      Op0I->getOperand(0));
2723          } else if (RHS->getValue().isSignBit()) {
2724            // (X + C) ^ signbit -> (X + C + signbit)
2725            Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2726            return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2727
2728          }
2729        } else if (Op0I->getOpcode() == Instruction::Or) {
2730          // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2731          if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2732                                0, &I)) {
2733            Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2734            // Anything in both C1 and C2 is known to be zero, remove it from
2735            // NewRHS.
2736            Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2737            NewRHS = ConstantExpr::getAnd(NewRHS,
2738                                       ConstantExpr::getNot(CommonBits));
2739            Worklist.Add(Op0I);
2740            I.setOperand(0, Op0I->getOperand(0));
2741            I.setOperand(1, NewRHS);
2742            return &I;
2743          }
2744        } else if (Op0I->getOpcode() == Instruction::LShr) {
2745          // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2746          // E1 = "X ^ C1"
2747          BinaryOperator *E1;
2748          ConstantInt *C1;
2749          if (Op0I->hasOneUse() &&
2750              (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2751              E1->getOpcode() == Instruction::Xor &&
2752              (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2753            // fold (C1 >> C2) ^ C3
2754            ConstantInt *C2 = Op0CI, *C3 = RHS;
2755            APInt FoldConst = C1->getValue().lshr(C2->getValue());
2756            FoldConst ^= C3->getValue();
2757            // Prepare the two operands.
2758            Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2759            Opnd0->takeName(Op0I);
2760            cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2761            Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2762
2763            return BinaryOperator::CreateXor(Opnd0, FoldVal);
2764          }
2765        }
2766      }
2767    }
2768
2769    // Try to fold constant and into select arguments.
2770    if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2771      if (Instruction *R = FoldOpIntoSelect(I, SI))
2772        return R;
2773    if (isa<PHINode>(Op0))
2774      if (Instruction *NV = FoldOpIntoPhi(I))
2775        return NV;
2776  }
2777
2778  BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2779  if (Op1I) {
2780    Value *A, *B;
2781    if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2782      if (A == Op0) {              // B^(B|A) == (A|B)^B
2783        Op1I->swapOperands();
2784        I.swapOperands();
2785        std::swap(Op0, Op1);
2786      } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2787        I.swapOperands();     // Simplified below.
2788        std::swap(Op0, Op1);
2789      }
2790    } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2791               Op1I->hasOneUse()){
2792      if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2793        Op1I->swapOperands();
2794        std::swap(A, B);
2795      }
2796      if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2797        I.swapOperands();     // Simplified below.
2798        std::swap(Op0, Op1);
2799      }
2800    }
2801  }
2802
2803  BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2804  if (Op0I) {
2805    Value *A, *B;
2806    if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2807        Op0I->hasOneUse()) {
2808      if (A == Op1)                                  // (B|A)^B == (A|B)^B
2809        std::swap(A, B);
2810      if (B == Op1)                                  // (A|B)^B == A & ~B
2811        return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2812    } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2813               Op0I->hasOneUse()){
2814      if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2815        std::swap(A, B);
2816      if (B == Op1 &&                                      // (B&A)^A == ~B & A
2817          !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2818        return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2819      }
2820    }
2821  }
2822
2823  if (Op0I && Op1I) {
2824    Value *A, *B, *C, *D;
2825    // (A & B)^(A | B) -> A ^ B
2826    if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2827        match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2828      if ((A == C && B == D) || (A == D && B == C))
2829        return BinaryOperator::CreateXor(A, B);
2830    }
2831    // (A | B)^(A & B) -> A ^ B
2832    if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2833        match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2834      if ((A == C && B == D) || (A == D && B == C))
2835        return BinaryOperator::CreateXor(A, B);
2836    }
2837    // (A | ~B) ^ (~A | B) -> A ^ B
2838    if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2839        match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2840      return BinaryOperator::CreateXor(A, B);
2841    }
2842    // (~A | B) ^ (A | ~B) -> A ^ B
2843    if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2844        match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2845      return BinaryOperator::CreateXor(A, B);
2846    }
2847    // (A & ~B) ^ (~A & B) -> A ^ B
2848    if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2849        match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2850      return BinaryOperator::CreateXor(A, B);
2851    }
2852    // (~A & B) ^ (A & ~B) -> A ^ B
2853    if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2854        match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2855      return BinaryOperator::CreateXor(A, B);
2856    }
2857    // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2858    if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2859        match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2860      if (D == A)
2861        return BinaryOperator::CreateXor(
2862            Builder->CreateAnd(Builder->CreateNot(A), B), C);
2863      if (D == B)
2864        return BinaryOperator::CreateXor(
2865            Builder->CreateAnd(Builder->CreateNot(B), A), C);
2866    }
2867    // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2868    if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2869        match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2870      if (D == A)
2871        return BinaryOperator::CreateXor(
2872            Builder->CreateAnd(Builder->CreateNot(A), B), C);
2873      if (D == B)
2874        return BinaryOperator::CreateXor(
2875            Builder->CreateAnd(Builder->CreateNot(B), A), C);
2876    }
2877    // (A & B) ^ (A ^ B) -> (A | B)
2878    if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2879        match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2880      return BinaryOperator::CreateOr(A, B);
2881    // (A ^ B) ^ (A & B) -> (A | B)
2882    if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2883        match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2884      return BinaryOperator::CreateOr(A, B);
2885  }
2886
2887  Value *A = nullptr, *B = nullptr;
2888  // (A & ~B) ^ (~A) -> ~(A & B)
2889  if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2890      match(Op1, m_Not(m_Specific(A))))
2891    return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2892
2893  // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2894  if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2895    if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2896      if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2897        if (LHS->getOperand(0) == RHS->getOperand(1) &&
2898            LHS->getOperand(1) == RHS->getOperand(0))
2899          LHS->swapOperands();
2900        if (LHS->getOperand(0) == RHS->getOperand(0) &&
2901            LHS->getOperand(1) == RHS->getOperand(1)) {
2902          Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2903          unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2904          bool isSigned = LHS->isSigned() || RHS->isSigned();
2905          return ReplaceInstUsesWith(I,
2906                               getNewICmpValue(isSigned, Code, Op0, Op1,
2907                                               Builder));
2908        }
2909      }
2910
2911  // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2912  if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2913    if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2914      if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2915        Type *SrcTy = Op0C->getOperand(0)->getType();
2916        if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2917            // Only do this if the casts both really cause code to be generated.
2918            ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2919                               I.getType()) &&
2920            ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2921                               I.getType())) {
2922          Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2923                                            Op1C->getOperand(0), I.getName());
2924          return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2925        }
2926      }
2927  }
2928
2929  return Changed ? &I : nullptr;
2930}
2931