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