blob: e210c99d126381771359c2a2591aaed767ce80b8 [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:
Nick Lewycky8075fd22015-08-14 22:46:49 +000096 if (!isordered)
97 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Owen Andersona8342002011-01-21 19:39:42 +000098 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +000099 }
Chris Lattner067459c2010-03-05 08:46:26 +0000100 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000101}
102
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000103/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
104/// \param I Binary operator to transform.
105/// \return Pointer to node that must replace the original binary operator, or
106/// null pointer if no transformation was made.
107Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
108 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
109
110 // Can't do vectors.
111 if (I.getType()->isVectorTy()) return nullptr;
112
113 // Can only do bitwise ops.
114 unsigned Op = I.getOpcode();
115 if (Op != Instruction::And && Op != Instruction::Or &&
116 Op != Instruction::Xor)
117 return nullptr;
118
119 Value *OldLHS = I.getOperand(0);
120 Value *OldRHS = I.getOperand(1);
121 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
122 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
123 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
124 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
125 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
126 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
127
128 if (!IsBswapLHS && !IsBswapRHS)
129 return nullptr;
130
131 if (!IsBswapLHS && !ConstLHS)
132 return nullptr;
133
134 if (!IsBswapRHS && !ConstRHS)
135 return nullptr;
136
137 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
138 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
139 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
140 Builder->getInt(ConstLHS->getValue().byteSwap());
141
142 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
143 Builder->getInt(ConstRHS->getValue().byteSwap());
144
145 Value *BinOp = nullptr;
146 if (Op == Instruction::And)
147 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
148 else if (Op == Instruction::Or)
149 BinOp = Builder->CreateOr(NewLHS, NewRHS);
150 else //if (Op == Instruction::Xor)
151 BinOp = Builder->CreateXor(NewLHS, NewRHS);
152
153 Module *M = I.getParent()->getParent()->getParent();
154 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
155 return Builder->CreateCall(F, BinOp);
156}
157
Chris Lattner0a8191e2010-01-05 07:50:36 +0000158// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
159// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
160// guaranteed to be a binary operator.
161Instruction *InstCombiner::OptAndOp(Instruction *Op,
162 ConstantInt *OpRHS,
163 ConstantInt *AndRHS,
164 BinaryOperator &TheAnd) {
165 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000166 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000167 if (!Op->isShift())
168 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
169
170 switch (Op->getOpcode()) {
171 case Instruction::Xor:
172 if (Op->hasOneUse()) {
173 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
174 Value *And = Builder->CreateAnd(X, AndRHS);
175 And->takeName(Op);
176 return BinaryOperator::CreateXor(And, Together);
177 }
178 break;
179 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000180 if (Op->hasOneUse()){
181 if (Together != OpRHS) {
182 // (X | C1) & C2 --> (X | (C1&C2)) & C2
183 Value *Or = Builder->CreateOr(X, Together);
184 Or->takeName(Op);
185 return BinaryOperator::CreateAnd(Or, AndRHS);
186 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000187
Owen Andersonc237a842010-09-13 17:59:27 +0000188 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
189 if (TogetherCI && !TogetherCI->isZero()){
190 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
191 // NOTE: This reduces the number of bits set in the & mask, which
192 // can expose opportunities for store narrowing.
193 Together = ConstantExpr::getXor(AndRHS, Together);
194 Value *And = Builder->CreateAnd(X, Together);
195 And->takeName(Op);
196 return BinaryOperator::CreateOr(And, OpRHS);
197 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000198 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000199
Chris Lattner0a8191e2010-01-05 07:50:36 +0000200 break;
201 case Instruction::Add:
202 if (Op->hasOneUse()) {
203 // Adding a one to a single bit bit-field should be turned into an XOR
204 // of the bit. First thing to check is to see if this AND is with a
205 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000206 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000207
208 // If there is only one bit set.
209 if (AndRHSV.isPowerOf2()) {
210 // Ok, at this point, we know that we are masking the result of the
211 // ADD down to exactly one bit. If the constant we are adding has
212 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000213 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000214
215 // Check to see if any bits below the one bit set in AndRHSV are set.
216 if ((AddRHS & (AndRHSV-1)) == 0) {
217 // If not, the only thing that can effect the output of the AND is
218 // the bit specified by AndRHSV. If that bit is set, the effect of
219 // the XOR is to toggle the bit. If it is clear, then the ADD has
220 // no effect.
221 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
222 TheAnd.setOperand(0, X);
223 return &TheAnd;
224 } else {
225 // Pull the XOR out of the AND.
226 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
227 NewAnd->takeName(Op);
228 return BinaryOperator::CreateXor(NewAnd, AndRHS);
229 }
230 }
231 }
232 }
233 break;
234
235 case Instruction::Shl: {
236 // We know that the AND will not produce any of the bits shifted in, so if
237 // the anded constant includes them, clear them now!
238 //
239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
241 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000242 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000243
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000244 if (CI->getValue() == ShlMask)
245 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000246 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000247
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000248 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000249 TheAnd.setOperand(1, CI);
250 return &TheAnd;
251 }
252 break;
253 }
254 case Instruction::LShr: {
255 // We know that the AND will not produce any of the bits shifted in, so if
256 // the anded constant includes them, clear them now! This only applies to
257 // unsigned shifts, because a signed shr may bring in set bits!
258 //
259 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
260 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
261 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000262 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000263
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000264 if (CI->getValue() == ShrMask)
265 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000266 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000267
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000268 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000269 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
270 return &TheAnd;
271 }
272 break;
273 }
274 case Instruction::AShr:
275 // Signed shr.
276 // See if this is shifting in some sign extension, then masking it out
277 // with an and.
278 if (Op->hasOneUse()) {
279 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
280 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
281 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000282 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000283 if (C == AndRHS) { // Masking out bits shifted in.
284 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
285 // Make the argument unsigned.
286 Value *ShVal = Op->getOperand(0);
287 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
288 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
289 }
290 }
291 break;
292 }
Craig Topperf40110f2014-04-25 05:29:35 +0000293 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000294}
295
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000296/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
297/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000298/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000299/// whether to treat the V, Lo and HI as signed or not. IB is the location to
300/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000301Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
302 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000303 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000304 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
305 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000306
Chris Lattner0a8191e2010-01-05 07:50:36 +0000307 if (Inside) {
308 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000309 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000310
311 // V >= Min && V < Hi --> V < Hi
312 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000313 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000314 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000315 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000316 }
317
318 // Emit V-Lo <u Hi-Lo
319 Constant *NegLo = ConstantExpr::getNeg(Lo);
320 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
321 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000322 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000323 }
324
325 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000326 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327
328 // V < Min || V >= Hi -> V > Hi-1
329 Hi = SubOne(cast<ConstantInt>(Hi));
330 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000331 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000332 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000333 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000334 }
335
336 // Emit V-Lo >u Hi-1-Lo
337 // Note that Hi has already had one subtracted from it, above.
338 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
339 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
340 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000341 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000342}
343
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000344// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000345// any number of 0s on either side. The 1s are allowed to wrap from LSB to
346// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
347// not, since all 1s are not contiguous.
348static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
349 const APInt& V = Val->getValue();
350 uint32_t BitWidth = Val->getType()->getBitWidth();
351 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
352
353 // look for the first zero bit after the run of ones
354 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
355 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000356 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000357 return true;
358}
359
360/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
361/// where isSub determines whether the operator is a sub. If we can fold one of
362/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000363///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000364/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
365/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
366/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000367///
368/// return (A +/- B).
369///
370Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
371 ConstantInt *Mask, bool isSub,
372 Instruction &I) {
373 Instruction *LHSI = dyn_cast<Instruction>(LHS);
374 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000375 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000376
377 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
378
379 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000380 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000381 case Instruction::And:
382 if (ConstantExpr::getAnd(N, Mask) == Mask) {
383 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000384 if ((Mask->getValue().countLeadingZeros() +
385 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000386 Mask->getValue().getBitWidth())
387 break;
388
389 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
390 // part, we don't need any explicit masks to take them out of A. If that
391 // is all N is, ignore it.
392 uint32_t MB = 0, ME = 0;
393 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
394 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
395 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000396 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000397 break;
398 }
399 }
Craig Topperf40110f2014-04-25 05:29:35 +0000400 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000401 case Instruction::Or:
402 case Instruction::Xor:
403 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000404 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000405 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
406 && ConstantExpr::getAnd(N, Mask)->isNullValue())
407 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000408 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000409 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000410
Chris Lattner0a8191e2010-01-05 07:50:36 +0000411 if (isSub)
412 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
413 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
414}
415
Owen Anderson3fe002d2010-09-08 22:16:17 +0000416/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000417/// One of A and B is considered the mask, the other the value. This is
418/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000419/// contains only "Mask", then both A and B can be considered masks.
420/// If A is the mask, then it was proven, that (A & C) == C. This
421/// is trivial if C == A, or C == 0. If both A and C are constants, this
422/// proof is also easy.
423/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000424/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000425/// if (A & B) == A, or all bits of A are set in B.
426/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000427/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000428/// if (A & B) == 0, or all bits of A are cleared in B.
429/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000430/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000431/// contain any number of one bits and zero bits.
432/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
433/// The Part "Not" means, that in above descriptions "==" should be replaced
434/// by "!=".
435/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
436/// If the mask A contains a single bit, then the following is equivalent:
437/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
438/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
439enum MaskedICmpType {
440 FoldMskICmp_AMask_AllOnes = 1,
441 FoldMskICmp_AMask_NotAllOnes = 2,
442 FoldMskICmp_BMask_AllOnes = 4,
443 FoldMskICmp_BMask_NotAllOnes = 8,
444 FoldMskICmp_Mask_AllZeroes = 16,
445 FoldMskICmp_Mask_NotAllZeroes = 32,
446 FoldMskICmp_AMask_Mixed = 64,
447 FoldMskICmp_AMask_NotMixed = 128,
448 FoldMskICmp_BMask_Mixed = 256,
449 FoldMskICmp_BMask_NotMixed = 512
450};
451
452/// return the set of pattern classes (from MaskedICmpType)
453/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000454static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000455 ICmpInst::Predicate SCC)
456{
457 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
458 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
459 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
460 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000461 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000462 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000463 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000464 BCst->getValue().isPowerOf2());
465 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000466 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000467 // if C is zero, then both A and B qualify as mask
468 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
469 FoldMskICmp_Mask_AllZeroes |
470 FoldMskICmp_AMask_Mixed |
471 FoldMskICmp_BMask_Mixed)
472 : (FoldMskICmp_Mask_NotAllZeroes |
473 FoldMskICmp_Mask_NotAllZeroes |
474 FoldMskICmp_AMask_NotMixed |
475 FoldMskICmp_BMask_NotMixed));
476 if (icmp_abit)
477 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000478 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000479 : (FoldMskICmp_AMask_AllOnes |
480 FoldMskICmp_AMask_Mixed));
481 if (icmp_bbit)
482 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000483 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000484 : (FoldMskICmp_BMask_AllOnes |
485 FoldMskICmp_BMask_Mixed));
486 return result;
487 }
488 if (A == C) {
489 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
490 FoldMskICmp_AMask_Mixed)
491 : (FoldMskICmp_AMask_NotAllOnes |
492 FoldMskICmp_AMask_NotMixed));
493 if (icmp_abit)
494 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
495 FoldMskICmp_AMask_NotMixed)
496 : (FoldMskICmp_Mask_AllZeroes |
497 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000498 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000499 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000500 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
501 : FoldMskICmp_AMask_NotMixed);
502 }
Craig Topperae48cb22012-12-20 07:15:54 +0000503 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000504 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
505 FoldMskICmp_BMask_Mixed)
506 : (FoldMskICmp_BMask_NotAllOnes |
507 FoldMskICmp_BMask_NotMixed));
508 if (icmp_bbit)
509 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000510 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000511 : (FoldMskICmp_Mask_AllZeroes |
512 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000513 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000514 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000515 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
516 : FoldMskICmp_BMask_NotMixed);
517 }
518 return result;
519}
520
Tim Northoverc0756c42013-09-04 11:57:13 +0000521/// Convert an analysis of a masked ICmp into its equivalent if all boolean
522/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
523/// is adjacent to the corresponding normal flag (recording ==), this just
524/// involves swapping those bits over.
525static unsigned conjugateICmpMask(unsigned Mask) {
526 unsigned NewMask;
527 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
528 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
529 FoldMskICmp_BMask_Mixed))
530 << 1;
531
532 NewMask |=
533 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
534 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
535 FoldMskICmp_BMask_NotMixed))
536 >> 1;
537
538 return NewMask;
539}
540
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000541/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
542/// if possible. The returned predicate is either == or !=. Returns false if
543/// decomposition fails.
544static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
545 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000546 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
547 if (!C)
548 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000549
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000550 switch (I->getPredicate()) {
551 default:
552 return false;
553 case ICmpInst::ICMP_SLT:
554 // X < 0 is equivalent to (X & SignBit) != 0.
555 if (!C->isZero())
556 return false;
557 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
558 Pred = ICmpInst::ICMP_NE;
559 break;
560 case ICmpInst::ICMP_SGT:
561 // X > -1 is equivalent to (X & SignBit) == 0.
562 if (!C->isAllOnesValue())
563 return false;
564 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
565 Pred = ICmpInst::ICMP_EQ;
566 break;
567 case ICmpInst::ICMP_ULT:
568 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
569 if (!C->getValue().isPowerOf2())
570 return false;
571 Y = ConstantInt::get(I->getContext(), -C->getValue());
572 Pred = ICmpInst::ICMP_EQ;
573 break;
574 case ICmpInst::ICMP_UGT:
575 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
576 if (!(C->getValue() + 1).isPowerOf2())
577 return false;
578 Y = ConstantInt::get(I->getContext(), ~C->getValue());
579 Pred = ICmpInst::ICMP_NE;
580 break;
581 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000582
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000583 X = I->getOperand(0);
584 Z = ConstantInt::getNullValue(C->getType());
585 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000586}
587
Owen Anderson3fe002d2010-09-08 22:16:17 +0000588/// foldLogOpOfMaskedICmpsHelper:
589/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
590/// return the set of pattern classes (from MaskedICmpType)
591/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000592static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000593 Value*& B, Value*& C,
594 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000595 ICmpInst *LHS, ICmpInst *RHS,
596 ICmpInst::Predicate &LHSCC,
597 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000598 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
599 // vectors are not (yet?) supported
600 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
601
602 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000603 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000604 // and L11 & L12 == L21 & L22. The same goes for RHS.
605 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000606 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000607 // above.
608 Value *L1 = LHS->getOperand(0);
609 Value *L2 = LHS->getOperand(1);
610 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000611 // Check whether the icmp can be decomposed into a bit test.
612 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000613 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000614 } else {
615 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000616 if (!L1->getType()->isIntegerTy()) {
617 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000618 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000619 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
620 // Any icmp can be viewed as being trivially masked; if it allows us to
621 // remove one, it's worth it.
622 L11 = L1;
623 L12 = Constant::getAllOnesValue(L1->getType());
624 }
625
626 if (!L2->getType()->isIntegerTy()) {
627 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000628 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000629 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
630 L21 = L2;
631 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000632 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000633 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000634
635 // Bail if LHS was a icmp that can't be decomposed into an equality.
636 if (!ICmpInst::isEquality(LHSCC))
637 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000638
639 Value *R1 = RHS->getOperand(0);
640 Value *R2 = RHS->getOperand(1);
641 Value *R11,*R12;
642 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000643 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
644 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
645 A = R11; D = R12;
646 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
647 A = R12; D = R11;
648 } else {
649 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000650 }
Craig Topperf40110f2014-04-25 05:29:35 +0000651 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000652 } else if (R1->getType()->isIntegerTy()) {
653 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
654 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000655 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000656 R11 = R1;
657 R12 = Constant::getAllOnesValue(R1->getType());
658 }
659
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000660 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
661 A = R11; D = R12; E = R2; ok = true;
662 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000663 A = R12; D = R11; E = R2; ok = true;
664 }
665 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000666
667 // Bail if RHS was a icmp that can't be decomposed into an equality.
668 if (!ICmpInst::isEquality(RHSCC))
669 return 0;
670
671 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000672 if (!ok && R2->getType()->isIntegerTy()) {
673 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
674 R11 = R2;
675 R12 = Constant::getAllOnesValue(R2->getType());
676 }
677
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000678 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
679 A = R11; D = R12; E = R1; ok = true;
680 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000681 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000682 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000683 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000684 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000685 }
686 if (!ok)
687 return 0;
688
689 if (L11 == A) {
690 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000691 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000692 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000693 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000694 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000695 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000696 B = L21; C = L1;
697 }
698
699 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
700 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
701 return left_type & right_type;
702}
703/// foldLogOpOfMaskedICmps:
704/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
705/// into a single (icmp(A & X) ==/!= Y)
David Majnemer1a3327b2014-11-18 09:31:36 +0000706static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
707 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000708 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000709 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
710 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
711 LHSCC, RHSCC);
Craig Topperf40110f2014-04-25 05:29:35 +0000712 if (mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000713 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
714 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000715
Tim Northoverc0756c42013-09-04 11:57:13 +0000716 // In full generality:
717 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
718 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
719 //
720 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
721 // equivalent to (icmp (A & X) !Op Y).
722 //
723 // Therefore, we can pretend for the rest of this function that we're dealing
724 // with the conjunction, provided we flip the sense of any comparisons (both
725 // input and output).
726
727 // In most cases we're going to produce an EQ for the "&&" case.
728 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
729 if (!IsAnd) {
730 // Convert the masking analysis into its equivalent with negated
731 // comparisons.
732 mask = conjugateICmpMask(mask);
733 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000734
735 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000736 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000737 // -> (icmp eq (A & (B|D)), 0)
David Majnemer1a3327b2014-11-18 09:31:36 +0000738 Value *newOr = Builder->CreateOr(B, D);
739 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000740 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000741 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000742 // with B and D, having a single bit set
David Majnemer1a3327b2014-11-18 09:31:36 +0000743 Value *zero = Constant::getNullValue(A->getType());
Owen Anderson3fe002d2010-09-08 22:16:17 +0000744 return Builder->CreateICmp(NEWCC, newAnd, zero);
745 }
Craig Topperae48cb22012-12-20 07:15:54 +0000746 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000747 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000748 // -> (icmp eq (A & (B|D)), (B|D))
David Majnemer1a3327b2014-11-18 09:31:36 +0000749 Value *newOr = Builder->CreateOr(B, D);
750 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000751 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000752 }
Craig Topperae48cb22012-12-20 07:15:54 +0000753 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000754 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000755 // -> (icmp eq (A & (B&D)), A)
David Majnemer1a3327b2014-11-18 09:31:36 +0000756 Value *newAnd1 = Builder->CreateAnd(B, D);
757 Value *newAnd = Builder->CreateAnd(A, newAnd1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000758 return Builder->CreateICmp(NEWCC, newAnd, A);
759 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000760
761 // Remaining cases assume at least that B and D are constant, and depend on
762 // their actual values. This isn't strictly, necessary, just a "handle the
763 // easy cases for now" decision.
764 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000765 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000766 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000767 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000768
769 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
770 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
771 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
772 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
773 // Only valid if one of the masks is a superset of the other (check "B&D" is
774 // the same as either B or D).
775 APInt NewMask = BCst->getValue() & DCst->getValue();
776
777 if (NewMask == BCst->getValue())
778 return LHS;
779 else if (NewMask == DCst->getValue())
780 return RHS;
781 }
782 if (mask & FoldMskICmp_AMask_NotAllOnes) {
783 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
784 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
785 // Only valid if one of the masks is a superset of the other (check "B|D" is
786 // the same as either B or D).
787 APInt NewMask = BCst->getValue() | DCst->getValue();
788
789 if (NewMask == BCst->getValue())
790 return LHS;
791 else if (NewMask == DCst->getValue())
792 return RHS;
793 }
Craig Topperae48cb22012-12-20 07:15:54 +0000794 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000795 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000796 // We already know that B & C == C && D & E == E.
797 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
798 // C and E, which are shared by both the mask B and the mask D, don't
799 // contradict, then we can transform to
800 // -> (icmp eq (A & (B|D)), (C|E))
801 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000802 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000803 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000804 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000805 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000806 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000807 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000808 if (!ECst) return nullptr;
David Majnemer1a3327b2014-11-18 09:31:36 +0000809 if (LHSCC != NEWCC)
810 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000811 if (RHSCC != NEWCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000812 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Owen Anderson3fe002d2010-09-08 22:16:17 +0000813 // if there is a conflict we should actually return a false for the
814 // whole construct
David Majnemer1a3327b2014-11-18 09:31:36 +0000815 if (((BCst->getValue() & DCst->getValue()) &
816 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000817 return ConstantInt::get(LHS->getType(), !IsAnd);
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000818 Value *newOr1 = Builder->CreateOr(B, D);
819 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
820 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000821 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
822 }
Craig Topperf40110f2014-04-25 05:29:35 +0000823 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000824}
825
Erik Ecksteind1817522014-12-03 10:39:15 +0000826/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
827/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
828/// If \p Inverted is true then the check is for the inverted range, e.g.
829/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
830Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
831 bool Inverted) {
832 // Check the lower range comparison, e.g. x >= 0
833 // InstCombine already ensured that if there is a constant it's on the RHS.
834 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
835 if (!RangeStart)
836 return nullptr;
837
838 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
839 Cmp0->getPredicate());
840
841 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
842 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
843 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
844 return nullptr;
845
846 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
847 Cmp1->getPredicate());
848
849 Value *Input = Cmp0->getOperand(0);
850 Value *RangeEnd;
851 if (Cmp1->getOperand(0) == Input) {
852 // For the upper range compare we have: icmp x, n
853 RangeEnd = Cmp1->getOperand(1);
854 } else if (Cmp1->getOperand(1) == Input) {
855 // For the upper range compare we have: icmp n, x
856 RangeEnd = Cmp1->getOperand(0);
857 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
858 } else {
859 return nullptr;
860 }
861
862 // Check the upper range comparison, e.g. x < n
863 ICmpInst::Predicate NewPred;
864 switch (Pred1) {
865 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
866 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
867 default: return nullptr;
868 }
869
870 // This simplification is only valid if the upper range is not negative.
871 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000872 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000873 if (!IsNotNegative)
874 return nullptr;
875
876 if (Inverted)
877 NewPred = ICmpInst::getInversePredicate(NewPred);
878
879 return Builder->CreateICmp(NewPred, Input, RangeEnd);
880}
881
Chris Lattner0a8191e2010-01-05 07:50:36 +0000882/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000883Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000884 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
885
886 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
887 if (PredicatesFoldable(LHSCC, RHSCC)) {
888 if (LHS->getOperand(0) == RHS->getOperand(1) &&
889 LHS->getOperand(1) == RHS->getOperand(0))
890 LHS->swapOperands();
891 if (LHS->getOperand(0) == RHS->getOperand(0) &&
892 LHS->getOperand(1) == RHS->getOperand(1)) {
893 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
894 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
895 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000896 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 }
898 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000899
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000900 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000901 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000902 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000903
Erik Ecksteind1817522014-12-03 10:39:15 +0000904 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
905 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
906 return V;
907
908 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
909 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
910 return V;
911
Chris Lattner0a8191e2010-01-05 07:50:36 +0000912 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
913 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
914 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
915 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000916 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000917
Chris Lattner0a8191e2010-01-05 07:50:36 +0000918 if (LHSCst == RHSCst && LHSCC == RHSCC) {
919 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
920 // where C is a power of 2
921 if (LHSCC == ICmpInst::ICMP_ULT &&
922 LHSCst->getValue().isPowerOf2()) {
923 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000924 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000926
Chris Lattner0a8191e2010-01-05 07:50:36 +0000927 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
928 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
929 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000930 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000931 }
932 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000933
Benjamin Kramer101720f2011-04-28 20:09:57 +0000934 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000935 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000936 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000937 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000938 LHS->hasOneUse() && RHS->hasOneUse()) {
939 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000940 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000941
942 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000943 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000944 if (match(Val2, m_Trunc(m_Value(V))) &&
945 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
946 SmallCst = RHSCst;
947 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000948 } else if (match(Val, m_Trunc(m_Value(V))) &&
949 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000950 SmallCst = LHSCst;
951 BigCst = RHSCst;
952 }
953
954 if (SmallCst && BigCst) {
955 unsigned BigBitSize = BigCst->getType()->getBitWidth();
956 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
957
958 // Check that the low bits are zero.
959 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000960 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000961 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
962 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
963 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
964 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
965 }
966 }
967 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000968
Chris Lattner0a8191e2010-01-05 07:50:36 +0000969 // From here on, we only handle:
970 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000971 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000972
Chris Lattner0a8191e2010-01-05 07:50:36 +0000973 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
974 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
975 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
976 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
977 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000978 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000979
980 // Make a constant range that's the intersection of the two icmp ranges.
981 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000982 ConstantRange LHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000983 ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000984 ConstantRange RHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000985 ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
Anders Carlssonda80afe2011-03-01 15:05:01 +0000986
987 if (LHSRange.intersectWith(RHSRange).isEmptySet())
988 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
989
Chris Lattner0a8191e2010-01-05 07:50:36 +0000990 // We can't fold (ugt x, C) & (sgt x, C2).
991 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000992 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000993
Chris Lattner0a8191e2010-01-05 07:50:36 +0000994 // Ensure that the larger constant is on the RHS.
995 bool ShouldSwap;
996 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000997 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998 CmpInst::isSigned(RHSCC)))
999 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1000 else
1001 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001002
Chris Lattner0a8191e2010-01-05 07:50:36 +00001003 if (ShouldSwap) {
1004 std::swap(LHS, RHS);
1005 std::swap(LHSCst, RHSCst);
1006 std::swap(LHSCC, RHSCC);
1007 }
1008
Dan Gohman4a618822010-02-10 16:03:48 +00001009 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001010 // comparing a value against two constants and and'ing the result
1011 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001012 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1013 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001014 // are not equal and that the larger constant is on the RHS
1015 assert(LHSCst != RHSCst && "Compares not folded above?");
1016
1017 switch (LHSCC) {
1018 default: llvm_unreachable("Unknown integer condition code!");
1019 case ICmpInst::ICMP_EQ:
1020 switch (RHSCC) {
1021 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1023 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1024 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +00001025 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001026 }
1027 case ICmpInst::ICMP_NE:
1028 switch (RHSCC) {
1029 default: llvm_unreachable("Unknown integer condition code!");
1030 case ICmpInst::ICMP_ULT:
1031 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001032 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001033 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1034 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001035 break; // (X != 13 & X u< 15) -> no change
1036 case ICmpInst::ICMP_SLT:
1037 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001038 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001039 break; // (X != 13 & X s< 15) -> no change
1040 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1041 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1042 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001043 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001044 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001045 // Special case to get the ordering right when the values wrap around
1046 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001047 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001048 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001049 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1050 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1051 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001052 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1053 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001054 }
1055 break; // (X != 13 & X != 15) -> no change
1056 }
1057 break;
1058 case ICmpInst::ICMP_ULT:
1059 switch (RHSCC) {
1060 default: llvm_unreachable("Unknown integer condition code!");
1061 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1062 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001063 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001064 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1065 break;
1066 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1067 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001068 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001069 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1070 break;
1071 }
1072 break;
1073 case ICmpInst::ICMP_SLT:
1074 switch (RHSCC) {
1075 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001076 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1077 break;
1078 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1079 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001080 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001081 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1082 break;
1083 }
1084 break;
1085 case ICmpInst::ICMP_UGT:
1086 switch (RHSCC) {
1087 default: llvm_unreachable("Unknown integer condition code!");
1088 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1089 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001090 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001091 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1092 break;
1093 case ICmpInst::ICMP_NE:
1094 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001095 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001096 break; // (X u> 13 & X != 15) -> no change
1097 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001098 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001099 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1100 break;
1101 }
1102 break;
1103 case ICmpInst::ICMP_SGT:
1104 switch (RHSCC) {
1105 default: llvm_unreachable("Unknown integer condition code!");
1106 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1107 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001108 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001109 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1110 break;
1111 case ICmpInst::ICMP_NE:
1112 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001113 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001114 break; // (X s> 13 & X != 15) -> no change
1115 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001116 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001117 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1118 break;
1119 }
1120 break;
1121 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001122
Craig Topperf40110f2014-04-25 05:29:35 +00001123 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001124}
1125
Chris Lattner067459c2010-03-05 08:46:26 +00001126/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1127/// instcombine, this returns a Value which should already be inserted into the
1128/// function.
1129Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001130 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1131 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001132 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001133 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001134
Chris Lattner0a8191e2010-01-05 07:50:36 +00001135 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1136 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1137 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1138 // If either of the constants are nans, then the whole thing returns
1139 // false.
1140 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001141 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001142 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001143 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001144
Chris Lattner0a8191e2010-01-05 07:50:36 +00001145 // Handle vector zeros. This occurs because the canonical form of
1146 // "fcmp ord x,x" is "fcmp ord x, 0".
1147 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1148 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001149 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001150 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001151 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001152
Chris Lattner0a8191e2010-01-05 07:50:36 +00001153 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1154 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1155 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001156
1157
Chris Lattner0a8191e2010-01-05 07:50:36 +00001158 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1159 // Swap RHS operands to match LHS.
1160 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1161 std::swap(Op1LHS, Op1RHS);
1162 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001163
Chris Lattner0a8191e2010-01-05 07:50:36 +00001164 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1165 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1166 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001167 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001168 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001169 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001170 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001171 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001172 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001173 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001174
Chris Lattner0a8191e2010-01-05 07:50:36 +00001175 bool Op0Ordered;
1176 bool Op1Ordered;
1177 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1178 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001179 // uno && ord -> false
1180 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1181 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001182 if (Op1Pred == 0) {
1183 std::swap(LHS, RHS);
1184 std::swap(Op0Pred, Op1Pred);
1185 std::swap(Op0Ordered, Op1Ordered);
1186 }
1187 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001188 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001189 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001190 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1191 return LHS;
1192 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001193 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001194
Chris Lattner0a8191e2010-01-05 07:50:36 +00001195 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001196 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001197 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001198 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001199 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001200 }
1201 }
1202
Craig Topperf40110f2014-04-25 05:29:35 +00001203 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001204}
1205
Chris Lattner0a8191e2010-01-05 07:50:36 +00001206Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001207 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001208 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1209
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001210 if (Value *V = SimplifyVectorOp(I))
1211 return ReplaceInstUsesWith(I, V);
1212
Chandler Carruth66b31302015-01-04 12:03:27 +00001213 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001214 return ReplaceInstUsesWith(I, V);
1215
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001216 // (A|B)&(A|C) -> A|(B&C) etc
1217 if (Value *V = SimplifyUsingDistributiveLaws(I))
1218 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001219
Craig Topper9d4171a2012-12-20 07:09:41 +00001220 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001221 // purpose is to compute bits we don't care about.
1222 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001223 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001224
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001225 if (Value *V = SimplifyBSwap(I))
1226 return ReplaceInstUsesWith(I, V);
1227
Chris Lattner0a8191e2010-01-05 07:50:36 +00001228 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1229 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001230
1231 // Optimize a variety of ((val OP C1) & C2) combinations...
1232 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1233 Value *Op0LHS = Op0I->getOperand(0);
1234 Value *Op0RHS = Op0I->getOperand(1);
1235 switch (Op0I->getOpcode()) {
1236 default: break;
1237 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001238 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001239 // If the mask is only needed on one incoming arm, push it up.
1240 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001241
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001242 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001243 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001244 // Not masking anything out for the LHS, move to RHS.
1245 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1246 Op0RHS->getName()+".masked");
1247 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1248 }
1249 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001250 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001251 // Not masking anything out for the RHS, move to LHS.
1252 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1253 Op0LHS->getName()+".masked");
1254 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1255 }
1256
1257 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001258 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001259 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001260 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1261 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1262 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001263 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1264 return BinaryOperator::CreateAnd(V, AndRHS);
1265 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1266 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1267 break;
1268
1269 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001270 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1271 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1272 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1274 return BinaryOperator::CreateAnd(V, AndRHS);
1275
Balaram Makamccf59732015-08-20 15:35:00 +00001276 // -x & 1 -> x & 1
1277 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1278 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1279
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001280 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001281 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001282 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001283 uint32_t BitWidth = AndRHSMask.getBitWidth();
1284 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1285 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1286
Hal Finkel60db0582014-09-07 18:57:58 +00001287 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001288 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1289 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1290 }
1291 }
1292 break;
1293
1294 case Instruction::Shl:
1295 case Instruction::LShr:
1296 // (1 << x) & 1 --> zext(x == 0)
1297 // (1 >> x) & 1 --> zext(x == 0)
1298 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1299 Value *NewICmp =
1300 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1301 return new ZExtInst(NewICmp, I.getType());
1302 }
1303 break;
1304 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001305
Chris Lattner0a8191e2010-01-05 07:50:36 +00001306 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1307 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1308 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001309 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001310
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001311 // If this is an integer truncation, and if the source is an 'and' with
1312 // immediate, transform it. This frequently occurs for bitfield accesses.
1313 {
Craig Topperf40110f2014-04-25 05:29:35 +00001314 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001315 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1316 // Change: and (trunc (and X, YC) to T), C2
1317 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001318 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001319 // other simplifications.
1320 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1321 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1322 C3 = ConstantExpr::getAnd(C3, AndRHS);
1323 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001324 }
1325 }
1326
1327 // Try to fold constant and into select arguments.
1328 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1329 if (Instruction *R = FoldOpIntoSelect(I, SI))
1330 return R;
1331 if (isa<PHINode>(Op0))
1332 if (Instruction *NV = FoldOpIntoPhi(I))
1333 return NV;
1334 }
1335
1336
1337 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1338 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1339 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1340 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1341 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1342 I.getName()+".demorgan");
1343 return BinaryOperator::CreateNot(Or);
1344 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001345
Chris Lattner0a8191e2010-01-05 07:50:36 +00001346 {
Craig Topperf40110f2014-04-25 05:29:35 +00001347 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001348 // (A|B) & ~(A&B) -> A^B
1349 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1350 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1351 ((A == C && B == D) || (A == D && B == C)))
1352 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001353
Chris Lattner0a8191e2010-01-05 07:50:36 +00001354 // ~(A&B) & (A|B) -> A^B
1355 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1356 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1357 ((A == C && B == D) || (A == D && B == C)))
1358 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001359
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001360 // A&(A^B) => A & ~B
1361 {
1362 Value *tmpOp0 = Op0;
1363 Value *tmpOp1 = Op1;
1364 if (Op0->hasOneUse() &&
1365 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1366 if (A == Op1 || B == Op1 ) {
1367 tmpOp1 = Op0;
1368 tmpOp0 = Op1;
1369 // Simplify below
1370 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001371 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001372
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001373 if (tmpOp1->hasOneUse() &&
1374 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1375 if (B == tmpOp0) {
1376 std::swap(A, B);
1377 }
1378 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1379 // A is originally -1 (or a vector of -1 and undefs), then we enter
1380 // an endless loop. By checking that A is non-constant we ensure that
1381 // we will never get to the loop.
1382 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001383 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001384 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385 }
1386
1387 // (A&((~A)|B)) -> A&B
1388 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1389 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1390 return BinaryOperator::CreateAnd(A, Op1);
1391 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1392 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1393 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001394
1395 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1396 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1397 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1398 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1399 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1400
1401 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1402 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1403 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1404 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1405 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001406
1407 // (A | B) & ((~A) ^ B) -> (A & B)
1408 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1409 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1410 return BinaryOperator::CreateAnd(A, B);
1411
1412 // ((~A) ^ B) & (A | B) -> (A & B)
1413 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1414 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1415 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001416 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001417
David Majnemer5e96f1b2014-08-30 06:18:20 +00001418 {
1419 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1420 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1421 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001422 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1423 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001424
David Majnemer5e96f1b2014-08-30 06:18:20 +00001425 // TODO: Make this recursive; it's a little tricky because an arbitrary
1426 // number of 'and' instructions might have to be created.
1427 Value *X, *Y;
1428 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1429 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1430 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1431 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1432 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1433 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1434 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1435 }
1436 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1437 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1438 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1439 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1440 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1441 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1442 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1443 }
1444 }
1445
Chris Lattner4e8137d2010-02-11 06:26:33 +00001446 // If and'ing two fcmp, try combine them into one.
1447 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1448 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001449 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1450 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001451
1452
Chris Lattner0a8191e2010-01-05 07:50:36 +00001453 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1454 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001455 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001456 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001457 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1458 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001459 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001460 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001461
Chris Lattner4e8137d2010-02-11 06:26:33 +00001462 // Only do this if the casts both really cause code to be generated.
1463 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1464 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1465 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001466 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1467 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001468
Chris Lattner4e8137d2010-02-11 06:26:33 +00001469 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1470 // cast is otherwise not optimizable. This happens for vector sexts.
1471 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1472 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001473 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001474 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001475
Chris Lattner4e8137d2010-02-11 06:26:33 +00001476 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1477 // cast is otherwise not optimizable. This happens for vector sexts.
1478 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1479 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001480 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001481 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001482 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001483 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001484
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001485 {
Craig Topperf40110f2014-04-25 05:29:35 +00001486 Value *X = nullptr;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001487 bool OpsSwapped = false;
1488 // Canonicalize SExt or Not to the LHS
1489 if (match(Op1, m_SExt(m_Value())) ||
1490 match(Op1, m_Not(m_Value()))) {
1491 std::swap(Op0, Op1);
1492 OpsSwapped = true;
1493 }
1494
1495 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1496 if (match(Op0, m_SExt(m_Value(X))) &&
1497 X->getType()->getScalarType()->isIntegerTy(1)) {
1498 Value *Zero = Constant::getNullValue(Op1->getType());
1499 return SelectInst::Create(X, Op1, Zero);
1500 }
1501
1502 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1503 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1504 X->getType()->getScalarType()->isIntegerTy(1)) {
1505 Value *Zero = Constant::getNullValue(Op0->getType());
1506 return SelectInst::Create(X, Zero, Op1);
1507 }
1508
1509 if (OpsSwapped)
1510 std::swap(Op0, Op1);
1511 }
1512
Craig Topperf40110f2014-04-25 05:29:35 +00001513 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001514}
1515
1516/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1517/// capable of providing pieces of a bswap. The subexpression provides pieces
1518/// of a bswap if it is proven that each of the non-zero bytes in the output of
1519/// the expression came from the corresponding "byte swapped" byte in some other
1520/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1521/// we know that the expression deposits the low byte of %X into the high byte
1522/// of the bswap result and that all other bytes are zero. This expression is
1523/// accepted, the high byte of ByteValues is set to X to indicate a correct
1524/// match.
1525///
1526/// This function returns true if the match was unsuccessful and false if so.
1527/// On entry to the function the "OverallLeftShift" is a signed integer value
1528/// indicating the number of bytes that the subexpression is later shifted. For
1529/// example, if the expression is later right shifted by 16 bits, the
1530/// OverallLeftShift value would be -2 on entry. This is used to specify which
1531/// byte of ByteValues is actually being set.
1532///
1533/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1534/// byte is masked to zero by a user. For example, in (X & 255), X will be
1535/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1536/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1537/// always in the local (OverallLeftShift) coordinate space.
1538///
1539static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
Craig Topperb94011f2013-07-14 04:42:23 +00001540 SmallVectorImpl<Value *> &ByteValues) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001541 if (Instruction *I = dyn_cast<Instruction>(V)) {
1542 // If this is an or instruction, it may be an inner node of the bswap.
1543 if (I->getOpcode() == Instruction::Or) {
1544 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1545 ByteValues) ||
1546 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1547 ByteValues);
1548 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001549
Chris Lattner0a8191e2010-01-05 07:50:36 +00001550 // If this is a logical shift by a constant multiple of 8, recurse with
1551 // OverallLeftShift and ByteMask adjusted.
1552 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001553 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001554 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1555 // Ensure the shift amount is defined and of a byte value.
1556 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1557 return true;
1558
1559 unsigned ByteShift = ShAmt >> 3;
1560 if (I->getOpcode() == Instruction::Shl) {
1561 // X << 2 -> collect(X, +2)
1562 OverallLeftShift += ByteShift;
1563 ByteMask >>= ByteShift;
1564 } else {
1565 // X >>u 2 -> collect(X, -2)
1566 OverallLeftShift -= ByteShift;
1567 ByteMask <<= ByteShift;
1568 ByteMask &= (~0U >> (32-ByteValues.size()));
1569 }
1570
1571 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1572 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1573
Craig Topper9d4171a2012-12-20 07:09:41 +00001574 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001575 ByteValues);
1576 }
1577
1578 // If this is a logical 'and' with a mask that clears bytes, clear the
1579 // corresponding bytes in ByteMask.
1580 if (I->getOpcode() == Instruction::And &&
1581 isa<ConstantInt>(I->getOperand(1))) {
1582 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1583 unsigned NumBytes = ByteValues.size();
1584 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1585 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001586
Chris Lattner0a8191e2010-01-05 07:50:36 +00001587 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1588 // If this byte is masked out by a later operation, we don't care what
1589 // the and mask is.
1590 if ((ByteMask & (1 << i)) == 0)
1591 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001592
Chris Lattner0a8191e2010-01-05 07:50:36 +00001593 // If the AndMask is all zeros for this byte, clear the bit.
1594 APInt MaskB = AndMask & Byte;
1595 if (MaskB == 0) {
1596 ByteMask &= ~(1U << i);
1597 continue;
1598 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001599
Chris Lattner0a8191e2010-01-05 07:50:36 +00001600 // If the AndMask is not all ones for this byte, it's not a bytezap.
1601 if (MaskB != Byte)
1602 return true;
1603
1604 // Otherwise, this byte is kept.
1605 }
1606
Craig Topper9d4171a2012-12-20 07:09:41 +00001607 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001608 ByteValues);
1609 }
1610 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001611
Chris Lattner0a8191e2010-01-05 07:50:36 +00001612 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1613 // the input value to the bswap. Some observations: 1) if more than one byte
1614 // is demanded from this input, then it could not be successfully assembled
1615 // into a byteswap. At least one of the two bytes would not be aligned with
1616 // their ultimate destination.
1617 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001618 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001619
Chris Lattner0a8191e2010-01-05 07:50:36 +00001620 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1621 // is demanded, it needs to go into byte 0 of the result. This means that the
1622 // byte needs to be shifted until it lands in the right byte bucket. The
1623 // shift amount depends on the position: if the byte is coming from the high
1624 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1625 // low part, it must be shifted left.
1626 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001627 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1628 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001629
Chris Lattner0a8191e2010-01-05 07:50:36 +00001630 // If the destination byte value is already defined, the values are or'd
1631 // together, which isn't a bswap (unless it's an or of the same bits).
1632 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1633 return true;
1634 ByteValues[DestByteNo] = V;
1635 return false;
1636}
1637
1638/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1639/// If so, insert the new bswap intrinsic and return it.
1640Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001641 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001642 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001643 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001644 ITy->getBitWidth() > 32*8)
Craig Topperf40110f2014-04-25 05:29:35 +00001645 return nullptr; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001646
Chris Lattner0a8191e2010-01-05 07:50:36 +00001647 /// ByteValues - For each byte of the result, we keep track of which value
1648 /// defines each byte.
1649 SmallVector<Value*, 8> ByteValues;
1650 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001651
Chris Lattner0a8191e2010-01-05 07:50:36 +00001652 // Try to find all the pieces corresponding to the bswap.
1653 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1654 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Craig Topperf40110f2014-04-25 05:29:35 +00001655 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001656
Chris Lattner0a8191e2010-01-05 07:50:36 +00001657 // Check to see if all of the bytes come from the same value.
1658 Value *V = ByteValues[0];
Craig Topperf40110f2014-04-25 05:29:35 +00001659 if (!V) return nullptr; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001660
Chris Lattner0a8191e2010-01-05 07:50:36 +00001661 // Check to make sure that all of the bytes come from the same value.
1662 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1663 if (ByteValues[i] != V)
Craig Topperf40110f2014-04-25 05:29:35 +00001664 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001665 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001666 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001667 return CallInst::Create(F, V);
1668}
1669
1670/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1671/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1672/// we can simplify this expression to "cond ? C : D or B".
1673static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1674 Value *C, Value *D) {
1675 // If A is not a select of -1/0, this cannot match.
Craig Topperf40110f2014-04-25 05:29:35 +00001676 Value *Cond = nullptr;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001677 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001678 !Cond->getType()->isIntegerTy(1))
Craig Topperf40110f2014-04-25 05:29:35 +00001679 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001680
1681 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001682 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001683 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001684 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001685 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001686
Chris Lattner0a8191e2010-01-05 07:50:36 +00001687 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001688 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001689 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001690 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001691 return SelectInst::Create(Cond, C, D);
Craig Topperf40110f2014-04-25 05:29:35 +00001692 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001693}
1694
Chris Lattner067459c2010-03-05 08:46:26 +00001695/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001696Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1697 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001698 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1699
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001700 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1701 // if K1 and K2 are a one-bit mask.
1702 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1703 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1704
1705 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1706 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1707
1708 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1709 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1710 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1711 LAnd->getOpcode() == Instruction::And &&
1712 RAnd->getOpcode() == Instruction::And) {
1713
Craig Topperf40110f2014-04-25 05:29:35 +00001714 Value *Mask = nullptr;
1715 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001716 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001717 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1718 DT) &&
1719 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1720 DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001721 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1722 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1723 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001724 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1725 CxtI, DT) &&
1726 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1727 CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001728 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1729 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1730 }
1731
1732 if (Masked)
1733 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1734 }
1735 }
1736
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001737 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1738 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1739 // The original condition actually refers to the following two ranges:
1740 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1741 // We can fold these two ranges if:
1742 // 1) C1 and C2 is unsigned greater than C3.
1743 // 2) The two ranges are separated.
1744 // 3) C1 ^ C2 is one-bit mask.
1745 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1746 // This implies all values in the two ranges differ by exactly one bit.
1747
1748 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1749 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1750 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1751 LHSCst->getValue() == (RHSCst->getValue())) {
1752
1753 Value *LAdd = LHS->getOperand(0);
1754 Value *RAdd = RHS->getOperand(0);
1755
1756 Value *LAddOpnd, *RAddOpnd;
1757 ConstantInt *LAddCst, *RAddCst;
1758 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1759 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1760 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1761 RAddCst->getValue().ugt(LHSCst->getValue())) {
1762
1763 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1764 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1765 ConstantInt *MaxAddCst = nullptr;
1766 if (LAddCst->getValue().ult(RAddCst->getValue()))
1767 MaxAddCst = RAddCst;
1768 else
1769 MaxAddCst = LAddCst;
1770
1771 APInt RRangeLow = -RAddCst->getValue();
1772 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1773 APInt LRangeLow = -LAddCst->getValue();
1774 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1775 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1776 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1777 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1778 : RRangeLow - LRangeLow;
1779
1780 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1781 RangeDiff.ugt(LHSCst->getValue())) {
1782 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1783
1784 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1785 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1786 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1787 }
1788 }
1789 }
1790 }
1791
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1793 if (PredicatesFoldable(LHSCC, RHSCC)) {
1794 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1795 LHS->getOperand(1) == RHS->getOperand(0))
1796 LHS->swapOperands();
1797 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1798 LHS->getOperand(1) == RHS->getOperand(1)) {
1799 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1800 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1801 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001802 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001803 }
1804 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001805
1806 // handle (roughly):
1807 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001808 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001809 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001810
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001812 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1813 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1814 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001815 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001816 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1817 B = Val;
1818 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1819 A = Val2;
1820 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1821 A = RHS->getOperand(1);
1822 }
1823 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1824 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1825 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1826 B = Val2;
1827 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1828 A = Val;
1829 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1830 A = LHS->getOperand(1);
1831 }
1832 if (A && B)
1833 return Builder->CreateICmp(
1834 ICmpInst::ICMP_UGE,
1835 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1836 }
1837
Erik Ecksteind1817522014-12-03 10:39:15 +00001838 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1839 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1840 return V;
1841
1842 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1843 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1844 return V;
1845
David Majnemerc2a990b2013-07-05 00:31:17 +00001846 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001847 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001848
Owen Anderson8f306a72010-08-02 09:32:13 +00001849 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1850 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1851 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1852 Value *NewOr = Builder->CreateOr(Val, Val2);
1853 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1854 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001855 }
1856
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001857 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001858 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001859 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001860 ConstantInt *AddCst;
1861 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1862 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001863 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001864 }
1865
Chris Lattner0a8191e2010-01-05 07:50:36 +00001866 // From here on, we only handle:
1867 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001868 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001869
Chris Lattner0a8191e2010-01-05 07:50:36 +00001870 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1871 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1872 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1873 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1874 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001875 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001876
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 // We can't fold (ugt x, C) | (sgt x, C2).
1878 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001879 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001880
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881 // Ensure that the larger constant is on the RHS.
1882 bool ShouldSwap;
1883 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001884 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 CmpInst::isSigned(RHSCC)))
1886 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1887 else
1888 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001889
Chris Lattner0a8191e2010-01-05 07:50:36 +00001890 if (ShouldSwap) {
1891 std::swap(LHS, RHS);
1892 std::swap(LHSCst, RHSCst);
1893 std::swap(LHSCC, RHSCC);
1894 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001895
Dan Gohman4a618822010-02-10 16:03:48 +00001896 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897 // comparing a value against two constants and or'ing the result
1898 // together. Because of the above check, we know that we only have
1899 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1900 // icmp folding check above), that the two constants are not
1901 // equal.
1902 assert(LHSCst != RHSCst && "Compares not folded above?");
1903
1904 switch (LHSCC) {
1905 default: llvm_unreachable("Unknown integer condition code!");
1906 case ICmpInst::ICMP_EQ:
1907 switch (RHSCC) {
1908 default: llvm_unreachable("Unknown integer condition code!");
1909 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001910 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001911 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001912 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001913 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1914
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001915 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1916 if (Xor.isPowerOf2()) {
1917 Value *NegCst = Builder->getInt(~Xor);
1918 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1919 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1920 }
1921 }
1922
David Majnemer1fae1952013-04-14 21:15:43 +00001923 if (LHSCst == SubOne(RHSCst)) {
1924 // (X == 13 | X == 14) -> X-13 <u 2
1925 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1926 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1927 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1928 return Builder->CreateICmpULT(Add, AddCST);
1929 }
1930
Chris Lattner0a8191e2010-01-05 07:50:36 +00001931 break; // (X == 13 | X == 15) -> no change
1932 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1933 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1934 break;
1935 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1936 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1937 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001938 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001939 }
1940 break;
1941 case ICmpInst::ICMP_NE:
1942 switch (RHSCC) {
1943 default: llvm_unreachable("Unknown integer condition code!");
1944 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1945 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1946 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001947 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001948 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1949 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1950 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001951 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001952 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001953 case ICmpInst::ICMP_ULT:
1954 switch (RHSCC) {
1955 default: llvm_unreachable("Unknown integer condition code!");
1956 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1957 break;
1958 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1959 // If RHSCst is [us]MAXINT, it is always false. Not handling
1960 // this can cause overflow.
1961 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001962 return LHS;
1963 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001964 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1965 break;
1966 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1967 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001968 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001969 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1970 break;
1971 }
1972 break;
1973 case ICmpInst::ICMP_SLT:
1974 switch (RHSCC) {
1975 default: llvm_unreachable("Unknown integer condition code!");
1976 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1977 break;
1978 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1979 // If RHSCst is [us]MAXINT, it is always false. Not handling
1980 // this can cause overflow.
1981 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001982 return LHS;
1983 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001984 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1985 break;
1986 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1987 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001988 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001989 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1990 break;
1991 }
1992 break;
1993 case ICmpInst::ICMP_UGT:
1994 switch (RHSCC) {
1995 default: llvm_unreachable("Unknown integer condition code!");
1996 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1997 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001998 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001999 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2000 break;
2001 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2002 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002003 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002004 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2005 break;
2006 }
2007 break;
2008 case ICmpInst::ICMP_SGT:
2009 switch (RHSCC) {
2010 default: llvm_unreachable("Unknown integer condition code!");
2011 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2012 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00002013 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002014 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2015 break;
2016 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2017 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002018 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002019 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2020 break;
2021 }
2022 break;
2023 }
Craig Topperf40110f2014-04-25 05:29:35 +00002024 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002025}
2026
Chris Lattner067459c2010-03-05 08:46:26 +00002027/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
2028/// instcombine, this returns a Value which should already be inserted into the
2029/// function.
2030Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002031 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002032 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002033 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2034 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2035 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2036 // If either of the constants are nans, then the whole thing returns
2037 // true.
2038 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002039 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002040
Chris Lattner0a8191e2010-01-05 07:50:36 +00002041 // Otherwise, no need to compare the two constants, compare the
2042 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002043 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002044 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002045
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 // Handle vector zeros. This occurs because the canonical form of
2047 // "fcmp uno x,x" is "fcmp uno x, 0".
2048 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2049 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002050 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002051
Craig Topperf40110f2014-04-25 05:29:35 +00002052 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002053 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002054
Chris Lattner0a8191e2010-01-05 07:50:36 +00002055 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2056 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2057 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00002058
Chris Lattner0a8191e2010-01-05 07:50:36 +00002059 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2060 // Swap RHS operands to match LHS.
2061 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2062 std::swap(Op1LHS, Op1RHS);
2063 }
2064 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2065 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2066 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00002067 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002068 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00002069 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002070 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002071 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002072 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002073 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002074 bool Op0Ordered;
2075 bool Op1Ordered;
2076 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2077 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2078 if (Op0Ordered == Op1Ordered) {
2079 // If both are ordered or unordered, return a new fcmp with
2080 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00002081 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002082 }
2083 }
Craig Topperf40110f2014-04-25 05:29:35 +00002084 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002085}
2086
2087/// FoldOrWithConstants - This helper function folds:
2088///
2089/// ((A | B) & C1) | (B & C2)
2090///
2091/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002092///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002093/// (A & C1) | B
2094///
2095/// when the XOR of the two constants is "all ones" (-1).
2096Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2097 Value *A, Value *B, Value *C) {
2098 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002099 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002100
Craig Topperf40110f2014-04-25 05:29:35 +00002101 Value *V1 = nullptr;
2102 ConstantInt *CI2 = nullptr;
2103 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002104
2105 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002106 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002107
2108 if (V1 == A || V1 == B) {
2109 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2110 return BinaryOperator::CreateOr(NewOp, V1);
2111 }
2112
Craig Topperf40110f2014-04-25 05:29:35 +00002113 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002114}
2115
David Majnemer5d1aeba2014-08-21 05:14:48 +00002116/// \brief This helper function folds:
2117///
2118/// ((A | B) & C1) ^ (B & C2)
2119///
2120/// into:
2121///
2122/// (A & C1) ^ B
2123///
2124/// when the XOR of the two constants is "all ones" (-1).
2125Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2126 Value *A, Value *B, Value *C) {
2127 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2128 if (!CI1)
2129 return nullptr;
2130
2131 Value *V1 = nullptr;
2132 ConstantInt *CI2 = nullptr;
2133 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2134 return nullptr;
2135
2136 APInt Xor = CI1->getValue() ^ CI2->getValue();
2137 if (!Xor.isAllOnesValue())
2138 return nullptr;
2139
2140 if (V1 == A || V1 == B) {
2141 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2142 return BinaryOperator::CreateXor(NewOp, V1);
2143 }
2144
2145 return nullptr;
2146}
2147
Chris Lattner0a8191e2010-01-05 07:50:36 +00002148Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002149 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002150 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2151
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002152 if (Value *V = SimplifyVectorOp(I))
2153 return ReplaceInstUsesWith(I, V);
2154
Chandler Carruth66b31302015-01-04 12:03:27 +00002155 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002156 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002157
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002158 // (A&B)|(A&C) -> A&(B|C) etc
2159 if (Value *V = SimplifyUsingDistributiveLaws(I))
2160 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002161
Craig Topper9d4171a2012-12-20 07:09:41 +00002162 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002163 // purpose is to compute bits we don't care about.
2164 if (SimplifyDemandedInstructionBits(I))
2165 return &I;
2166
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002167 if (Value *V = SimplifyBSwap(I))
2168 return ReplaceInstUsesWith(I, V);
2169
Chris Lattner0a8191e2010-01-05 07:50:36 +00002170 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002171 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002172 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002173 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002174 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002175 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002176 Op0->hasOneUse()) {
2177 Value *Or = Builder->CreateOr(X, RHS);
2178 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002179 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002180 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002181 }
2182
2183 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2184 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2185 Op0->hasOneUse()) {
2186 Value *Or = Builder->CreateOr(X, RHS);
2187 Or->takeName(Op0);
2188 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002189 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002190 }
2191
2192 // Try to fold constant and into select arguments.
2193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2194 if (Instruction *R = FoldOpIntoSelect(I, SI))
2195 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002196
Chris Lattner0a8191e2010-01-05 07:50:36 +00002197 if (isa<PHINode>(Op0))
2198 if (Instruction *NV = FoldOpIntoPhi(I))
2199 return NV;
2200 }
2201
Craig Topperf40110f2014-04-25 05:29:35 +00002202 Value *A = nullptr, *B = nullptr;
2203 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002204
2205 // (A | B) | C and A | (B | C) -> bswap if possible.
2206 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
2207 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2208 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00002209 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2210 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002211 if (Instruction *BSwap = MatchBSwap(I))
2212 return BSwap;
2213 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002214
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002215 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002216 if (Op0->hasOneUse() &&
2217 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002218 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002219 Value *NOr = Builder->CreateOr(A, Op1);
2220 NOr->takeName(Op0);
2221 return BinaryOperator::CreateXor(NOr, C1);
2222 }
2223
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002224 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002225 if (Op1->hasOneUse() &&
2226 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002227 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002228 Value *NOr = Builder->CreateOr(A, Op0);
2229 NOr->takeName(Op0);
2230 return BinaryOperator::CreateXor(NOr, C1);
2231 }
2232
Suyog Sardad64faf62014-07-22 18:09:41 +00002233 // ((~A & B) | A) -> (A | B)
2234 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2235 match(Op1, m_Specific(A)))
2236 return BinaryOperator::CreateOr(A, B);
2237
2238 // ((A & B) | ~A) -> (~A | B)
2239 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2240 match(Op1, m_Not(m_Specific(A))))
2241 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2242
Suyog Sarda52324c82014-08-01 04:50:31 +00002243 // (A & (~B)) | (A ^ B) -> (A ^ B)
2244 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2245 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2246 return BinaryOperator::CreateXor(A, B);
2247
2248 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2249 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2250 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2251 return BinaryOperator::CreateXor(A, B);
2252
Chris Lattner0a8191e2010-01-05 07:50:36 +00002253 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002254 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002255 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2256 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002257 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002258 C1 = dyn_cast<ConstantInt>(C);
2259 C2 = dyn_cast<ConstantInt>(D);
2260 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002261 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002262 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002263 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002264 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002265 ((V1 == B &&
2266 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2267 (V2 == B &&
2268 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002269 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002270 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002271 // Or commutes, try both ways.
2272 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002273 ((V1 == A &&
2274 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2275 (V2 == A &&
2276 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002277 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002278 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002279
Chris Lattner95188692010-01-11 06:55:24 +00002280 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002281 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002282 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002283 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2284 (C3->getValue() & ~C1->getValue()) == 0 &&
2285 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2286 (C4->getValue() & ~C2->getValue()) == 0) {
2287 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2288 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002289 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002290 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002291 }
2292 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002293
Chris Lattner8e2c4712010-02-02 02:43:51 +00002294 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2295 // Don't do this for vector select idioms, the code generator doesn't handle
2296 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002297 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002298 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2299 return Match;
2300 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2301 return Match;
2302 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2303 return Match;
2304 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2305 return Match;
2306 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002307
2308 // ((A&~B)|(~A&B)) -> A^B
2309 if ((match(C, m_Not(m_Specific(D))) &&
2310 match(B, m_Not(m_Specific(A)))))
2311 return BinaryOperator::CreateXor(A, D);
2312 // ((~B&A)|(~A&B)) -> A^B
2313 if ((match(A, m_Not(m_Specific(D))) &&
2314 match(B, m_Not(m_Specific(C)))))
2315 return BinaryOperator::CreateXor(C, D);
2316 // ((A&~B)|(B&~A)) -> A^B
2317 if ((match(C, m_Not(m_Specific(B))) &&
2318 match(D, m_Not(m_Specific(A)))))
2319 return BinaryOperator::CreateXor(A, B);
2320 // ((~B&A)|(B&~A)) -> A^B
2321 if ((match(A, m_Not(m_Specific(B))) &&
2322 match(D, m_Not(m_Specific(C)))))
2323 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002324
2325 // ((A|B)&1)|(B&-2) -> (A&1) | B
2326 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2327 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2328 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2329 if (Ret) return Ret;
2330 }
2331 // (B&-2)|((A|B)&1) -> (A&1) | B
2332 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2333 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2334 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2335 if (Ret) return Ret;
2336 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002337 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2338 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2339 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2340 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2341 if (Ret) return Ret;
2342 }
2343 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2344 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2345 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2346 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2347 if (Ret) return Ret;
2348 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002349 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002350
David Majnemer42af3602014-07-30 21:26:37 +00002351 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2352 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2353 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2354 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2355 return BinaryOperator::CreateOr(Op0, C);
2356
2357 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2358 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2359 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2360 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2361 return BinaryOperator::CreateOr(Op1, C);
2362
David Majnemerf1eda232014-08-14 06:41:38 +00002363 // ((B | C) & A) | B -> B | (A & C)
2364 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2365 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2366
Chris Lattner0a8191e2010-01-05 07:50:36 +00002367 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2368 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2369 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2370 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2371 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2372 I.getName()+".demorgan");
2373 return BinaryOperator::CreateNot(And);
2374 }
2375
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002376 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002377 bool SwappedForXor = false;
2378 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002379 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002380 SwappedForXor = true;
2381 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002382
2383 // A | ( A ^ B) -> A | B
2384 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002385 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002386 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2387 if (Op0 == A || Op0 == B)
2388 return BinaryOperator::CreateOr(A, B);
2389
Chad Rosier7813dce2012-04-26 23:29:14 +00002390 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2391 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2392 return BinaryOperator::CreateOr(A, B);
2393
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002394 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2395 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2396 return BinaryOperator::CreateOr(Not, Op0);
2397 }
2398 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2399 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2400 return BinaryOperator::CreateOr(Not, Op0);
2401 }
2402 }
2403
2404 // A | ~(A | B) -> A | ~B
2405 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002406 if (match(Op1, m_Not(m_Value(A))))
2407 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002408 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2409 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2410 B->getOpcode() == Instruction::Xor)) {
2411 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2412 B->getOperand(0);
2413 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2414 return BinaryOperator::CreateOr(Not, Op0);
2415 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002416
Suyog Sarda16d64652014-08-01 04:41:43 +00002417 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2418 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2419 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2420 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2421
2422 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2423 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2424 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2425 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2426
Eli Friedmane06535b2012-03-16 00:52:42 +00002427 if (SwappedForXor)
2428 std::swap(Op0, Op1);
2429
David Majnemer3d6f80b2014-11-28 19:58:29 +00002430 {
2431 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2432 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2433 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002434 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner067459c2010-03-05 08:46:26 +00002435 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002436
David Majnemer3d6f80b2014-11-28 19:58:29 +00002437 // TODO: Make this recursive; it's a little tricky because an arbitrary
2438 // number of 'or' instructions might have to be created.
2439 Value *X, *Y;
2440 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2441 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2442 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2443 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2444 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2445 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2446 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2447 }
2448 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2449 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2450 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2451 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2452 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2453 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2454 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2455 }
2456 }
2457
Chris Lattner4e8137d2010-02-11 06:26:33 +00002458 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2459 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2460 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002461 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2462 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002463
Chris Lattner0a8191e2010-01-05 07:50:36 +00002464 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2465 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002466 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2467 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002468 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002469 if (SrcTy == Op1C->getOperand(0)->getType() &&
2470 SrcTy->isIntOrIntVectorTy()) {
2471 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002472
Chris Lattner311aa632011-01-15 05:40:29 +00002473 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2474 // Only do this if the casts both really cause code to be
2475 // generated.
2476 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2477 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2478 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2479 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002480 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002481
Chris Lattner311aa632011-01-15 05:40:29 +00002482 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2483 // cast is otherwise not optimizable. This happens for vector sexts.
2484 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2485 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Hal Finkel60db0582014-09-07 18:57:58 +00002486 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner311aa632011-01-15 05:40:29 +00002487 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002488
Chris Lattner311aa632011-01-15 05:40:29 +00002489 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2490 // cast is otherwise not optimizable. This happens for vector sexts.
2491 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2492 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2493 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2494 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002495 }
Chris Lattner311aa632011-01-15 05:40:29 +00002496 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002497 }
Eli Friedman23956262011-04-14 22:41:27 +00002498
2499 // or(sext(A), B) -> A ? -1 : B where A is an i1
2500 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2501 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2502 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2503 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2504 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2505
Owen Andersonc237a842010-09-13 17:59:27 +00002506 // Note: If we've gotten to the point of visiting the outer OR, then the
2507 // inner one couldn't be simplified. If it was a constant, then it won't
2508 // be simplified by a later pass either, so we try swapping the inner/outer
2509 // ORs in the hopes that we'll be able to simplify it this way.
2510 // (X|C) | V --> (X|V) | C
2511 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2512 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2513 Value *Inner = Builder->CreateOr(A, Op1);
2514 Inner->takeName(Op0);
2515 return BinaryOperator::CreateOr(Inner, C1);
2516 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002517
Bill Wendling23242092013-02-16 23:41:36 +00002518 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2519 // Since this OR statement hasn't been optimized further yet, we hope
2520 // that this transformation will allow the new ORs to be optimized.
2521 {
Craig Topperf40110f2014-04-25 05:29:35 +00002522 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002523 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2524 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2525 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2526 Value *orTrue = Builder->CreateOr(A, C);
2527 Value *orFalse = Builder->CreateOr(B, D);
2528 return SelectInst::Create(X, orTrue, orFalse);
2529 }
2530 }
2531
Craig Topperf40110f2014-04-25 05:29:35 +00002532 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002533}
2534
2535Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002536 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002539 if (Value *V = SimplifyVectorOp(I))
2540 return ReplaceInstUsesWith(I, V);
2541
Chandler Carruth66b31302015-01-04 12:03:27 +00002542 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002543 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002544
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002545 // (A&B)^(A&C) -> A&(B^C) etc
2546 if (Value *V = SimplifyUsingDistributiveLaws(I))
2547 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002548
Craig Topper9d4171a2012-12-20 07:09:41 +00002549 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002550 // purpose is to compute bits we don't care about.
2551 if (SimplifyDemandedInstructionBits(I))
2552 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002553
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002554 if (Value *V = SimplifyBSwap(I))
2555 return ReplaceInstUsesWith(I, V);
2556
Chris Lattner0a8191e2010-01-05 07:50:36 +00002557 // Is this a ~ operation?
2558 if (Value *NotOp = dyn_castNotVal(&I)) {
2559 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002560 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002561 Op0I->getOpcode() == Instruction::Or) {
2562 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2563 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2564 if (dyn_castNotVal(Op0I->getOperand(1)))
2565 Op0I->swapOperands();
2566 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2567 Value *NotY =
2568 Builder->CreateNot(Op0I->getOperand(1),
2569 Op0I->getOperand(1)->getName()+".not");
2570 if (Op0I->getOpcode() == Instruction::And)
2571 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2572 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2573 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002574
Chris Lattner0a8191e2010-01-05 07:50:36 +00002575 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2576 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002577 if (IsFreeToInvert(Op0I->getOperand(0),
2578 Op0I->getOperand(0)->hasOneUse()) &&
2579 IsFreeToInvert(Op0I->getOperand(1),
2580 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002581 Value *NotX =
2582 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2583 Value *NotY =
2584 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2585 if (Op0I->getOpcode() == Instruction::And)
2586 return BinaryOperator::CreateOr(NotX, NotY);
2587 return BinaryOperator::CreateAnd(NotX, NotY);
2588 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002589
2590 } else if (Op0I->getOpcode() == Instruction::AShr) {
2591 // ~(~X >>s Y) --> (X >>s Y)
2592 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2593 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002594 }
2595 }
2596 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002597
Benjamin Kramer443c7962015-02-12 20:26:46 +00002598 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2599 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002600 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002601 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2602 return CmpInst::Create(CI->getOpcode(),
2603 CI->getInversePredicate(),
2604 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002605 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002606
Benjamin Kramer443c7962015-02-12 20:26:46 +00002607 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002608 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2609 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2610 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2611 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2612 Instruction::CastOps Opcode = Op0C->getOpcode();
2613 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002614 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002615 Op0C->getDestTy()))) {
2616 CI->setPredicate(CI->getInversePredicate());
2617 return CastInst::Create(Opcode, CI, Op0C->getType());
2618 }
2619 }
2620 }
2621 }
2622
2623 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2624 // ~(c-X) == X-c-1 == X+(-c-1)
2625 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2626 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2627 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2628 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2629 ConstantInt::get(I.getType(), 1));
2630 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2631 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002632
Chris Lattner0a8191e2010-01-05 07:50:36 +00002633 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2634 if (Op0I->getOpcode() == Instruction::Add) {
2635 // ~(X-c) --> (-c-1)-X
2636 if (RHS->isAllOnesValue()) {
2637 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2638 return BinaryOperator::CreateSub(
2639 ConstantExpr::getSub(NegOp0CI,
2640 ConstantInt::get(I.getType(), 1)),
2641 Op0I->getOperand(0));
2642 } else if (RHS->getValue().isSignBit()) {
2643 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002644 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002645 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2646
2647 }
2648 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002649 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002650 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2651 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002652 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2653 // Anything in both C1 and C2 is known to be zero, remove it from
2654 // NewRHS.
2655 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002656 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002657 ConstantExpr::getNot(CommonBits));
2658 Worklist.Add(Op0I);
2659 I.setOperand(0, Op0I->getOperand(0));
2660 I.setOperand(1, NewRHS);
2661 return &I;
2662 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002663 } else if (Op0I->getOpcode() == Instruction::LShr) {
2664 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2665 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002666 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002667 ConstantInt *C1;
2668 if (Op0I->hasOneUse() &&
2669 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2670 E1->getOpcode() == Instruction::Xor &&
2671 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2672 // fold (C1 >> C2) ^ C3
2673 ConstantInt *C2 = Op0CI, *C3 = RHS;
2674 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2675 FoldConst ^= C3->getValue();
2676 // Prepare the two operands.
2677 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2678 Opnd0->takeName(Op0I);
2679 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2680 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2681
2682 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2683 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002684 }
2685 }
2686 }
2687
2688 // Try to fold constant and into select arguments.
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2690 if (Instruction *R = FoldOpIntoSelect(I, SI))
2691 return R;
2692 if (isa<PHINode>(Op0))
2693 if (Instruction *NV = FoldOpIntoPhi(I))
2694 return NV;
2695 }
2696
Chris Lattner0a8191e2010-01-05 07:50:36 +00002697 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2698 if (Op1I) {
2699 Value *A, *B;
2700 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2701 if (A == Op0) { // B^(B|A) == (A|B)^B
2702 Op1I->swapOperands();
2703 I.swapOperands();
2704 std::swap(Op0, Op1);
2705 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2706 I.swapOperands(); // Simplified below.
2707 std::swap(Op0, Op1);
2708 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002709 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002710 Op1I->hasOneUse()){
2711 if (A == Op0) { // A^(A&B) -> A^(B&A)
2712 Op1I->swapOperands();
2713 std::swap(A, B);
2714 }
2715 if (B == Op0) { // A^(B&A) -> (B&A)^A
2716 I.swapOperands(); // Simplified below.
2717 std::swap(Op0, Op1);
2718 }
2719 }
2720 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002721
Chris Lattner0a8191e2010-01-05 07:50:36 +00002722 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2723 if (Op0I) {
2724 Value *A, *B;
2725 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2726 Op0I->hasOneUse()) {
2727 if (A == Op1) // (B|A)^B == (A|B)^B
2728 std::swap(A, B);
2729 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002730 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002731 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002732 Op0I->hasOneUse()){
2733 if (A == Op1) // (A&B)^A -> (B&A)^A
2734 std::swap(A, B);
2735 if (B == Op1 && // (B&A)^A == ~B & A
2736 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002737 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002738 }
2739 }
2740 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002741
Chris Lattner0a8191e2010-01-05 07:50:36 +00002742 if (Op0I && Op1I) {
2743 Value *A, *B, *C, *D;
2744 // (A & B)^(A | B) -> A ^ B
2745 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2746 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002747 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002748 return BinaryOperator::CreateXor(A, B);
2749 }
2750 // (A | B)^(A & B) -> A ^ B
2751 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2752 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002753 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002754 return BinaryOperator::CreateXor(A, B);
2755 }
David Majnemer698dca02014-08-14 06:46:25 +00002756 // (A | ~B) ^ (~A | B) -> A ^ B
2757 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2758 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2759 return BinaryOperator::CreateXor(A, B);
2760 }
2761 // (~A | B) ^ (A | ~B) -> A ^ B
2762 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2763 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2764 return BinaryOperator::CreateXor(A, B);
2765 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002766 // (A & ~B) ^ (~A & B) -> A ^ B
2767 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2768 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2769 return BinaryOperator::CreateXor(A, B);
2770 }
2771 // (~A & B) ^ (A & ~B) -> A ^ B
2772 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2773 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2774 return BinaryOperator::CreateXor(A, B);
2775 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002776 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2777 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2778 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2779 if (D == A)
2780 return BinaryOperator::CreateXor(
2781 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2782 if (D == B)
2783 return BinaryOperator::CreateXor(
2784 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002785 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002786 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002787 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002788 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2789 if (D == A)
2790 return BinaryOperator::CreateXor(
2791 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2792 if (D == B)
2793 return BinaryOperator::CreateXor(
2794 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002795 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002796 // (A & B) ^ (A ^ B) -> (A | B)
2797 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2798 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2799 return BinaryOperator::CreateOr(A, B);
2800 // (A ^ B) ^ (A & B) -> (A | B)
2801 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2802 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2803 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002804 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002805
Suyog Sarda521237c2014-07-22 15:37:39 +00002806 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002807 // (A & ~B) ^ (~A) -> ~(A & B)
2808 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2809 match(Op1, m_Not(m_Specific(A))))
2810 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2811
Chris Lattner0a8191e2010-01-05 07:50:36 +00002812 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2813 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2814 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2815 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2816 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2817 LHS->getOperand(1) == RHS->getOperand(0))
2818 LHS->swapOperands();
2819 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2820 LHS->getOperand(1) == RHS->getOperand(1)) {
2821 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2822 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2823 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002824 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002825 getNewICmpValue(isSigned, Code, Op0, Op1,
2826 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002827 }
2828 }
2829
2830 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2831 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2832 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2833 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002834 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002835 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002836 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002837 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002838 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002839 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002840 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002841 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2842 Op1C->getOperand(0), I.getName());
2843 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2844 }
2845 }
2846 }
2847
Craig Topperf40110f2014-04-25 05:29:35 +00002848 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002849}