blob: e70171ce989ad3d8c7c678d20e59ebd961a1fee3 [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"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Chris Lattner0a8191e2010-01-05 07:50:36 +000026static inline Value *dyn_castNotVal(Value *V) {
27 // If this is not(not(x)) don't return that this is a not: we want the two
28 // not's to be folded first.
29 if (BinaryOperator::isNot(V)) {
30 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000031 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 return Operand;
33 }
Craig Topper9d4171a2012-12-20 07:09:41 +000034
Chris Lattner0a8191e2010-01-05 07:50:36 +000035 // Constants can be considered to be not'ed values...
36 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000038 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000039}
40
Sanjay Patel18549272015-09-08 18:24:36 +000041/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
42/// a three bit mask. It also returns whether it is an ordered predicate by
43/// reference.
Chris Lattner0a8191e2010-01-05 07:50:36 +000044static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
45 isOrdered = false;
46 switch (CC) {
47 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
48 case FCmpInst::FCMP_UNO: return 0; // 000
49 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
50 case FCmpInst::FCMP_UGT: return 1; // 001
51 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
52 case FCmpInst::FCMP_UEQ: return 2; // 010
53 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
54 case FCmpInst::FCMP_UGE: return 3; // 011
55 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
56 case FCmpInst::FCMP_ULT: return 4; // 100
57 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
58 case FCmpInst::FCMP_UNE: return 5; // 101
59 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
60 case FCmpInst::FCMP_ULE: return 6; // 110
61 // True -> 7
62 default:
63 // Not expecting FCMP_FALSE and FCMP_TRUE;
64 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000065 }
66}
67
Sanjay Patel18549272015-09-08 18:24:36 +000068/// This is the complement of getICmpCode, which turns an opcode and two
69/// operands into either a constant true or false, or a brand new ICmp
70/// instruction. The sign is passed in to determine which kind of predicate to
71/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000072static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
73 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000074 ICmpInst::Predicate NewPred;
75 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
76 return NewConstant;
77 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000078}
79
Sanjay Patel18549272015-09-08 18:24:36 +000080/// This is the complement of getFCmpCode, which turns an opcode and two
81/// operands into either a FCmp instruction. isordered is passed in to determine
82/// which kind of predicate to use in the new fcmp instruction.
Chris Lattner0a8191e2010-01-05 07:50:36 +000083static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +000084 Value *LHS, Value *RHS,
85 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +000086 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +000087 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +000088 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +000089 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
90 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
91 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
92 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
93 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
94 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
95 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +000096 case 7:
Nick Lewycky8075fd22015-08-14 22:46:49 +000097 if (!isordered)
98 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Owen Andersona8342002011-01-21 19:39:42 +000099 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000100 }
Chris Lattner067459c2010-03-05 08:46:26 +0000101 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000102}
103
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000104/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
105/// \param I Binary operator to transform.
106/// \return Pointer to node that must replace the original binary operator, or
107/// null pointer if no transformation was made.
108Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
109 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
110
111 // Can't do vectors.
112 if (I.getType()->isVectorTy()) return nullptr;
113
114 // Can only do bitwise ops.
115 unsigned Op = I.getOpcode();
116 if (Op != Instruction::And && Op != Instruction::Or &&
117 Op != Instruction::Xor)
118 return nullptr;
119
120 Value *OldLHS = I.getOperand(0);
121 Value *OldRHS = I.getOperand(1);
122 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
123 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
124 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
125 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
126 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
127 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
128
129 if (!IsBswapLHS && !IsBswapRHS)
130 return nullptr;
131
132 if (!IsBswapLHS && !ConstLHS)
133 return nullptr;
134
135 if (!IsBswapRHS && !ConstRHS)
136 return nullptr;
137
138 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
139 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
140 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
141 Builder->getInt(ConstLHS->getValue().byteSwap());
142
143 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
144 Builder->getInt(ConstRHS->getValue().byteSwap());
145
146 Value *BinOp = nullptr;
147 if (Op == Instruction::And)
148 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
149 else if (Op == Instruction::Or)
150 BinOp = Builder->CreateOr(NewLHS, NewRHS);
151 else //if (Op == Instruction::Xor)
152 BinOp = Builder->CreateXor(NewLHS, NewRHS);
153
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000154 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000155 return Builder->CreateCall(F, BinOp);
156}
157
Sanjay Patel18549272015-09-08 18:24:36 +0000158/// 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.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000161Instruction *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.
Sanjay Patel4b198802016-02-01 22:23:39 +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.
Sanjay Patel4b198802016-02-01 22:23:39 +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
Sanjay Patel18549272015-09-08 18:24:36 +0000344/// Returns true iff Val consists of one contiguous run of 1s with any number
345/// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
346/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
347/// not, since all 1s are not contiguous.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000348static 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
Sanjay Patel18549272015-09-08 18:24:36 +0000360/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
361/// whether the operator is a sub. If we can fold one of the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000362///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000363/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
364/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
365/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000366///
367/// return (A +/- B).
368///
369Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
370 ConstantInt *Mask, bool isSub,
371 Instruction &I) {
372 Instruction *LHSI = dyn_cast<Instruction>(LHS);
373 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000374 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000375
376 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
377
378 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000379 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000380 case Instruction::And:
381 if (ConstantExpr::getAnd(N, Mask) == Mask) {
382 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000383 if ((Mask->getValue().countLeadingZeros() +
384 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000385 Mask->getValue().getBitWidth())
386 break;
387
388 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
389 // part, we don't need any explicit masks to take them out of A. If that
390 // is all N is, ignore it.
391 uint32_t MB = 0, ME = 0;
392 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
393 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
394 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000395 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000396 break;
397 }
398 }
Craig Topperf40110f2014-04-25 05:29:35 +0000399 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000400 case Instruction::Or:
401 case Instruction::Xor:
402 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000403 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000404 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
405 && ConstantExpr::getAnd(N, Mask)->isNullValue())
406 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000407 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000408 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000409
Chris Lattner0a8191e2010-01-05 07:50:36 +0000410 if (isSub)
411 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
412 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
413}
414
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000416/// One of A and B is considered the mask, the other the value. This is
417/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000418/// contains only "Mask", then both A and B can be considered masks.
419/// If A is the mask, then it was proven, that (A & C) == C. This
420/// is trivial if C == A, or C == 0. If both A and C are constants, this
421/// proof is also easy.
422/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000423/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424/// if (A & B) == A, or all bits of A are set in B.
425/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000426/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000427/// if (A & B) == 0, or all bits of A are cleared in B.
428/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000429/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000430/// contain any number of one bits and zero bits.
431/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
432/// The Part "Not" means, that in above descriptions "==" should be replaced
433/// by "!=".
434/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
435/// If the mask A contains a single bit, then the following is equivalent:
436/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
437/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
438enum MaskedICmpType {
439 FoldMskICmp_AMask_AllOnes = 1,
440 FoldMskICmp_AMask_NotAllOnes = 2,
441 FoldMskICmp_BMask_AllOnes = 4,
442 FoldMskICmp_BMask_NotAllOnes = 8,
443 FoldMskICmp_Mask_AllZeroes = 16,
444 FoldMskICmp_Mask_NotAllZeroes = 32,
445 FoldMskICmp_AMask_Mixed = 64,
446 FoldMskICmp_AMask_NotMixed = 128,
447 FoldMskICmp_BMask_Mixed = 256,
448 FoldMskICmp_BMask_NotMixed = 512
449};
450
Sanjay Patel18549272015-09-08 18:24:36 +0000451/// Return the set of pattern classes (from MaskedICmpType)
452/// that (icmp SCC (A & B), C) satisfies.
Craig Topper9d4171a2012-12-20 07:09:41 +0000453static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000454 ICmpInst::Predicate SCC)
455{
456 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
457 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
458 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
459 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000460 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000461 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000462 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000463 BCst->getValue().isPowerOf2());
464 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000465 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000466 // if C is zero, then both A and B qualify as mask
467 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
Owen Anderson3fe002d2010-09-08 22:16:17 +0000468 FoldMskICmp_AMask_Mixed |
469 FoldMskICmp_BMask_Mixed)
470 : (FoldMskICmp_Mask_NotAllZeroes |
Owen Anderson3fe002d2010-09-08 22:16:17 +0000471 FoldMskICmp_AMask_NotMixed |
472 FoldMskICmp_BMask_NotMixed));
473 if (icmp_abit)
474 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000475 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000476 : (FoldMskICmp_AMask_AllOnes |
477 FoldMskICmp_AMask_Mixed));
478 if (icmp_bbit)
479 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000480 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000481 : (FoldMskICmp_BMask_AllOnes |
482 FoldMskICmp_BMask_Mixed));
483 return result;
484 }
485 if (A == C) {
486 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
487 FoldMskICmp_AMask_Mixed)
488 : (FoldMskICmp_AMask_NotAllOnes |
489 FoldMskICmp_AMask_NotMixed));
490 if (icmp_abit)
491 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
492 FoldMskICmp_AMask_NotMixed)
493 : (FoldMskICmp_Mask_AllZeroes |
494 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000495 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000496 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000497 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
498 : FoldMskICmp_AMask_NotMixed);
499 }
Craig Topperae48cb22012-12-20 07:15:54 +0000500 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000501 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
502 FoldMskICmp_BMask_Mixed)
503 : (FoldMskICmp_BMask_NotAllOnes |
504 FoldMskICmp_BMask_NotMixed));
505 if (icmp_bbit)
506 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000507 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000508 : (FoldMskICmp_Mask_AllZeroes |
509 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000510 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000511 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000512 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
513 : FoldMskICmp_BMask_NotMixed);
514 }
515 return result;
516}
517
Tim Northoverc0756c42013-09-04 11:57:13 +0000518/// Convert an analysis of a masked ICmp into its equivalent if all boolean
519/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
520/// is adjacent to the corresponding normal flag (recording ==), this just
521/// involves swapping those bits over.
522static unsigned conjugateICmpMask(unsigned Mask) {
523 unsigned NewMask;
524 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
525 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
526 FoldMskICmp_BMask_Mixed))
527 << 1;
528
529 NewMask |=
530 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
531 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
532 FoldMskICmp_BMask_NotMixed))
533 >> 1;
534
535 return NewMask;
536}
537
Sanjay Patel18549272015-09-08 18:24:36 +0000538/// Decompose an icmp into the form ((X & Y) pred Z) if possible.
539/// The returned predicate is either == or !=. Returns false if
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000540/// decomposition fails.
541static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
542 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000543 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
544 if (!C)
545 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000546
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000547 switch (I->getPredicate()) {
548 default:
549 return false;
550 case ICmpInst::ICMP_SLT:
551 // X < 0 is equivalent to (X & SignBit) != 0.
552 if (!C->isZero())
553 return false;
554 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
555 Pred = ICmpInst::ICMP_NE;
556 break;
557 case ICmpInst::ICMP_SGT:
558 // X > -1 is equivalent to (X & SignBit) == 0.
559 if (!C->isAllOnesValue())
560 return false;
561 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
562 Pred = ICmpInst::ICMP_EQ;
563 break;
564 case ICmpInst::ICMP_ULT:
565 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
566 if (!C->getValue().isPowerOf2())
567 return false;
568 Y = ConstantInt::get(I->getContext(), -C->getValue());
569 Pred = ICmpInst::ICMP_EQ;
570 break;
571 case ICmpInst::ICMP_UGT:
572 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
573 if (!(C->getValue() + 1).isPowerOf2())
574 return false;
575 Y = ConstantInt::get(I->getContext(), ~C->getValue());
576 Pred = ICmpInst::ICMP_NE;
577 break;
578 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000579
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000580 X = I->getOperand(0);
581 Z = ConstantInt::getNullValue(C->getType());
582 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000583}
584
Sanjay Patel18549272015-09-08 18:24:36 +0000585/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
586/// Return the set of pattern classes (from MaskedICmpType)
587/// that both LHS and RHS satisfy.
Craig Topper9d4171a2012-12-20 07:09:41 +0000588static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000589 Value*& B, Value*& C,
590 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000591 ICmpInst *LHS, ICmpInst *RHS,
592 ICmpInst::Predicate &LHSCC,
593 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000594 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
595 // vectors are not (yet?) supported
596 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
597
598 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000599 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000600 // and L11 & L12 == L21 & L22. The same goes for RHS.
601 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000602 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000603 // above.
604 Value *L1 = LHS->getOperand(0);
605 Value *L2 = LHS->getOperand(1);
606 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000607 // Check whether the icmp can be decomposed into a bit test.
608 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000609 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000610 } else {
611 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000612 if (!L1->getType()->isIntegerTy()) {
613 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000614 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000615 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
616 // Any icmp can be viewed as being trivially masked; if it allows us to
617 // remove one, it's worth it.
618 L11 = L1;
619 L12 = Constant::getAllOnesValue(L1->getType());
620 }
621
622 if (!L2->getType()->isIntegerTy()) {
623 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000624 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000625 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
626 L21 = L2;
627 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000628 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000629 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000630
631 // Bail if LHS was a icmp that can't be decomposed into an equality.
632 if (!ICmpInst::isEquality(LHSCC))
633 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000634
635 Value *R1 = RHS->getOperand(0);
636 Value *R2 = RHS->getOperand(1);
637 Value *R11,*R12;
638 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000639 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
640 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
641 A = R11; D = R12;
642 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
643 A = R12; D = R11;
644 } else {
645 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000646 }
Craig Topperf40110f2014-04-25 05:29:35 +0000647 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000648 } else if (R1->getType()->isIntegerTy()) {
649 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
650 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000651 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000652 R11 = R1;
653 R12 = Constant::getAllOnesValue(R1->getType());
654 }
655
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000656 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
657 A = R11; D = R12; E = R2; ok = true;
658 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000659 A = R12; D = R11; E = R2; ok = true;
660 }
661 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000662
663 // Bail if RHS was a icmp that can't be decomposed into an equality.
664 if (!ICmpInst::isEquality(RHSCC))
665 return 0;
666
Chad Rosier58919cc2016-05-09 21:37:43 +0000667 // Look for ANDs on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000668 if (!ok && R2->getType()->isIntegerTy()) {
669 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
670 R11 = R2;
671 R12 = Constant::getAllOnesValue(R2->getType());
672 }
673
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000674 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
675 A = R11; D = R12; E = R1; ok = true;
676 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000677 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000678 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000679 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000680 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000681 }
682 if (!ok)
683 return 0;
684
685 if (L11 == A) {
686 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000687 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000688 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000689 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000690 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000691 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000692 B = L21; C = L1;
693 }
694
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000695 unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
696 unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
697 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000698}
Sanjay Patel18549272015-09-08 18:24:36 +0000699
700/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
701/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000702static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
703 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000704 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000705 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000706 unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000707 LHSCC, RHSCC);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000708 if (Mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000709 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
710 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000711
Tim Northoverc0756c42013-09-04 11:57:13 +0000712 // In full generality:
713 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
714 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
715 //
716 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
717 // equivalent to (icmp (A & X) !Op Y).
718 //
719 // Therefore, we can pretend for the rest of this function that we're dealing
720 // with the conjunction, provided we flip the sense of any comparisons (both
721 // input and output).
722
723 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000724 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000725 if (!IsAnd) {
726 // Convert the masking analysis into its equivalent with negated
727 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000728 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000729 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000730
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000731 if (Mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000732 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000733 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000734 Value *NewOr = Builder->CreateOr(B, D);
735 Value *NewAnd = Builder->CreateAnd(A, NewOr);
736 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000737 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000738 // with B and D, having a single bit set.
739 Value *Zero = Constant::getNullValue(A->getType());
740 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000741 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000742 if (Mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000743 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000744 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000745 Value *NewOr = Builder->CreateOr(B, D);
746 Value *NewAnd = Builder->CreateAnd(A, NewOr);
747 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000748 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000749 if (Mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000750 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000751 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000752 Value *NewAnd1 = Builder->CreateAnd(B, D);
753 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
754 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000755 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000756
757 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000758 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000759 // easy cases for now" decision.
760 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000761 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000762 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000763 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000764
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000765 if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000766 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
767 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
768 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
769 // Only valid if one of the masks is a superset of the other (check "B&D" is
770 // the same as either B or D).
771 APInt NewMask = BCst->getValue() & DCst->getValue();
772
773 if (NewMask == BCst->getValue())
774 return LHS;
775 else if (NewMask == DCst->getValue())
776 return RHS;
777 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000778 if (Mask & FoldMskICmp_AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000779 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
780 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
781 // Only valid if one of the masks is a superset of the other (check "B|D" is
782 // the same as either B or D).
783 APInt NewMask = BCst->getValue() | DCst->getValue();
784
785 if (NewMask == BCst->getValue())
786 return LHS;
787 else if (NewMask == DCst->getValue())
788 return RHS;
789 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000790 if (Mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000791 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000792 // We already know that B & C == C && D & E == E.
793 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
794 // C and E, which are shared by both the mask B and the mask D, don't
795 // contradict, then we can transform to
796 // -> (icmp eq (A & (B|D)), (C|E))
797 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000798 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000799 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000800 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000801 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000802 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000803 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000804 if (!ECst) return nullptr;
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000805 if (LHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000806 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000807 if (RHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000808 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000809 // If there is a conflict, we should actually return a false for the
810 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000811 if (((BCst->getValue() & DCst->getValue()) &
812 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000813 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000814 Value *NewOr1 = Builder->CreateOr(B, D);
815 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
816 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
817 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000818 }
Craig Topperf40110f2014-04-25 05:29:35 +0000819 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000820}
821
Erik Ecksteind1817522014-12-03 10:39:15 +0000822/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
823/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
824/// If \p Inverted is true then the check is for the inverted range, e.g.
825/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
826Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
827 bool Inverted) {
828 // Check the lower range comparison, e.g. x >= 0
829 // InstCombine already ensured that if there is a constant it's on the RHS.
830 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
831 if (!RangeStart)
832 return nullptr;
833
834 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
835 Cmp0->getPredicate());
836
837 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
838 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
839 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
840 return nullptr;
841
842 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
843 Cmp1->getPredicate());
844
845 Value *Input = Cmp0->getOperand(0);
846 Value *RangeEnd;
847 if (Cmp1->getOperand(0) == Input) {
848 // For the upper range compare we have: icmp x, n
849 RangeEnd = Cmp1->getOperand(1);
850 } else if (Cmp1->getOperand(1) == Input) {
851 // For the upper range compare we have: icmp n, x
852 RangeEnd = Cmp1->getOperand(0);
853 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
854 } else {
855 return nullptr;
856 }
857
858 // Check the upper range comparison, e.g. x < n
859 ICmpInst::Predicate NewPred;
860 switch (Pred1) {
861 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
862 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
863 default: return nullptr;
864 }
865
866 // This simplification is only valid if the upper range is not negative.
867 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000868 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000869 if (!IsNotNegative)
870 return nullptr;
871
872 if (Inverted)
873 NewPred = ICmpInst::getInversePredicate(NewPred);
874
875 return Builder->CreateICmp(NewPred, Input, RangeEnd);
876}
877
Sanjay Patel18549272015-09-08 18:24:36 +0000878/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000879Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000880 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
881
882 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
883 if (PredicatesFoldable(LHSCC, RHSCC)) {
884 if (LHS->getOperand(0) == RHS->getOperand(1) &&
885 LHS->getOperand(1) == RHS->getOperand(0))
886 LHS->swapOperands();
887 if (LHS->getOperand(0) == RHS->getOperand(0) &&
888 LHS->getOperand(1) == RHS->getOperand(1)) {
889 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
890 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
891 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000892 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000893 }
894 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000895
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000896 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000897 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000898 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000899
Erik Ecksteind1817522014-12-03 10:39:15 +0000900 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
901 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
902 return V;
903
904 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
905 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
906 return V;
907
Chris Lattner0a8191e2010-01-05 07:50:36 +0000908 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
909 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
910 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
911 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000912 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000913
Chris Lattner0a8191e2010-01-05 07:50:36 +0000914 if (LHSCst == RHSCst && LHSCC == RHSCC) {
915 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000916 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000918 if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
919 (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000920 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000921 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000922 }
923 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000924
Benjamin Kramer101720f2011-04-28 20:09:57 +0000925 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000926 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000927 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000928 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000929 LHS->hasOneUse() && RHS->hasOneUse()) {
930 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000931 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000932
933 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000934 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000935 if (match(Val2, m_Trunc(m_Value(V))) &&
936 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
937 SmallCst = RHSCst;
938 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000939 } else if (match(Val, m_Trunc(m_Value(V))) &&
940 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000941 SmallCst = LHSCst;
942 BigCst = RHSCst;
943 }
944
945 if (SmallCst && BigCst) {
946 unsigned BigBitSize = BigCst->getType()->getBitWidth();
947 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
948
949 // Check that the low bits are zero.
950 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000951 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000952 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
953 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
954 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
955 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
956 }
957 }
958 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000959
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 // From here on, we only handle:
961 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000962 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000963
Chris Lattner0a8191e2010-01-05 07:50:36 +0000964 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
965 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
966 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
967 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
968 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000969 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000970
971 // Make a constant range that's the intersection of the two icmp ranges.
972 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000973 ConstantRange LHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000974 ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000975 ConstantRange RHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000976 ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
Anders Carlssonda80afe2011-03-01 15:05:01 +0000977
978 if (LHSRange.intersectWith(RHSRange).isEmptySet())
979 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
980
Chris Lattner0a8191e2010-01-05 07:50:36 +0000981 // We can't fold (ugt x, C) & (sgt x, C2).
982 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000983 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000984
Chris Lattner0a8191e2010-01-05 07:50:36 +0000985 // Ensure that the larger constant is on the RHS.
986 bool ShouldSwap;
987 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000988 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000989 CmpInst::isSigned(RHSCC)))
990 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
991 else
992 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000993
Chris Lattner0a8191e2010-01-05 07:50:36 +0000994 if (ShouldSwap) {
995 std::swap(LHS, RHS);
996 std::swap(LHSCst, RHSCst);
997 std::swap(LHSCC, RHSCC);
998 }
999
Dan Gohman4a618822010-02-10 16:03:48 +00001000 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001001 // comparing a value against two constants and and'ing the result
1002 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001003 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1004 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001005 // are not equal and that the larger constant is on the RHS
1006 assert(LHSCst != RHSCst && "Compares not folded above?");
1007
1008 switch (LHSCC) {
1009 default: llvm_unreachable("Unknown integer condition code!");
1010 case ICmpInst::ICMP_EQ:
1011 switch (RHSCC) {
1012 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001013 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1014 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1015 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +00001016 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001017 }
1018 case ICmpInst::ICMP_NE:
1019 switch (RHSCC) {
1020 default: llvm_unreachable("Unknown integer condition code!");
1021 case ICmpInst::ICMP_ULT:
1022 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001023 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001024 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1025 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001026 break; // (X != 13 & X u< 15) -> no change
1027 case ICmpInst::ICMP_SLT:
1028 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001029 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001030 break; // (X != 13 & X s< 15) -> no change
1031 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1032 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1033 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001034 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001035 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001036 // Special case to get the ordering right when the values wrap around
1037 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001038 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001039 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001040 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1041 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1042 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001043 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1044 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001045 }
1046 break; // (X != 13 & X != 15) -> no change
1047 }
1048 break;
1049 case ICmpInst::ICMP_ULT:
1050 switch (RHSCC) {
1051 default: llvm_unreachable("Unknown integer condition code!");
1052 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1053 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001054 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001055 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1056 break;
1057 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1058 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001059 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001060 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1061 break;
1062 }
1063 break;
1064 case ICmpInst::ICMP_SLT:
1065 switch (RHSCC) {
1066 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001067 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1068 break;
1069 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1070 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001071 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001072 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1073 break;
1074 }
1075 break;
1076 case ICmpInst::ICMP_UGT:
1077 switch (RHSCC) {
1078 default: llvm_unreachable("Unknown integer condition code!");
1079 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1080 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001081 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001082 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1083 break;
1084 case ICmpInst::ICMP_NE:
1085 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001086 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001087 break; // (X u> 13 & X != 15) -> no change
1088 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001089 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001090 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1091 break;
1092 }
1093 break;
1094 case ICmpInst::ICMP_SGT:
1095 switch (RHSCC) {
1096 default: llvm_unreachable("Unknown integer condition code!");
1097 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1098 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001099 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001100 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1101 break;
1102 case ICmpInst::ICMP_NE:
1103 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001104 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001105 break; // (X s> 13 & X != 15) -> no change
1106 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001107 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001108 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1109 break;
1110 }
1111 break;
1112 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001113
Craig Topperf40110f2014-04-25 05:29:35 +00001114 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001115}
1116
Sanjay Patel18549272015-09-08 18:24:36 +00001117/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1118/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001119Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001120 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1121 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001122 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001123 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001124
Chris Lattner0a8191e2010-01-05 07:50:36 +00001125 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1126 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1127 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1128 // If either of the constants are nans, then the whole thing returns
1129 // false.
1130 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001131 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001132 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001133 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001134
Chris Lattner0a8191e2010-01-05 07:50:36 +00001135 // Handle vector zeros. This occurs because the canonical form of
1136 // "fcmp ord x,x" is "fcmp ord x, 0".
1137 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1138 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001139 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001140 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001141 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001142
Chris Lattner0a8191e2010-01-05 07:50:36 +00001143 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1144 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1145 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001146
1147
Chris Lattner0a8191e2010-01-05 07:50:36 +00001148 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1149 // Swap RHS operands to match LHS.
1150 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1151 std::swap(Op1LHS, Op1RHS);
1152 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001153
Chris Lattner0a8191e2010-01-05 07:50:36 +00001154 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1155 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1156 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001157 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001158 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001159 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001160 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001161 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001162 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001163 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001164
Chris Lattner0a8191e2010-01-05 07:50:36 +00001165 bool Op0Ordered;
1166 bool Op1Ordered;
1167 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1168 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001169 // uno && ord -> false
1170 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1171 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001172 if (Op1Pred == 0) {
1173 std::swap(LHS, RHS);
1174 std::swap(Op0Pred, Op1Pred);
1175 std::swap(Op0Ordered, Op1Ordered);
1176 }
1177 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001178 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001179 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001180 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1181 return LHS;
1182 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001183 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001184
Chris Lattner0a8191e2010-01-05 07:50:36 +00001185 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001186 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001187 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001188 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001189 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001190 }
1191 }
1192
Craig Topperf40110f2014-04-25 05:29:35 +00001193 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001194}
1195
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001196/// Match De Morgan's Laws:
1197/// (~A & ~B) == (~(A | B))
1198/// (~A | ~B) == (~(A & B))
1199static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1200 InstCombiner::BuilderTy *Builder) {
1201 auto Opcode = I.getOpcode();
1202 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1203 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001204 // Flip the logic operation.
1205 if (Opcode == Instruction::And)
1206 Opcode = Instruction::Or;
1207 else
1208 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001209
1210 Value *Op0 = I.getOperand(0);
1211 Value *Op1 = I.getOperand(1);
1212 // TODO: Use pattern matchers instead of dyn_cast.
1213 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1214 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1215 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001216 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1217 I.getName() + ".demorgan");
1218 return BinaryOperator::CreateNot(LogicOp);
1219 }
1220
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001221 // De Morgan's Law in disguise:
1222 // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1223 // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1224 Value *A = nullptr;
1225 Value *B = nullptr;
1226 ConstantInt *C1 = nullptr;
1227 if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1228 match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1229 // TODO: This check could be loosened to handle different type sizes.
1230 // Alternatively, we could fix the definition of m_Not to recognize a not
1231 // operation hidden by a zext?
1232 if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1233 C1->isOne()) {
1234 Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1235 I.getName() + ".demorgan");
1236 Value *Not = Builder->CreateNot(LogicOp);
1237 return CastInst::CreateZExtOrBitCast(Not, I.getType());
1238 }
1239 }
1240
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001241 return nullptr;
1242}
1243
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001244Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001245 auto LogicOpc = I.getOpcode();
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001246 assert((LogicOpc == Instruction::And || LogicOpc == Instruction::Or ||
1247 LogicOpc == Instruction::Xor) &&
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001248 "Unexpected opcode for bitwise logic folding");
1249
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001250 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001251 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001252 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001253 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001254
Sanjay Patel9bba7502016-03-03 19:19:04 +00001255 // This must be a cast from an integer or integer vector source type to allow
1256 // transformation of the logic operation to the source type.
1257 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001258 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001259 if (!SrcTy->isIntOrIntVectorTy())
1260 return nullptr;
1261
1262 // If one operand is a bitcast and the other is a constant, move the logic
1263 // operation ahead of the bitcast. That is, do the logic operation in the
1264 // original type. This can eliminate useless bitcasts and allow normal
1265 // combines that would otherwise be impeded by the bitcast. Canonicalization
1266 // ensures that if there is a constant operand, it will be the second operand.
1267 Value *BC = nullptr;
1268 Constant *C = nullptr;
1269 if ((match(Op0, m_BitCast(m_Value(BC))) && match(Op1, m_Constant(C)))) {
1270 // A bitcast of a constant will be removed.
1271 Value *NewConstant = Builder->CreateBitCast(C, SrcTy);
1272 Value *NewOp = Builder->CreateBinOp(LogicOpc, BC, NewConstant, I.getName());
1273 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1274 }
1275
1276 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1277 if (!Cast1)
1278 return nullptr;
1279
1280 // Both operands of the logic operation are casts. The casts must be of the
1281 // same type for reduction.
1282 auto CastOpcode = Cast0->getOpcode();
1283 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001284 return nullptr;
1285
1286 Value *Cast0Src = Cast0->getOperand(0);
1287 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001288
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001289 // fold (logic (cast A), (cast B)) -> (cast (logic A, B))
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001290
Sanjay Patel713f25e2016-02-23 17:41:34 +00001291 // Only do this if the casts both really cause code to be generated.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001292 if ((!isa<ICmpInst>(Cast0Src) || !isa<ICmpInst>(Cast1Src)) &&
1293 ShouldOptimizeCast(CastOpcode, Cast0Src, DestTy) &&
Sanjay Patel713f25e2016-02-23 17:41:34 +00001294 ShouldOptimizeCast(CastOpcode, Cast1Src, DestTy)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001295 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1296 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001297 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001298 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001299
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001300 // For now, only 'and'/'or' have optimizations after this.
1301 if (LogicOpc == Instruction::Xor)
1302 return nullptr;
1303
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001304 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001305 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001306 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1307 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1308 if (ICmp0 && ICmp1) {
1309 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1310 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1311 if (Res)
1312 return CastInst::Create(CastOpcode, Res, DestTy);
1313 return nullptr;
1314 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001315
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001316 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001317 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001318 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1319 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1320 if (FCmp0 && FCmp1) {
1321 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1322 : FoldOrOfFCmps(FCmp0, FCmp1);
1323 if (Res)
1324 return CastInst::Create(CastOpcode, Res, DestTy);
1325 return nullptr;
1326 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001327
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001328 return nullptr;
1329}
1330
Chris Lattner0a8191e2010-01-05 07:50:36 +00001331Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001332 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001333 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1334
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001335 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001336 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001337
Chandler Carruth66b31302015-01-04 12:03:27 +00001338 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001339 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001340
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001341 // (A|B)&(A|C) -> A|(B&C) etc
1342 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001343 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001344
Craig Topper9d4171a2012-12-20 07:09:41 +00001345 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001346 // purpose is to compute bits we don't care about.
1347 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001348 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001349
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001350 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001351 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001352
Chris Lattner0a8191e2010-01-05 07:50:36 +00001353 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1354 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001355
1356 // Optimize a variety of ((val OP C1) & C2) combinations...
1357 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1358 Value *Op0LHS = Op0I->getOperand(0);
1359 Value *Op0RHS = Op0I->getOperand(1);
1360 switch (Op0I->getOpcode()) {
1361 default: break;
1362 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001363 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001364 // If the mask is only needed on one incoming arm, push it up.
1365 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001366
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001367 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001368 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001369 // Not masking anything out for the LHS, move to RHS.
1370 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1371 Op0RHS->getName()+".masked");
1372 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1373 }
1374 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001375 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001376 // Not masking anything out for the RHS, move to LHS.
1377 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1378 Op0LHS->getName()+".masked");
1379 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1380 }
1381
1382 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001383 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001384 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001385 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1386 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1387 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001388 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1389 return BinaryOperator::CreateAnd(V, AndRHS);
1390 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1391 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1392 break;
1393
1394 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001395 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1396 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1397 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001398 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1399 return BinaryOperator::CreateAnd(V, AndRHS);
1400
Balaram Makamccf59732015-08-20 15:35:00 +00001401 // -x & 1 -> x & 1
1402 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1403 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1404
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001405 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001406 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001407 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001408 uint32_t BitWidth = AndRHSMask.getBitWidth();
1409 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1410 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1411
Hal Finkel60db0582014-09-07 18:57:58 +00001412 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001413 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1414 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1415 }
1416 }
1417 break;
1418
1419 case Instruction::Shl:
1420 case Instruction::LShr:
1421 // (1 << x) & 1 --> zext(x == 0)
1422 // (1 >> x) & 1 --> zext(x == 0)
1423 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1424 Value *NewICmp =
1425 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1426 return new ZExtInst(NewICmp, I.getType());
1427 }
1428 break;
1429 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001430
Chris Lattner0a8191e2010-01-05 07:50:36 +00001431 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1432 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1433 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001434 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001435
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001436 // If this is an integer truncation, and if the source is an 'and' with
1437 // immediate, transform it. This frequently occurs for bitfield accesses.
1438 {
Craig Topperf40110f2014-04-25 05:29:35 +00001439 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001440 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1441 // Change: and (trunc (and X, YC) to T), C2
1442 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001443 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001444 // other simplifications.
1445 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1446 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1447 C3 = ConstantExpr::getAnd(C3, AndRHS);
1448 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001449 }
1450 }
1451
1452 // Try to fold constant and into select arguments.
1453 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1454 if (Instruction *R = FoldOpIntoSelect(I, SI))
1455 return R;
1456 if (isa<PHINode>(Op0))
1457 if (Instruction *NV = FoldOpIntoPhi(I))
1458 return NV;
1459 }
1460
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001461 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1462 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001463
Chris Lattner0a8191e2010-01-05 07:50:36 +00001464 {
Craig Topperf40110f2014-04-25 05:29:35 +00001465 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001466 // (A|B) & ~(A&B) -> A^B
1467 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1468 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1469 ((A == C && B == D) || (A == D && B == C)))
1470 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001471
Chris Lattner0a8191e2010-01-05 07:50:36 +00001472 // ~(A&B) & (A|B) -> A^B
1473 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1474 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1475 ((A == C && B == D) || (A == D && B == C)))
1476 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001477
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001478 // A&(A^B) => A & ~B
1479 {
1480 Value *tmpOp0 = Op0;
1481 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001482 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001483 if (A == Op1 || B == Op1 ) {
1484 tmpOp1 = Op0;
1485 tmpOp0 = Op1;
1486 // Simplify below
1487 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001488 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001489
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001490 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001491 if (B == tmpOp0) {
1492 std::swap(A, B);
1493 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001494 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001495 // A is originally -1 (or a vector of -1 and undefs), then we enter
1496 // an endless loop. By checking that A is non-constant we ensure that
1497 // we will never get to the loop.
1498 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001499 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001500 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001501 }
1502
1503 // (A&((~A)|B)) -> A&B
1504 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1505 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1506 return BinaryOperator::CreateAnd(A, Op1);
1507 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1508 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1509 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001510
1511 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1512 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1513 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1514 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1515 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1516
1517 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1518 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1519 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1520 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1521 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001522
1523 // (A | B) & ((~A) ^ B) -> (A & B)
1524 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1525 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1526 return BinaryOperator::CreateAnd(A, B);
1527
1528 // ((~A) ^ B) & (A | B) -> (A & B)
1529 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1530 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1531 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001532 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001533
David Majnemer5e96f1b2014-08-30 06:18:20 +00001534 {
1535 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1536 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1537 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001538 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001539 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001540
David Majnemer5e96f1b2014-08-30 06:18:20 +00001541 // TODO: Make this recursive; it's a little tricky because an arbitrary
1542 // number of 'and' instructions might have to be created.
1543 Value *X, *Y;
1544 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1545 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1546 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001547 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001548 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1549 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001550 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001551 }
1552 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1553 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1554 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001555 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001556 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1557 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001558 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001559 }
1560 }
1561
Chris Lattner4e8137d2010-02-11 06:26:33 +00001562 // If and'ing two fcmp, try combine them into one.
1563 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1564 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001565 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001566 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001567
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001568 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1569 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001570
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001571 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1572 Value *Op0COp = Op0C->getOperand(0);
1573 Type *SrcTy = Op0COp->getType();
Craig Topper9d4171a2012-12-20 07:09:41 +00001574
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001575 // If we are masking off the sign bit of a floating-point value, convert
1576 // this to the canonical fabs intrinsic call and cast back to integer.
1577 // The backend should know how to optimize fabs().
1578 // TODO: This transform should also apply to vectors.
1579 ConstantInt *CI;
1580 if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
1581 match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001582 Module *M = I.getModule();
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001583 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
1584 Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
1585 return CastInst::CreateBitOrPointerCast(Call, I.getType());
1586 }
1587 }
1588
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001589 {
Craig Topperf40110f2014-04-25 05:29:35 +00001590 Value *X = nullptr;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001591 bool OpsSwapped = false;
1592 // Canonicalize SExt or Not to the LHS
1593 if (match(Op1, m_SExt(m_Value())) ||
1594 match(Op1, m_Not(m_Value()))) {
1595 std::swap(Op0, Op1);
1596 OpsSwapped = true;
1597 }
1598
1599 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1600 if (match(Op0, m_SExt(m_Value(X))) &&
1601 X->getType()->getScalarType()->isIntegerTy(1)) {
1602 Value *Zero = Constant::getNullValue(Op1->getType());
1603 return SelectInst::Create(X, Op1, Zero);
1604 }
1605
1606 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1607 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1608 X->getType()->getScalarType()->isIntegerTy(1)) {
1609 Value *Zero = Constant::getNullValue(Op0->getType());
1610 return SelectInst::Create(X, Zero, Op1);
1611 }
1612
1613 if (OpsSwapped)
1614 std::swap(Op0, Op1);
1615 }
1616
Craig Topperf40110f2014-04-25 05:29:35 +00001617 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001618}
1619
Chad Rosiera00df492016-05-25 16:22:14 +00001620/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1621/// insert the new intrinsic and return it.
1622Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001623 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1624
1625 // Look through zero extends.
1626 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1627 Op0 = Ext->getOperand(0);
1628
1629 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1630 Op1 = Ext->getOperand(0);
1631
1632 // (A | B) | C and A | (B | C) -> bswap if possible.
1633 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1634 match(Op1, m_Or(m_Value(), m_Value()));
1635
1636 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1637 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1638 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1639
1640 // (A & B) | (C & D) -> bswap if possible.
1641 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1642 match(Op1, m_And(m_Value(), m_Value()));
1643
1644 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1645 return nullptr;
1646
James Molloyf01488e2016-01-15 09:20:19 +00001647 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001648 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001649 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001650 Instruction *LastInst = Insts.pop_back_val();
1651 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001652
James Molloyf01488e2016-01-15 09:20:19 +00001653 for (auto *Inst : Insts)
1654 Worklist.Add(Inst);
1655 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001656}
1657
Sanjay Patel18549272015-09-08 18:24:36 +00001658/// We have an expression of the form (A&C)|(B&D). Check if A is (cond?-1:0)
1659/// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
1660/// expression to "cond ? C : D or B".
Chris Lattner0a8191e2010-01-05 07:50:36 +00001661static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1662 Value *C, Value *D) {
1663 // If A is not a select of -1/0, this cannot match.
Craig Topperf40110f2014-04-25 05:29:35 +00001664 Value *Cond = nullptr;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001665 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001666 !Cond->getType()->isIntegerTy(1))
Craig Topperf40110f2014-04-25 05:29:35 +00001667 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001668
1669 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001670 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001671 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001672 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001673 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001674
Chris Lattner0a8191e2010-01-05 07:50:36 +00001675 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001676 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001677 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001678 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001679 return SelectInst::Create(Cond, C, D);
Craig Topperf40110f2014-04-25 05:29:35 +00001680 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001681}
1682
Sanjay Patel18549272015-09-08 18:24:36 +00001683/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001684Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1685 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001686 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1687
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001688 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1689 // if K1 and K2 are a one-bit mask.
1690 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1691 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1692
1693 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1694 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1695
1696 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1697 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1698 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1699 LAnd->getOpcode() == Instruction::And &&
1700 RAnd->getOpcode() == Instruction::And) {
1701
Craig Topperf40110f2014-04-25 05:29:35 +00001702 Value *Mask = nullptr;
1703 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001704 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001705 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1706 DT) &&
1707 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1708 DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001709 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1710 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1711 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001712 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1713 CxtI, DT) &&
1714 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1715 CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001716 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1717 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1718 }
1719
1720 if (Masked)
1721 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1722 }
1723 }
1724
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001725 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1726 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1727 // The original condition actually refers to the following two ranges:
1728 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1729 // We can fold these two ranges if:
1730 // 1) C1 and C2 is unsigned greater than C3.
1731 // 2) The two ranges are separated.
1732 // 3) C1 ^ C2 is one-bit mask.
1733 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1734 // This implies all values in the two ranges differ by exactly one bit.
1735
1736 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1737 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1738 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1739 LHSCst->getValue() == (RHSCst->getValue())) {
1740
1741 Value *LAdd = LHS->getOperand(0);
1742 Value *RAdd = RHS->getOperand(0);
1743
1744 Value *LAddOpnd, *RAddOpnd;
1745 ConstantInt *LAddCst, *RAddCst;
1746 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1747 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1748 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1749 RAddCst->getValue().ugt(LHSCst->getValue())) {
1750
1751 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1752 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1753 ConstantInt *MaxAddCst = nullptr;
1754 if (LAddCst->getValue().ult(RAddCst->getValue()))
1755 MaxAddCst = RAddCst;
1756 else
1757 MaxAddCst = LAddCst;
1758
1759 APInt RRangeLow = -RAddCst->getValue();
1760 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1761 APInt LRangeLow = -LAddCst->getValue();
1762 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1763 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1764 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1765 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1766 : RRangeLow - LRangeLow;
1767
1768 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1769 RangeDiff.ugt(LHSCst->getValue())) {
1770 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1771
1772 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1773 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1774 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1775 }
1776 }
1777 }
1778 }
1779
Chris Lattner0a8191e2010-01-05 07:50:36 +00001780 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1781 if (PredicatesFoldable(LHSCC, RHSCC)) {
1782 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1783 LHS->getOperand(1) == RHS->getOperand(0))
1784 LHS->swapOperands();
1785 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1786 LHS->getOperand(1) == RHS->getOperand(1)) {
1787 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1788 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1789 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001790 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001791 }
1792 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001793
1794 // handle (roughly):
1795 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001796 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001797 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001798
Chris Lattner0a8191e2010-01-05 07:50:36 +00001799 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001800 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1801 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1802 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001803 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001804 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1805 B = Val;
1806 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1807 A = Val2;
1808 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1809 A = RHS->getOperand(1);
1810 }
1811 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1812 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1813 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1814 B = Val2;
1815 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1816 A = Val;
1817 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1818 A = LHS->getOperand(1);
1819 }
1820 if (A && B)
1821 return Builder->CreateICmp(
1822 ICmpInst::ICMP_UGE,
1823 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1824 }
1825
Erik Ecksteind1817522014-12-03 10:39:15 +00001826 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1827 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1828 return V;
1829
1830 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1831 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1832 return V;
1833
David Majnemerc2a990b2013-07-05 00:31:17 +00001834 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001835 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001836
Owen Anderson8f306a72010-08-02 09:32:13 +00001837 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1838 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1839 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1840 Value *NewOr = Builder->CreateOr(Val, Val2);
1841 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1842 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001843 }
1844
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001845 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001846 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001847 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001848 ConstantInt *AddCst;
1849 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1850 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001851 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001852 }
1853
Chris Lattner0a8191e2010-01-05 07:50:36 +00001854 // From here on, we only handle:
1855 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001856 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001857
Chris Lattner0a8191e2010-01-05 07:50:36 +00001858 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1859 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1860 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1861 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1862 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001863 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001864
Chris Lattner0a8191e2010-01-05 07:50:36 +00001865 // We can't fold (ugt x, C) | (sgt x, C2).
1866 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001867 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001868
Chris Lattner0a8191e2010-01-05 07:50:36 +00001869 // Ensure that the larger constant is on the RHS.
1870 bool ShouldSwap;
1871 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001872 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001873 CmpInst::isSigned(RHSCC)))
1874 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1875 else
1876 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001877
Chris Lattner0a8191e2010-01-05 07:50:36 +00001878 if (ShouldSwap) {
1879 std::swap(LHS, RHS);
1880 std::swap(LHSCst, RHSCst);
1881 std::swap(LHSCC, RHSCC);
1882 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001883
Dan Gohman4a618822010-02-10 16:03:48 +00001884 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 // comparing a value against two constants and or'ing the result
1886 // together. Because of the above check, we know that we only have
1887 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1888 // icmp folding check above), that the two constants are not
1889 // equal.
1890 assert(LHSCst != RHSCst && "Compares not folded above?");
1891
1892 switch (LHSCC) {
1893 default: llvm_unreachable("Unknown integer condition code!");
1894 case ICmpInst::ICMP_EQ:
1895 switch (RHSCC) {
1896 default: llvm_unreachable("Unknown integer condition code!");
1897 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001898 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001899 // if LHSCst and RHSCst differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001900 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001901 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1902
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001903 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1904 if (Xor.isPowerOf2()) {
David Majnemer942003a2015-12-02 16:15:07 +00001905 Value *Cst = Builder->getInt(Xor);
1906 Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1907 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001908 }
1909 }
1910
David Majnemer1fae1952013-04-14 21:15:43 +00001911 if (LHSCst == SubOne(RHSCst)) {
1912 // (X == 13 | X == 14) -> X-13 <u 2
1913 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1914 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1915 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1916 return Builder->CreateICmpULT(Add, AddCST);
1917 }
1918
Chris Lattner0a8191e2010-01-05 07:50:36 +00001919 break; // (X == 13 | X == 15) -> no change
1920 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1921 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1922 break;
1923 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1924 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1925 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001926 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001927 }
1928 break;
1929 case ICmpInst::ICMP_NE:
1930 switch (RHSCC) {
1931 default: llvm_unreachable("Unknown integer condition code!");
1932 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1933 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1934 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001935 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001936 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1937 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1938 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001939 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001940 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941 case ICmpInst::ICMP_ULT:
1942 switch (RHSCC) {
1943 default: llvm_unreachable("Unknown integer condition code!");
1944 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1945 break;
1946 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1947 // If RHSCst is [us]MAXINT, it is always false. Not handling
1948 // this can cause overflow.
1949 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001950 return LHS;
1951 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001952 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1953 break;
1954 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1955 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001956 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001957 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1958 break;
1959 }
1960 break;
1961 case ICmpInst::ICMP_SLT:
1962 switch (RHSCC) {
1963 default: llvm_unreachable("Unknown integer condition code!");
1964 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1965 break;
1966 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1967 // If RHSCst is [us]MAXINT, it is always false. Not handling
1968 // this can cause overflow.
1969 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001970 return LHS;
1971 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001972 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1973 break;
1974 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1975 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001976 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1978 break;
1979 }
1980 break;
1981 case ICmpInst::ICMP_UGT:
1982 switch (RHSCC) {
1983 default: llvm_unreachable("Unknown integer condition code!");
1984 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1985 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001986 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001987 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1988 break;
1989 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1990 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001991 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001992 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1993 break;
1994 }
1995 break;
1996 case ICmpInst::ICMP_SGT:
1997 switch (RHSCC) {
1998 default: llvm_unreachable("Unknown integer condition code!");
1999 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2000 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00002001 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002002 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2003 break;
2004 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2005 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002006 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002007 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2008 break;
2009 }
2010 break;
2011 }
Craig Topperf40110f2014-04-25 05:29:35 +00002012 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002013}
2014
Sanjay Patel18549272015-09-08 18:24:36 +00002015/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
2016/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00002017Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002018 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002019 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002020 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2021 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2022 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2023 // If either of the constants are nans, then the whole thing returns
2024 // true.
2025 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002026 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002027
Chris Lattner0a8191e2010-01-05 07:50:36 +00002028 // Otherwise, no need to compare the two constants, compare the
2029 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002030 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002031 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002032
Chris Lattner0a8191e2010-01-05 07:50:36 +00002033 // Handle vector zeros. This occurs because the canonical form of
2034 // "fcmp uno x,x" is "fcmp uno x, 0".
2035 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2036 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002037 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002038
Craig Topperf40110f2014-04-25 05:29:35 +00002039 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002040 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002041
Chris Lattner0a8191e2010-01-05 07:50:36 +00002042 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2043 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2044 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00002045
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2047 // Swap RHS operands to match LHS.
2048 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2049 std::swap(Op1LHS, Op1RHS);
2050 }
2051 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2052 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2053 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00002054 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002055 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00002056 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002057 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002058 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002059 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002060 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002061 bool Op0Ordered;
2062 bool Op1Ordered;
2063 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2064 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2065 if (Op0Ordered == Op1Ordered) {
2066 // If both are ordered or unordered, return a new fcmp with
2067 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00002068 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002069 }
2070 }
Craig Topperf40110f2014-04-25 05:29:35 +00002071 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002072}
2073
Sanjay Patel18549272015-09-08 18:24:36 +00002074/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00002075///
2076/// ((A | B) & C1) | (B & C2)
2077///
2078/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002079///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002080/// (A & C1) | B
2081///
2082/// when the XOR of the two constants is "all ones" (-1).
2083Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2084 Value *A, Value *B, Value *C) {
2085 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002086 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002087
Craig Topperf40110f2014-04-25 05:29:35 +00002088 Value *V1 = nullptr;
2089 ConstantInt *CI2 = nullptr;
2090 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002091
2092 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002093 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002094
2095 if (V1 == A || V1 == B) {
2096 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2097 return BinaryOperator::CreateOr(NewOp, V1);
2098 }
2099
Craig Topperf40110f2014-04-25 05:29:35 +00002100 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002101}
2102
David Majnemer5d1aeba2014-08-21 05:14:48 +00002103/// \brief This helper function folds:
2104///
2105/// ((A | B) & C1) ^ (B & C2)
2106///
2107/// into:
2108///
2109/// (A & C1) ^ B
2110///
2111/// when the XOR of the two constants is "all ones" (-1).
2112Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2113 Value *A, Value *B, Value *C) {
2114 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2115 if (!CI1)
2116 return nullptr;
2117
2118 Value *V1 = nullptr;
2119 ConstantInt *CI2 = nullptr;
2120 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2121 return nullptr;
2122
2123 APInt Xor = CI1->getValue() ^ CI2->getValue();
2124 if (!Xor.isAllOnesValue())
2125 return nullptr;
2126
2127 if (V1 == A || V1 == B) {
2128 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2129 return BinaryOperator::CreateXor(NewOp, V1);
2130 }
2131
2132 return nullptr;
2133}
2134
Chris Lattner0a8191e2010-01-05 07:50:36 +00002135Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002136 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002137 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2138
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002139 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002140 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002141
Chandler Carruth66b31302015-01-04 12:03:27 +00002142 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002143 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002144
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002145 // (A&B)|(A&C) -> A&(B|C) etc
2146 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002147 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002148
Craig Topper9d4171a2012-12-20 07:09:41 +00002149 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002150 // purpose is to compute bits we don't care about.
2151 if (SimplifyDemandedInstructionBits(I))
2152 return &I;
2153
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002154 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002155 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002156
Chris Lattner0a8191e2010-01-05 07:50:36 +00002157 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002158 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002159 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002160 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002161 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002162 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002163 Op0->hasOneUse()) {
2164 Value *Or = Builder->CreateOr(X, RHS);
2165 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002166 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002167 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002168 }
2169
2170 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2171 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2172 Op0->hasOneUse()) {
2173 Value *Or = Builder->CreateOr(X, RHS);
2174 Or->takeName(Op0);
2175 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002176 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002177 }
2178
2179 // Try to fold constant and into select arguments.
2180 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2181 if (Instruction *R = FoldOpIntoSelect(I, SI))
2182 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002183
Chris Lattner0a8191e2010-01-05 07:50:36 +00002184 if (isa<PHINode>(Op0))
2185 if (Instruction *NV = FoldOpIntoPhi(I))
2186 return NV;
2187 }
2188
Chad Rosiere5819e22016-05-26 14:58:51 +00002189 // Given an OR instruction, check to see if this is a bswap.
2190 if (Instruction *BSwap = MatchBSwap(I))
2191 return BSwap;
2192
Craig Topperf40110f2014-04-25 05:29:35 +00002193 Value *A = nullptr, *B = nullptr;
2194 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002195
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002196 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002197 if (Op0->hasOneUse() &&
2198 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002199 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002200 Value *NOr = Builder->CreateOr(A, Op1);
2201 NOr->takeName(Op0);
2202 return BinaryOperator::CreateXor(NOr, C1);
2203 }
2204
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002205 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002206 if (Op1->hasOneUse() &&
2207 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002208 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002209 Value *NOr = Builder->CreateOr(A, Op0);
2210 NOr->takeName(Op0);
2211 return BinaryOperator::CreateXor(NOr, C1);
2212 }
2213
Suyog Sardad64faf62014-07-22 18:09:41 +00002214 // ((~A & B) | A) -> (A | B)
2215 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2216 match(Op1, m_Specific(A)))
2217 return BinaryOperator::CreateOr(A, B);
2218
2219 // ((A & B) | ~A) -> (~A | B)
2220 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2221 match(Op1, m_Not(m_Specific(A))))
2222 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2223
Suyog Sarda52324c82014-08-01 04:50:31 +00002224 // (A & (~B)) | (A ^ B) -> (A ^ B)
2225 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2226 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2227 return BinaryOperator::CreateXor(A, B);
2228
2229 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2230 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2231 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2232 return BinaryOperator::CreateXor(A, B);
2233
Chris Lattner0a8191e2010-01-05 07:50:36 +00002234 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002235 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002236 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2237 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002238 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002239 C1 = dyn_cast<ConstantInt>(C);
2240 C2 = dyn_cast<ConstantInt>(D);
2241 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002242 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002243 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002244 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002245 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002246 ((V1 == B &&
2247 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2248 (V2 == B &&
2249 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002250 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002251 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002252 // Or commutes, try both ways.
2253 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002254 ((V1 == A &&
2255 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2256 (V2 == A &&
2257 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002258 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002259 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002260
Chris Lattner95188692010-01-11 06:55:24 +00002261 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002262 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002263 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002264 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2265 (C3->getValue() & ~C1->getValue()) == 0 &&
2266 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2267 (C4->getValue() & ~C2->getValue()) == 0) {
2268 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2269 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002270 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002271 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002272 }
2273 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002274
Chris Lattner8e2c4712010-02-02 02:43:51 +00002275 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2276 // Don't do this for vector select idioms, the code generator doesn't handle
2277 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002278 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002279 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2280 return Match;
2281 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2282 return Match;
2283 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2284 return Match;
2285 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2286 return Match;
2287 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002288
2289 // ((A&~B)|(~A&B)) -> A^B
2290 if ((match(C, m_Not(m_Specific(D))) &&
2291 match(B, m_Not(m_Specific(A)))))
2292 return BinaryOperator::CreateXor(A, D);
2293 // ((~B&A)|(~A&B)) -> A^B
2294 if ((match(A, m_Not(m_Specific(D))) &&
2295 match(B, m_Not(m_Specific(C)))))
2296 return BinaryOperator::CreateXor(C, D);
2297 // ((A&~B)|(B&~A)) -> A^B
2298 if ((match(C, m_Not(m_Specific(B))) &&
2299 match(D, m_Not(m_Specific(A)))))
2300 return BinaryOperator::CreateXor(A, B);
2301 // ((~B&A)|(B&~A)) -> A^B
2302 if ((match(A, m_Not(m_Specific(B))) &&
2303 match(D, m_Not(m_Specific(C)))))
2304 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002305
2306 // ((A|B)&1)|(B&-2) -> (A&1) | B
2307 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2308 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2309 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2310 if (Ret) return Ret;
2311 }
2312 // (B&-2)|((A|B)&1) -> (A&1) | B
2313 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2314 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2315 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2316 if (Ret) return Ret;
2317 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002318 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2319 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2320 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2321 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2322 if (Ret) return Ret;
2323 }
2324 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2325 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2326 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2327 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2328 if (Ret) return Ret;
2329 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002330 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002331
David Majnemer42af3602014-07-30 21:26:37 +00002332 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2333 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2334 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2335 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2336 return BinaryOperator::CreateOr(Op0, C);
2337
2338 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2339 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2340 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2341 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2342 return BinaryOperator::CreateOr(Op1, C);
2343
David Majnemerf1eda232014-08-14 06:41:38 +00002344 // ((B | C) & A) | B -> B | (A & C)
2345 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2346 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2347
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002348 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2349 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002350
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002351 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002352 bool SwappedForXor = false;
2353 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002354 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002355 SwappedForXor = true;
2356 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002357
2358 // A | ( A ^ B) -> A | B
2359 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002360 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002361 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2362 if (Op0 == A || Op0 == B)
2363 return BinaryOperator::CreateOr(A, B);
2364
Chad Rosier7813dce2012-04-26 23:29:14 +00002365 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2366 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2367 return BinaryOperator::CreateOr(A, B);
2368
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002369 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2370 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2371 return BinaryOperator::CreateOr(Not, Op0);
2372 }
2373 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2374 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2375 return BinaryOperator::CreateOr(Not, Op0);
2376 }
2377 }
2378
2379 // A | ~(A | B) -> A | ~B
2380 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002381 if (match(Op1, m_Not(m_Value(A))))
2382 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002383 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2384 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2385 B->getOpcode() == Instruction::Xor)) {
2386 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2387 B->getOperand(0);
2388 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2389 return BinaryOperator::CreateOr(Not, Op0);
2390 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002391
Suyog Sarda16d64652014-08-01 04:41:43 +00002392 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2393 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2394 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2395 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2396
2397 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2398 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2399 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2400 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2401
Eli Friedmane06535b2012-03-16 00:52:42 +00002402 if (SwappedForXor)
2403 std::swap(Op0, Op1);
2404
David Majnemer3d6f80b2014-11-28 19:58:29 +00002405 {
2406 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2407 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2408 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002409 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002410 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002411
David Majnemer3d6f80b2014-11-28 19:58:29 +00002412 // TODO: Make this recursive; it's a little tricky because an arbitrary
2413 // number of 'or' instructions might have to be created.
2414 Value *X, *Y;
2415 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2416 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2417 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002418 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002419 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2420 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002421 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002422 }
2423 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2424 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2425 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002426 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002427 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2428 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002429 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002430 }
2431 }
2432
Chris Lattner4e8137d2010-02-11 06:26:33 +00002433 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2434 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2435 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002436 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002437 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002438
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002439 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2440 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002441
2442 // or(sext(A), B) -> A ? -1 : B where A is an i1
2443 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2444 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2445 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2446 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2447 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2448
Owen Andersonc237a842010-09-13 17:59:27 +00002449 // Note: If we've gotten to the point of visiting the outer OR, then the
2450 // inner one couldn't be simplified. If it was a constant, then it won't
2451 // be simplified by a later pass either, so we try swapping the inner/outer
2452 // ORs in the hopes that we'll be able to simplify it this way.
2453 // (X|C) | V --> (X|V) | C
2454 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2455 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2456 Value *Inner = Builder->CreateOr(A, Op1);
2457 Inner->takeName(Op0);
2458 return BinaryOperator::CreateOr(Inner, C1);
2459 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002460
Bill Wendling23242092013-02-16 23:41:36 +00002461 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2462 // Since this OR statement hasn't been optimized further yet, we hope
2463 // that this transformation will allow the new ORs to be optimized.
2464 {
Craig Topperf40110f2014-04-25 05:29:35 +00002465 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002466 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2467 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2468 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2469 Value *orTrue = Builder->CreateOr(A, C);
2470 Value *orFalse = Builder->CreateOr(B, D);
2471 return SelectInst::Create(X, orTrue, orFalse);
2472 }
2473 }
2474
Craig Topperf40110f2014-04-25 05:29:35 +00002475 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002476}
2477
2478Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002479 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002480 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2481
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002482 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002483 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002484
Chandler Carruth66b31302015-01-04 12:03:27 +00002485 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002486 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002487
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002488 // (A&B)^(A&C) -> A&(B^C) etc
2489 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002490 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002491
Craig Topper9d4171a2012-12-20 07:09:41 +00002492 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002493 // purpose is to compute bits we don't care about.
2494 if (SimplifyDemandedInstructionBits(I))
2495 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002496
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002497 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002498 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002499
Chris Lattner0a8191e2010-01-05 07:50:36 +00002500 // Is this a ~ operation?
2501 if (Value *NotOp = dyn_castNotVal(&I)) {
2502 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002503 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002504 Op0I->getOpcode() == Instruction::Or) {
2505 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2506 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2507 if (dyn_castNotVal(Op0I->getOperand(1)))
2508 Op0I->swapOperands();
2509 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2510 Value *NotY =
2511 Builder->CreateNot(Op0I->getOperand(1),
2512 Op0I->getOperand(1)->getName()+".not");
2513 if (Op0I->getOpcode() == Instruction::And)
2514 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2515 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2516 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002517
Chris Lattner0a8191e2010-01-05 07:50:36 +00002518 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2519 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002520 if (IsFreeToInvert(Op0I->getOperand(0),
2521 Op0I->getOperand(0)->hasOneUse()) &&
2522 IsFreeToInvert(Op0I->getOperand(1),
2523 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002524 Value *NotX =
2525 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2526 Value *NotY =
2527 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2528 if (Op0I->getOpcode() == Instruction::And)
2529 return BinaryOperator::CreateOr(NotX, NotY);
2530 return BinaryOperator::CreateAnd(NotX, NotY);
2531 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002532
2533 } else if (Op0I->getOpcode() == Instruction::AShr) {
2534 // ~(~X >>s Y) --> (X >>s Y)
2535 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2536 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002537 }
2538 }
2539 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002540
Benjamin Kramer443c7962015-02-12 20:26:46 +00002541 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2542 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002543 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002544 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2545 return CmpInst::Create(CI->getOpcode(),
2546 CI->getInversePredicate(),
2547 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002548 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002549
Benjamin Kramer443c7962015-02-12 20:26:46 +00002550 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002551 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2552 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2553 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2554 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2555 Instruction::CastOps Opcode = Op0C->getOpcode();
2556 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002557 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002558 Op0C->getDestTy()))) {
2559 CI->setPredicate(CI->getInversePredicate());
2560 return CastInst::Create(Opcode, CI, Op0C->getType());
2561 }
2562 }
2563 }
2564 }
2565
2566 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2567 // ~(c-X) == X-c-1 == X+(-c-1)
2568 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2569 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2570 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2571 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2572 ConstantInt::get(I.getType(), 1));
2573 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2574 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002575
Chris Lattner0a8191e2010-01-05 07:50:36 +00002576 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2577 if (Op0I->getOpcode() == Instruction::Add) {
2578 // ~(X-c) --> (-c-1)-X
2579 if (RHS->isAllOnesValue()) {
2580 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2581 return BinaryOperator::CreateSub(
2582 ConstantExpr::getSub(NegOp0CI,
2583 ConstantInt::get(I.getType(), 1)),
2584 Op0I->getOperand(0));
2585 } else if (RHS->getValue().isSignBit()) {
2586 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002587 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002588 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2589
2590 }
2591 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002592 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002593 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2594 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002595 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2596 // Anything in both C1 and C2 is known to be zero, remove it from
2597 // NewRHS.
2598 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002599 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002600 ConstantExpr::getNot(CommonBits));
2601 Worklist.Add(Op0I);
2602 I.setOperand(0, Op0I->getOperand(0));
2603 I.setOperand(1, NewRHS);
2604 return &I;
2605 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002606 } else if (Op0I->getOpcode() == Instruction::LShr) {
2607 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2608 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002609 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002610 ConstantInt *C1;
2611 if (Op0I->hasOneUse() &&
2612 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2613 E1->getOpcode() == Instruction::Xor &&
2614 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2615 // fold (C1 >> C2) ^ C3
2616 ConstantInt *C2 = Op0CI, *C3 = RHS;
2617 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2618 FoldConst ^= C3->getValue();
2619 // Prepare the two operands.
2620 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2621 Opnd0->takeName(Op0I);
2622 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2623 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2624
2625 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2626 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002627 }
2628 }
2629 }
2630
2631 // Try to fold constant and into select arguments.
2632 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2633 if (Instruction *R = FoldOpIntoSelect(I, SI))
2634 return R;
2635 if (isa<PHINode>(Op0))
2636 if (Instruction *NV = FoldOpIntoPhi(I))
2637 return NV;
2638 }
2639
Chris Lattner0a8191e2010-01-05 07:50:36 +00002640 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2641 if (Op1I) {
2642 Value *A, *B;
2643 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2644 if (A == Op0) { // B^(B|A) == (A|B)^B
2645 Op1I->swapOperands();
2646 I.swapOperands();
2647 std::swap(Op0, Op1);
2648 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2649 I.swapOperands(); // Simplified below.
2650 std::swap(Op0, Op1);
2651 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002652 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002653 Op1I->hasOneUse()){
2654 if (A == Op0) { // A^(A&B) -> A^(B&A)
2655 Op1I->swapOperands();
2656 std::swap(A, B);
2657 }
2658 if (B == Op0) { // A^(B&A) -> (B&A)^A
2659 I.swapOperands(); // Simplified below.
2660 std::swap(Op0, Op1);
2661 }
2662 }
2663 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002664
Chris Lattner0a8191e2010-01-05 07:50:36 +00002665 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2666 if (Op0I) {
2667 Value *A, *B;
2668 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2669 Op0I->hasOneUse()) {
2670 if (A == Op1) // (B|A)^B == (A|B)^B
2671 std::swap(A, B);
2672 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002673 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002674 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002675 Op0I->hasOneUse()){
2676 if (A == Op1) // (A&B)^A -> (B&A)^A
2677 std::swap(A, B);
2678 if (B == Op1 && // (B&A)^A == ~B & A
2679 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002680 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002681 }
2682 }
2683 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002684
Chris Lattner0a8191e2010-01-05 07:50:36 +00002685 if (Op0I && Op1I) {
2686 Value *A, *B, *C, *D;
2687 // (A & B)^(A | B) -> A ^ B
2688 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2689 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002690 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002691 return BinaryOperator::CreateXor(A, B);
2692 }
2693 // (A | B)^(A & B) -> A ^ B
2694 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2695 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002696 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002697 return BinaryOperator::CreateXor(A, B);
2698 }
David Majnemer698dca02014-08-14 06:46:25 +00002699 // (A | ~B) ^ (~A | B) -> A ^ B
2700 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2701 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2702 return BinaryOperator::CreateXor(A, B);
2703 }
2704 // (~A | B) ^ (A | ~B) -> A ^ B
2705 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2706 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2707 return BinaryOperator::CreateXor(A, B);
2708 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002709 // (A & ~B) ^ (~A & B) -> A ^ B
2710 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2711 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2712 return BinaryOperator::CreateXor(A, B);
2713 }
2714 // (~A & B) ^ (A & ~B) -> A ^ B
2715 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2716 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2717 return BinaryOperator::CreateXor(A, B);
2718 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002719 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2720 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2721 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2722 if (D == A)
2723 return BinaryOperator::CreateXor(
2724 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2725 if (D == B)
2726 return BinaryOperator::CreateXor(
2727 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002728 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002729 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002730 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002731 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2732 if (D == A)
2733 return BinaryOperator::CreateXor(
2734 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2735 if (D == B)
2736 return BinaryOperator::CreateXor(
2737 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002738 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002739 // (A & B) ^ (A ^ B) -> (A | B)
2740 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2741 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2742 return BinaryOperator::CreateOr(A, B);
2743 // (A ^ B) ^ (A & B) -> (A | B)
2744 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2745 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2746 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002747 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002748
Suyog Sarda521237c2014-07-22 15:37:39 +00002749 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002750 // (A & ~B) ^ (~A) -> ~(A & B)
2751 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2752 match(Op1, m_Not(m_Specific(A))))
2753 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2754
Chris Lattner0a8191e2010-01-05 07:50:36 +00002755 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2756 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2757 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2758 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2759 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2760 LHS->getOperand(1) == RHS->getOperand(0))
2761 LHS->swapOperands();
2762 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2763 LHS->getOperand(1) == RHS->getOperand(1)) {
2764 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2765 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2766 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002767 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002768 getNewICmpValue(isSigned, Code, Op0, Op1,
2769 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002770 }
2771 }
2772
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002773 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2774 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002775
Craig Topperf40110f2014-04-25 05:29:35 +00002776 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002777}