blob: 2c1bfc73fd90e21f0db06694b3bf41dbf917464d [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
14#include "InstCombine.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chris Lattner0a8191e2010-01-05 07:50:36 +000023/// isFreeToInvert - Return true if the specified value is free to invert (apply
24/// ~ to). This happens in cases where the ~ can be eliminated.
25static inline bool isFreeToInvert(Value *V) {
26 // ~(~(X)) -> X.
27 if (BinaryOperator::isNot(V))
28 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000029
Chris Lattner0a8191e2010-01-05 07:50:36 +000030 // Constants can be considered to be not'ed values.
31 if (isa<ConstantInt>(V))
32 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000033
Chris Lattner0a8191e2010-01-05 07:50:36 +000034 // Compares can be inverted if they have a single use.
35 if (CmpInst *CI = dyn_cast<CmpInst>(V))
36 return CI->hasOneUse();
Craig Topper9d4171a2012-12-20 07:09:41 +000037
Chris Lattner0a8191e2010-01-05 07:50:36 +000038 return false;
39}
40
41static inline Value *dyn_castNotVal(Value *V) {
42 // If this is not(not(x)) don't return that this is a not: we want the two
43 // not's to be folded first.
44 if (BinaryOperator::isNot(V)) {
45 Value *Operand = BinaryOperator::getNotArgument(V);
46 if (!isFreeToInvert(Operand))
47 return Operand;
48 }
Craig Topper9d4171a2012-12-20 07:09:41 +000049
Chris Lattner0a8191e2010-01-05 07:50:36 +000050 // Constants can be considered to be not'ed values...
51 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
52 return ConstantInt::get(C->getType(), ~C->getValue());
53 return 0;
54}
55
Chris Lattner0a8191e2010-01-05 07:50:36 +000056/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
57/// predicate into a three bit mask. It also returns whether it is an ordered
58/// predicate by reference.
59static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
60 isOrdered = false;
61 switch (CC) {
62 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
63 case FCmpInst::FCMP_UNO: return 0; // 000
64 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
65 case FCmpInst::FCMP_UGT: return 1; // 001
66 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
67 case FCmpInst::FCMP_UEQ: return 2; // 010
68 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
69 case FCmpInst::FCMP_UGE: return 3; // 011
70 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
71 case FCmpInst::FCMP_ULT: return 4; // 100
72 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
73 case FCmpInst::FCMP_UNE: return 5; // 101
74 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
75 case FCmpInst::FCMP_ULE: return 6; // 110
76 // True -> 7
77 default:
78 // Not expecting FCMP_FALSE and FCMP_TRUE;
79 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000080 }
81}
82
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000083/// getNewICmpValue - This is the complement of getICmpCode, which turns an
Craig Topper9d4171a2012-12-20 07:09:41 +000084/// opcode and two operands into either a constant true or false, or a brand
Chris Lattner0a8191e2010-01-05 07:50:36 +000085/// new ICmp instruction. The sign is passed in to determine which kind
86/// of predicate to use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000087static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
88 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000089 ICmpInst::Predicate NewPred;
90 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
91 return NewConstant;
92 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000093}
94
95/// getFCmpValue - This is the complement of getFCmpCode, which turns an
96/// opcode and two operands into either a FCmp instruction. isordered is passed
97/// in to determine which kind of predicate to use in the new fcmp instruction.
98static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +000099 Value *LHS, Value *RHS,
100 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000101 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000102 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +0000103 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +0000104 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
105 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
106 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
107 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
108 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
109 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
110 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +0000111 case 7:
Owen Andersona8342002011-01-21 19:39:42 +0000112 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
113 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000114 }
Chris Lattner067459c2010-03-05 08:46:26 +0000115 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000116}
117
Chris Lattner0a8191e2010-01-05 07:50:36 +0000118// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
119// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
120// guaranteed to be a binary operator.
121Instruction *InstCombiner::OptAndOp(Instruction *Op,
122 ConstantInt *OpRHS,
123 ConstantInt *AndRHS,
124 BinaryOperator &TheAnd) {
125 Value *X = Op->getOperand(0);
126 Constant *Together = 0;
127 if (!Op->isShift())
128 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
129
130 switch (Op->getOpcode()) {
131 case Instruction::Xor:
132 if (Op->hasOneUse()) {
133 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
134 Value *And = Builder->CreateAnd(X, AndRHS);
135 And->takeName(Op);
136 return BinaryOperator::CreateXor(And, Together);
137 }
138 break;
139 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000140 if (Op->hasOneUse()){
141 if (Together != OpRHS) {
142 // (X | C1) & C2 --> (X | (C1&C2)) & C2
143 Value *Or = Builder->CreateOr(X, Together);
144 Or->takeName(Op);
145 return BinaryOperator::CreateAnd(Or, AndRHS);
146 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000147
Owen Andersonc237a842010-09-13 17:59:27 +0000148 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
149 if (TogetherCI && !TogetherCI->isZero()){
150 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
151 // NOTE: This reduces the number of bits set in the & mask, which
152 // can expose opportunities for store narrowing.
153 Together = ConstantExpr::getXor(AndRHS, Together);
154 Value *And = Builder->CreateAnd(X, Together);
155 And->takeName(Op);
156 return BinaryOperator::CreateOr(And, OpRHS);
157 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000158 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000159
Chris Lattner0a8191e2010-01-05 07:50:36 +0000160 break;
161 case Instruction::Add:
162 if (Op->hasOneUse()) {
163 // Adding a one to a single bit bit-field should be turned into an XOR
164 // of the bit. First thing to check is to see if this AND is with a
165 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000166 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000167
168 // If there is only one bit set.
169 if (AndRHSV.isPowerOf2()) {
170 // Ok, at this point, we know that we are masking the result of the
171 // ADD down to exactly one bit. If the constant we are adding has
172 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000173 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000174
175 // Check to see if any bits below the one bit set in AndRHSV are set.
176 if ((AddRHS & (AndRHSV-1)) == 0) {
177 // If not, the only thing that can effect the output of the AND is
178 // the bit specified by AndRHSV. If that bit is set, the effect of
179 // the XOR is to toggle the bit. If it is clear, then the ADD has
180 // no effect.
181 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
182 TheAnd.setOperand(0, X);
183 return &TheAnd;
184 } else {
185 // Pull the XOR out of the AND.
186 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
187 NewAnd->takeName(Op);
188 return BinaryOperator::CreateXor(NewAnd, AndRHS);
189 }
190 }
191 }
192 }
193 break;
194
195 case Instruction::Shl: {
196 // We know that the AND will not produce any of the bits shifted in, so if
197 // the anded constant includes them, clear them now!
198 //
199 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
200 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
201 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000202 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000203
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000204 if (CI->getValue() == ShlMask)
205 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000206 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000207
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000208 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000209 TheAnd.setOperand(1, CI);
210 return &TheAnd;
211 }
212 break;
213 }
214 case Instruction::LShr: {
215 // We know that the AND will not produce any of the bits shifted in, so if
216 // the anded constant includes them, clear them now! This only applies to
217 // unsigned shifts, because a signed shr may bring in set bits!
218 //
219 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
220 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
221 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000222 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000223
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000224 if (CI->getValue() == ShrMask)
225 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000226 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000227
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000228 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000229 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
230 return &TheAnd;
231 }
232 break;
233 }
234 case Instruction::AShr:
235 // Signed shr.
236 // See if this is shifting in some sign extension, then masking it out
237 // with an and.
238 if (Op->hasOneUse()) {
239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
241 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000242 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000243 if (C == AndRHS) { // Masking out bits shifted in.
244 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
245 // Make the argument unsigned.
246 Value *ShVal = Op->getOperand(0);
247 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
248 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
249 }
250 }
251 break;
252 }
253 return 0;
254}
255
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000256/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
257/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000258/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000259/// whether to treat the V, Lo and HI as signed or not. IB is the location to
260/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000261Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
262 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000263 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000264 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
265 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000266
Chris Lattner0a8191e2010-01-05 07:50:36 +0000267 if (Inside) {
268 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000269 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000270
271 // V >= Min && V < Hi --> V < Hi
272 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000273 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000274 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000275 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000276 }
277
278 // Emit V-Lo <u Hi-Lo
279 Constant *NegLo = ConstantExpr::getNeg(Lo);
280 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
281 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000282 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000283 }
284
285 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000286 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000287
288 // V < Min || V >= Hi -> V > Hi-1
289 Hi = SubOne(cast<ConstantInt>(Hi));
290 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000291 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000292 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000293 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000294 }
295
296 // Emit V-Lo >u Hi-1-Lo
297 // Note that Hi has already had one subtracted from it, above.
298 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
299 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
300 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000301 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000302}
303
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000304// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000305// any number of 0s on either side. The 1s are allowed to wrap from LSB to
306// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
307// not, since all 1s are not contiguous.
308static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
309 const APInt& V = Val->getValue();
310 uint32_t BitWidth = Val->getType()->getBitWidth();
311 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
312
313 // look for the first zero bit after the run of ones
314 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
315 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000316 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000317 return true;
318}
319
320/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
321/// where isSub determines whether the operator is a sub. If we can fold one of
322/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000323///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000324/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
325/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
326/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327///
328/// return (A +/- B).
329///
330Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
331 ConstantInt *Mask, bool isSub,
332 Instruction &I) {
333 Instruction *LHSI = dyn_cast<Instruction>(LHS);
334 if (!LHSI || LHSI->getNumOperands() != 2 ||
335 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
336
337 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
338
339 switch (LHSI->getOpcode()) {
340 default: return 0;
341 case Instruction::And:
342 if (ConstantExpr::getAnd(N, Mask) == Mask) {
343 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000344 if ((Mask->getValue().countLeadingZeros() +
345 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000346 Mask->getValue().getBitWidth())
347 break;
348
349 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
350 // part, we don't need any explicit masks to take them out of A. If that
351 // is all N is, ignore it.
352 uint32_t MB = 0, ME = 0;
353 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
354 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
355 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
356 if (MaskedValueIsZero(RHS, Mask))
357 break;
358 }
359 }
360 return 0;
361 case Instruction::Or:
362 case Instruction::Xor:
363 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000364 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000365 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
366 && ConstantExpr::getAnd(N, Mask)->isNullValue())
367 break;
368 return 0;
369 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000370
Chris Lattner0a8191e2010-01-05 07:50:36 +0000371 if (isSub)
372 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
373 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
374}
375
Owen Anderson3fe002d2010-09-08 22:16:17 +0000376/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000377/// One of A and B is considered the mask, the other the value. This is
378/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000379/// contains only "Mask", then both A and B can be considered masks.
380/// If A is the mask, then it was proven, that (A & C) == C. This
381/// is trivial if C == A, or C == 0. If both A and C are constants, this
382/// proof is also easy.
383/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000384/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000385/// if (A & B) == A, or all bits of A are set in B.
386/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000387/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000388/// if (A & B) == 0, or all bits of A are cleared in B.
389/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000390/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000391/// contain any number of one bits and zero bits.
392/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
393/// The Part "Not" means, that in above descriptions "==" should be replaced
394/// by "!=".
395/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
396/// If the mask A contains a single bit, then the following is equivalent:
397/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
398/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
399enum MaskedICmpType {
400 FoldMskICmp_AMask_AllOnes = 1,
401 FoldMskICmp_AMask_NotAllOnes = 2,
402 FoldMskICmp_BMask_AllOnes = 4,
403 FoldMskICmp_BMask_NotAllOnes = 8,
404 FoldMskICmp_Mask_AllZeroes = 16,
405 FoldMskICmp_Mask_NotAllZeroes = 32,
406 FoldMskICmp_AMask_Mixed = 64,
407 FoldMskICmp_AMask_NotMixed = 128,
408 FoldMskICmp_BMask_Mixed = 256,
409 FoldMskICmp_BMask_NotMixed = 512
410};
411
412/// return the set of pattern classes (from MaskedICmpType)
413/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000414static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415 ICmpInst::Predicate SCC)
416{
417 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
418 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
419 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
420 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topper9d4171a2012-12-20 07:09:41 +0000421 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000422 ACst->getValue().isPowerOf2());
Craig Topper9d4171a2012-12-20 07:09:41 +0000423 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424 BCst->getValue().isPowerOf2());
425 unsigned result = 0;
426 if (CCst != 0 && CCst->isZero()) {
427 // if C is zero, then both A and B qualify as mask
428 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
429 FoldMskICmp_Mask_AllZeroes |
430 FoldMskICmp_AMask_Mixed |
431 FoldMskICmp_BMask_Mixed)
432 : (FoldMskICmp_Mask_NotAllZeroes |
433 FoldMskICmp_Mask_NotAllZeroes |
434 FoldMskICmp_AMask_NotMixed |
435 FoldMskICmp_BMask_NotMixed));
436 if (icmp_abit)
437 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000438 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000439 : (FoldMskICmp_AMask_AllOnes |
440 FoldMskICmp_AMask_Mixed));
441 if (icmp_bbit)
442 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000443 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000444 : (FoldMskICmp_BMask_AllOnes |
445 FoldMskICmp_BMask_Mixed));
446 return result;
447 }
448 if (A == C) {
449 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
450 FoldMskICmp_AMask_Mixed)
451 : (FoldMskICmp_AMask_NotAllOnes |
452 FoldMskICmp_AMask_NotMixed));
453 if (icmp_abit)
454 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
455 FoldMskICmp_AMask_NotMixed)
456 : (FoldMskICmp_Mask_AllZeroes |
457 FoldMskICmp_AMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000458 } else if (ACst != 0 && CCst != 0 &&
459 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000460 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
461 : FoldMskICmp_AMask_NotMixed);
462 }
Craig Topperae48cb22012-12-20 07:15:54 +0000463 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000464 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
465 FoldMskICmp_BMask_Mixed)
466 : (FoldMskICmp_BMask_NotAllOnes |
467 FoldMskICmp_BMask_NotMixed));
468 if (icmp_bbit)
469 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000470 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000471 : (FoldMskICmp_Mask_AllZeroes |
472 FoldMskICmp_BMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000473 } else if (BCst != 0 && CCst != 0 &&
474 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000475 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
476 : FoldMskICmp_BMask_NotMixed);
477 }
478 return result;
479}
480
Tim Northoverc0756c42013-09-04 11:57:13 +0000481/// Convert an analysis of a masked ICmp into its equivalent if all boolean
482/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
483/// is adjacent to the corresponding normal flag (recording ==), this just
484/// involves swapping those bits over.
485static unsigned conjugateICmpMask(unsigned Mask) {
486 unsigned NewMask;
487 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
488 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
489 FoldMskICmp_BMask_Mixed))
490 << 1;
491
492 NewMask |=
493 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
494 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
495 FoldMskICmp_BMask_NotMixed))
496 >> 1;
497
498 return NewMask;
499}
500
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000501/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
502/// if possible. The returned predicate is either == or !=. Returns false if
503/// decomposition fails.
504static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
505 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000506 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
507 if (!C)
508 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000509
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000510 switch (I->getPredicate()) {
511 default:
512 return false;
513 case ICmpInst::ICMP_SLT:
514 // X < 0 is equivalent to (X & SignBit) != 0.
515 if (!C->isZero())
516 return false;
517 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
518 Pred = ICmpInst::ICMP_NE;
519 break;
520 case ICmpInst::ICMP_SGT:
521 // X > -1 is equivalent to (X & SignBit) == 0.
522 if (!C->isAllOnesValue())
523 return false;
524 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
525 Pred = ICmpInst::ICMP_EQ;
526 break;
527 case ICmpInst::ICMP_ULT:
528 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
529 if (!C->getValue().isPowerOf2())
530 return false;
531 Y = ConstantInt::get(I->getContext(), -C->getValue());
532 Pred = ICmpInst::ICMP_EQ;
533 break;
534 case ICmpInst::ICMP_UGT:
535 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
536 if (!(C->getValue() + 1).isPowerOf2())
537 return false;
538 Y = ConstantInt::get(I->getContext(), ~C->getValue());
539 Pred = ICmpInst::ICMP_NE;
540 break;
541 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000542
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000543 X = I->getOperand(0);
544 Z = ConstantInt::getNullValue(C->getType());
545 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000546}
547
Owen Anderson3fe002d2010-09-08 22:16:17 +0000548/// foldLogOpOfMaskedICmpsHelper:
549/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
550/// return the set of pattern classes (from MaskedICmpType)
551/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000552static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000553 Value*& B, Value*& C,
554 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000555 ICmpInst *LHS, ICmpInst *RHS,
556 ICmpInst::Predicate &LHSCC,
557 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000558 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
559 // vectors are not (yet?) supported
560 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
561
562 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000563 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000564 // and L11 & L12 == L21 & L22. The same goes for RHS.
565 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000566 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000567 // above.
568 Value *L1 = LHS->getOperand(0);
569 Value *L2 = LHS->getOperand(1);
570 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000571 // Check whether the icmp can be decomposed into a bit test.
572 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
573 L21 = L22 = L1 = 0;
574 } else {
575 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000576 if (!L1->getType()->isIntegerTy()) {
577 // You can icmp pointers, for example. They really aren't masks.
578 L11 = L12 = 0;
579 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
580 // Any icmp can be viewed as being trivially masked; if it allows us to
581 // remove one, it's worth it.
582 L11 = L1;
583 L12 = Constant::getAllOnesValue(L1->getType());
584 }
585
586 if (!L2->getType()->isIntegerTy()) {
587 // You can icmp pointers, for example. They really aren't masks.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000588 L21 = L22 = 0;
Tim Northoverdc647a22013-09-04 11:57:17 +0000589 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
590 L21 = L2;
591 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000592 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000593 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000594
595 // Bail if LHS was a icmp that can't be decomposed into an equality.
596 if (!ICmpInst::isEquality(LHSCC))
597 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000598
599 Value *R1 = RHS->getOperand(0);
600 Value *R2 = RHS->getOperand(1);
601 Value *R11,*R12;
602 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000603 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
604 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
605 A = R11; D = R12;
606 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
607 A = R12; D = R11;
608 } else {
609 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000610 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000611 E = R2; R1 = 0; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000612 } else if (R1->getType()->isIntegerTy()) {
613 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
614 // As before, model no mask as a trivial mask if it'll let us do an
615 // optimisation.
616 R11 = R1;
617 R12 = Constant::getAllOnesValue(R1->getType());
618 }
619
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000620 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
621 A = R11; D = R12; E = R2; ok = true;
622 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000623 A = R12; D = R11; E = R2; ok = true;
624 }
625 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000626
627 // Bail if RHS was a icmp that can't be decomposed into an equality.
628 if (!ICmpInst::isEquality(RHSCC))
629 return 0;
630
631 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000632 if (!ok && R2->getType()->isIntegerTy()) {
633 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
634 R11 = R2;
635 R12 = Constant::getAllOnesValue(R2->getType());
636 }
637
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000638 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
639 A = R11; D = R12; E = R1; ok = true;
640 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000641 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000642 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000643 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000644 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000645 }
646 if (!ok)
647 return 0;
648
649 if (L11 == A) {
650 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000651 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000652 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000653 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000654 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000655 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000656 B = L21; C = L1;
657 }
658
659 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
660 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
661 return left_type & right_type;
662}
663/// foldLogOpOfMaskedICmps:
664/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
665/// into a single (icmp(A & X) ==/!= Y)
Tim Northoverc0756c42013-09-04 11:57:13 +0000666static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000667 llvm::InstCombiner::BuilderTy* Builder) {
668 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000669 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
670 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
671 LHSCC, RHSCC);
Benjamin Kramerf7fe24f2012-01-09 17:36:29 +0000672 if (mask == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000673 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
674 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000675
Tim Northoverc0756c42013-09-04 11:57:13 +0000676 // In full generality:
677 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
678 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
679 //
680 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
681 // equivalent to (icmp (A & X) !Op Y).
682 //
683 // Therefore, we can pretend for the rest of this function that we're dealing
684 // with the conjunction, provided we flip the sense of any comparisons (both
685 // input and output).
686
687 // In most cases we're going to produce an EQ for the "&&" case.
688 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
689 if (!IsAnd) {
690 // Convert the masking analysis into its equivalent with negated
691 // comparisons.
692 mask = conjugateICmpMask(mask);
693 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000694
695 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000696 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000697 // -> (icmp eq (A & (B|D)), 0)
698 Value* newOr = Builder->CreateOr(B, D);
699 Value* newAnd = Builder->CreateAnd(A, newOr);
700 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000701 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000702 // with B and D, having a single bit set
703 Value* zero = Constant::getNullValue(A->getType());
704 return Builder->CreateICmp(NEWCC, newAnd, zero);
705 }
Craig Topperae48cb22012-12-20 07:15:54 +0000706 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000707 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000708 // -> (icmp eq (A & (B|D)), (B|D))
709 Value* newOr = Builder->CreateOr(B, D);
710 Value* newAnd = Builder->CreateAnd(A, newOr);
711 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000712 }
Craig Topperae48cb22012-12-20 07:15:54 +0000713 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000714 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000715 // -> (icmp eq (A & (B&D)), A)
716 Value* newAnd1 = Builder->CreateAnd(B, D);
717 Value* newAnd = Builder->CreateAnd(A, newAnd1);
718 return Builder->CreateICmp(NEWCC, newAnd, A);
719 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000720
721 // Remaining cases assume at least that B and D are constant, and depend on
722 // their actual values. This isn't strictly, necessary, just a "handle the
723 // easy cases for now" decision.
724 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
725 if (BCst == 0) return 0;
726 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
727 if (DCst == 0) return 0;
728
729 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
730 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
731 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
732 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
733 // Only valid if one of the masks is a superset of the other (check "B&D" is
734 // the same as either B or D).
735 APInt NewMask = BCst->getValue() & DCst->getValue();
736
737 if (NewMask == BCst->getValue())
738 return LHS;
739 else if (NewMask == DCst->getValue())
740 return RHS;
741 }
742 if (mask & FoldMskICmp_AMask_NotAllOnes) {
743 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
744 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
745 // Only valid if one of the masks is a superset of the other (check "B|D" is
746 // the same as either B or D).
747 APInt NewMask = BCst->getValue() | DCst->getValue();
748
749 if (NewMask == BCst->getValue())
750 return LHS;
751 else if (NewMask == DCst->getValue())
752 return RHS;
753 }
Craig Topperae48cb22012-12-20 07:15:54 +0000754 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000755 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000756 // We already know that B & C == C && D & E == E.
757 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
758 // C and E, which are shared by both the mask B and the mask D, don't
759 // contradict, then we can transform to
760 // -> (icmp eq (A & (B|D)), (C|E))
761 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000762 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000763 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000764 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000765 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
766 if (CCst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000767 if (LHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000768 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
769 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
770 if (ECst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000771 if (RHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000772 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
773 ConstantInt* MCst = dyn_cast<ConstantInt>(
774 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
775 ConstantExpr::getXor(CCst, ECst)) );
776 // if there is a conflict we should actually return a false for the
777 // whole construct
778 if (!MCst->isZero())
779 return 0;
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000780 Value *newOr1 = Builder->CreateOr(B, D);
781 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
782 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000783 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
784 }
785 return 0;
786}
787
Chris Lattner0a8191e2010-01-05 07:50:36 +0000788/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000789Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000790 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
791
792 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
793 if (PredicatesFoldable(LHSCC, RHSCC)) {
794 if (LHS->getOperand(0) == RHS->getOperand(1) &&
795 LHS->getOperand(1) == RHS->getOperand(0))
796 LHS->swapOperands();
797 if (LHS->getOperand(0) == RHS->getOperand(0) &&
798 LHS->getOperand(1) == RHS->getOperand(1)) {
799 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
800 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
801 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000802 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000803 }
804 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000805
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000806 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000807 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000808 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000809
Chris Lattner0a8191e2010-01-05 07:50:36 +0000810 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
811 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
812 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
813 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
814 if (LHSCst == 0 || RHSCst == 0) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000815
Chris Lattner0a8191e2010-01-05 07:50:36 +0000816 if (LHSCst == RHSCst && LHSCC == RHSCC) {
817 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
818 // where C is a power of 2
819 if (LHSCC == ICmpInst::ICMP_ULT &&
820 LHSCst->getValue().isPowerOf2()) {
821 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000822 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000823 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000824
Chris Lattner0a8191e2010-01-05 07:50:36 +0000825 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
826 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
827 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000828 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000829 }
830 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000831
Benjamin Kramer101720f2011-04-28 20:09:57 +0000832 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000833 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000834 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000835 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000836 LHS->hasOneUse() && RHS->hasOneUse()) {
837 Value *V;
838 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
839
840 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000841 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000842 if (match(Val2, m_Trunc(m_Value(V))) &&
843 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
844 SmallCst = RHSCst;
845 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000846 } else if (match(Val, m_Trunc(m_Value(V))) &&
847 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000848 SmallCst = LHSCst;
849 BigCst = RHSCst;
850 }
851
852 if (SmallCst && BigCst) {
853 unsigned BigBitSize = BigCst->getType()->getBitWidth();
854 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
855
856 // Check that the low bits are zero.
857 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000858 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000859 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
860 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
861 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
862 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
863 }
864 }
865 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000866
Chris Lattner0a8191e2010-01-05 07:50:36 +0000867 // From here on, we only handle:
868 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
869 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000870
Chris Lattner0a8191e2010-01-05 07:50:36 +0000871 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
872 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
873 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
874 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
875 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
876 return 0;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000877
878 // Make a constant range that's the intersection of the two icmp ranges.
879 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000880 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000881 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000882 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000883 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
884
885 if (LHSRange.intersectWith(RHSRange).isEmptySet())
886 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
887
Chris Lattner0a8191e2010-01-05 07:50:36 +0000888 // We can't fold (ugt x, C) & (sgt x, C2).
889 if (!PredicatesFoldable(LHSCC, RHSCC))
890 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000891
Chris Lattner0a8191e2010-01-05 07:50:36 +0000892 // Ensure that the larger constant is on the RHS.
893 bool ShouldSwap;
894 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000895 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000896 CmpInst::isSigned(RHSCC)))
897 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
898 else
899 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000900
Chris Lattner0a8191e2010-01-05 07:50:36 +0000901 if (ShouldSwap) {
902 std::swap(LHS, RHS);
903 std::swap(LHSCst, RHSCst);
904 std::swap(LHSCC, RHSCC);
905 }
906
Dan Gohman4a618822010-02-10 16:03:48 +0000907 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000908 // comparing a value against two constants and and'ing the result
909 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000910 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
911 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000912 // are not equal and that the larger constant is on the RHS
913 assert(LHSCst != RHSCst && "Compares not folded above?");
914
915 switch (LHSCC) {
916 default: llvm_unreachable("Unknown integer condition code!");
917 case ICmpInst::ICMP_EQ:
918 switch (RHSCC) {
919 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000920 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
921 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
922 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000923 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000924 }
925 case ICmpInst::ICMP_NE:
926 switch (RHSCC) {
927 default: llvm_unreachable("Unknown integer condition code!");
928 case ICmpInst::ICMP_ULT:
929 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000930 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000931 break; // (X != 13 & X u< 15) -> no change
932 case ICmpInst::ICMP_SLT:
933 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000934 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000935 break; // (X != 13 & X s< 15) -> no change
936 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
937 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
938 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000939 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000940 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000941 // Special case to get the ordering right when the values wrap around
942 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +0000943 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000944 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
946 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
947 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000948 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
949 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000950 }
951 break; // (X != 13 & X != 15) -> no change
952 }
953 break;
954 case ICmpInst::ICMP_ULT:
955 switch (RHSCC) {
956 default: llvm_unreachable("Unknown integer condition code!");
957 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
958 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000959 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
961 break;
962 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
963 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000964 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000965 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
966 break;
967 }
968 break;
969 case ICmpInst::ICMP_SLT:
970 switch (RHSCC) {
971 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000972 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
973 break;
974 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
975 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000976 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000977 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
978 break;
979 }
980 break;
981 case ICmpInst::ICMP_UGT:
982 switch (RHSCC) {
983 default: llvm_unreachable("Unknown integer condition code!");
984 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
985 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000986 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000987 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
988 break;
989 case ICmpInst::ICMP_NE:
990 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000991 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000992 break; // (X u> 13 & X != 15) -> no change
993 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000994 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000995 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
996 break;
997 }
998 break;
999 case ICmpInst::ICMP_SGT:
1000 switch (RHSCC) {
1001 default: llvm_unreachable("Unknown integer condition code!");
1002 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1003 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001004 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001005 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1006 break;
1007 case ICmpInst::ICMP_NE:
1008 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001009 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001010 break; // (X s> 13 & X != 15) -> no change
1011 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001012 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001013 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1014 break;
1015 }
1016 break;
1017 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001018
Chris Lattner0a8191e2010-01-05 07:50:36 +00001019 return 0;
1020}
1021
Chris Lattner067459c2010-03-05 08:46:26 +00001022/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1023/// instcombine, this returns a Value which should already be inserted into the
1024/// function.
1025Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001026 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1027 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001028 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1029 return 0;
1030
Chris Lattner0a8191e2010-01-05 07:50:36 +00001031 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1032 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1033 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1034 // If either of the constants are nans, then the whole thing returns
1035 // false.
1036 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001037 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001038 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001039 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001040
Chris Lattner0a8191e2010-01-05 07:50:36 +00001041 // Handle vector zeros. This occurs because the canonical form of
1042 // "fcmp ord x,x" is "fcmp ord x, 0".
1043 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1044 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001045 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001046 return 0;
1047 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001048
Chris Lattner0a8191e2010-01-05 07:50:36 +00001049 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1050 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1051 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001052
1053
Chris Lattner0a8191e2010-01-05 07:50:36 +00001054 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1055 // Swap RHS operands to match LHS.
1056 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1057 std::swap(Op1LHS, Op1RHS);
1058 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001059
Chris Lattner0a8191e2010-01-05 07:50:36 +00001060 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1061 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1062 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001063 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001064 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001065 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001066 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001067 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001068 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001069 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001070
Chris Lattner0a8191e2010-01-05 07:50:36 +00001071 bool Op0Ordered;
1072 bool Op1Ordered;
1073 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1074 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001075 // uno && ord -> false
1076 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1077 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001078 if (Op1Pred == 0) {
1079 std::swap(LHS, RHS);
1080 std::swap(Op0Pred, Op1Pred);
1081 std::swap(Op0Ordered, Op1Ordered);
1082 }
1083 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001084 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001085 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001086 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1087 return LHS;
1088 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001089 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001090
Chris Lattner0a8191e2010-01-05 07:50:36 +00001091 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001092 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001093 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001094 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001095 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001096 }
1097 }
1098
1099 return 0;
1100}
1101
1102
1103Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001104 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1106
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001107 if (Value *V = SimplifyAndInst(Op0, Op1, DL))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001108 return ReplaceInstUsesWith(I, V);
1109
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001110 // (A|B)&(A|C) -> A|(B&C) etc
1111 if (Value *V = SimplifyUsingDistributiveLaws(I))
1112 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001113
Craig Topper9d4171a2012-12-20 07:09:41 +00001114 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001115 // purpose is to compute bits we don't care about.
1116 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001117 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001118
1119 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1120 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001121
1122 // Optimize a variety of ((val OP C1) & C2) combinations...
1123 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1124 Value *Op0LHS = Op0I->getOperand(0);
1125 Value *Op0RHS = Op0I->getOperand(1);
1126 switch (Op0I->getOpcode()) {
1127 default: break;
1128 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001129 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001130 // If the mask is only needed on one incoming arm, push it up.
1131 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001132
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001133 APInt NotAndRHS(~AndRHSMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001134 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1135 // Not masking anything out for the LHS, move to RHS.
1136 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1137 Op0RHS->getName()+".masked");
1138 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1139 }
1140 if (!isa<Constant>(Op0RHS) &&
1141 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1142 // Not masking anything out for the RHS, move to LHS.
1143 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1144 Op0LHS->getName()+".masked");
1145 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1146 }
1147
1148 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001149 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001150 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001151 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1152 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1153 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001154 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1155 return BinaryOperator::CreateAnd(V, AndRHS);
1156 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1157 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1158 break;
1159
1160 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001161 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1162 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1163 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001164 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1165 return BinaryOperator::CreateAnd(V, AndRHS);
1166
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001167 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001168 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001169 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001170 uint32_t BitWidth = AndRHSMask.getBitWidth();
1171 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1172 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1173
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001174 if (MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001175 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1176 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1177 }
1178 }
1179 break;
1180
1181 case Instruction::Shl:
1182 case Instruction::LShr:
1183 // (1 << x) & 1 --> zext(x == 0)
1184 // (1 >> x) & 1 --> zext(x == 0)
1185 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1186 Value *NewICmp =
1187 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1188 return new ZExtInst(NewICmp, I.getType());
1189 }
1190 break;
1191 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001192
Chris Lattner0a8191e2010-01-05 07:50:36 +00001193 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1194 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1195 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001196 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001197
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001198 // If this is an integer truncation, and if the source is an 'and' with
1199 // immediate, transform it. This frequently occurs for bitfield accesses.
1200 {
1201 Value *X = 0; ConstantInt *YC = 0;
1202 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1203 // Change: and (trunc (and X, YC) to T), C2
1204 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001205 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001206 // other simplifications.
1207 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1208 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1209 C3 = ConstantExpr::getAnd(C3, AndRHS);
1210 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001211 }
1212 }
1213
1214 // Try to fold constant and into select arguments.
1215 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1216 if (Instruction *R = FoldOpIntoSelect(I, SI))
1217 return R;
1218 if (isa<PHINode>(Op0))
1219 if (Instruction *NV = FoldOpIntoPhi(I))
1220 return NV;
1221 }
1222
1223
1224 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1225 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1226 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1227 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1228 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1229 I.getName()+".demorgan");
1230 return BinaryOperator::CreateNot(Or);
1231 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001232
Chris Lattner0a8191e2010-01-05 07:50:36 +00001233 {
1234 Value *A = 0, *B = 0, *C = 0, *D = 0;
1235 // (A|B) & ~(A&B) -> A^B
1236 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1237 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1238 ((A == C && B == D) || (A == D && B == C)))
1239 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001240
Chris Lattner0a8191e2010-01-05 07:50:36 +00001241 // ~(A&B) & (A|B) -> A^B
1242 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1243 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1244 ((A == C && B == D) || (A == D && B == C)))
1245 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001246
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001247 // A&(A^B) => A & ~B
1248 {
1249 Value *tmpOp0 = Op0;
1250 Value *tmpOp1 = Op1;
1251 if (Op0->hasOneUse() &&
1252 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1253 if (A == Op1 || B == Op1 ) {
1254 tmpOp1 = Op0;
1255 tmpOp0 = Op1;
1256 // Simplify below
1257 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001258 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001259
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001260 if (tmpOp1->hasOneUse() &&
1261 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1262 if (B == tmpOp0) {
1263 std::swap(A, B);
1264 }
1265 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1266 // A is originally -1 (or a vector of -1 and undefs), then we enter
1267 // an endless loop. By checking that A is non-constant we ensure that
1268 // we will never get to the loop.
1269 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001270 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001271 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001272 }
1273
1274 // (A&((~A)|B)) -> A&B
1275 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1276 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1277 return BinaryOperator::CreateAnd(A, Op1);
1278 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1279 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1280 return BinaryOperator::CreateAnd(A, Op0);
1281 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001282
Chris Lattner0a8191e2010-01-05 07:50:36 +00001283 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1284 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +00001285 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1286 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001287
Chris Lattner4e8137d2010-02-11 06:26:33 +00001288 // If and'ing two fcmp, try combine them into one.
1289 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1290 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001291 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1292 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001293
1294
Chris Lattner0a8191e2010-01-05 07:50:36 +00001295 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1296 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001297 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001298 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001299 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1300 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001301 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001302 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001303
Chris Lattner4e8137d2010-02-11 06:26:33 +00001304 // Only do this if the casts both really cause code to be generated.
1305 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1306 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1307 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001308 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1309 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001310
Chris Lattner4e8137d2010-02-11 06:26:33 +00001311 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1312 // cast is otherwise not optimizable. This happens for vector sexts.
1313 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1314 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001315 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001316 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001317
Chris Lattner4e8137d2010-02-11 06:26:33 +00001318 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1319 // cast is otherwise not optimizable. This happens for vector sexts.
1320 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1321 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001322 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001323 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001324 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001325 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001326
Chris Lattner0a8191e2010-01-05 07:50:36 +00001327 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1328 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1329 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001330 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001331 SI0->getOperand(1) == SI1->getOperand(1) &&
1332 (SI0->hasOneUse() || SI1->hasOneUse())) {
1333 Value *NewOp =
1334 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1335 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001336 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001337 SI1->getOperand(1));
1338 }
1339 }
1340
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001341 {
1342 Value *X = 0;
1343 bool OpsSwapped = false;
1344 // Canonicalize SExt or Not to the LHS
1345 if (match(Op1, m_SExt(m_Value())) ||
1346 match(Op1, m_Not(m_Value()))) {
1347 std::swap(Op0, Op1);
1348 OpsSwapped = true;
1349 }
1350
1351 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1352 if (match(Op0, m_SExt(m_Value(X))) &&
1353 X->getType()->getScalarType()->isIntegerTy(1)) {
1354 Value *Zero = Constant::getNullValue(Op1->getType());
1355 return SelectInst::Create(X, Op1, Zero);
1356 }
1357
1358 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1359 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1360 X->getType()->getScalarType()->isIntegerTy(1)) {
1361 Value *Zero = Constant::getNullValue(Op0->getType());
1362 return SelectInst::Create(X, Zero, Op1);
1363 }
1364
1365 if (OpsSwapped)
1366 std::swap(Op0, Op1);
1367 }
1368
Chris Lattner0a8191e2010-01-05 07:50:36 +00001369 return Changed ? &I : 0;
1370}
1371
1372/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1373/// capable of providing pieces of a bswap. The subexpression provides pieces
1374/// of a bswap if it is proven that each of the non-zero bytes in the output of
1375/// the expression came from the corresponding "byte swapped" byte in some other
1376/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1377/// we know that the expression deposits the low byte of %X into the high byte
1378/// of the bswap result and that all other bytes are zero. This expression is
1379/// accepted, the high byte of ByteValues is set to X to indicate a correct
1380/// match.
1381///
1382/// This function returns true if the match was unsuccessful and false if so.
1383/// On entry to the function the "OverallLeftShift" is a signed integer value
1384/// indicating the number of bytes that the subexpression is later shifted. For
1385/// example, if the expression is later right shifted by 16 bits, the
1386/// OverallLeftShift value would be -2 on entry. This is used to specify which
1387/// byte of ByteValues is actually being set.
1388///
1389/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1390/// byte is masked to zero by a user. For example, in (X & 255), X will be
1391/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1392/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1393/// always in the local (OverallLeftShift) coordinate space.
1394///
1395static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
Craig Topperb94011f2013-07-14 04:42:23 +00001396 SmallVectorImpl<Value *> &ByteValues) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001397 if (Instruction *I = dyn_cast<Instruction>(V)) {
1398 // If this is an or instruction, it may be an inner node of the bswap.
1399 if (I->getOpcode() == Instruction::Or) {
1400 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1401 ByteValues) ||
1402 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1403 ByteValues);
1404 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001405
Chris Lattner0a8191e2010-01-05 07:50:36 +00001406 // If this is a logical shift by a constant multiple of 8, recurse with
1407 // OverallLeftShift and ByteMask adjusted.
1408 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001409 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001410 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1411 // Ensure the shift amount is defined and of a byte value.
1412 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1413 return true;
1414
1415 unsigned ByteShift = ShAmt >> 3;
1416 if (I->getOpcode() == Instruction::Shl) {
1417 // X << 2 -> collect(X, +2)
1418 OverallLeftShift += ByteShift;
1419 ByteMask >>= ByteShift;
1420 } else {
1421 // X >>u 2 -> collect(X, -2)
1422 OverallLeftShift -= ByteShift;
1423 ByteMask <<= ByteShift;
1424 ByteMask &= (~0U >> (32-ByteValues.size()));
1425 }
1426
1427 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1428 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1429
Craig Topper9d4171a2012-12-20 07:09:41 +00001430 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001431 ByteValues);
1432 }
1433
1434 // If this is a logical 'and' with a mask that clears bytes, clear the
1435 // corresponding bytes in ByteMask.
1436 if (I->getOpcode() == Instruction::And &&
1437 isa<ConstantInt>(I->getOperand(1))) {
1438 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1439 unsigned NumBytes = ByteValues.size();
1440 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1441 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001442
Chris Lattner0a8191e2010-01-05 07:50:36 +00001443 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1444 // If this byte is masked out by a later operation, we don't care what
1445 // the and mask is.
1446 if ((ByteMask & (1 << i)) == 0)
1447 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001448
Chris Lattner0a8191e2010-01-05 07:50:36 +00001449 // If the AndMask is all zeros for this byte, clear the bit.
1450 APInt MaskB = AndMask & Byte;
1451 if (MaskB == 0) {
1452 ByteMask &= ~(1U << i);
1453 continue;
1454 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001455
Chris Lattner0a8191e2010-01-05 07:50:36 +00001456 // If the AndMask is not all ones for this byte, it's not a bytezap.
1457 if (MaskB != Byte)
1458 return true;
1459
1460 // Otherwise, this byte is kept.
1461 }
1462
Craig Topper9d4171a2012-12-20 07:09:41 +00001463 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001464 ByteValues);
1465 }
1466 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001467
Chris Lattner0a8191e2010-01-05 07:50:36 +00001468 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1469 // the input value to the bswap. Some observations: 1) if more than one byte
1470 // is demanded from this input, then it could not be successfully assembled
1471 // into a byteswap. At least one of the two bytes would not be aligned with
1472 // their ultimate destination.
1473 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001474 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001475
Chris Lattner0a8191e2010-01-05 07:50:36 +00001476 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1477 // is demanded, it needs to go into byte 0 of the result. This means that the
1478 // byte needs to be shifted until it lands in the right byte bucket. The
1479 // shift amount depends on the position: if the byte is coming from the high
1480 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1481 // low part, it must be shifted left.
1482 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001483 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1484 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001485
Chris Lattner0a8191e2010-01-05 07:50:36 +00001486 // If the destination byte value is already defined, the values are or'd
1487 // together, which isn't a bswap (unless it's an or of the same bits).
1488 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1489 return true;
1490 ByteValues[DestByteNo] = V;
1491 return false;
1492}
1493
1494/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1495/// If so, insert the new bswap intrinsic and return it.
1496Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001497 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001498 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001499 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001500 ITy->getBitWidth() > 32*8)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001501 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001502
Chris Lattner0a8191e2010-01-05 07:50:36 +00001503 /// ByteValues - For each byte of the result, we keep track of which value
1504 /// defines each byte.
1505 SmallVector<Value*, 8> ByteValues;
1506 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001507
Chris Lattner0a8191e2010-01-05 07:50:36 +00001508 // Try to find all the pieces corresponding to the bswap.
1509 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1510 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1511 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001512
Chris Lattner0a8191e2010-01-05 07:50:36 +00001513 // Check to see if all of the bytes come from the same value.
1514 Value *V = ByteValues[0];
1515 if (V == 0) return 0; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001516
Chris Lattner0a8191e2010-01-05 07:50:36 +00001517 // Check to make sure that all of the bytes come from the same value.
1518 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1519 if (ByteValues[i] != V)
1520 return 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001521 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001522 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001523 return CallInst::Create(F, V);
1524}
1525
1526/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1527/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1528/// we can simplify this expression to "cond ? C : D or B".
1529static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1530 Value *C, Value *D) {
1531 // If A is not a select of -1/0, this cannot match.
1532 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001533 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001534 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001535 return 0;
1536
1537 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001538 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001539 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001540 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001541 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001542
Chris Lattner0a8191e2010-01-05 07:50:36 +00001543 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001544 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001545 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001546 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001547 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001548 return 0;
1549}
1550
Chris Lattner067459c2010-03-05 08:46:26 +00001551/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1552Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001553 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1554
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001555 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1556 // if K1 and K2 are a one-bit mask.
1557 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1558 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1559
1560 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1561 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1562
1563 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1564 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1565 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1566 LAnd->getOpcode() == Instruction::And &&
1567 RAnd->getOpcode() == Instruction::And) {
1568
1569 Value *Mask = 0;
1570 Value *Masked = 0;
1571 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Benjamin Kramer7a74bd42014-01-19 16:48:41 +00001572 isKnownToBeAPowerOfTwo(LAnd->getOperand(1)) &&
1573 isKnownToBeAPowerOfTwo(RAnd->getOperand(1))) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001574 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1575 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1576 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Benjamin Kramer7a74bd42014-01-19 16:48:41 +00001577 isKnownToBeAPowerOfTwo(LAnd->getOperand(0)) &&
1578 isKnownToBeAPowerOfTwo(RAnd->getOperand(0))) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001579 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1580 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1581 }
1582
1583 if (Masked)
1584 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1585 }
1586 }
1587
Chris Lattner0a8191e2010-01-05 07:50:36 +00001588 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1589 if (PredicatesFoldable(LHSCC, RHSCC)) {
1590 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1591 LHS->getOperand(1) == RHS->getOperand(0))
1592 LHS->swapOperands();
1593 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1594 LHS->getOperand(1) == RHS->getOperand(1)) {
1595 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1596 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1597 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001598 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001599 }
1600 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001601
1602 // handle (roughly):
1603 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001604 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001605 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001606
Chris Lattner0a8191e2010-01-05 07:50:36 +00001607 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001608 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1609 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1610 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1611 Value *A = 0, *B = 0;
1612 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1613 B = Val;
1614 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1615 A = Val2;
1616 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1617 A = RHS->getOperand(1);
1618 }
1619 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1620 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1621 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1622 B = Val2;
1623 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1624 A = Val;
1625 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1626 A = LHS->getOperand(1);
1627 }
1628 if (A && B)
1629 return Builder->CreateICmp(
1630 ICmpInst::ICMP_UGE,
1631 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1632 }
1633
1634 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner0a8191e2010-01-05 07:50:36 +00001635 if (LHSCst == 0 || RHSCst == 0) return 0;
1636
Owen Anderson8f306a72010-08-02 09:32:13 +00001637 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1638 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1639 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1640 Value *NewOr = Builder->CreateOr(Val, Val2);
1641 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1642 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001643 }
1644
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001645 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001646 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001647 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001648 ConstantInt *AddCst;
1649 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1650 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001651 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001652 }
1653
Chris Lattner0a8191e2010-01-05 07:50:36 +00001654 // From here on, we only handle:
1655 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1656 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001657
Chris Lattner0a8191e2010-01-05 07:50:36 +00001658 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1659 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1660 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1661 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1662 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1663 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001664
Chris Lattner0a8191e2010-01-05 07:50:36 +00001665 // We can't fold (ugt x, C) | (sgt x, C2).
1666 if (!PredicatesFoldable(LHSCC, RHSCC))
1667 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001668
Chris Lattner0a8191e2010-01-05 07:50:36 +00001669 // Ensure that the larger constant is on the RHS.
1670 bool ShouldSwap;
1671 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001672 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001673 CmpInst::isSigned(RHSCC)))
1674 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1675 else
1676 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001677
Chris Lattner0a8191e2010-01-05 07:50:36 +00001678 if (ShouldSwap) {
1679 std::swap(LHS, RHS);
1680 std::swap(LHSCst, RHSCst);
1681 std::swap(LHSCC, RHSCC);
1682 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001683
Dan Gohman4a618822010-02-10 16:03:48 +00001684 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001685 // comparing a value against two constants and or'ing the result
1686 // together. Because of the above check, we know that we only have
1687 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1688 // icmp folding check above), that the two constants are not
1689 // equal.
1690 assert(LHSCst != RHSCst && "Compares not folded above?");
1691
1692 switch (LHSCC) {
1693 default: llvm_unreachable("Unknown integer condition code!");
1694 case ICmpInst::ICMP_EQ:
1695 switch (RHSCC) {
1696 default: llvm_unreachable("Unknown integer condition code!");
1697 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001698 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001699 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001700 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001701 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1702
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001703 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1704 if (Xor.isPowerOf2()) {
1705 Value *NegCst = Builder->getInt(~Xor);
1706 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1707 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1708 }
1709 }
1710
David Majnemer1fae1952013-04-14 21:15:43 +00001711 if (LHSCst == SubOne(RHSCst)) {
1712 // (X == 13 | X == 14) -> X-13 <u 2
1713 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1714 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1715 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1716 return Builder->CreateICmpULT(Add, AddCST);
1717 }
1718
Chris Lattner0a8191e2010-01-05 07:50:36 +00001719 break; // (X == 13 | X == 15) -> no change
1720 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1721 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1722 break;
1723 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1724 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1725 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001726 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001727 }
1728 break;
1729 case ICmpInst::ICMP_NE:
1730 switch (RHSCC) {
1731 default: llvm_unreachable("Unknown integer condition code!");
1732 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1733 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1734 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001735 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001736 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1737 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1738 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001739 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001740 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001741 case ICmpInst::ICMP_ULT:
1742 switch (RHSCC) {
1743 default: llvm_unreachable("Unknown integer condition code!");
1744 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1745 break;
1746 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1747 // If RHSCst is [us]MAXINT, it is always false. Not handling
1748 // this can cause overflow.
1749 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001750 return LHS;
1751 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001752 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1753 break;
1754 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1755 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001756 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001757 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1758 break;
1759 }
1760 break;
1761 case ICmpInst::ICMP_SLT:
1762 switch (RHSCC) {
1763 default: llvm_unreachable("Unknown integer condition code!");
1764 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1765 break;
1766 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1767 // If RHSCst is [us]MAXINT, it is always false. Not handling
1768 // this can cause overflow.
1769 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001770 return LHS;
1771 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001772 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1773 break;
1774 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1775 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001776 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001777 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1778 break;
1779 }
1780 break;
1781 case ICmpInst::ICMP_UGT:
1782 switch (RHSCC) {
1783 default: llvm_unreachable("Unknown integer condition code!");
1784 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1785 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001786 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001787 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1788 break;
1789 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1790 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001791 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1793 break;
1794 }
1795 break;
1796 case ICmpInst::ICMP_SGT:
1797 switch (RHSCC) {
1798 default: llvm_unreachable("Unknown integer condition code!");
1799 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1800 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001801 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001802 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1803 break;
1804 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1805 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001806 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001807 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1808 break;
1809 }
1810 break;
1811 }
1812 return 0;
1813}
1814
Chris Lattner067459c2010-03-05 08:46:26 +00001815/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1816/// instcombine, this returns a Value which should already be inserted into the
1817/// function.
1818Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001819 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001820 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1822 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1823 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1824 // If either of the constants are nans, then the whole thing returns
1825 // true.
1826 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001827 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001828
Chris Lattner0a8191e2010-01-05 07:50:36 +00001829 // Otherwise, no need to compare the two constants, compare the
1830 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001831 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001832 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001833
Chris Lattner0a8191e2010-01-05 07:50:36 +00001834 // Handle vector zeros. This occurs because the canonical form of
1835 // "fcmp uno x,x" is "fcmp uno x, 0".
1836 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1837 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001838 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001839
Chris Lattner0a8191e2010-01-05 07:50:36 +00001840 return 0;
1841 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001842
Chris Lattner0a8191e2010-01-05 07:50:36 +00001843 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1844 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1845 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001846
Chris Lattner0a8191e2010-01-05 07:50:36 +00001847 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1848 // Swap RHS operands to match LHS.
1849 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1850 std::swap(Op1LHS, Op1RHS);
1851 }
1852 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1853 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1854 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001855 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001856 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001857 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001858 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001859 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001860 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001861 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001862 bool Op0Ordered;
1863 bool Op1Ordered;
1864 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1865 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1866 if (Op0Ordered == Op1Ordered) {
1867 // If both are ordered or unordered, return a new fcmp with
1868 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001869 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001870 }
1871 }
1872 return 0;
1873}
1874
1875/// FoldOrWithConstants - This helper function folds:
1876///
1877/// ((A | B) & C1) | (B & C2)
1878///
1879/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001880///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881/// (A & C1) | B
1882///
1883/// when the XOR of the two constants is "all ones" (-1).
1884Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1885 Value *A, Value *B, Value *C) {
1886 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1887 if (!CI1) return 0;
1888
1889 Value *V1 = 0;
1890 ConstantInt *CI2 = 0;
1891 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1892
1893 APInt Xor = CI1->getValue() ^ CI2->getValue();
1894 if (!Xor.isAllOnesValue()) return 0;
1895
1896 if (V1 == A || V1 == B) {
1897 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1898 return BinaryOperator::CreateOr(NewOp, V1);
1899 }
1900
1901 return 0;
1902}
1903
1904Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001905 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1907
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001908 if (Value *V = SimplifyOrInst(Op0, Op1, DL))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001910
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001911 // (A&B)|(A&C) -> A&(B|C) etc
1912 if (Value *V = SimplifyUsingDistributiveLaws(I))
1913 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001914
Craig Topper9d4171a2012-12-20 07:09:41 +00001915 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001916 // purpose is to compute bits we don't care about.
1917 if (SimplifyDemandedInstructionBits(I))
1918 return &I;
1919
1920 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1921 ConstantInt *C1 = 0; Value *X = 0;
1922 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001923 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001924 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001925 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926 Op0->hasOneUse()) {
1927 Value *Or = Builder->CreateOr(X, RHS);
1928 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001929 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001930 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001931 }
1932
1933 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1934 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1935 Op0->hasOneUse()) {
1936 Value *Or = Builder->CreateOr(X, RHS);
1937 Or->takeName(Op0);
1938 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001939 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001940 }
1941
1942 // Try to fold constant and into select arguments.
1943 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1944 if (Instruction *R = FoldOpIntoSelect(I, SI))
1945 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001946
Chris Lattner0a8191e2010-01-05 07:50:36 +00001947 if (isa<PHINode>(Op0))
1948 if (Instruction *NV = FoldOpIntoPhi(I))
1949 return NV;
1950 }
1951
1952 Value *A = 0, *B = 0;
1953 ConstantInt *C1 = 0, *C2 = 0;
1954
1955 // (A | B) | C and A | (B | C) -> bswap if possible.
1956 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1957 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1958 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00001959 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1960 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001961 if (Instruction *BSwap = MatchBSwap(I))
1962 return BSwap;
1963 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001964
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001965 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001966 if (Op0->hasOneUse() &&
1967 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1968 MaskedValueIsZero(Op1, C1->getValue())) {
1969 Value *NOr = Builder->CreateOr(A, Op1);
1970 NOr->takeName(Op0);
1971 return BinaryOperator::CreateXor(NOr, C1);
1972 }
1973
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001974 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001975 if (Op1->hasOneUse() &&
1976 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1977 MaskedValueIsZero(Op0, C1->getValue())) {
1978 Value *NOr = Builder->CreateOr(A, Op0);
1979 NOr->takeName(Op0);
1980 return BinaryOperator::CreateXor(NOr, C1);
1981 }
1982
1983 // (A & C)|(B & D)
1984 Value *C = 0, *D = 0;
1985 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1986 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001987 Value *V1 = 0, *V2 = 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001988 C1 = dyn_cast<ConstantInt>(C);
1989 C2 = dyn_cast<ConstantInt>(D);
1990 if (C1 && C2) { // (A & C1)|(B & C2)
1991 // If we have: ((V + N) & C1) | (V & C2)
1992 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1993 // replace with V+N.
1994 if (C1->getValue() == ~C2->getValue()) {
1995 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1996 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1997 // Add commutes, try both ways.
1998 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1999 return ReplaceInstUsesWith(I, A);
2000 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2001 return ReplaceInstUsesWith(I, A);
2002 }
2003 // Or commutes, try both ways.
2004 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
2005 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2006 // Add commutes, try both ways.
2007 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2008 return ReplaceInstUsesWith(I, B);
2009 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2010 return ReplaceInstUsesWith(I, B);
2011 }
2012 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002013
Chris Lattner0a8191e2010-01-05 07:50:36 +00002014 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002015 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002016 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002017 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2018 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2019 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2020 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002021 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002022 // Or commutes, try both ways.
2023 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2024 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2025 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2026 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002027 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002028
Chris Lattner95188692010-01-11 06:55:24 +00002029 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002030 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Chris Lattner95188692010-01-11 06:55:24 +00002031 ConstantInt *C3 = 0, *C4 = 0;
2032 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2033 (C3->getValue() & ~C1->getValue()) == 0 &&
2034 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2035 (C4->getValue() & ~C2->getValue()) == 0) {
2036 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2037 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002038 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002039 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002040 }
2041 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002042
Chris Lattner8e2c4712010-02-02 02:43:51 +00002043 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2044 // Don't do this for vector select idioms, the code generator doesn't handle
2045 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002046 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002047 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2048 return Match;
2049 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2050 return Match;
2051 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2052 return Match;
2053 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2054 return Match;
2055 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002056
2057 // ((A&~B)|(~A&B)) -> A^B
2058 if ((match(C, m_Not(m_Specific(D))) &&
2059 match(B, m_Not(m_Specific(A)))))
2060 return BinaryOperator::CreateXor(A, D);
2061 // ((~B&A)|(~A&B)) -> A^B
2062 if ((match(A, m_Not(m_Specific(D))) &&
2063 match(B, m_Not(m_Specific(C)))))
2064 return BinaryOperator::CreateXor(C, D);
2065 // ((A&~B)|(B&~A)) -> A^B
2066 if ((match(C, m_Not(m_Specific(B))) &&
2067 match(D, m_Not(m_Specific(A)))))
2068 return BinaryOperator::CreateXor(A, B);
2069 // ((~B&A)|(B&~A)) -> A^B
2070 if ((match(A, m_Not(m_Specific(B))) &&
2071 match(D, m_Not(m_Specific(C)))))
2072 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002073
2074 // ((A|B)&1)|(B&-2) -> (A&1) | B
2075 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2076 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2077 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2078 if (Ret) return Ret;
2079 }
2080 // (B&-2)|((A|B)&1) -> (A&1) | B
2081 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2082 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2083 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2084 if (Ret) return Ret;
2085 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002087
Chris Lattner0a8191e2010-01-05 07:50:36 +00002088 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
2089 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2090 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00002091 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002092 SI0->getOperand(1) == SI1->getOperand(1) &&
2093 (SI0->hasOneUse() || SI1->hasOneUse())) {
2094 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2095 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002096 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097 SI1->getOperand(1));
2098 }
2099 }
2100
Chris Lattner0a8191e2010-01-05 07:50:36 +00002101 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2102 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2103 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2104 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2105 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2106 I.getName()+".demorgan");
2107 return BinaryOperator::CreateNot(And);
2108 }
2109
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002110 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002111 bool SwappedForXor = false;
2112 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002113 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002114 SwappedForXor = true;
2115 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002116
2117 // A | ( A ^ B) -> A | B
2118 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002119 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002120 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2121 if (Op0 == A || Op0 == B)
2122 return BinaryOperator::CreateOr(A, B);
2123
Chad Rosier7813dce2012-04-26 23:29:14 +00002124 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2125 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2126 return BinaryOperator::CreateOr(A, B);
2127
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002128 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2129 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2130 return BinaryOperator::CreateOr(Not, Op0);
2131 }
2132 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2133 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2134 return BinaryOperator::CreateOr(Not, Op0);
2135 }
2136 }
2137
2138 // A | ~(A | B) -> A | ~B
2139 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002140 if (match(Op1, m_Not(m_Value(A))))
2141 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002142 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2143 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2144 B->getOpcode() == Instruction::Xor)) {
2145 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2146 B->getOperand(0);
2147 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2148 return BinaryOperator::CreateOr(Not, Op0);
2149 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002150
Eli Friedmane06535b2012-03-16 00:52:42 +00002151 if (SwappedForXor)
2152 std::swap(Op0, Op1);
2153
Chris Lattner0a8191e2010-01-05 07:50:36 +00002154 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2155 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00002156 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2157 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002158
Chris Lattner4e8137d2010-02-11 06:26:33 +00002159 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2160 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2161 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002162 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2163 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002164
Chris Lattner0a8191e2010-01-05 07:50:36 +00002165 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2166 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002167 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2168 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002169 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002170 if (SrcTy == Op1C->getOperand(0)->getType() &&
2171 SrcTy->isIntOrIntVectorTy()) {
2172 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002173
Chris Lattner311aa632011-01-15 05:40:29 +00002174 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2175 // Only do this if the casts both really cause code to be
2176 // generated.
2177 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2178 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2179 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2180 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002181 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002182
Chris Lattner311aa632011-01-15 05:40:29 +00002183 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2184 // cast is otherwise not optimizable. This happens for vector sexts.
2185 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2186 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2187 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2188 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002189
Chris Lattner311aa632011-01-15 05:40:29 +00002190 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2191 // cast is otherwise not optimizable. This happens for vector sexts.
2192 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2193 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2194 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2195 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002196 }
Chris Lattner311aa632011-01-15 05:40:29 +00002197 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002198 }
Eli Friedman23956262011-04-14 22:41:27 +00002199
2200 // or(sext(A), B) -> A ? -1 : B where A is an i1
2201 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2202 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2203 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2204 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2205 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2206
Owen Andersonc237a842010-09-13 17:59:27 +00002207 // Note: If we've gotten to the point of visiting the outer OR, then the
2208 // inner one couldn't be simplified. If it was a constant, then it won't
2209 // be simplified by a later pass either, so we try swapping the inner/outer
2210 // ORs in the hopes that we'll be able to simplify it this way.
2211 // (X|C) | V --> (X|V) | C
2212 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2213 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2214 Value *Inner = Builder->CreateOr(A, Op1);
2215 Inner->takeName(Op0);
2216 return BinaryOperator::CreateOr(Inner, C1);
2217 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002218
Bill Wendling23242092013-02-16 23:41:36 +00002219 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2220 // Since this OR statement hasn't been optimized further yet, we hope
2221 // that this transformation will allow the new ORs to be optimized.
2222 {
2223 Value *X = 0, *Y = 0;
2224 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2225 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2226 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2227 Value *orTrue = Builder->CreateOr(A, C);
2228 Value *orFalse = Builder->CreateOr(B, D);
2229 return SelectInst::Create(X, orTrue, orFalse);
2230 }
2231 }
2232
Chris Lattner0a8191e2010-01-05 07:50:36 +00002233 return Changed ? &I : 0;
2234}
2235
2236Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002237 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002238 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2239
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002240 if (Value *V = SimplifyXorInst(Op0, Op1, DL))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002241 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002242
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002243 // (A&B)^(A&C) -> A&(B^C) etc
2244 if (Value *V = SimplifyUsingDistributiveLaws(I))
2245 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002246
Craig Topper9d4171a2012-12-20 07:09:41 +00002247 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002248 // purpose is to compute bits we don't care about.
2249 if (SimplifyDemandedInstructionBits(I))
2250 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002251
2252 // Is this a ~ operation?
2253 if (Value *NotOp = dyn_castNotVal(&I)) {
2254 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002255 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002256 Op0I->getOpcode() == Instruction::Or) {
2257 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2258 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2259 if (dyn_castNotVal(Op0I->getOperand(1)))
2260 Op0I->swapOperands();
2261 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2262 Value *NotY =
2263 Builder->CreateNot(Op0I->getOperand(1),
2264 Op0I->getOperand(1)->getName()+".not");
2265 if (Op0I->getOpcode() == Instruction::And)
2266 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2267 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2268 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002269
Chris Lattner0a8191e2010-01-05 07:50:36 +00002270 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2271 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Craig Topper9d4171a2012-12-20 07:09:41 +00002272 if (isFreeToInvert(Op0I->getOperand(0)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002273 isFreeToInvert(Op0I->getOperand(1))) {
2274 Value *NotX =
2275 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2276 Value *NotY =
2277 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2278 if (Op0I->getOpcode() == Instruction::And)
2279 return BinaryOperator::CreateOr(NotX, NotY);
2280 return BinaryOperator::CreateAnd(NotX, NotY);
2281 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002282
2283 } else if (Op0I->getOpcode() == Instruction::AShr) {
2284 // ~(~X >>s Y) --> (X >>s Y)
2285 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2286 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002287 }
2288 }
2289 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002290
2291
Chris Lattner0a8191e2010-01-05 07:50:36 +00002292 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002293 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002294 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002295 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2296 return CmpInst::Create(CI->getOpcode(),
2297 CI->getInversePredicate(),
2298 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002299
2300 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2301 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2302 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2303 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2304 Instruction::CastOps Opcode = Op0C->getOpcode();
2305 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002306 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002307 Op0C->getDestTy()))) {
2308 CI->setPredicate(CI->getInversePredicate());
2309 return CastInst::Create(Opcode, CI, Op0C->getType());
2310 }
2311 }
2312 }
2313 }
2314
2315 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2316 // ~(c-X) == X-c-1 == X+(-c-1)
2317 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2318 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2319 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2320 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2321 ConstantInt::get(I.getType(), 1));
2322 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2323 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002324
Chris Lattner0a8191e2010-01-05 07:50:36 +00002325 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2326 if (Op0I->getOpcode() == Instruction::Add) {
2327 // ~(X-c) --> (-c-1)-X
2328 if (RHS->isAllOnesValue()) {
2329 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2330 return BinaryOperator::CreateSub(
2331 ConstantExpr::getSub(NegOp0CI,
2332 ConstantInt::get(I.getType(), 1)),
2333 Op0I->getOperand(0));
2334 } else if (RHS->getValue().isSignBit()) {
2335 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002336 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002337 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2338
2339 }
2340 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002341 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002342 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2343 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2344 // Anything in both C1 and C2 is known to be zero, remove it from
2345 // NewRHS.
2346 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002347 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002348 ConstantExpr::getNot(CommonBits));
2349 Worklist.Add(Op0I);
2350 I.setOperand(0, Op0I->getOperand(0));
2351 I.setOperand(1, NewRHS);
2352 return &I;
2353 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002354 } else if (Op0I->getOpcode() == Instruction::LShr) {
2355 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2356 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002357 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002358 ConstantInt *C1;
2359 if (Op0I->hasOneUse() &&
2360 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2361 E1->getOpcode() == Instruction::Xor &&
2362 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2363 // fold (C1 >> C2) ^ C3
2364 ConstantInt *C2 = Op0CI, *C3 = RHS;
2365 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2366 FoldConst ^= C3->getValue();
2367 // Prepare the two operands.
2368 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2369 Opnd0->takeName(Op0I);
2370 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2371 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2372
2373 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2374 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002375 }
2376 }
2377 }
2378
2379 // Try to fold constant and into select arguments.
2380 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2381 if (Instruction *R = FoldOpIntoSelect(I, SI))
2382 return R;
2383 if (isa<PHINode>(Op0))
2384 if (Instruction *NV = FoldOpIntoPhi(I))
2385 return NV;
2386 }
2387
Chris Lattner0a8191e2010-01-05 07:50:36 +00002388 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2389 if (Op1I) {
2390 Value *A, *B;
2391 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2392 if (A == Op0) { // B^(B|A) == (A|B)^B
2393 Op1I->swapOperands();
2394 I.swapOperands();
2395 std::swap(Op0, Op1);
2396 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2397 I.swapOperands(); // Simplified below.
2398 std::swap(Op0, Op1);
2399 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002400 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002401 Op1I->hasOneUse()){
2402 if (A == Op0) { // A^(A&B) -> A^(B&A)
2403 Op1I->swapOperands();
2404 std::swap(A, B);
2405 }
2406 if (B == Op0) { // A^(B&A) -> (B&A)^A
2407 I.swapOperands(); // Simplified below.
2408 std::swap(Op0, Op1);
2409 }
2410 }
2411 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002412
Chris Lattner0a8191e2010-01-05 07:50:36 +00002413 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2414 if (Op0I) {
2415 Value *A, *B;
2416 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2417 Op0I->hasOneUse()) {
2418 if (A == Op1) // (B|A)^B == (A|B)^B
2419 std::swap(A, B);
2420 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002421 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002422 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002423 Op0I->hasOneUse()){
2424 if (A == Op1) // (A&B)^A -> (B&A)^A
2425 std::swap(A, B);
2426 if (B == Op1 && // (B&A)^A == ~B & A
2427 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002428 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002429 }
2430 }
2431 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002432
Chris Lattner0a8191e2010-01-05 07:50:36 +00002433 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Craig Topper9d4171a2012-12-20 07:09:41 +00002434 if (Op0I && Op1I && Op0I->isShift() &&
2435 Op0I->getOpcode() == Op1I->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002436 Op0I->getOperand(1) == Op1I->getOperand(1) &&
Benjamin Kramer9d5849f2012-05-28 20:52:48 +00002437 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002438 Value *NewOp =
2439 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2440 Op0I->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002441 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002442 Op1I->getOperand(1));
2443 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002444
Chris Lattner0a8191e2010-01-05 07:50:36 +00002445 if (Op0I && Op1I) {
2446 Value *A, *B, *C, *D;
2447 // (A & B)^(A | B) -> A ^ B
2448 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2449 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002450 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002451 return BinaryOperator::CreateXor(A, B);
2452 }
2453 // (A | B)^(A & B) -> A ^ B
2454 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2455 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002456 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002457 return BinaryOperator::CreateXor(A, B);
2458 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002459 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002460
Chris Lattner0a8191e2010-01-05 07:50:36 +00002461 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2462 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2463 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2464 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2465 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2466 LHS->getOperand(1) == RHS->getOperand(0))
2467 LHS->swapOperands();
2468 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2469 LHS->getOperand(1) == RHS->getOperand(1)) {
2470 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2471 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2472 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002473 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002474 getNewICmpValue(isSigned, Code, Op0, Op1,
2475 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002476 }
2477 }
2478
2479 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2480 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2481 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2482 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002483 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002484 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002485 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002486 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002487 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002488 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002489 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002490 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2491 Op1C->getOperand(0), I.getName());
2492 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2493 }
2494 }
2495 }
2496
2497 return Changed ? &I : 0;
2498}