blob: 863eeafe3b983dc3456c919fb62ee7f526d143ee [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Chris Lattner0a8191e2010-01-05 07:50:36 +000025static inline Value *dyn_castNotVal(Value *V) {
26 // If this is not(not(x)) don't return that this is a not: we want the two
27 // not's to be folded first.
28 if (BinaryOperator::isNot(V)) {
29 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000030 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000031 return Operand;
32 }
Craig Topper9d4171a2012-12-20 07:09:41 +000033
Chris Lattner0a8191e2010-01-05 07:50:36 +000034 // Constants can be considered to be not'ed values...
35 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
36 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000037 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000038}
39
Chris Lattner0a8191e2010-01-05 07:50:36 +000040/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
41/// predicate into a three bit mask. It also returns whether it is an ordered
42/// predicate by reference.
43static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
44 isOrdered = false;
45 switch (CC) {
46 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
47 case FCmpInst::FCMP_UNO: return 0; // 000
48 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
49 case FCmpInst::FCMP_UGT: return 1; // 001
50 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
51 case FCmpInst::FCMP_UEQ: return 2; // 010
52 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
53 case FCmpInst::FCMP_UGE: return 3; // 011
54 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
55 case FCmpInst::FCMP_ULT: return 4; // 100
56 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
57 case FCmpInst::FCMP_UNE: return 5; // 101
58 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
59 case FCmpInst::FCMP_ULE: return 6; // 110
60 // True -> 7
61 default:
62 // Not expecting FCMP_FALSE and FCMP_TRUE;
63 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000064 }
65}
66
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000067/// getNewICmpValue - This is the complement of getICmpCode, which turns an
Craig Topper9d4171a2012-12-20 07:09:41 +000068/// opcode and two operands into either a constant true or false, or a brand
Chris Lattner0a8191e2010-01-05 07:50:36 +000069/// new ICmp instruction. The sign is passed in to determine which kind
70/// of predicate to use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000071static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000073 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75 return NewConstant;
76 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000077}
78
79/// getFCmpValue - This is the complement of getFCmpCode, which turns an
80/// opcode and two operands into either a FCmp instruction. isordered is passed
81/// in to determine which kind of predicate to use in the new fcmp instruction.
82static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +000083 Value *LHS, Value *RHS,
84 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +000085 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +000086 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +000087 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +000088 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
89 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
90 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
91 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
92 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
93 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
94 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +000095 case 7:
Owen Andersona8342002011-01-21 19:39:42 +000096 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
97 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +000098 }
Chris Lattner067459c2010-03-05 08:46:26 +000099 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000100}
101
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000102/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
103/// \param I Binary operator to transform.
104/// \return Pointer to node that must replace the original binary operator, or
105/// null pointer if no transformation was made.
106Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
107 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
108
109 // Can't do vectors.
110 if (I.getType()->isVectorTy()) return nullptr;
111
112 // Can only do bitwise ops.
113 unsigned Op = I.getOpcode();
114 if (Op != Instruction::And && Op != Instruction::Or &&
115 Op != Instruction::Xor)
116 return nullptr;
117
118 Value *OldLHS = I.getOperand(0);
119 Value *OldRHS = I.getOperand(1);
120 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
121 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
122 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
123 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
124 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
125 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
126
127 if (!IsBswapLHS && !IsBswapRHS)
128 return nullptr;
129
130 if (!IsBswapLHS && !ConstLHS)
131 return nullptr;
132
133 if (!IsBswapRHS && !ConstRHS)
134 return nullptr;
135
136 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
137 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
138 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
139 Builder->getInt(ConstLHS->getValue().byteSwap());
140
141 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
142 Builder->getInt(ConstRHS->getValue().byteSwap());
143
144 Value *BinOp = nullptr;
145 if (Op == Instruction::And)
146 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
147 else if (Op == Instruction::Or)
148 BinOp = Builder->CreateOr(NewLHS, NewRHS);
149 else //if (Op == Instruction::Xor)
150 BinOp = Builder->CreateXor(NewLHS, NewRHS);
151
152 Module *M = I.getParent()->getParent()->getParent();
153 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
154 return Builder->CreateCall(F, BinOp);
155}
156
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
158// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
159// guaranteed to be a binary operator.
160Instruction *InstCombiner::OptAndOp(Instruction *Op,
161 ConstantInt *OpRHS,
162 ConstantInt *AndRHS,
163 BinaryOperator &TheAnd) {
164 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000165 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000166 if (!Op->isShift())
167 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
168
169 switch (Op->getOpcode()) {
170 case Instruction::Xor:
171 if (Op->hasOneUse()) {
172 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
173 Value *And = Builder->CreateAnd(X, AndRHS);
174 And->takeName(Op);
175 return BinaryOperator::CreateXor(And, Together);
176 }
177 break;
178 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000179 if (Op->hasOneUse()){
180 if (Together != OpRHS) {
181 // (X | C1) & C2 --> (X | (C1&C2)) & C2
182 Value *Or = Builder->CreateOr(X, Together);
183 Or->takeName(Op);
184 return BinaryOperator::CreateAnd(Or, AndRHS);
185 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000186
Owen Andersonc237a842010-09-13 17:59:27 +0000187 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
188 if (TogetherCI && !TogetherCI->isZero()){
189 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
190 // NOTE: This reduces the number of bits set in the & mask, which
191 // can expose opportunities for store narrowing.
192 Together = ConstantExpr::getXor(AndRHS, Together);
193 Value *And = Builder->CreateAnd(X, Together);
194 And->takeName(Op);
195 return BinaryOperator::CreateOr(And, OpRHS);
196 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000197 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000198
Chris Lattner0a8191e2010-01-05 07:50:36 +0000199 break;
200 case Instruction::Add:
201 if (Op->hasOneUse()) {
202 // Adding a one to a single bit bit-field should be turned into an XOR
203 // of the bit. First thing to check is to see if this AND is with a
204 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000205 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000206
207 // If there is only one bit set.
208 if (AndRHSV.isPowerOf2()) {
209 // Ok, at this point, we know that we are masking the result of the
210 // ADD down to exactly one bit. If the constant we are adding has
211 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000212 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000213
214 // Check to see if any bits below the one bit set in AndRHSV are set.
215 if ((AddRHS & (AndRHSV-1)) == 0) {
216 // If not, the only thing that can effect the output of the AND is
217 // the bit specified by AndRHSV. If that bit is set, the effect of
218 // the XOR is to toggle the bit. If it is clear, then the ADD has
219 // no effect.
220 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
221 TheAnd.setOperand(0, X);
222 return &TheAnd;
223 } else {
224 // Pull the XOR out of the AND.
225 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
226 NewAnd->takeName(Op);
227 return BinaryOperator::CreateXor(NewAnd, AndRHS);
228 }
229 }
230 }
231 }
232 break;
233
234 case Instruction::Shl: {
235 // We know that the AND will not produce any of the bits shifted in, so if
236 // the anded constant includes them, clear them now!
237 //
238 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
239 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
240 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000241 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000242
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000243 if (CI->getValue() == ShlMask)
244 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000245 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000246
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000247 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000248 TheAnd.setOperand(1, CI);
249 return &TheAnd;
250 }
251 break;
252 }
253 case Instruction::LShr: {
254 // We know that the AND will not produce any of the bits shifted in, so if
255 // the anded constant includes them, clear them now! This only applies to
256 // unsigned shifts, because a signed shr may bring in set bits!
257 //
258 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
259 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
260 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000261 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000262
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000263 if (CI->getValue() == ShrMask)
264 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000265 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000266
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000267 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000268 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
269 return &TheAnd;
270 }
271 break;
272 }
273 case Instruction::AShr:
274 // Signed shr.
275 // See if this is shifting in some sign extension, then masking it out
276 // with an and.
277 if (Op->hasOneUse()) {
278 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
279 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
280 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000281 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000282 if (C == AndRHS) { // Masking out bits shifted in.
283 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
284 // Make the argument unsigned.
285 Value *ShVal = Op->getOperand(0);
286 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
287 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
288 }
289 }
290 break;
291 }
Craig Topperf40110f2014-04-25 05:29:35 +0000292 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000293}
294
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000295/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
296/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000297/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000298/// whether to treat the V, Lo and HI as signed or not. IB is the location to
299/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000300Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
301 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000302 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000303 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
304 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000305
Chris Lattner0a8191e2010-01-05 07:50:36 +0000306 if (Inside) {
307 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000308 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000309
310 // V >= Min && V < Hi --> V < Hi
311 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000312 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000313 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000314 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000315 }
316
317 // Emit V-Lo <u Hi-Lo
318 Constant *NegLo = ConstantExpr::getNeg(Lo);
319 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
320 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000321 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000322 }
323
324 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000325 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000326
327 // V < Min || V >= Hi -> V > Hi-1
328 Hi = SubOne(cast<ConstantInt>(Hi));
329 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000330 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000331 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000332 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000333 }
334
335 // Emit V-Lo >u Hi-1-Lo
336 // Note that Hi has already had one subtracted from it, above.
337 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
338 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
339 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000340 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000341}
342
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000343// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000344// any number of 0s on either side. The 1s are allowed to wrap from LSB to
345// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
346// not, since all 1s are not contiguous.
347static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
348 const APInt& V = Val->getValue();
349 uint32_t BitWidth = Val->getType()->getBitWidth();
350 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
351
352 // look for the first zero bit after the run of ones
353 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
354 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000355 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000356 return true;
357}
358
359/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
360/// where isSub determines whether the operator is a sub. If we can fold one of
361/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000362///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000363/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
364/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
365/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000366///
367/// return (A +/- B).
368///
369Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
370 ConstantInt *Mask, bool isSub,
371 Instruction &I) {
372 Instruction *LHSI = dyn_cast<Instruction>(LHS);
373 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000374 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000375
376 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
377
378 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000379 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000380 case Instruction::And:
381 if (ConstantExpr::getAnd(N, Mask) == Mask) {
382 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000383 if ((Mask->getValue().countLeadingZeros() +
384 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000385 Mask->getValue().getBitWidth())
386 break;
387
388 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
389 // part, we don't need any explicit masks to take them out of A. If that
390 // is all N is, ignore it.
391 uint32_t MB = 0, ME = 0;
392 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
393 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
394 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000395 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000396 break;
397 }
398 }
Craig Topperf40110f2014-04-25 05:29:35 +0000399 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000400 case Instruction::Or:
401 case Instruction::Xor:
402 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000403 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000404 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
405 && ConstantExpr::getAnd(N, Mask)->isNullValue())
406 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000407 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000408 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000409
Chris Lattner0a8191e2010-01-05 07:50:36 +0000410 if (isSub)
411 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
412 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
413}
414
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000416/// One of A and B is considered the mask, the other the value. This is
417/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000418/// contains only "Mask", then both A and B can be considered masks.
419/// If A is the mask, then it was proven, that (A & C) == C. This
420/// is trivial if C == A, or C == 0. If both A and C are constants, this
421/// proof is also easy.
422/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000423/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424/// if (A & B) == A, or all bits of A are set in B.
425/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000426/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000427/// if (A & B) == 0, or all bits of A are cleared in B.
428/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000429/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000430/// contain any number of one bits and zero bits.
431/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
432/// The Part "Not" means, that in above descriptions "==" should be replaced
433/// by "!=".
434/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
435/// If the mask A contains a single bit, then the following is equivalent:
436/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
437/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
438enum MaskedICmpType {
439 FoldMskICmp_AMask_AllOnes = 1,
440 FoldMskICmp_AMask_NotAllOnes = 2,
441 FoldMskICmp_BMask_AllOnes = 4,
442 FoldMskICmp_BMask_NotAllOnes = 8,
443 FoldMskICmp_Mask_AllZeroes = 16,
444 FoldMskICmp_Mask_NotAllZeroes = 32,
445 FoldMskICmp_AMask_Mixed = 64,
446 FoldMskICmp_AMask_NotMixed = 128,
447 FoldMskICmp_BMask_Mixed = 256,
448 FoldMskICmp_BMask_NotMixed = 512
449};
450
451/// return the set of pattern classes (from MaskedICmpType)
452/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000453static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000454 ICmpInst::Predicate SCC)
455{
456 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
457 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
458 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
459 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000460 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000461 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000462 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000463 BCst->getValue().isPowerOf2());
464 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000465 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000466 // if C is zero, then both A and B qualify as mask
467 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
468 FoldMskICmp_Mask_AllZeroes |
469 FoldMskICmp_AMask_Mixed |
470 FoldMskICmp_BMask_Mixed)
471 : (FoldMskICmp_Mask_NotAllZeroes |
472 FoldMskICmp_Mask_NotAllZeroes |
473 FoldMskICmp_AMask_NotMixed |
474 FoldMskICmp_BMask_NotMixed));
475 if (icmp_abit)
476 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000477 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000478 : (FoldMskICmp_AMask_AllOnes |
479 FoldMskICmp_AMask_Mixed));
480 if (icmp_bbit)
481 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000482 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000483 : (FoldMskICmp_BMask_AllOnes |
484 FoldMskICmp_BMask_Mixed));
485 return result;
486 }
487 if (A == C) {
488 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
489 FoldMskICmp_AMask_Mixed)
490 : (FoldMskICmp_AMask_NotAllOnes |
491 FoldMskICmp_AMask_NotMixed));
492 if (icmp_abit)
493 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
494 FoldMskICmp_AMask_NotMixed)
495 : (FoldMskICmp_Mask_AllZeroes |
496 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000497 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000498 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000499 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
500 : FoldMskICmp_AMask_NotMixed);
501 }
Craig Topperae48cb22012-12-20 07:15:54 +0000502 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000503 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
504 FoldMskICmp_BMask_Mixed)
505 : (FoldMskICmp_BMask_NotAllOnes |
506 FoldMskICmp_BMask_NotMixed));
507 if (icmp_bbit)
508 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000509 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000510 : (FoldMskICmp_Mask_AllZeroes |
511 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000512 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000513 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000514 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
515 : FoldMskICmp_BMask_NotMixed);
516 }
517 return result;
518}
519
Tim Northoverc0756c42013-09-04 11:57:13 +0000520/// Convert an analysis of a masked ICmp into its equivalent if all boolean
521/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
522/// is adjacent to the corresponding normal flag (recording ==), this just
523/// involves swapping those bits over.
524static unsigned conjugateICmpMask(unsigned Mask) {
525 unsigned NewMask;
526 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
527 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
528 FoldMskICmp_BMask_Mixed))
529 << 1;
530
531 NewMask |=
532 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
533 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
534 FoldMskICmp_BMask_NotMixed))
535 >> 1;
536
537 return NewMask;
538}
539
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000540/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
541/// if possible. The returned predicate is either == or !=. Returns false if
542/// decomposition fails.
543static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
544 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000545 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
546 if (!C)
547 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000548
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000549 switch (I->getPredicate()) {
550 default:
551 return false;
552 case ICmpInst::ICMP_SLT:
553 // X < 0 is equivalent to (X & SignBit) != 0.
554 if (!C->isZero())
555 return false;
556 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
557 Pred = ICmpInst::ICMP_NE;
558 break;
559 case ICmpInst::ICMP_SGT:
560 // X > -1 is equivalent to (X & SignBit) == 0.
561 if (!C->isAllOnesValue())
562 return false;
563 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
564 Pred = ICmpInst::ICMP_EQ;
565 break;
566 case ICmpInst::ICMP_ULT:
567 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
568 if (!C->getValue().isPowerOf2())
569 return false;
570 Y = ConstantInt::get(I->getContext(), -C->getValue());
571 Pred = ICmpInst::ICMP_EQ;
572 break;
573 case ICmpInst::ICMP_UGT:
574 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
575 if (!(C->getValue() + 1).isPowerOf2())
576 return false;
577 Y = ConstantInt::get(I->getContext(), ~C->getValue());
578 Pred = ICmpInst::ICMP_NE;
579 break;
580 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000581
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000582 X = I->getOperand(0);
583 Z = ConstantInt::getNullValue(C->getType());
584 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000585}
586
Owen Anderson3fe002d2010-09-08 22:16:17 +0000587/// foldLogOpOfMaskedICmpsHelper:
588/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
589/// return the set of pattern classes (from MaskedICmpType)
590/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000591static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000592 Value*& B, Value*& C,
593 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000594 ICmpInst *LHS, ICmpInst *RHS,
595 ICmpInst::Predicate &LHSCC,
596 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000597 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
598 // vectors are not (yet?) supported
599 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
600
601 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000602 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000603 // and L11 & L12 == L21 & L22. The same goes for RHS.
604 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000605 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000606 // above.
607 Value *L1 = LHS->getOperand(0);
608 Value *L2 = LHS->getOperand(1);
609 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000610 // Check whether the icmp can be decomposed into a bit test.
611 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000612 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000613 } else {
614 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000615 if (!L1->getType()->isIntegerTy()) {
616 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000617 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000618 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
619 // Any icmp can be viewed as being trivially masked; if it allows us to
620 // remove one, it's worth it.
621 L11 = L1;
622 L12 = Constant::getAllOnesValue(L1->getType());
623 }
624
625 if (!L2->getType()->isIntegerTy()) {
626 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000627 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000628 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
629 L21 = L2;
630 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000631 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000632 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000633
634 // Bail if LHS was a icmp that can't be decomposed into an equality.
635 if (!ICmpInst::isEquality(LHSCC))
636 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000637
638 Value *R1 = RHS->getOperand(0);
639 Value *R2 = RHS->getOperand(1);
640 Value *R11,*R12;
641 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000642 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
643 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
644 A = R11; D = R12;
645 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
646 A = R12; D = R11;
647 } else {
648 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000649 }
Craig Topperf40110f2014-04-25 05:29:35 +0000650 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000651 } else if (R1->getType()->isIntegerTy()) {
652 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
653 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000654 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000655 R11 = R1;
656 R12 = Constant::getAllOnesValue(R1->getType());
657 }
658
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000659 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
660 A = R11; D = R12; E = R2; ok = true;
661 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000662 A = R12; D = R11; E = R2; ok = true;
663 }
664 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000665
666 // Bail if RHS was a icmp that can't be decomposed into an equality.
667 if (!ICmpInst::isEquality(RHSCC))
668 return 0;
669
670 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000671 if (!ok && R2->getType()->isIntegerTy()) {
672 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
673 R11 = R2;
674 R12 = Constant::getAllOnesValue(R2->getType());
675 }
676
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000677 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
678 A = R11; D = R12; E = R1; ok = true;
679 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000680 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000681 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000682 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000683 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000684 }
685 if (!ok)
686 return 0;
687
688 if (L11 == A) {
689 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000690 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000691 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000692 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000693 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000694 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000695 B = L21; C = L1;
696 }
697
698 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
699 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
700 return left_type & right_type;
701}
702/// foldLogOpOfMaskedICmps:
703/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
704/// into a single (icmp(A & X) ==/!= Y)
David Majnemer1a3327b2014-11-18 09:31:36 +0000705static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
706 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000707 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000708 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
709 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
710 LHSCC, RHSCC);
Craig Topperf40110f2014-04-25 05:29:35 +0000711 if (mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000712 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
713 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000714
Tim Northoverc0756c42013-09-04 11:57:13 +0000715 // In full generality:
716 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
717 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
718 //
719 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
720 // equivalent to (icmp (A & X) !Op Y).
721 //
722 // Therefore, we can pretend for the rest of this function that we're dealing
723 // with the conjunction, provided we flip the sense of any comparisons (both
724 // input and output).
725
726 // In most cases we're going to produce an EQ for the "&&" case.
727 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
728 if (!IsAnd) {
729 // Convert the masking analysis into its equivalent with negated
730 // comparisons.
731 mask = conjugateICmpMask(mask);
732 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000733
734 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000735 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000736 // -> (icmp eq (A & (B|D)), 0)
David Majnemer1a3327b2014-11-18 09:31:36 +0000737 Value *newOr = Builder->CreateOr(B, D);
738 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000739 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000740 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000741 // with B and D, having a single bit set
David Majnemer1a3327b2014-11-18 09:31:36 +0000742 Value *zero = Constant::getNullValue(A->getType());
Owen Anderson3fe002d2010-09-08 22:16:17 +0000743 return Builder->CreateICmp(NEWCC, newAnd, zero);
744 }
Craig Topperae48cb22012-12-20 07:15:54 +0000745 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000746 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000747 // -> (icmp eq (A & (B|D)), (B|D))
David Majnemer1a3327b2014-11-18 09:31:36 +0000748 Value *newOr = Builder->CreateOr(B, D);
749 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000750 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000751 }
Craig Topperae48cb22012-12-20 07:15:54 +0000752 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000753 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000754 // -> (icmp eq (A & (B&D)), A)
David Majnemer1a3327b2014-11-18 09:31:36 +0000755 Value *newAnd1 = Builder->CreateAnd(B, D);
756 Value *newAnd = Builder->CreateAnd(A, newAnd1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000757 return Builder->CreateICmp(NEWCC, newAnd, A);
758 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000759
760 // Remaining cases assume at least that B and D are constant, and depend on
761 // their actual values. This isn't strictly, necessary, just a "handle the
762 // easy cases for now" decision.
763 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000764 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000765 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000766 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000767
768 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
769 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
770 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
771 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
772 // Only valid if one of the masks is a superset of the other (check "B&D" is
773 // the same as either B or D).
774 APInt NewMask = BCst->getValue() & DCst->getValue();
775
776 if (NewMask == BCst->getValue())
777 return LHS;
778 else if (NewMask == DCst->getValue())
779 return RHS;
780 }
781 if (mask & FoldMskICmp_AMask_NotAllOnes) {
782 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
783 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
784 // Only valid if one of the masks is a superset of the other (check "B|D" is
785 // the same as either B or D).
786 APInt NewMask = BCst->getValue() | DCst->getValue();
787
788 if (NewMask == BCst->getValue())
789 return LHS;
790 else if (NewMask == DCst->getValue())
791 return RHS;
792 }
Craig Topperae48cb22012-12-20 07:15:54 +0000793 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000794 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000795 // We already know that B & C == C && D & E == E.
796 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
797 // C and E, which are shared by both the mask B and the mask D, don't
798 // contradict, then we can transform to
799 // -> (icmp eq (A & (B|D)), (C|E))
800 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000801 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000802 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000803 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000804 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000805 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000806 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000807 if (!ECst) return nullptr;
David Majnemer1a3327b2014-11-18 09:31:36 +0000808 if (LHSCC != NEWCC)
809 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000810 if (RHSCC != NEWCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000811 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Owen Anderson3fe002d2010-09-08 22:16:17 +0000812 // if there is a conflict we should actually return a false for the
813 // whole construct
David Majnemer1a3327b2014-11-18 09:31:36 +0000814 if (((BCst->getValue() & DCst->getValue()) &
815 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000816 return ConstantInt::get(LHS->getType(), !IsAnd);
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000817 Value *newOr1 = Builder->CreateOr(B, D);
818 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
819 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000820 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
821 }
Craig Topperf40110f2014-04-25 05:29:35 +0000822 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000823}
824
Erik Ecksteind1817522014-12-03 10:39:15 +0000825/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
826/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
827/// If \p Inverted is true then the check is for the inverted range, e.g.
828/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
829Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
830 bool Inverted) {
831 // Check the lower range comparison, e.g. x >= 0
832 // InstCombine already ensured that if there is a constant it's on the RHS.
833 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
834 if (!RangeStart)
835 return nullptr;
836
837 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
838 Cmp0->getPredicate());
839
840 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
841 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
842 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
843 return nullptr;
844
845 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
846 Cmp1->getPredicate());
847
848 Value *Input = Cmp0->getOperand(0);
849 Value *RangeEnd;
850 if (Cmp1->getOperand(0) == Input) {
851 // For the upper range compare we have: icmp x, n
852 RangeEnd = Cmp1->getOperand(1);
853 } else if (Cmp1->getOperand(1) == Input) {
854 // For the upper range compare we have: icmp n, x
855 RangeEnd = Cmp1->getOperand(0);
856 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
857 } else {
858 return nullptr;
859 }
860
861 // Check the upper range comparison, e.g. x < n
862 ICmpInst::Predicate NewPred;
863 switch (Pred1) {
864 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
865 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
866 default: return nullptr;
867 }
868
869 // This simplification is only valid if the upper range is not negative.
870 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000871 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000872 if (!IsNotNegative)
873 return nullptr;
874
875 if (Inverted)
876 NewPred = ICmpInst::getInversePredicate(NewPred);
877
878 return Builder->CreateICmp(NewPred, Input, RangeEnd);
879}
880
Chris Lattner0a8191e2010-01-05 07:50:36 +0000881/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000882Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000883 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
884
885 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
886 if (PredicatesFoldable(LHSCC, RHSCC)) {
887 if (LHS->getOperand(0) == RHS->getOperand(1) &&
888 LHS->getOperand(1) == RHS->getOperand(0))
889 LHS->swapOperands();
890 if (LHS->getOperand(0) == RHS->getOperand(0) &&
891 LHS->getOperand(1) == RHS->getOperand(1)) {
892 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
893 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
894 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000895 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000896 }
897 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000898
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000899 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000900 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000901 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000902
Erik Ecksteind1817522014-12-03 10:39:15 +0000903 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
904 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
905 return V;
906
907 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
908 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
909 return V;
910
Chris Lattner0a8191e2010-01-05 07:50:36 +0000911 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
912 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
913 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
914 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000915 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000916
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 if (LHSCst == RHSCst && LHSCC == RHSCC) {
918 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
919 // where C is a power of 2
920 if (LHSCC == ICmpInst::ICMP_ULT &&
921 LHSCst->getValue().isPowerOf2()) {
922 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000923 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000924 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000925
Chris Lattner0a8191e2010-01-05 07:50:36 +0000926 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
927 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
928 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000929 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 }
931 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000932
Benjamin Kramer101720f2011-04-28 20:09:57 +0000933 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000934 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000935 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000936 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000937 LHS->hasOneUse() && RHS->hasOneUse()) {
938 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000939 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000940
941 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000942 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000943 if (match(Val2, m_Trunc(m_Value(V))) &&
944 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
945 SmallCst = RHSCst;
946 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000947 } else if (match(Val, m_Trunc(m_Value(V))) &&
948 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000949 SmallCst = LHSCst;
950 BigCst = RHSCst;
951 }
952
953 if (SmallCst && BigCst) {
954 unsigned BigBitSize = BigCst->getType()->getBitWidth();
955 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
956
957 // Check that the low bits are zero.
958 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000959 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000960 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
961 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
962 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
963 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
964 }
965 }
966 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000967
Chris Lattner0a8191e2010-01-05 07:50:36 +0000968 // From here on, we only handle:
969 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000970 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000971
Chris Lattner0a8191e2010-01-05 07:50:36 +0000972 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
973 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
974 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
975 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
976 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000977 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000978
979 // Make a constant range that's the intersection of the two icmp ranges.
980 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000981 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000982 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000983 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000984 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
985
986 if (LHSRange.intersectWith(RHSRange).isEmptySet())
987 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
988
Chris Lattner0a8191e2010-01-05 07:50:36 +0000989 // We can't fold (ugt x, C) & (sgt x, C2).
990 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000991 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000992
Chris Lattner0a8191e2010-01-05 07:50:36 +0000993 // Ensure that the larger constant is on the RHS.
994 bool ShouldSwap;
995 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000996 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000997 CmpInst::isSigned(RHSCC)))
998 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
999 else
1000 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001001
Chris Lattner0a8191e2010-01-05 07:50:36 +00001002 if (ShouldSwap) {
1003 std::swap(LHS, RHS);
1004 std::swap(LHSCst, RHSCst);
1005 std::swap(LHSCC, RHSCC);
1006 }
1007
Dan Gohman4a618822010-02-10 16:03:48 +00001008 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001009 // comparing a value against two constants and and'ing the result
1010 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001011 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1012 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001013 // are not equal and that the larger constant is on the RHS
1014 assert(LHSCst != RHSCst && "Compares not folded above?");
1015
1016 switch (LHSCC) {
1017 default: llvm_unreachable("Unknown integer condition code!");
1018 case ICmpInst::ICMP_EQ:
1019 switch (RHSCC) {
1020 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1022 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1023 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +00001024 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001025 }
1026 case ICmpInst::ICMP_NE:
1027 switch (RHSCC) {
1028 default: llvm_unreachable("Unknown integer condition code!");
1029 case ICmpInst::ICMP_ULT:
1030 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001031 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001032 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1033 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001034 break; // (X != 13 & X u< 15) -> no change
1035 case ICmpInst::ICMP_SLT:
1036 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001037 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001038 break; // (X != 13 & X s< 15) -> no change
1039 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1040 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1041 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001042 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001043 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001044 // Special case to get the ordering right when the values wrap around
1045 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001046 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001047 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001048 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1049 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1050 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001051 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1052 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001053 }
1054 break; // (X != 13 & X != 15) -> no change
1055 }
1056 break;
1057 case ICmpInst::ICMP_ULT:
1058 switch (RHSCC) {
1059 default: llvm_unreachable("Unknown integer condition code!");
1060 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1061 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001062 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001063 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1064 break;
1065 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1066 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001067 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001068 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1069 break;
1070 }
1071 break;
1072 case ICmpInst::ICMP_SLT:
1073 switch (RHSCC) {
1074 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001075 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1076 break;
1077 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1078 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001079 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001080 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1081 break;
1082 }
1083 break;
1084 case ICmpInst::ICMP_UGT:
1085 switch (RHSCC) {
1086 default: llvm_unreachable("Unknown integer condition code!");
1087 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1088 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001089 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001090 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1091 break;
1092 case ICmpInst::ICMP_NE:
1093 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001094 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001095 break; // (X u> 13 & X != 15) -> no change
1096 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001097 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001098 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1099 break;
1100 }
1101 break;
1102 case ICmpInst::ICMP_SGT:
1103 switch (RHSCC) {
1104 default: llvm_unreachable("Unknown integer condition code!");
1105 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1106 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001107 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001108 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1109 break;
1110 case ICmpInst::ICMP_NE:
1111 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001112 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001113 break; // (X s> 13 & X != 15) -> no change
1114 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001115 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001116 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1117 break;
1118 }
1119 break;
1120 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001121
Craig Topperf40110f2014-04-25 05:29:35 +00001122 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001123}
1124
Chris Lattner067459c2010-03-05 08:46:26 +00001125/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1126/// instcombine, this returns a Value which should already be inserted into the
1127/// function.
1128Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001129 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1130 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001131 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001132 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001133
Chris Lattner0a8191e2010-01-05 07:50:36 +00001134 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1135 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1136 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1137 // If either of the constants are nans, then the whole thing returns
1138 // false.
1139 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001140 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001141 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001142 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001143
Chris Lattner0a8191e2010-01-05 07:50:36 +00001144 // Handle vector zeros. This occurs because the canonical form of
1145 // "fcmp ord x,x" is "fcmp ord x, 0".
1146 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1147 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001148 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001149 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001150 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001151
Chris Lattner0a8191e2010-01-05 07:50:36 +00001152 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1153 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1154 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001155
1156
Chris Lattner0a8191e2010-01-05 07:50:36 +00001157 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1158 // Swap RHS operands to match LHS.
1159 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1160 std::swap(Op1LHS, Op1RHS);
1161 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001162
Chris Lattner0a8191e2010-01-05 07:50:36 +00001163 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1164 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1165 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001166 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001167 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001168 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001169 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001170 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001171 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001172 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001173
Chris Lattner0a8191e2010-01-05 07:50:36 +00001174 bool Op0Ordered;
1175 bool Op1Ordered;
1176 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1177 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001178 // uno && ord -> false
1179 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1180 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001181 if (Op1Pred == 0) {
1182 std::swap(LHS, RHS);
1183 std::swap(Op0Pred, Op1Pred);
1184 std::swap(Op0Ordered, Op1Ordered);
1185 }
1186 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001187 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001188 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001189 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1190 return LHS;
1191 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001192 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001193
Chris Lattner0a8191e2010-01-05 07:50:36 +00001194 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001195 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001196 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001197 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001198 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001199 }
1200 }
1201
Craig Topperf40110f2014-04-25 05:29:35 +00001202 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001203}
1204
Chris Lattner0a8191e2010-01-05 07:50:36 +00001205Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001206 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1208
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001209 if (Value *V = SimplifyVectorOp(I))
1210 return ReplaceInstUsesWith(I, V);
1211
Chandler Carruth66b31302015-01-04 12:03:27 +00001212 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001213 return ReplaceInstUsesWith(I, V);
1214
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001215 // (A|B)&(A|C) -> A|(B&C) etc
1216 if (Value *V = SimplifyUsingDistributiveLaws(I))
1217 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001218
Craig Topper9d4171a2012-12-20 07:09:41 +00001219 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001220 // purpose is to compute bits we don't care about.
1221 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001222 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001223
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001224 if (Value *V = SimplifyBSwap(I))
1225 return ReplaceInstUsesWith(I, V);
1226
Chris Lattner0a8191e2010-01-05 07:50:36 +00001227 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1228 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001229
1230 // Optimize a variety of ((val OP C1) & C2) combinations...
1231 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1232 Value *Op0LHS = Op0I->getOperand(0);
1233 Value *Op0RHS = Op0I->getOperand(1);
1234 switch (Op0I->getOpcode()) {
1235 default: break;
1236 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001237 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001238 // If the mask is only needed on one incoming arm, push it up.
1239 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001240
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001241 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001242 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001243 // Not masking anything out for the LHS, move to RHS.
1244 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1245 Op0RHS->getName()+".masked");
1246 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1247 }
1248 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001249 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001250 // Not masking anything out for the RHS, move to LHS.
1251 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1252 Op0LHS->getName()+".masked");
1253 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1254 }
1255
1256 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001257 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001258 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001259 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1260 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1261 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1263 return BinaryOperator::CreateAnd(V, AndRHS);
1264 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1265 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1266 break;
1267
1268 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001269 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1270 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1271 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001272 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1273 return BinaryOperator::CreateAnd(V, AndRHS);
1274
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001275 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001276 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001277 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001278 uint32_t BitWidth = AndRHSMask.getBitWidth();
1279 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1280 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1281
Hal Finkel60db0582014-09-07 18:57:58 +00001282 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001283 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1284 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1285 }
1286 }
1287 break;
1288
1289 case Instruction::Shl:
1290 case Instruction::LShr:
1291 // (1 << x) & 1 --> zext(x == 0)
1292 // (1 >> x) & 1 --> zext(x == 0)
1293 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1294 Value *NewICmp =
1295 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1296 return new ZExtInst(NewICmp, I.getType());
1297 }
1298 break;
1299 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001300
Chris Lattner0a8191e2010-01-05 07:50:36 +00001301 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1302 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1303 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001304 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001305
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001306 // If this is an integer truncation, and if the source is an 'and' with
1307 // immediate, transform it. This frequently occurs for bitfield accesses.
1308 {
Craig Topperf40110f2014-04-25 05:29:35 +00001309 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001310 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1311 // Change: and (trunc (and X, YC) to T), C2
1312 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001313 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001314 // other simplifications.
1315 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1316 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1317 C3 = ConstantExpr::getAnd(C3, AndRHS);
1318 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001319 }
1320 }
1321
1322 // Try to fold constant and into select arguments.
1323 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1324 if (Instruction *R = FoldOpIntoSelect(I, SI))
1325 return R;
1326 if (isa<PHINode>(Op0))
1327 if (Instruction *NV = FoldOpIntoPhi(I))
1328 return NV;
1329 }
1330
1331
1332 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1333 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1334 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1335 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1336 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1337 I.getName()+".demorgan");
1338 return BinaryOperator::CreateNot(Or);
1339 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001340
Chris Lattner0a8191e2010-01-05 07:50:36 +00001341 {
Craig Topperf40110f2014-04-25 05:29:35 +00001342 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001343 // (A|B) & ~(A&B) -> A^B
1344 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1345 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1346 ((A == C && B == D) || (A == D && B == C)))
1347 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001348
Chris Lattner0a8191e2010-01-05 07:50:36 +00001349 // ~(A&B) & (A|B) -> A^B
1350 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1351 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1352 ((A == C && B == D) || (A == D && B == C)))
1353 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001354
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001355 // A&(A^B) => A & ~B
1356 {
1357 Value *tmpOp0 = Op0;
1358 Value *tmpOp1 = Op1;
1359 if (Op0->hasOneUse() &&
1360 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1361 if (A == Op1 || B == Op1 ) {
1362 tmpOp1 = Op0;
1363 tmpOp0 = Op1;
1364 // Simplify below
1365 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001366 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001367
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001368 if (tmpOp1->hasOneUse() &&
1369 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1370 if (B == tmpOp0) {
1371 std::swap(A, B);
1372 }
1373 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1374 // A is originally -1 (or a vector of -1 and undefs), then we enter
1375 // an endless loop. By checking that A is non-constant we ensure that
1376 // we will never get to the loop.
1377 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001378 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001379 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001380 }
1381
1382 // (A&((~A)|B)) -> A&B
1383 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1384 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1385 return BinaryOperator::CreateAnd(A, Op1);
1386 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1387 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1388 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001389
1390 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1391 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1392 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1393 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1394 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1395
1396 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1397 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1398 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1399 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1400 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001401
1402 // (A | B) & ((~A) ^ B) -> (A & B)
1403 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1404 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1405 return BinaryOperator::CreateAnd(A, B);
1406
1407 // ((~A) ^ B) & (A | B) -> (A & B)
1408 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1409 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1410 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001411 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001412
David Majnemer5e96f1b2014-08-30 06:18:20 +00001413 {
1414 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1415 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1416 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001417 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1418 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001419
David Majnemer5e96f1b2014-08-30 06:18:20 +00001420 // TODO: Make this recursive; it's a little tricky because an arbitrary
1421 // number of 'and' instructions might have to be created.
1422 Value *X, *Y;
1423 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1424 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1425 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1426 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1427 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1428 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1429 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1430 }
1431 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1432 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1433 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1434 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1435 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1436 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1437 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1438 }
1439 }
1440
Chris Lattner4e8137d2010-02-11 06:26:33 +00001441 // If and'ing two fcmp, try combine them into one.
1442 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1443 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001444 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1445 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001446
1447
Chris Lattner0a8191e2010-01-05 07:50:36 +00001448 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1449 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001450 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001451 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001452 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1453 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001454 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001455 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001456
Chris Lattner4e8137d2010-02-11 06:26:33 +00001457 // Only do this if the casts both really cause code to be generated.
1458 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1459 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1460 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001461 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1462 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001463
Chris Lattner4e8137d2010-02-11 06:26:33 +00001464 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1465 // cast is otherwise not optimizable. This happens for vector sexts.
1466 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1467 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001468 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001469 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001470
Chris Lattner4e8137d2010-02-11 06:26:33 +00001471 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1472 // cast is otherwise not optimizable. This happens for vector sexts.
1473 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1474 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001475 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001476 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001477 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001478 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001479
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001480 {
Craig Topperf40110f2014-04-25 05:29:35 +00001481 Value *X = nullptr;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001482 bool OpsSwapped = false;
1483 // Canonicalize SExt or Not to the LHS
1484 if (match(Op1, m_SExt(m_Value())) ||
1485 match(Op1, m_Not(m_Value()))) {
1486 std::swap(Op0, Op1);
1487 OpsSwapped = true;
1488 }
1489
1490 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1491 if (match(Op0, m_SExt(m_Value(X))) &&
1492 X->getType()->getScalarType()->isIntegerTy(1)) {
1493 Value *Zero = Constant::getNullValue(Op1->getType());
1494 return SelectInst::Create(X, Op1, Zero);
1495 }
1496
1497 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1498 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1499 X->getType()->getScalarType()->isIntegerTy(1)) {
1500 Value *Zero = Constant::getNullValue(Op0->getType());
1501 return SelectInst::Create(X, Zero, Op1);
1502 }
1503
1504 if (OpsSwapped)
1505 std::swap(Op0, Op1);
1506 }
1507
Craig Topperf40110f2014-04-25 05:29:35 +00001508 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001509}
1510
1511/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1512/// capable of providing pieces of a bswap. The subexpression provides pieces
1513/// of a bswap if it is proven that each of the non-zero bytes in the output of
1514/// the expression came from the corresponding "byte swapped" byte in some other
1515/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1516/// we know that the expression deposits the low byte of %X into the high byte
1517/// of the bswap result and that all other bytes are zero. This expression is
1518/// accepted, the high byte of ByteValues is set to X to indicate a correct
1519/// match.
1520///
1521/// This function returns true if the match was unsuccessful and false if so.
1522/// On entry to the function the "OverallLeftShift" is a signed integer value
1523/// indicating the number of bytes that the subexpression is later shifted. For
1524/// example, if the expression is later right shifted by 16 bits, the
1525/// OverallLeftShift value would be -2 on entry. This is used to specify which
1526/// byte of ByteValues is actually being set.
1527///
1528/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1529/// byte is masked to zero by a user. For example, in (X & 255), X will be
1530/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1531/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1532/// always in the local (OverallLeftShift) coordinate space.
1533///
1534static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
Craig Topperb94011f2013-07-14 04:42:23 +00001535 SmallVectorImpl<Value *> &ByteValues) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001536 if (Instruction *I = dyn_cast<Instruction>(V)) {
1537 // If this is an or instruction, it may be an inner node of the bswap.
1538 if (I->getOpcode() == Instruction::Or) {
1539 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1540 ByteValues) ||
1541 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1542 ByteValues);
1543 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001544
Chris Lattner0a8191e2010-01-05 07:50:36 +00001545 // If this is a logical shift by a constant multiple of 8, recurse with
1546 // OverallLeftShift and ByteMask adjusted.
1547 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001548 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001549 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1550 // Ensure the shift amount is defined and of a byte value.
1551 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1552 return true;
1553
1554 unsigned ByteShift = ShAmt >> 3;
1555 if (I->getOpcode() == Instruction::Shl) {
1556 // X << 2 -> collect(X, +2)
1557 OverallLeftShift += ByteShift;
1558 ByteMask >>= ByteShift;
1559 } else {
1560 // X >>u 2 -> collect(X, -2)
1561 OverallLeftShift -= ByteShift;
1562 ByteMask <<= ByteShift;
1563 ByteMask &= (~0U >> (32-ByteValues.size()));
1564 }
1565
1566 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1567 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1568
Craig Topper9d4171a2012-12-20 07:09:41 +00001569 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001570 ByteValues);
1571 }
1572
1573 // If this is a logical 'and' with a mask that clears bytes, clear the
1574 // corresponding bytes in ByteMask.
1575 if (I->getOpcode() == Instruction::And &&
1576 isa<ConstantInt>(I->getOperand(1))) {
1577 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1578 unsigned NumBytes = ByteValues.size();
1579 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1580 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001581
Chris Lattner0a8191e2010-01-05 07:50:36 +00001582 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1583 // If this byte is masked out by a later operation, we don't care what
1584 // the and mask is.
1585 if ((ByteMask & (1 << i)) == 0)
1586 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001587
Chris Lattner0a8191e2010-01-05 07:50:36 +00001588 // If the AndMask is all zeros for this byte, clear the bit.
1589 APInt MaskB = AndMask & Byte;
1590 if (MaskB == 0) {
1591 ByteMask &= ~(1U << i);
1592 continue;
1593 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001594
Chris Lattner0a8191e2010-01-05 07:50:36 +00001595 // If the AndMask is not all ones for this byte, it's not a bytezap.
1596 if (MaskB != Byte)
1597 return true;
1598
1599 // Otherwise, this byte is kept.
1600 }
1601
Craig Topper9d4171a2012-12-20 07:09:41 +00001602 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001603 ByteValues);
1604 }
1605 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001606
Chris Lattner0a8191e2010-01-05 07:50:36 +00001607 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1608 // the input value to the bswap. Some observations: 1) if more than one byte
1609 // is demanded from this input, then it could not be successfully assembled
1610 // into a byteswap. At least one of the two bytes would not be aligned with
1611 // their ultimate destination.
1612 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001613 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001614
Chris Lattner0a8191e2010-01-05 07:50:36 +00001615 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1616 // is demanded, it needs to go into byte 0 of the result. This means that the
1617 // byte needs to be shifted until it lands in the right byte bucket. The
1618 // shift amount depends on the position: if the byte is coming from the high
1619 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1620 // low part, it must be shifted left.
1621 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001622 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1623 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001624
Chris Lattner0a8191e2010-01-05 07:50:36 +00001625 // If the destination byte value is already defined, the values are or'd
1626 // together, which isn't a bswap (unless it's an or of the same bits).
1627 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1628 return true;
1629 ByteValues[DestByteNo] = V;
1630 return false;
1631}
1632
1633/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1634/// If so, insert the new bswap intrinsic and return it.
1635Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001636 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001637 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001638 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001639 ITy->getBitWidth() > 32*8)
Craig Topperf40110f2014-04-25 05:29:35 +00001640 return nullptr; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001641
Chris Lattner0a8191e2010-01-05 07:50:36 +00001642 /// ByteValues - For each byte of the result, we keep track of which value
1643 /// defines each byte.
1644 SmallVector<Value*, 8> ByteValues;
1645 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001646
Chris Lattner0a8191e2010-01-05 07:50:36 +00001647 // Try to find all the pieces corresponding to the bswap.
1648 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1649 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Craig Topperf40110f2014-04-25 05:29:35 +00001650 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001651
Chris Lattner0a8191e2010-01-05 07:50:36 +00001652 // Check to see if all of the bytes come from the same value.
1653 Value *V = ByteValues[0];
Craig Topperf40110f2014-04-25 05:29:35 +00001654 if (!V) return nullptr; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001655
Chris Lattner0a8191e2010-01-05 07:50:36 +00001656 // Check to make sure that all of the bytes come from the same value.
1657 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1658 if (ByteValues[i] != V)
Craig Topperf40110f2014-04-25 05:29:35 +00001659 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001660 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001661 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001662 return CallInst::Create(F, V);
1663}
1664
1665/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1666/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1667/// we can simplify this expression to "cond ? C : D or B".
1668static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1669 Value *C, Value *D) {
1670 // If A is not a select of -1/0, this cannot match.
Craig Topperf40110f2014-04-25 05:29:35 +00001671 Value *Cond = nullptr;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001672 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001673 !Cond->getType()->isIntegerTy(1))
Craig Topperf40110f2014-04-25 05:29:35 +00001674 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001675
1676 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001677 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001678 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001679 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001680 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001681
Chris Lattner0a8191e2010-01-05 07:50:36 +00001682 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001683 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001684 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001685 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001686 return SelectInst::Create(Cond, C, D);
Craig Topperf40110f2014-04-25 05:29:35 +00001687 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001688}
1689
Chris Lattner067459c2010-03-05 08:46:26 +00001690/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001691Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1692 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001693 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1694
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001695 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1696 // if K1 and K2 are a one-bit mask.
1697 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1698 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1699
1700 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1701 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1702
1703 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1704 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1705 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1706 LAnd->getOpcode() == Instruction::And &&
1707 RAnd->getOpcode() == Instruction::And) {
1708
Craig Topperf40110f2014-04-25 05:29:35 +00001709 Value *Mask = nullptr;
1710 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001711 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00001712 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), false, 0, AC, CxtI, DT) &&
1713 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), false, 0, AC, CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001714 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1715 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1716 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00001717 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), false, 0, AC, CxtI,
1718 DT) &&
1719 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), false, 0, AC, CxtI,
1720 DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001721 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1722 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1723 }
1724
1725 if (Masked)
1726 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1727 }
1728 }
1729
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001730 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1731 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1732 // The original condition actually refers to the following two ranges:
1733 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1734 // We can fold these two ranges if:
1735 // 1) C1 and C2 is unsigned greater than C3.
1736 // 2) The two ranges are separated.
1737 // 3) C1 ^ C2 is one-bit mask.
1738 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1739 // This implies all values in the two ranges differ by exactly one bit.
1740
1741 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1742 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1743 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1744 LHSCst->getValue() == (RHSCst->getValue())) {
1745
1746 Value *LAdd = LHS->getOperand(0);
1747 Value *RAdd = RHS->getOperand(0);
1748
1749 Value *LAddOpnd, *RAddOpnd;
1750 ConstantInt *LAddCst, *RAddCst;
1751 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1752 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1753 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1754 RAddCst->getValue().ugt(LHSCst->getValue())) {
1755
1756 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1757 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1758 ConstantInt *MaxAddCst = nullptr;
1759 if (LAddCst->getValue().ult(RAddCst->getValue()))
1760 MaxAddCst = RAddCst;
1761 else
1762 MaxAddCst = LAddCst;
1763
1764 APInt RRangeLow = -RAddCst->getValue();
1765 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1766 APInt LRangeLow = -LAddCst->getValue();
1767 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1768 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1769 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1770 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1771 : RRangeLow - LRangeLow;
1772
1773 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1774 RangeDiff.ugt(LHSCst->getValue())) {
1775 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1776
1777 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1778 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1779 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1780 }
1781 }
1782 }
1783 }
1784
Chris Lattner0a8191e2010-01-05 07:50:36 +00001785 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1786 if (PredicatesFoldable(LHSCC, RHSCC)) {
1787 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1788 LHS->getOperand(1) == RHS->getOperand(0))
1789 LHS->swapOperands();
1790 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1791 LHS->getOperand(1) == RHS->getOperand(1)) {
1792 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1793 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1794 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001795 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001796 }
1797 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001798
1799 // handle (roughly):
1800 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001801 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001802 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001803
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001805 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1806 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1807 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001808 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001809 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1810 B = Val;
1811 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1812 A = Val2;
1813 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1814 A = RHS->getOperand(1);
1815 }
1816 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1817 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1818 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1819 B = Val2;
1820 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1821 A = Val;
1822 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1823 A = LHS->getOperand(1);
1824 }
1825 if (A && B)
1826 return Builder->CreateICmp(
1827 ICmpInst::ICMP_UGE,
1828 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1829 }
1830
Erik Ecksteind1817522014-12-03 10:39:15 +00001831 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1832 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1833 return V;
1834
1835 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1836 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1837 return V;
1838
David Majnemerc2a990b2013-07-05 00:31:17 +00001839 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001840 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001841
Owen Anderson8f306a72010-08-02 09:32:13 +00001842 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1843 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1844 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1845 Value *NewOr = Builder->CreateOr(Val, Val2);
1846 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1847 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001848 }
1849
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001850 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001851 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001852 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001853 ConstantInt *AddCst;
1854 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1855 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001856 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001857 }
1858
Chris Lattner0a8191e2010-01-05 07:50:36 +00001859 // From here on, we only handle:
1860 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001861 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001862
Chris Lattner0a8191e2010-01-05 07:50:36 +00001863 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1864 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1865 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1866 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1867 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001868 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001869
Chris Lattner0a8191e2010-01-05 07:50:36 +00001870 // We can't fold (ugt x, C) | (sgt x, C2).
1871 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001872 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001873
Chris Lattner0a8191e2010-01-05 07:50:36 +00001874 // Ensure that the larger constant is on the RHS.
1875 bool ShouldSwap;
1876 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001877 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001878 CmpInst::isSigned(RHSCC)))
1879 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1880 else
1881 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001882
Chris Lattner0a8191e2010-01-05 07:50:36 +00001883 if (ShouldSwap) {
1884 std::swap(LHS, RHS);
1885 std::swap(LHSCst, RHSCst);
1886 std::swap(LHSCC, RHSCC);
1887 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001888
Dan Gohman4a618822010-02-10 16:03:48 +00001889 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001890 // comparing a value against two constants and or'ing the result
1891 // together. Because of the above check, we know that we only have
1892 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1893 // icmp folding check above), that the two constants are not
1894 // equal.
1895 assert(LHSCst != RHSCst && "Compares not folded above?");
1896
1897 switch (LHSCC) {
1898 default: llvm_unreachable("Unknown integer condition code!");
1899 case ICmpInst::ICMP_EQ:
1900 switch (RHSCC) {
1901 default: llvm_unreachable("Unknown integer condition code!");
1902 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001903 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001904 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001905 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001906 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1907
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001908 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1909 if (Xor.isPowerOf2()) {
1910 Value *NegCst = Builder->getInt(~Xor);
1911 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1912 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1913 }
1914 }
1915
David Majnemer1fae1952013-04-14 21:15:43 +00001916 if (LHSCst == SubOne(RHSCst)) {
1917 // (X == 13 | X == 14) -> X-13 <u 2
1918 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1919 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1920 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1921 return Builder->CreateICmpULT(Add, AddCST);
1922 }
1923
Chris Lattner0a8191e2010-01-05 07:50:36 +00001924 break; // (X == 13 | X == 15) -> no change
1925 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1926 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1927 break;
1928 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1929 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1930 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001931 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001932 }
1933 break;
1934 case ICmpInst::ICMP_NE:
1935 switch (RHSCC) {
1936 default: llvm_unreachable("Unknown integer condition code!");
1937 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1938 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1939 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001940 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1942 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1943 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001944 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001945 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001946 case ICmpInst::ICMP_ULT:
1947 switch (RHSCC) {
1948 default: llvm_unreachable("Unknown integer condition code!");
1949 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1950 break;
1951 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1952 // If RHSCst is [us]MAXINT, it is always false. Not handling
1953 // this can cause overflow.
1954 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001955 return LHS;
1956 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001957 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1958 break;
1959 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1960 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001961 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001962 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1963 break;
1964 }
1965 break;
1966 case ICmpInst::ICMP_SLT:
1967 switch (RHSCC) {
1968 default: llvm_unreachable("Unknown integer condition code!");
1969 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1970 break;
1971 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1972 // If RHSCst is [us]MAXINT, it is always false. Not handling
1973 // this can cause overflow.
1974 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001975 return LHS;
1976 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1978 break;
1979 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1980 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001981 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001982 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1983 break;
1984 }
1985 break;
1986 case ICmpInst::ICMP_UGT:
1987 switch (RHSCC) {
1988 default: llvm_unreachable("Unknown integer condition code!");
1989 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1990 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001991 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001992 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1993 break;
1994 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1995 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001996 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001997 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1998 break;
1999 }
2000 break;
2001 case ICmpInst::ICMP_SGT:
2002 switch (RHSCC) {
2003 default: llvm_unreachable("Unknown integer condition code!");
2004 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2005 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00002006 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002007 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2008 break;
2009 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2010 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002011 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002012 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2013 break;
2014 }
2015 break;
2016 }
Craig Topperf40110f2014-04-25 05:29:35 +00002017 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002018}
2019
Chris Lattner067459c2010-03-05 08:46:26 +00002020/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
2021/// instcombine, this returns a Value which should already be inserted into the
2022/// function.
2023Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002024 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002025 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002026 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2027 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2028 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2029 // If either of the constants are nans, then the whole thing returns
2030 // true.
2031 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002032 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002033
Chris Lattner0a8191e2010-01-05 07:50:36 +00002034 // Otherwise, no need to compare the two constants, compare the
2035 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002036 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002038
Chris Lattner0a8191e2010-01-05 07:50:36 +00002039 // Handle vector zeros. This occurs because the canonical form of
2040 // "fcmp uno x,x" is "fcmp uno x, 0".
2041 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2042 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002043 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002044
Craig Topperf40110f2014-04-25 05:29:35 +00002045 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002047
Chris Lattner0a8191e2010-01-05 07:50:36 +00002048 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2049 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2050 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00002051
Chris Lattner0a8191e2010-01-05 07:50:36 +00002052 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2053 // Swap RHS operands to match LHS.
2054 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2055 std::swap(Op1LHS, Op1RHS);
2056 }
2057 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2058 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2059 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00002060 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002061 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00002062 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002063 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002064 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002065 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002066 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002067 bool Op0Ordered;
2068 bool Op1Ordered;
2069 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2070 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2071 if (Op0Ordered == Op1Ordered) {
2072 // If both are ordered or unordered, return a new fcmp with
2073 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00002074 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002075 }
2076 }
Craig Topperf40110f2014-04-25 05:29:35 +00002077 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002078}
2079
2080/// FoldOrWithConstants - This helper function folds:
2081///
2082/// ((A | B) & C1) | (B & C2)
2083///
2084/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002085///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086/// (A & C1) | B
2087///
2088/// when the XOR of the two constants is "all ones" (-1).
2089Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2090 Value *A, Value *B, Value *C) {
2091 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002092 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002093
Craig Topperf40110f2014-04-25 05:29:35 +00002094 Value *V1 = nullptr;
2095 ConstantInt *CI2 = nullptr;
2096 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097
2098 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002099 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002100
2101 if (V1 == A || V1 == B) {
2102 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2103 return BinaryOperator::CreateOr(NewOp, V1);
2104 }
2105
Craig Topperf40110f2014-04-25 05:29:35 +00002106 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002107}
2108
David Majnemer5d1aeba2014-08-21 05:14:48 +00002109/// \brief This helper function folds:
2110///
2111/// ((A | B) & C1) ^ (B & C2)
2112///
2113/// into:
2114///
2115/// (A & C1) ^ B
2116///
2117/// when the XOR of the two constants is "all ones" (-1).
2118Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2119 Value *A, Value *B, Value *C) {
2120 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2121 if (!CI1)
2122 return nullptr;
2123
2124 Value *V1 = nullptr;
2125 ConstantInt *CI2 = nullptr;
2126 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2127 return nullptr;
2128
2129 APInt Xor = CI1->getValue() ^ CI2->getValue();
2130 if (!Xor.isAllOnesValue())
2131 return nullptr;
2132
2133 if (V1 == A || V1 == B) {
2134 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2135 return BinaryOperator::CreateXor(NewOp, V1);
2136 }
2137
2138 return nullptr;
2139}
2140
Chris Lattner0a8191e2010-01-05 07:50:36 +00002141Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002142 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2144
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002145 if (Value *V = SimplifyVectorOp(I))
2146 return ReplaceInstUsesWith(I, V);
2147
Chandler Carruth66b31302015-01-04 12:03:27 +00002148 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002149 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002150
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002151 // (A&B)|(A&C) -> A&(B|C) etc
2152 if (Value *V = SimplifyUsingDistributiveLaws(I))
2153 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002154
Craig Topper9d4171a2012-12-20 07:09:41 +00002155 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002156 // purpose is to compute bits we don't care about.
2157 if (SimplifyDemandedInstructionBits(I))
2158 return &I;
2159
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002160 if (Value *V = SimplifyBSwap(I))
2161 return ReplaceInstUsesWith(I, V);
2162
Chris Lattner0a8191e2010-01-05 07:50:36 +00002163 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002164 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002165 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002166 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002167 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002168 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002169 Op0->hasOneUse()) {
2170 Value *Or = Builder->CreateOr(X, RHS);
2171 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002172 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002173 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002174 }
2175
2176 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2177 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2178 Op0->hasOneUse()) {
2179 Value *Or = Builder->CreateOr(X, RHS);
2180 Or->takeName(Op0);
2181 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002182 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002183 }
2184
2185 // Try to fold constant and into select arguments.
2186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2187 if (Instruction *R = FoldOpIntoSelect(I, SI))
2188 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002189
Chris Lattner0a8191e2010-01-05 07:50:36 +00002190 if (isa<PHINode>(Op0))
2191 if (Instruction *NV = FoldOpIntoPhi(I))
2192 return NV;
2193 }
2194
Craig Topperf40110f2014-04-25 05:29:35 +00002195 Value *A = nullptr, *B = nullptr;
2196 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002197
2198 // (A | B) | C and A | (B | C) -> bswap if possible.
2199 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
2200 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2201 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00002202 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2203 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002204 if (Instruction *BSwap = MatchBSwap(I))
2205 return BSwap;
2206 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002207
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002208 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002209 if (Op0->hasOneUse() &&
2210 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002211 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002212 Value *NOr = Builder->CreateOr(A, Op1);
2213 NOr->takeName(Op0);
2214 return BinaryOperator::CreateXor(NOr, C1);
2215 }
2216
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002217 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002218 if (Op1->hasOneUse() &&
2219 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002220 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002221 Value *NOr = Builder->CreateOr(A, Op0);
2222 NOr->takeName(Op0);
2223 return BinaryOperator::CreateXor(NOr, C1);
2224 }
2225
Suyog Sardad64faf62014-07-22 18:09:41 +00002226 // ((~A & B) | A) -> (A | B)
2227 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2228 match(Op1, m_Specific(A)))
2229 return BinaryOperator::CreateOr(A, B);
2230
2231 // ((A & B) | ~A) -> (~A | B)
2232 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2233 match(Op1, m_Not(m_Specific(A))))
2234 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2235
Suyog Sarda52324c82014-08-01 04:50:31 +00002236 // (A & (~B)) | (A ^ B) -> (A ^ B)
2237 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2238 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2239 return BinaryOperator::CreateXor(A, B);
2240
2241 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2242 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2243 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2244 return BinaryOperator::CreateXor(A, B);
2245
Chris Lattner0a8191e2010-01-05 07:50:36 +00002246 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002247 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002248 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2249 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002250 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002251 C1 = dyn_cast<ConstantInt>(C);
2252 C2 = dyn_cast<ConstantInt>(D);
2253 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002254 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002255 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002256 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002257 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002258 ((V1 == B &&
2259 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2260 (V2 == B &&
2261 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002262 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002263 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002264 // Or commutes, try both ways.
2265 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002266 ((V1 == A &&
2267 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2268 (V2 == A &&
2269 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002270 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002271 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002272
Chris Lattner95188692010-01-11 06:55:24 +00002273 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002274 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002275 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002276 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2277 (C3->getValue() & ~C1->getValue()) == 0 &&
2278 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2279 (C4->getValue() & ~C2->getValue()) == 0) {
2280 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2281 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002282 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002283 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002284 }
2285 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002286
Chris Lattner8e2c4712010-02-02 02:43:51 +00002287 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2288 // Don't do this for vector select idioms, the code generator doesn't handle
2289 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002290 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002291 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2292 return Match;
2293 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2294 return Match;
2295 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2296 return Match;
2297 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2298 return Match;
2299 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002300
2301 // ((A&~B)|(~A&B)) -> A^B
2302 if ((match(C, m_Not(m_Specific(D))) &&
2303 match(B, m_Not(m_Specific(A)))))
2304 return BinaryOperator::CreateXor(A, D);
2305 // ((~B&A)|(~A&B)) -> A^B
2306 if ((match(A, m_Not(m_Specific(D))) &&
2307 match(B, m_Not(m_Specific(C)))))
2308 return BinaryOperator::CreateXor(C, D);
2309 // ((A&~B)|(B&~A)) -> A^B
2310 if ((match(C, m_Not(m_Specific(B))) &&
2311 match(D, m_Not(m_Specific(A)))))
2312 return BinaryOperator::CreateXor(A, B);
2313 // ((~B&A)|(B&~A)) -> A^B
2314 if ((match(A, m_Not(m_Specific(B))) &&
2315 match(D, m_Not(m_Specific(C)))))
2316 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002317
2318 // ((A|B)&1)|(B&-2) -> (A&1) | B
2319 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2320 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2321 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2322 if (Ret) return Ret;
2323 }
2324 // (B&-2)|((A|B)&1) -> (A&1) | B
2325 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2326 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2327 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2328 if (Ret) return Ret;
2329 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002330 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2331 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2332 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2333 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2334 if (Ret) return Ret;
2335 }
2336 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2337 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2338 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2339 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2340 if (Ret) return Ret;
2341 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002342 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002343
David Majnemer42af3602014-07-30 21:26:37 +00002344 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2345 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2346 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2347 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2348 return BinaryOperator::CreateOr(Op0, C);
2349
2350 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2351 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2352 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2353 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2354 return BinaryOperator::CreateOr(Op1, C);
2355
David Majnemerf1eda232014-08-14 06:41:38 +00002356 // ((B | C) & A) | B -> B | (A & C)
2357 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2358 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2359
Chris Lattner0a8191e2010-01-05 07:50:36 +00002360 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2361 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2362 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2363 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2364 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2365 I.getName()+".demorgan");
2366 return BinaryOperator::CreateNot(And);
2367 }
2368
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002369 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002370 bool SwappedForXor = false;
2371 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002372 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002373 SwappedForXor = true;
2374 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002375
2376 // A | ( A ^ B) -> A | B
2377 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002378 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002379 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2380 if (Op0 == A || Op0 == B)
2381 return BinaryOperator::CreateOr(A, B);
2382
Chad Rosier7813dce2012-04-26 23:29:14 +00002383 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2384 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2385 return BinaryOperator::CreateOr(A, B);
2386
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002387 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2388 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2389 return BinaryOperator::CreateOr(Not, Op0);
2390 }
2391 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2392 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2393 return BinaryOperator::CreateOr(Not, Op0);
2394 }
2395 }
2396
2397 // A | ~(A | B) -> A | ~B
2398 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002399 if (match(Op1, m_Not(m_Value(A))))
2400 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002401 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2402 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2403 B->getOpcode() == Instruction::Xor)) {
2404 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2405 B->getOperand(0);
2406 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2407 return BinaryOperator::CreateOr(Not, Op0);
2408 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002409
Suyog Sarda16d64652014-08-01 04:41:43 +00002410 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2411 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2412 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2413 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2414
2415 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2416 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2417 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2418 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2419
Eli Friedmane06535b2012-03-16 00:52:42 +00002420 if (SwappedForXor)
2421 std::swap(Op0, Op1);
2422
David Majnemer3d6f80b2014-11-28 19:58:29 +00002423 {
2424 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2425 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2426 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002427 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner067459c2010-03-05 08:46:26 +00002428 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002429
David Majnemer3d6f80b2014-11-28 19:58:29 +00002430 // TODO: Make this recursive; it's a little tricky because an arbitrary
2431 // number of 'or' instructions might have to be created.
2432 Value *X, *Y;
2433 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2434 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2435 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2436 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2437 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2438 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2439 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2440 }
2441 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2442 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2443 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2444 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2445 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2446 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2447 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2448 }
2449 }
2450
Chris Lattner4e8137d2010-02-11 06:26:33 +00002451 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2452 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2453 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002454 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2455 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002456
Chris Lattner0a8191e2010-01-05 07:50:36 +00002457 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2458 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002459 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2460 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002461 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002462 if (SrcTy == Op1C->getOperand(0)->getType() &&
2463 SrcTy->isIntOrIntVectorTy()) {
2464 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002465
Chris Lattner311aa632011-01-15 05:40:29 +00002466 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2467 // Only do this if the casts both really cause code to be
2468 // generated.
2469 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2470 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2471 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2472 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002473 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002474
Chris Lattner311aa632011-01-15 05:40:29 +00002475 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2476 // cast is otherwise not optimizable. This happens for vector sexts.
2477 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2478 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Hal Finkel60db0582014-09-07 18:57:58 +00002479 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner311aa632011-01-15 05:40:29 +00002480 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002481
Chris Lattner311aa632011-01-15 05:40:29 +00002482 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2483 // cast is otherwise not optimizable. This happens for vector sexts.
2484 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2485 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2486 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2487 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002488 }
Chris Lattner311aa632011-01-15 05:40:29 +00002489 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002490 }
Eli Friedman23956262011-04-14 22:41:27 +00002491
2492 // or(sext(A), B) -> A ? -1 : B where A is an i1
2493 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2494 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2495 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2496 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2497 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2498
Owen Andersonc237a842010-09-13 17:59:27 +00002499 // Note: If we've gotten to the point of visiting the outer OR, then the
2500 // inner one couldn't be simplified. If it was a constant, then it won't
2501 // be simplified by a later pass either, so we try swapping the inner/outer
2502 // ORs in the hopes that we'll be able to simplify it this way.
2503 // (X|C) | V --> (X|V) | C
2504 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2505 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2506 Value *Inner = Builder->CreateOr(A, Op1);
2507 Inner->takeName(Op0);
2508 return BinaryOperator::CreateOr(Inner, C1);
2509 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002510
Bill Wendling23242092013-02-16 23:41:36 +00002511 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2512 // Since this OR statement hasn't been optimized further yet, we hope
2513 // that this transformation will allow the new ORs to be optimized.
2514 {
Craig Topperf40110f2014-04-25 05:29:35 +00002515 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002516 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2517 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2518 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2519 Value *orTrue = Builder->CreateOr(A, C);
2520 Value *orFalse = Builder->CreateOr(B, D);
2521 return SelectInst::Create(X, orTrue, orFalse);
2522 }
2523 }
2524
Craig Topperf40110f2014-04-25 05:29:35 +00002525 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002526}
2527
2528Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002529 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002530 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2531
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002532 if (Value *V = SimplifyVectorOp(I))
2533 return ReplaceInstUsesWith(I, V);
2534
Chandler Carruth66b31302015-01-04 12:03:27 +00002535 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002536 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002537
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002538 // (A&B)^(A&C) -> A&(B^C) etc
2539 if (Value *V = SimplifyUsingDistributiveLaws(I))
2540 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002541
Craig Topper9d4171a2012-12-20 07:09:41 +00002542 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002543 // purpose is to compute bits we don't care about.
2544 if (SimplifyDemandedInstructionBits(I))
2545 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002546
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002547 if (Value *V = SimplifyBSwap(I))
2548 return ReplaceInstUsesWith(I, V);
2549
Chris Lattner0a8191e2010-01-05 07:50:36 +00002550 // Is this a ~ operation?
2551 if (Value *NotOp = dyn_castNotVal(&I)) {
2552 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002553 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554 Op0I->getOpcode() == Instruction::Or) {
2555 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2556 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2557 if (dyn_castNotVal(Op0I->getOperand(1)))
2558 Op0I->swapOperands();
2559 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2560 Value *NotY =
2561 Builder->CreateNot(Op0I->getOperand(1),
2562 Op0I->getOperand(1)->getName()+".not");
2563 if (Op0I->getOpcode() == Instruction::And)
2564 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2565 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2566 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002567
Chris Lattner0a8191e2010-01-05 07:50:36 +00002568 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2569 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002570 if (IsFreeToInvert(Op0I->getOperand(0),
2571 Op0I->getOperand(0)->hasOneUse()) &&
2572 IsFreeToInvert(Op0I->getOperand(1),
2573 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002574 Value *NotX =
2575 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2576 Value *NotY =
2577 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2578 if (Op0I->getOpcode() == Instruction::And)
2579 return BinaryOperator::CreateOr(NotX, NotY);
2580 return BinaryOperator::CreateAnd(NotX, NotY);
2581 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002582
2583 } else if (Op0I->getOpcode() == Instruction::AShr) {
2584 // ~(~X >>s Y) --> (X >>s Y)
2585 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2586 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002587 }
2588 }
2589 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002590
Benjamin Kramer443c7962015-02-12 20:26:46 +00002591 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2592 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002593 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002594 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2595 return CmpInst::Create(CI->getOpcode(),
2596 CI->getInversePredicate(),
2597 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002598 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002599
Benjamin Kramer443c7962015-02-12 20:26:46 +00002600 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002601 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2602 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2603 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2604 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2605 Instruction::CastOps Opcode = Op0C->getOpcode();
2606 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002607 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002608 Op0C->getDestTy()))) {
2609 CI->setPredicate(CI->getInversePredicate());
2610 return CastInst::Create(Opcode, CI, Op0C->getType());
2611 }
2612 }
2613 }
2614 }
2615
2616 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2617 // ~(c-X) == X-c-1 == X+(-c-1)
2618 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2619 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2620 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2621 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2622 ConstantInt::get(I.getType(), 1));
2623 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2624 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002625
Chris Lattner0a8191e2010-01-05 07:50:36 +00002626 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2627 if (Op0I->getOpcode() == Instruction::Add) {
2628 // ~(X-c) --> (-c-1)-X
2629 if (RHS->isAllOnesValue()) {
2630 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2631 return BinaryOperator::CreateSub(
2632 ConstantExpr::getSub(NegOp0CI,
2633 ConstantInt::get(I.getType(), 1)),
2634 Op0I->getOperand(0));
2635 } else if (RHS->getValue().isSignBit()) {
2636 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002637 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002638 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2639
2640 }
2641 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002642 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002643 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2644 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002645 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2646 // Anything in both C1 and C2 is known to be zero, remove it from
2647 // NewRHS.
2648 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002649 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002650 ConstantExpr::getNot(CommonBits));
2651 Worklist.Add(Op0I);
2652 I.setOperand(0, Op0I->getOperand(0));
2653 I.setOperand(1, NewRHS);
2654 return &I;
2655 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002656 } else if (Op0I->getOpcode() == Instruction::LShr) {
2657 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2658 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002659 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002660 ConstantInt *C1;
2661 if (Op0I->hasOneUse() &&
2662 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2663 E1->getOpcode() == Instruction::Xor &&
2664 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2665 // fold (C1 >> C2) ^ C3
2666 ConstantInt *C2 = Op0CI, *C3 = RHS;
2667 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2668 FoldConst ^= C3->getValue();
2669 // Prepare the two operands.
2670 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2671 Opnd0->takeName(Op0I);
2672 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2673 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2674
2675 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2676 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002677 }
2678 }
2679 }
2680
2681 // Try to fold constant and into select arguments.
2682 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2683 if (Instruction *R = FoldOpIntoSelect(I, SI))
2684 return R;
2685 if (isa<PHINode>(Op0))
2686 if (Instruction *NV = FoldOpIntoPhi(I))
2687 return NV;
2688 }
2689
Chris Lattner0a8191e2010-01-05 07:50:36 +00002690 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2691 if (Op1I) {
2692 Value *A, *B;
2693 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2694 if (A == Op0) { // B^(B|A) == (A|B)^B
2695 Op1I->swapOperands();
2696 I.swapOperands();
2697 std::swap(Op0, Op1);
2698 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2699 I.swapOperands(); // Simplified below.
2700 std::swap(Op0, Op1);
2701 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002702 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002703 Op1I->hasOneUse()){
2704 if (A == Op0) { // A^(A&B) -> A^(B&A)
2705 Op1I->swapOperands();
2706 std::swap(A, B);
2707 }
2708 if (B == Op0) { // A^(B&A) -> (B&A)^A
2709 I.swapOperands(); // Simplified below.
2710 std::swap(Op0, Op1);
2711 }
2712 }
2713 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002714
Chris Lattner0a8191e2010-01-05 07:50:36 +00002715 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2716 if (Op0I) {
2717 Value *A, *B;
2718 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2719 Op0I->hasOneUse()) {
2720 if (A == Op1) // (B|A)^B == (A|B)^B
2721 std::swap(A, B);
2722 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002723 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002724 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002725 Op0I->hasOneUse()){
2726 if (A == Op1) // (A&B)^A -> (B&A)^A
2727 std::swap(A, B);
2728 if (B == Op1 && // (B&A)^A == ~B & A
2729 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002730 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002731 }
2732 }
2733 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002734
Chris Lattner0a8191e2010-01-05 07:50:36 +00002735 if (Op0I && Op1I) {
2736 Value *A, *B, *C, *D;
2737 // (A & B)^(A | B) -> A ^ B
2738 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2739 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002740 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002741 return BinaryOperator::CreateXor(A, B);
2742 }
2743 // (A | B)^(A & B) -> A ^ B
2744 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2745 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002746 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002747 return BinaryOperator::CreateXor(A, B);
2748 }
David Majnemer698dca02014-08-14 06:46:25 +00002749 // (A | ~B) ^ (~A | B) -> A ^ B
2750 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2751 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2752 return BinaryOperator::CreateXor(A, B);
2753 }
2754 // (~A | B) ^ (A | ~B) -> A ^ B
2755 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2756 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2757 return BinaryOperator::CreateXor(A, B);
2758 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002759 // (A & ~B) ^ (~A & B) -> A ^ B
2760 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2761 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2762 return BinaryOperator::CreateXor(A, B);
2763 }
2764 // (~A & B) ^ (A & ~B) -> A ^ B
2765 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2766 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2767 return BinaryOperator::CreateXor(A, B);
2768 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002769 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2770 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2771 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2772 if (D == A)
2773 return BinaryOperator::CreateXor(
2774 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2775 if (D == B)
2776 return BinaryOperator::CreateXor(
2777 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002778 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002779 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002780 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002781 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2782 if (D == A)
2783 return BinaryOperator::CreateXor(
2784 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2785 if (D == B)
2786 return BinaryOperator::CreateXor(
2787 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002788 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002789 // (A & B) ^ (A ^ B) -> (A | B)
2790 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2791 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2792 return BinaryOperator::CreateOr(A, B);
2793 // (A ^ B) ^ (A & B) -> (A | B)
2794 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2795 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2796 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002797 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002798
Suyog Sarda521237c2014-07-22 15:37:39 +00002799 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002800 // (A & ~B) ^ (~A) -> ~(A & B)
2801 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2802 match(Op1, m_Not(m_Specific(A))))
2803 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2804
Chris Lattner0a8191e2010-01-05 07:50:36 +00002805 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2806 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2807 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2808 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2809 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2810 LHS->getOperand(1) == RHS->getOperand(0))
2811 LHS->swapOperands();
2812 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2813 LHS->getOperand(1) == RHS->getOperand(1)) {
2814 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2815 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2816 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002817 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002818 getNewICmpValue(isSigned, Code, Op0, Op1,
2819 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002820 }
2821 }
2822
2823 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2824 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2825 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2826 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002827 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002828 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002829 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002830 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002831 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002832 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002833 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002834 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2835 Op1C->getOperand(0), I.getName());
2836 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2837 }
2838 }
2839 }
2840
Craig Topperf40110f2014-04-25 05:29:35 +00002841 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002842}