blob: c520db597c318b5c3675dcc58bb40942c79f96b4 [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 Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Intrinsics.h"
Anders Carlssonda80afe2011-03-01 15:05:01 +000017#include "llvm/Support/ConstantRange.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000018#include "llvm/Support/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
23
24/// AddOne - Add one to a ConstantInt.
Jakub Staszak2ef36b62013-03-09 11:18:59 +000025static Constant *AddOne(ConstantInt *C) {
26 return ConstantInt::get(C->getContext(), C->getValue() + 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +000027}
28/// SubOne - Subtract one from a ConstantInt.
29static Constant *SubOne(ConstantInt *C) {
30 return ConstantInt::get(C->getContext(), C->getValue()-1);
31}
32
33/// isFreeToInvert - Return true if the specified value is free to invert (apply
34/// ~ to). This happens in cases where the ~ can be eliminated.
35static inline bool isFreeToInvert(Value *V) {
36 // ~(~(X)) -> X.
37 if (BinaryOperator::isNot(V))
38 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000039
Chris Lattner0a8191e2010-01-05 07:50:36 +000040 // Constants can be considered to be not'ed values.
41 if (isa<ConstantInt>(V))
42 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000043
Chris Lattner0a8191e2010-01-05 07:50:36 +000044 // Compares can be inverted if they have a single use.
45 if (CmpInst *CI = dyn_cast<CmpInst>(V))
46 return CI->hasOneUse();
Craig Topper9d4171a2012-12-20 07:09:41 +000047
Chris Lattner0a8191e2010-01-05 07:50:36 +000048 return false;
49}
50
51static inline Value *dyn_castNotVal(Value *V) {
52 // If this is not(not(x)) don't return that this is a not: we want the two
53 // not's to be folded first.
54 if (BinaryOperator::isNot(V)) {
55 Value *Operand = BinaryOperator::getNotArgument(V);
56 if (!isFreeToInvert(Operand))
57 return Operand;
58 }
Craig Topper9d4171a2012-12-20 07:09:41 +000059
Chris Lattner0a8191e2010-01-05 07:50:36 +000060 // Constants can be considered to be not'ed values...
61 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
62 return ConstantInt::get(C->getType(), ~C->getValue());
63 return 0;
64}
65
Chris Lattner0a8191e2010-01-05 07:50:36 +000066/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
67/// predicate into a three bit mask. It also returns whether it is an ordered
68/// predicate by reference.
69static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
70 isOrdered = false;
71 switch (CC) {
72 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
73 case FCmpInst::FCMP_UNO: return 0; // 000
74 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
75 case FCmpInst::FCMP_UGT: return 1; // 001
76 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
77 case FCmpInst::FCMP_UEQ: return 2; // 010
78 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
79 case FCmpInst::FCMP_UGE: return 3; // 011
80 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
81 case FCmpInst::FCMP_ULT: return 4; // 100
82 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
83 case FCmpInst::FCMP_UNE: return 5; // 101
84 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
85 case FCmpInst::FCMP_ULE: return 6; // 110
86 // True -> 7
87 default:
88 // Not expecting FCMP_FALSE and FCMP_TRUE;
89 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000090 }
91}
92
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000093/// getNewICmpValue - This is the complement of getICmpCode, which turns an
Craig Topper9d4171a2012-12-20 07:09:41 +000094/// opcode and two operands into either a constant true or false, or a brand
Chris Lattner0a8191e2010-01-05 07:50:36 +000095/// new ICmp instruction. The sign is passed in to determine which kind
96/// of predicate to use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000097static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
98 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000099 ICmpInst::Predicate NewPred;
100 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
101 return NewConstant;
102 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000103}
104
105/// getFCmpValue - This is the complement of getFCmpCode, which turns an
106/// opcode and two operands into either a FCmp instruction. isordered is passed
107/// in to determine which kind of predicate to use in the new fcmp instruction.
108static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +0000109 Value *LHS, Value *RHS,
110 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000111 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000112 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +0000113 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +0000114 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
115 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
116 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
117 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
118 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
119 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
120 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +0000121 case 7:
Owen Andersona8342002011-01-21 19:39:42 +0000122 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
123 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000124 }
Chris Lattner067459c2010-03-05 08:46:26 +0000125 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000126}
127
Chris Lattner0a8191e2010-01-05 07:50:36 +0000128// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
129// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
130// guaranteed to be a binary operator.
131Instruction *InstCombiner::OptAndOp(Instruction *Op,
132 ConstantInt *OpRHS,
133 ConstantInt *AndRHS,
134 BinaryOperator &TheAnd) {
135 Value *X = Op->getOperand(0);
136 Constant *Together = 0;
137 if (!Op->isShift())
138 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
139
140 switch (Op->getOpcode()) {
141 case Instruction::Xor:
142 if (Op->hasOneUse()) {
143 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
144 Value *And = Builder->CreateAnd(X, AndRHS);
145 And->takeName(Op);
146 return BinaryOperator::CreateXor(And, Together);
147 }
148 break;
149 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000150 if (Op->hasOneUse()){
151 if (Together != OpRHS) {
152 // (X | C1) & C2 --> (X | (C1&C2)) & C2
153 Value *Or = Builder->CreateOr(X, Together);
154 Or->takeName(Op);
155 return BinaryOperator::CreateAnd(Or, AndRHS);
156 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000157
Owen Andersonc237a842010-09-13 17:59:27 +0000158 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
159 if (TogetherCI && !TogetherCI->isZero()){
160 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
161 // NOTE: This reduces the number of bits set in the & mask, which
162 // can expose opportunities for store narrowing.
163 Together = ConstantExpr::getXor(AndRHS, Together);
164 Value *And = Builder->CreateAnd(X, Together);
165 And->takeName(Op);
166 return BinaryOperator::CreateOr(And, OpRHS);
167 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000168 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000169
Chris Lattner0a8191e2010-01-05 07:50:36 +0000170 break;
171 case Instruction::Add:
172 if (Op->hasOneUse()) {
173 // Adding a one to a single bit bit-field should be turned into an XOR
174 // of the bit. First thing to check is to see if this AND is with a
175 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000176 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000177
178 // If there is only one bit set.
179 if (AndRHSV.isPowerOf2()) {
180 // Ok, at this point, we know that we are masking the result of the
181 // ADD down to exactly one bit. If the constant we are adding has
182 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000183 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000184
185 // Check to see if any bits below the one bit set in AndRHSV are set.
186 if ((AddRHS & (AndRHSV-1)) == 0) {
187 // If not, the only thing that can effect the output of the AND is
188 // the bit specified by AndRHSV. If that bit is set, the effect of
189 // the XOR is to toggle the bit. If it is clear, then the ADD has
190 // no effect.
191 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
192 TheAnd.setOperand(0, X);
193 return &TheAnd;
194 } else {
195 // Pull the XOR out of the AND.
196 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
197 NewAnd->takeName(Op);
198 return BinaryOperator::CreateXor(NewAnd, AndRHS);
199 }
200 }
201 }
202 }
203 break;
204
205 case Instruction::Shl: {
206 // We know that the AND will not produce any of the bits shifted in, so if
207 // the anded constant includes them, clear them now!
208 //
209 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
210 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
211 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000212 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000213
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000214 if (CI->getValue() == ShlMask)
215 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000216 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000217
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000218 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000219 TheAnd.setOperand(1, CI);
220 return &TheAnd;
221 }
222 break;
223 }
224 case Instruction::LShr: {
225 // We know that the AND will not produce any of the bits shifted in, so if
226 // the anded constant includes them, clear them now! This only applies to
227 // unsigned shifts, because a signed shr may bring in set bits!
228 //
229 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
230 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
231 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000232 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000233
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000234 if (CI->getValue() == ShrMask)
235 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000236 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000237
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000238 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000239 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
240 return &TheAnd;
241 }
242 break;
243 }
244 case Instruction::AShr:
245 // Signed shr.
246 // See if this is shifting in some sign extension, then masking it out
247 // with an and.
248 if (Op->hasOneUse()) {
249 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
250 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
251 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000252 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000253 if (C == AndRHS) { // Masking out bits shifted in.
254 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
255 // Make the argument unsigned.
256 Value *ShVal = Op->getOperand(0);
257 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
258 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
259 }
260 }
261 break;
262 }
263 return 0;
264}
265
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000266/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
267/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000268/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000269/// whether to treat the V, Lo and HI as signed or not. IB is the location to
270/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000271Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
272 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000273 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000274 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
275 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000276
Chris Lattner0a8191e2010-01-05 07:50:36 +0000277 if (Inside) {
278 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000279 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000280
281 // V >= Min && V < Hi --> V < Hi
282 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000283 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000284 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000285 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000286 }
287
288 // Emit V-Lo <u Hi-Lo
289 Constant *NegLo = ConstantExpr::getNeg(Lo);
290 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
291 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000292 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000293 }
294
295 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000296 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000297
298 // V < Min || V >= Hi -> V > Hi-1
299 Hi = SubOne(cast<ConstantInt>(Hi));
300 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000301 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000302 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000303 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000304 }
305
306 // Emit V-Lo >u Hi-1-Lo
307 // Note that Hi has already had one subtracted from it, above.
308 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
309 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
310 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000311 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000312}
313
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000314// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000315// any number of 0s on either side. The 1s are allowed to wrap from LSB to
316// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
317// not, since all 1s are not contiguous.
318static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
319 const APInt& V = Val->getValue();
320 uint32_t BitWidth = Val->getType()->getBitWidth();
321 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
322
323 // look for the first zero bit after the run of ones
324 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
325 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000326 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327 return true;
328}
329
330/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
331/// where isSub determines whether the operator is a sub. If we can fold one of
332/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000333///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000334/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
335/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
336/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000337///
338/// return (A +/- B).
339///
340Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
341 ConstantInt *Mask, bool isSub,
342 Instruction &I) {
343 Instruction *LHSI = dyn_cast<Instruction>(LHS);
344 if (!LHSI || LHSI->getNumOperands() != 2 ||
345 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
346
347 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
348
349 switch (LHSI->getOpcode()) {
350 default: return 0;
351 case Instruction::And:
352 if (ConstantExpr::getAnd(N, Mask) == Mask) {
353 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000354 if ((Mask->getValue().countLeadingZeros() +
355 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000356 Mask->getValue().getBitWidth())
357 break;
358
359 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
360 // part, we don't need any explicit masks to take them out of A. If that
361 // is all N is, ignore it.
362 uint32_t MB = 0, ME = 0;
363 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
364 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
365 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
366 if (MaskedValueIsZero(RHS, Mask))
367 break;
368 }
369 }
370 return 0;
371 case Instruction::Or:
372 case Instruction::Xor:
373 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000374 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000375 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
376 && ConstantExpr::getAnd(N, Mask)->isNullValue())
377 break;
378 return 0;
379 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000380
Chris Lattner0a8191e2010-01-05 07:50:36 +0000381 if (isSub)
382 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
383 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
384}
385
Owen Anderson3fe002d2010-09-08 22:16:17 +0000386/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000387/// One of A and B is considered the mask, the other the value. This is
388/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000389/// contains only "Mask", then both A and B can be considered masks.
390/// If A is the mask, then it was proven, that (A & C) == C. This
391/// is trivial if C == A, or C == 0. If both A and C are constants, this
392/// proof is also easy.
393/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000394/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000395/// if (A & B) == A, or all bits of A are set in B.
396/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000397/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000398/// if (A & B) == 0, or all bits of A are cleared in B.
399/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000400/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000401/// contain any number of one bits and zero bits.
402/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
403/// The Part "Not" means, that in above descriptions "==" should be replaced
404/// by "!=".
405/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
406/// If the mask A contains a single bit, then the following is equivalent:
407/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
408/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
409enum MaskedICmpType {
410 FoldMskICmp_AMask_AllOnes = 1,
411 FoldMskICmp_AMask_NotAllOnes = 2,
412 FoldMskICmp_BMask_AllOnes = 4,
413 FoldMskICmp_BMask_NotAllOnes = 8,
414 FoldMskICmp_Mask_AllZeroes = 16,
415 FoldMskICmp_Mask_NotAllZeroes = 32,
416 FoldMskICmp_AMask_Mixed = 64,
417 FoldMskICmp_AMask_NotMixed = 128,
418 FoldMskICmp_BMask_Mixed = 256,
419 FoldMskICmp_BMask_NotMixed = 512
420};
421
422/// return the set of pattern classes (from MaskedICmpType)
423/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000424static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000425 ICmpInst::Predicate SCC)
426{
427 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
428 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
429 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
430 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topper9d4171a2012-12-20 07:09:41 +0000431 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000432 ACst->getValue().isPowerOf2());
Craig Topper9d4171a2012-12-20 07:09:41 +0000433 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000434 BCst->getValue().isPowerOf2());
435 unsigned result = 0;
436 if (CCst != 0 && CCst->isZero()) {
437 // if C is zero, then both A and B qualify as mask
438 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
439 FoldMskICmp_Mask_AllZeroes |
440 FoldMskICmp_AMask_Mixed |
441 FoldMskICmp_BMask_Mixed)
442 : (FoldMskICmp_Mask_NotAllZeroes |
443 FoldMskICmp_Mask_NotAllZeroes |
444 FoldMskICmp_AMask_NotMixed |
445 FoldMskICmp_BMask_NotMixed));
446 if (icmp_abit)
447 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000448 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000449 : (FoldMskICmp_AMask_AllOnes |
450 FoldMskICmp_AMask_Mixed));
451 if (icmp_bbit)
452 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000453 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000454 : (FoldMskICmp_BMask_AllOnes |
455 FoldMskICmp_BMask_Mixed));
456 return result;
457 }
458 if (A == C) {
459 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
460 FoldMskICmp_AMask_Mixed)
461 : (FoldMskICmp_AMask_NotAllOnes |
462 FoldMskICmp_AMask_NotMixed));
463 if (icmp_abit)
464 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
465 FoldMskICmp_AMask_NotMixed)
466 : (FoldMskICmp_Mask_AllZeroes |
467 FoldMskICmp_AMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000468 } else if (ACst != 0 && CCst != 0 &&
469 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000470 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
471 : FoldMskICmp_AMask_NotMixed);
472 }
Craig Topperae48cb22012-12-20 07:15:54 +0000473 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000474 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
475 FoldMskICmp_BMask_Mixed)
476 : (FoldMskICmp_BMask_NotAllOnes |
477 FoldMskICmp_BMask_NotMixed));
478 if (icmp_bbit)
479 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000480 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000481 : (FoldMskICmp_Mask_AllZeroes |
482 FoldMskICmp_BMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000483 } else if (BCst != 0 && CCst != 0 &&
484 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000485 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
486 : FoldMskICmp_BMask_NotMixed);
487 }
488 return result;
489}
490
Tim Northoverc0756c42013-09-04 11:57:13 +0000491/// Convert an analysis of a masked ICmp into its equivalent if all boolean
492/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
493/// is adjacent to the corresponding normal flag (recording ==), this just
494/// involves swapping those bits over.
495static unsigned conjugateICmpMask(unsigned Mask) {
496 unsigned NewMask;
497 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
498 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
499 FoldMskICmp_BMask_Mixed))
500 << 1;
501
502 NewMask |=
503 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
504 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
505 FoldMskICmp_BMask_NotMixed))
506 >> 1;
507
508 return NewMask;
509}
510
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000511/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
512/// if possible. The returned predicate is either == or !=. Returns false if
513/// decomposition fails.
514static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
515 Value *&X, Value *&Y, Value *&Z) {
516 // X < 0 is equivalent to (X & SignBit) != 0.
517 if (I->getPredicate() == ICmpInst::ICMP_SLT)
518 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
519 if (C->isZero()) {
520 X = I->getOperand(0);
521 Y = ConstantInt::get(I->getContext(),
522 APInt::getSignBit(C->getBitWidth()));
523 Pred = ICmpInst::ICMP_NE;
524 Z = C;
525 return true;
526 }
527
528 // X > -1 is equivalent to (X & SignBit) == 0.
529 if (I->getPredicate() == ICmpInst::ICMP_SGT)
530 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
531 if (C->isAllOnesValue()) {
532 X = I->getOperand(0);
533 Y = ConstantInt::get(I->getContext(),
534 APInt::getSignBit(C->getBitWidth()));
535 Pred = ICmpInst::ICMP_EQ;
536 Z = ConstantInt::getNullValue(C->getType());
537 return true;
538 }
539
540 return false;
541}
542
Owen Anderson3fe002d2010-09-08 22:16:17 +0000543/// foldLogOpOfMaskedICmpsHelper:
544/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
545/// return the set of pattern classes (from MaskedICmpType)
546/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000547static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000548 Value*& B, Value*& C,
549 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000550 ICmpInst *LHS, ICmpInst *RHS,
551 ICmpInst::Predicate &LHSCC,
552 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000553 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
554 // vectors are not (yet?) supported
555 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
556
557 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000558 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000559 // and L11 & L12 == L21 & L22. The same goes for RHS.
560 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000561 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000562 // above.
563 Value *L1 = LHS->getOperand(0);
564 Value *L2 = LHS->getOperand(1);
565 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000566 // Check whether the icmp can be decomposed into a bit test.
567 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
568 L21 = L22 = L1 = 0;
569 } else {
570 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000571 if (!L1->getType()->isIntegerTy()) {
572 // You can icmp pointers, for example. They really aren't masks.
573 L11 = L12 = 0;
574 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
575 // Any icmp can be viewed as being trivially masked; if it allows us to
576 // remove one, it's worth it.
577 L11 = L1;
578 L12 = Constant::getAllOnesValue(L1->getType());
579 }
580
581 if (!L2->getType()->isIntegerTy()) {
582 // You can icmp pointers, for example. They really aren't masks.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000583 L21 = L22 = 0;
Tim Northoverdc647a22013-09-04 11:57:17 +0000584 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
585 L21 = L2;
586 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000587 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000588 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000589
590 // Bail if LHS was a icmp that can't be decomposed into an equality.
591 if (!ICmpInst::isEquality(LHSCC))
592 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000593
594 Value *R1 = RHS->getOperand(0);
595 Value *R2 = RHS->getOperand(1);
596 Value *R11,*R12;
597 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000598 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
599 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
600 A = R11; D = R12;
601 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
602 A = R12; D = R11;
603 } else {
604 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000605 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000606 E = R2; R1 = 0; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000607 } else if (R1->getType()->isIntegerTy()) {
608 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
609 // As before, model no mask as a trivial mask if it'll let us do an
610 // optimisation.
611 R11 = R1;
612 R12 = Constant::getAllOnesValue(R1->getType());
613 }
614
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000615 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
616 A = R11; D = R12; E = R2; ok = true;
617 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000618 A = R12; D = R11; E = R2; ok = true;
619 }
620 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000621
622 // Bail if RHS was a icmp that can't be decomposed into an equality.
623 if (!ICmpInst::isEquality(RHSCC))
624 return 0;
625
626 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000627 if (!ok && R2->getType()->isIntegerTy()) {
628 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
629 R11 = R2;
630 R12 = Constant::getAllOnesValue(R2->getType());
631 }
632
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000633 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
634 A = R11; D = R12; E = R1; ok = true;
635 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000636 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000637 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000638 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000639 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000640 }
641 if (!ok)
642 return 0;
643
644 if (L11 == A) {
645 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000646 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000647 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000648 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000649 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000650 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000651 B = L21; C = L1;
652 }
653
654 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
655 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
656 return left_type & right_type;
657}
658/// foldLogOpOfMaskedICmps:
659/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
660/// into a single (icmp(A & X) ==/!= Y)
Tim Northoverc0756c42013-09-04 11:57:13 +0000661static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000662 llvm::InstCombiner::BuilderTy* Builder) {
663 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000664 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
665 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
666 LHSCC, RHSCC);
Benjamin Kramerf7fe24f2012-01-09 17:36:29 +0000667 if (mask == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000668 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
669 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000670
Tim Northoverc0756c42013-09-04 11:57:13 +0000671 // In full generality:
672 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
673 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
674 //
675 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
676 // equivalent to (icmp (A & X) !Op Y).
677 //
678 // Therefore, we can pretend for the rest of this function that we're dealing
679 // with the conjunction, provided we flip the sense of any comparisons (both
680 // input and output).
681
682 // In most cases we're going to produce an EQ for the "&&" case.
683 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
684 if (!IsAnd) {
685 // Convert the masking analysis into its equivalent with negated
686 // comparisons.
687 mask = conjugateICmpMask(mask);
688 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000689
690 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000691 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000692 // -> (icmp eq (A & (B|D)), 0)
693 Value* newOr = Builder->CreateOr(B, D);
694 Value* newAnd = Builder->CreateAnd(A, newOr);
695 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000696 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000697 // with B and D, having a single bit set
698 Value* zero = Constant::getNullValue(A->getType());
699 return Builder->CreateICmp(NEWCC, newAnd, zero);
700 }
Craig Topperae48cb22012-12-20 07:15:54 +0000701 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000702 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000703 // -> (icmp eq (A & (B|D)), (B|D))
704 Value* newOr = Builder->CreateOr(B, D);
705 Value* newAnd = Builder->CreateAnd(A, newOr);
706 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000707 }
Craig Topperae48cb22012-12-20 07:15:54 +0000708 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000709 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000710 // -> (icmp eq (A & (B&D)), A)
711 Value* newAnd1 = Builder->CreateAnd(B, D);
712 Value* newAnd = Builder->CreateAnd(A, newAnd1);
713 return Builder->CreateICmp(NEWCC, newAnd, A);
714 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000715
716 // Remaining cases assume at least that B and D are constant, and depend on
717 // their actual values. This isn't strictly, necessary, just a "handle the
718 // easy cases for now" decision.
719 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
720 if (BCst == 0) return 0;
721 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
722 if (DCst == 0) return 0;
723
724 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
725 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
726 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
727 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
728 // Only valid if one of the masks is a superset of the other (check "B&D" is
729 // the same as either B or D).
730 APInt NewMask = BCst->getValue() & DCst->getValue();
731
732 if (NewMask == BCst->getValue())
733 return LHS;
734 else if (NewMask == DCst->getValue())
735 return RHS;
736 }
737 if (mask & FoldMskICmp_AMask_NotAllOnes) {
738 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
739 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
740 // Only valid if one of the masks is a superset of the other (check "B|D" is
741 // the same as either B or D).
742 APInt NewMask = BCst->getValue() | DCst->getValue();
743
744 if (NewMask == BCst->getValue())
745 return LHS;
746 else if (NewMask == DCst->getValue())
747 return RHS;
748 }
Craig Topperae48cb22012-12-20 07:15:54 +0000749 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000750 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000751 // We already know that B & C == C && D & E == E.
752 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
753 // C and E, which are shared by both the mask B and the mask D, don't
754 // contradict, then we can transform to
755 // -> (icmp eq (A & (B|D)), (C|E))
756 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000757 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000758 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000759 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000760 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
761 if (CCst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000762 if (LHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000763 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
764 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
765 if (ECst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000766 if (RHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000767 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
768 ConstantInt* MCst = dyn_cast<ConstantInt>(
769 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
770 ConstantExpr::getXor(CCst, ECst)) );
771 // if there is a conflict we should actually return a false for the
772 // whole construct
773 if (!MCst->isZero())
774 return 0;
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000775 Value *newOr1 = Builder->CreateOr(B, D);
776 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
777 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000778 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
779 }
780 return 0;
781}
782
Chris Lattner0a8191e2010-01-05 07:50:36 +0000783/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000784Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000785 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
786
787 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
788 if (PredicatesFoldable(LHSCC, RHSCC)) {
789 if (LHS->getOperand(0) == RHS->getOperand(1) &&
790 LHS->getOperand(1) == RHS->getOperand(0))
791 LHS->swapOperands();
792 if (LHS->getOperand(0) == RHS->getOperand(0) &&
793 LHS->getOperand(1) == RHS->getOperand(1)) {
794 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
795 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
796 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000797 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000798 }
799 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000800
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000801 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000802 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000803 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000804
Chris Lattner0a8191e2010-01-05 07:50:36 +0000805 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
806 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
807 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
808 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
809 if (LHSCst == 0 || RHSCst == 0) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000810
Chris Lattner0a8191e2010-01-05 07:50:36 +0000811 if (LHSCst == RHSCst && LHSCC == RHSCC) {
812 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
813 // where C is a power of 2
814 if (LHSCC == ICmpInst::ICMP_ULT &&
815 LHSCst->getValue().isPowerOf2()) {
816 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000817 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000818 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000819
Chris Lattner0a8191e2010-01-05 07:50:36 +0000820 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
821 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
822 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000823 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000824 }
825 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000826
Benjamin Kramer101720f2011-04-28 20:09:57 +0000827 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000828 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000829 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000830 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000831 LHS->hasOneUse() && RHS->hasOneUse()) {
832 Value *V;
833 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
834
835 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000836 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000837 if (match(Val2, m_Trunc(m_Value(V))) &&
838 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
839 SmallCst = RHSCst;
840 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000841 } else if (match(Val, m_Trunc(m_Value(V))) &&
842 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000843 SmallCst = LHSCst;
844 BigCst = RHSCst;
845 }
846
847 if (SmallCst && BigCst) {
848 unsigned BigBitSize = BigCst->getType()->getBitWidth();
849 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
850
851 // Check that the low bits are zero.
852 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000853 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000854 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
855 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
856 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
857 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
858 }
859 }
860 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000861
Chris Lattner0a8191e2010-01-05 07:50:36 +0000862 // From here on, we only handle:
863 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
864 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000865
Chris Lattner0a8191e2010-01-05 07:50:36 +0000866 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
867 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
868 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
869 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
870 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
871 return 0;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000872
873 // Make a constant range that's the intersection of the two icmp ranges.
874 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000875 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000876 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000877 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000878 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
879
880 if (LHSRange.intersectWith(RHSRange).isEmptySet())
881 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
882
Chris Lattner0a8191e2010-01-05 07:50:36 +0000883 // We can't fold (ugt x, C) & (sgt x, C2).
884 if (!PredicatesFoldable(LHSCC, RHSCC))
885 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000886
Chris Lattner0a8191e2010-01-05 07:50:36 +0000887 // Ensure that the larger constant is on the RHS.
888 bool ShouldSwap;
889 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000890 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000891 CmpInst::isSigned(RHSCC)))
892 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
893 else
894 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000895
Chris Lattner0a8191e2010-01-05 07:50:36 +0000896 if (ShouldSwap) {
897 std::swap(LHS, RHS);
898 std::swap(LHSCst, RHSCst);
899 std::swap(LHSCC, RHSCC);
900 }
901
Dan Gohman4a618822010-02-10 16:03:48 +0000902 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 // comparing a value against two constants and and'ing the result
904 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000905 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
906 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000907 // are not equal and that the larger constant is on the RHS
908 assert(LHSCst != RHSCst && "Compares not folded above?");
909
910 switch (LHSCC) {
911 default: llvm_unreachable("Unknown integer condition code!");
912 case ICmpInst::ICMP_EQ:
913 switch (RHSCC) {
914 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
916 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
917 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000918 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000919 }
920 case ICmpInst::ICMP_NE:
921 switch (RHSCC) {
922 default: llvm_unreachable("Unknown integer condition code!");
923 case ICmpInst::ICMP_ULT:
924 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000925 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000926 break; // (X != 13 & X u< 15) -> no change
927 case ICmpInst::ICMP_SLT:
928 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000929 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 break; // (X != 13 & X s< 15) -> no change
931 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
932 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
933 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000934 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000935 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000936 // Special case to get the ordering right when the values wrap around
937 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +0000938 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000939 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000940 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
941 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
942 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000943 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
944 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 }
946 break; // (X != 13 & X != 15) -> no change
947 }
948 break;
949 case ICmpInst::ICMP_ULT:
950 switch (RHSCC) {
951 default: llvm_unreachable("Unknown integer condition code!");
952 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
953 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000954 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000955 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
956 break;
957 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
958 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000959 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
961 break;
962 }
963 break;
964 case ICmpInst::ICMP_SLT:
965 switch (RHSCC) {
966 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
968 break;
969 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
970 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000971 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000972 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
973 break;
974 }
975 break;
976 case ICmpInst::ICMP_UGT:
977 switch (RHSCC) {
978 default: llvm_unreachable("Unknown integer condition code!");
979 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
980 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000981 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000982 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
983 break;
984 case ICmpInst::ICMP_NE:
985 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000986 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000987 break; // (X u> 13 & X != 15) -> no change
988 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000989 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000990 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
991 break;
992 }
993 break;
994 case ICmpInst::ICMP_SGT:
995 switch (RHSCC) {
996 default: llvm_unreachable("Unknown integer condition code!");
997 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
998 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000999 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001000 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1001 break;
1002 case ICmpInst::ICMP_NE:
1003 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001004 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001005 break; // (X s> 13 & X != 15) -> no change
1006 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001007 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001008 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1009 break;
1010 }
1011 break;
1012 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001013
Chris Lattner0a8191e2010-01-05 07:50:36 +00001014 return 0;
1015}
1016
Chris Lattner067459c2010-03-05 08:46:26 +00001017/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1018/// instcombine, this returns a Value which should already be inserted into the
1019/// function.
1020Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1022 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001023 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1024 return 0;
1025
Chris Lattner0a8191e2010-01-05 07:50:36 +00001026 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1027 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1028 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1029 // If either of the constants are nans, then the whole thing returns
1030 // false.
1031 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001032 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001033 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001034 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001035
Chris Lattner0a8191e2010-01-05 07:50:36 +00001036 // Handle vector zeros. This occurs because the canonical form of
1037 // "fcmp ord x,x" is "fcmp ord x, 0".
1038 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1039 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001040 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001041 return 0;
1042 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001043
Chris Lattner0a8191e2010-01-05 07:50:36 +00001044 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1045 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1046 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001047
1048
Chris Lattner0a8191e2010-01-05 07:50:36 +00001049 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1050 // Swap RHS operands to match LHS.
1051 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1052 std::swap(Op1LHS, Op1RHS);
1053 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001054
Chris Lattner0a8191e2010-01-05 07:50:36 +00001055 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1056 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1057 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001058 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001059 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001060 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001061 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001062 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001063 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001064 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001065
Chris Lattner0a8191e2010-01-05 07:50:36 +00001066 bool Op0Ordered;
1067 bool Op1Ordered;
1068 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1069 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001070 // uno && ord -> false
1071 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1072 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001073 if (Op1Pred == 0) {
1074 std::swap(LHS, RHS);
1075 std::swap(Op0Pred, Op1Pred);
1076 std::swap(Op0Ordered, Op1Ordered);
1077 }
1078 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001079 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001080 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001081 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1082 return LHS;
1083 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001084 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001085
Chris Lattner0a8191e2010-01-05 07:50:36 +00001086 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001087 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001088 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001089 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001090 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001091 }
1092 }
1093
1094 return 0;
1095}
1096
1097
1098Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001099 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1101
1102 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1103 return ReplaceInstUsesWith(I, V);
1104
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001105 // (A|B)&(A|C) -> A|(B&C) etc
1106 if (Value *V = SimplifyUsingDistributiveLaws(I))
1107 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001108
Craig Topper9d4171a2012-12-20 07:09:41 +00001109 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001110 // purpose is to compute bits we don't care about.
1111 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001112 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001113
1114 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1115 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001116
1117 // Optimize a variety of ((val OP C1) & C2) combinations...
1118 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1119 Value *Op0LHS = Op0I->getOperand(0);
1120 Value *Op0RHS = Op0I->getOperand(1);
1121 switch (Op0I->getOpcode()) {
1122 default: break;
1123 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001124 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001125 // If the mask is only needed on one incoming arm, push it up.
1126 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001127
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001128 APInt NotAndRHS(~AndRHSMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001129 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1130 // Not masking anything out for the LHS, move to RHS.
1131 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1132 Op0RHS->getName()+".masked");
1133 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1134 }
1135 if (!isa<Constant>(Op0RHS) &&
1136 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1137 // Not masking anything out for the RHS, move to LHS.
1138 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1139 Op0LHS->getName()+".masked");
1140 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1141 }
1142
1143 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001144 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001145 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001146 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1147 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1148 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001149 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1150 return BinaryOperator::CreateAnd(V, AndRHS);
1151 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1152 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1153 break;
1154
1155 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001156 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1157 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1158 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001159 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1160 return BinaryOperator::CreateAnd(V, AndRHS);
1161
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001162 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001163 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001164 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001165 uint32_t BitWidth = AndRHSMask.getBitWidth();
1166 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1167 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1168
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001169 if (MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001170 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1171 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1172 }
1173 }
1174 break;
1175
1176 case Instruction::Shl:
1177 case Instruction::LShr:
1178 // (1 << x) & 1 --> zext(x == 0)
1179 // (1 >> x) & 1 --> zext(x == 0)
1180 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1181 Value *NewICmp =
1182 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1183 return new ZExtInst(NewICmp, I.getType());
1184 }
1185 break;
1186 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001187
Chris Lattner0a8191e2010-01-05 07:50:36 +00001188 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1189 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1190 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001191 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001192
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001193 // If this is an integer truncation, and if the source is an 'and' with
1194 // immediate, transform it. This frequently occurs for bitfield accesses.
1195 {
1196 Value *X = 0; ConstantInt *YC = 0;
1197 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1198 // Change: and (trunc (and X, YC) to T), C2
1199 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001200 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001201 // other simplifications.
1202 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1203 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1204 C3 = ConstantExpr::getAnd(C3, AndRHS);
1205 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001206 }
1207 }
1208
1209 // Try to fold constant and into select arguments.
1210 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1211 if (Instruction *R = FoldOpIntoSelect(I, SI))
1212 return R;
1213 if (isa<PHINode>(Op0))
1214 if (Instruction *NV = FoldOpIntoPhi(I))
1215 return NV;
1216 }
1217
1218
1219 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1220 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1221 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1222 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1223 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1224 I.getName()+".demorgan");
1225 return BinaryOperator::CreateNot(Or);
1226 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001227
Chris Lattner0a8191e2010-01-05 07:50:36 +00001228 {
1229 Value *A = 0, *B = 0, *C = 0, *D = 0;
1230 // (A|B) & ~(A&B) -> A^B
1231 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1232 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1233 ((A == C && B == D) || (A == D && B == C)))
1234 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001235
Chris Lattner0a8191e2010-01-05 07:50:36 +00001236 // ~(A&B) & (A|B) -> A^B
1237 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1238 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1239 ((A == C && B == D) || (A == D && B == C)))
1240 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001241
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001242 // A&(A^B) => A & ~B
1243 {
1244 Value *tmpOp0 = Op0;
1245 Value *tmpOp1 = Op1;
1246 if (Op0->hasOneUse() &&
1247 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1248 if (A == Op1 || B == Op1 ) {
1249 tmpOp1 = Op0;
1250 tmpOp0 = Op1;
1251 // Simplify below
1252 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001253 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001254
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001255 if (tmpOp1->hasOneUse() &&
1256 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1257 if (B == tmpOp0) {
1258 std::swap(A, B);
1259 }
1260 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1261 // A is originally -1 (or a vector of -1 and undefs), then we enter
1262 // an endless loop. By checking that A is non-constant we ensure that
1263 // we will never get to the loop.
1264 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001265 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001266 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001267 }
1268
1269 // (A&((~A)|B)) -> A&B
1270 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1271 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1272 return BinaryOperator::CreateAnd(A, Op1);
1273 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1274 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1275 return BinaryOperator::CreateAnd(A, Op0);
1276 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001277
Chris Lattner0a8191e2010-01-05 07:50:36 +00001278 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1279 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +00001280 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1281 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001282
Chris Lattner4e8137d2010-02-11 06:26:33 +00001283 // If and'ing two fcmp, try combine them into one.
1284 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1285 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001286 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1287 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001288
1289
Chris Lattner0a8191e2010-01-05 07:50:36 +00001290 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1291 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001292 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001293 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001294 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1295 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001296 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001297 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001298
Chris Lattner4e8137d2010-02-11 06:26:33 +00001299 // Only do this if the casts both really cause code to be generated.
1300 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1301 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1302 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001303 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1304 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001305
Chris Lattner4e8137d2010-02-11 06:26:33 +00001306 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1307 // cast is otherwise not optimizable. This happens for vector sexts.
1308 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1309 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001310 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001311 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001312
Chris Lattner4e8137d2010-02-11 06:26:33 +00001313 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1314 // cast is otherwise not optimizable. This happens for vector sexts.
1315 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1316 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001317 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001318 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001319 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001320 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001321
Chris Lattner0a8191e2010-01-05 07:50:36 +00001322 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1323 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1324 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001325 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001326 SI0->getOperand(1) == SI1->getOperand(1) &&
1327 (SI0->hasOneUse() || SI1->hasOneUse())) {
1328 Value *NewOp =
1329 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1330 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001331 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001332 SI1->getOperand(1));
1333 }
1334 }
1335
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001336 {
1337 Value *X = 0;
1338 bool OpsSwapped = false;
1339 // Canonicalize SExt or Not to the LHS
1340 if (match(Op1, m_SExt(m_Value())) ||
1341 match(Op1, m_Not(m_Value()))) {
1342 std::swap(Op0, Op1);
1343 OpsSwapped = true;
1344 }
1345
1346 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1347 if (match(Op0, m_SExt(m_Value(X))) &&
1348 X->getType()->getScalarType()->isIntegerTy(1)) {
1349 Value *Zero = Constant::getNullValue(Op1->getType());
1350 return SelectInst::Create(X, Op1, Zero);
1351 }
1352
1353 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1354 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1355 X->getType()->getScalarType()->isIntegerTy(1)) {
1356 Value *Zero = Constant::getNullValue(Op0->getType());
1357 return SelectInst::Create(X, Zero, Op1);
1358 }
1359
1360 if (OpsSwapped)
1361 std::swap(Op0, Op1);
1362 }
1363
Chris Lattner0a8191e2010-01-05 07:50:36 +00001364 return Changed ? &I : 0;
1365}
1366
1367/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1368/// capable of providing pieces of a bswap. The subexpression provides pieces
1369/// of a bswap if it is proven that each of the non-zero bytes in the output of
1370/// the expression came from the corresponding "byte swapped" byte in some other
1371/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1372/// we know that the expression deposits the low byte of %X into the high byte
1373/// of the bswap result and that all other bytes are zero. This expression is
1374/// accepted, the high byte of ByteValues is set to X to indicate a correct
1375/// match.
1376///
1377/// This function returns true if the match was unsuccessful and false if so.
1378/// On entry to the function the "OverallLeftShift" is a signed integer value
1379/// indicating the number of bytes that the subexpression is later shifted. For
1380/// example, if the expression is later right shifted by 16 bits, the
1381/// OverallLeftShift value would be -2 on entry. This is used to specify which
1382/// byte of ByteValues is actually being set.
1383///
1384/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1385/// byte is masked to zero by a user. For example, in (X & 255), X will be
1386/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1387/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1388/// always in the local (OverallLeftShift) coordinate space.
1389///
1390static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
Craig Topperb94011f2013-07-14 04:42:23 +00001391 SmallVectorImpl<Value *> &ByteValues) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 if (Instruction *I = dyn_cast<Instruction>(V)) {
1393 // If this is an or instruction, it may be an inner node of the bswap.
1394 if (I->getOpcode() == Instruction::Or) {
1395 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1396 ByteValues) ||
1397 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1398 ByteValues);
1399 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001400
Chris Lattner0a8191e2010-01-05 07:50:36 +00001401 // If this is a logical shift by a constant multiple of 8, recurse with
1402 // OverallLeftShift and ByteMask adjusted.
1403 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001404 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001405 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1406 // Ensure the shift amount is defined and of a byte value.
1407 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1408 return true;
1409
1410 unsigned ByteShift = ShAmt >> 3;
1411 if (I->getOpcode() == Instruction::Shl) {
1412 // X << 2 -> collect(X, +2)
1413 OverallLeftShift += ByteShift;
1414 ByteMask >>= ByteShift;
1415 } else {
1416 // X >>u 2 -> collect(X, -2)
1417 OverallLeftShift -= ByteShift;
1418 ByteMask <<= ByteShift;
1419 ByteMask &= (~0U >> (32-ByteValues.size()));
1420 }
1421
1422 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1423 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1424
Craig Topper9d4171a2012-12-20 07:09:41 +00001425 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001426 ByteValues);
1427 }
1428
1429 // If this is a logical 'and' with a mask that clears bytes, clear the
1430 // corresponding bytes in ByteMask.
1431 if (I->getOpcode() == Instruction::And &&
1432 isa<ConstantInt>(I->getOperand(1))) {
1433 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1434 unsigned NumBytes = ByteValues.size();
1435 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1436 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001437
Chris Lattner0a8191e2010-01-05 07:50:36 +00001438 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1439 // If this byte is masked out by a later operation, we don't care what
1440 // the and mask is.
1441 if ((ByteMask & (1 << i)) == 0)
1442 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001443
Chris Lattner0a8191e2010-01-05 07:50:36 +00001444 // If the AndMask is all zeros for this byte, clear the bit.
1445 APInt MaskB = AndMask & Byte;
1446 if (MaskB == 0) {
1447 ByteMask &= ~(1U << i);
1448 continue;
1449 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001450
Chris Lattner0a8191e2010-01-05 07:50:36 +00001451 // If the AndMask is not all ones for this byte, it's not a bytezap.
1452 if (MaskB != Byte)
1453 return true;
1454
1455 // Otherwise, this byte is kept.
1456 }
1457
Craig Topper9d4171a2012-12-20 07:09:41 +00001458 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001459 ByteValues);
1460 }
1461 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001462
Chris Lattner0a8191e2010-01-05 07:50:36 +00001463 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1464 // the input value to the bswap. Some observations: 1) if more than one byte
1465 // is demanded from this input, then it could not be successfully assembled
1466 // into a byteswap. At least one of the two bytes would not be aligned with
1467 // their ultimate destination.
1468 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001469 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001470
Chris Lattner0a8191e2010-01-05 07:50:36 +00001471 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1472 // is demanded, it needs to go into byte 0 of the result. This means that the
1473 // byte needs to be shifted until it lands in the right byte bucket. The
1474 // shift amount depends on the position: if the byte is coming from the high
1475 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1476 // low part, it must be shifted left.
1477 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001478 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1479 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001480
Chris Lattner0a8191e2010-01-05 07:50:36 +00001481 // If the destination byte value is already defined, the values are or'd
1482 // together, which isn't a bswap (unless it's an or of the same bits).
1483 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1484 return true;
1485 ByteValues[DestByteNo] = V;
1486 return false;
1487}
1488
1489/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1490/// If so, insert the new bswap intrinsic and return it.
1491Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001492 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001493 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001494 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001495 ITy->getBitWidth() > 32*8)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001496 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001497
Chris Lattner0a8191e2010-01-05 07:50:36 +00001498 /// ByteValues - For each byte of the result, we keep track of which value
1499 /// defines each byte.
1500 SmallVector<Value*, 8> ByteValues;
1501 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001502
Chris Lattner0a8191e2010-01-05 07:50:36 +00001503 // Try to find all the pieces corresponding to the bswap.
1504 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1505 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1506 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001507
Chris Lattner0a8191e2010-01-05 07:50:36 +00001508 // Check to see if all of the bytes come from the same value.
1509 Value *V = ByteValues[0];
1510 if (V == 0) return 0; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001511
Chris Lattner0a8191e2010-01-05 07:50:36 +00001512 // Check to make sure that all of the bytes come from the same value.
1513 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1514 if (ByteValues[i] != V)
1515 return 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001516 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001517 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001518 return CallInst::Create(F, V);
1519}
1520
1521/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1522/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1523/// we can simplify this expression to "cond ? C : D or B".
1524static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1525 Value *C, Value *D) {
1526 // If A is not a select of -1/0, this cannot match.
1527 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001528 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001529 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001530 return 0;
1531
1532 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001533 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001534 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001535 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001536 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001537
Chris Lattner0a8191e2010-01-05 07:50:36 +00001538 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001539 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001540 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001541 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001542 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001543 return 0;
1544}
1545
Chris Lattner067459c2010-03-05 08:46:26 +00001546/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1547Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001548 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1549
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001550 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1551 // if K1 and K2 are a one-bit mask.
1552 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1553 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1554
1555 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1556 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1557
1558 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1559 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1560 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1561 LAnd->getOpcode() == Instruction::And &&
1562 RAnd->getOpcode() == Instruction::And) {
1563
1564 Value *Mask = 0;
1565 Value *Masked = 0;
1566 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Benjamin Kramer7a74bd42014-01-19 16:48:41 +00001567 isKnownToBeAPowerOfTwo(LAnd->getOperand(1)) &&
1568 isKnownToBeAPowerOfTwo(RAnd->getOperand(1))) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001569 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1570 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1571 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Benjamin Kramer7a74bd42014-01-19 16:48:41 +00001572 isKnownToBeAPowerOfTwo(LAnd->getOperand(0)) &&
1573 isKnownToBeAPowerOfTwo(RAnd->getOperand(0))) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001574 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1575 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1576 }
1577
1578 if (Masked)
1579 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1580 }
1581 }
1582
Chris Lattner0a8191e2010-01-05 07:50:36 +00001583 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1584 if (PredicatesFoldable(LHSCC, RHSCC)) {
1585 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1586 LHS->getOperand(1) == RHS->getOperand(0))
1587 LHS->swapOperands();
1588 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1589 LHS->getOperand(1) == RHS->getOperand(1)) {
1590 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1591 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1592 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001593 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001594 }
1595 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001596
1597 // handle (roughly):
1598 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001599 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001600 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001601
Chris Lattner0a8191e2010-01-05 07:50:36 +00001602 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001603 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1604 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1605 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1606 Value *A = 0, *B = 0;
1607 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1608 B = Val;
1609 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1610 A = Val2;
1611 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1612 A = RHS->getOperand(1);
1613 }
1614 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1615 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1616 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1617 B = Val2;
1618 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1619 A = Val;
1620 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1621 A = LHS->getOperand(1);
1622 }
1623 if (A && B)
1624 return Builder->CreateICmp(
1625 ICmpInst::ICMP_UGE,
1626 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1627 }
1628
1629 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner0a8191e2010-01-05 07:50:36 +00001630 if (LHSCst == 0 || RHSCst == 0) return 0;
1631
Owen Anderson8f306a72010-08-02 09:32:13 +00001632 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1633 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1634 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1635 Value *NewOr = Builder->CreateOr(Val, Val2);
1636 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1637 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001638 }
1639
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001640 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001641 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001642 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001643 ConstantInt *AddCst;
1644 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1645 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001646 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001647 }
1648
Chris Lattner0a8191e2010-01-05 07:50:36 +00001649 // From here on, we only handle:
1650 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1651 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001652
Chris Lattner0a8191e2010-01-05 07:50:36 +00001653 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1654 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1655 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1656 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1657 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1658 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001659
Chris Lattner0a8191e2010-01-05 07:50:36 +00001660 // We can't fold (ugt x, C) | (sgt x, C2).
1661 if (!PredicatesFoldable(LHSCC, RHSCC))
1662 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001663
Chris Lattner0a8191e2010-01-05 07:50:36 +00001664 // Ensure that the larger constant is on the RHS.
1665 bool ShouldSwap;
1666 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001667 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001668 CmpInst::isSigned(RHSCC)))
1669 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1670 else
1671 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001672
Chris Lattner0a8191e2010-01-05 07:50:36 +00001673 if (ShouldSwap) {
1674 std::swap(LHS, RHS);
1675 std::swap(LHSCst, RHSCst);
1676 std::swap(LHSCC, RHSCC);
1677 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001678
Dan Gohman4a618822010-02-10 16:03:48 +00001679 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001680 // comparing a value against two constants and or'ing the result
1681 // together. Because of the above check, we know that we only have
1682 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1683 // icmp folding check above), that the two constants are not
1684 // equal.
1685 assert(LHSCst != RHSCst && "Compares not folded above?");
1686
1687 switch (LHSCC) {
1688 default: llvm_unreachable("Unknown integer condition code!");
1689 case ICmpInst::ICMP_EQ:
1690 switch (RHSCC) {
1691 default: llvm_unreachable("Unknown integer condition code!");
1692 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001693 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001694 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001695 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001696 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1697
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001698 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1699 if (Xor.isPowerOf2()) {
1700 Value *NegCst = Builder->getInt(~Xor);
1701 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1702 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1703 }
1704 }
1705
David Majnemer1fae1952013-04-14 21:15:43 +00001706 if (LHSCst == SubOne(RHSCst)) {
1707 // (X == 13 | X == 14) -> X-13 <u 2
1708 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1709 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1710 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1711 return Builder->CreateICmpULT(Add, AddCST);
1712 }
1713
Chris Lattner0a8191e2010-01-05 07:50:36 +00001714 break; // (X == 13 | X == 15) -> no change
1715 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1716 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1717 break;
1718 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1719 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1720 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001721 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001722 }
1723 break;
1724 case ICmpInst::ICMP_NE:
1725 switch (RHSCC) {
1726 default: llvm_unreachable("Unknown integer condition code!");
1727 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1728 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1729 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001730 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001731 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1732 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1733 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001734 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001735 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001736 case ICmpInst::ICMP_ULT:
1737 switch (RHSCC) {
1738 default: llvm_unreachable("Unknown integer condition code!");
1739 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1740 break;
1741 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1742 // If RHSCst is [us]MAXINT, it is always false. Not handling
1743 // this can cause overflow.
1744 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001745 return LHS;
1746 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001747 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1748 break;
1749 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1750 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001751 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001752 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1753 break;
1754 }
1755 break;
1756 case ICmpInst::ICMP_SLT:
1757 switch (RHSCC) {
1758 default: llvm_unreachable("Unknown integer condition code!");
1759 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1760 break;
1761 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1762 // If RHSCst is [us]MAXINT, it is always false. Not handling
1763 // this can cause overflow.
1764 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001765 return LHS;
1766 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001767 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1768 break;
1769 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1770 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001771 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001772 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1773 break;
1774 }
1775 break;
1776 case ICmpInst::ICMP_UGT:
1777 switch (RHSCC) {
1778 default: llvm_unreachable("Unknown integer condition code!");
1779 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1780 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001781 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1783 break;
1784 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1785 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001786 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001787 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1788 break;
1789 }
1790 break;
1791 case ICmpInst::ICMP_SGT:
1792 switch (RHSCC) {
1793 default: llvm_unreachable("Unknown integer condition code!");
1794 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1795 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001796 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001797 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1798 break;
1799 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1800 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001801 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001802 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1803 break;
1804 }
1805 break;
1806 }
1807 return 0;
1808}
1809
Chris Lattner067459c2010-03-05 08:46:26 +00001810/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1811/// instcombine, this returns a Value which should already be inserted into the
1812/// function.
1813Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001814 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001815 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001816 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1817 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1818 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1819 // If either of the constants are nans, then the whole thing returns
1820 // true.
1821 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001822 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001823
Chris Lattner0a8191e2010-01-05 07:50:36 +00001824 // Otherwise, no need to compare the two constants, compare the
1825 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001826 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001828
Chris Lattner0a8191e2010-01-05 07:50:36 +00001829 // Handle vector zeros. This occurs because the canonical form of
1830 // "fcmp uno x,x" is "fcmp uno x, 0".
1831 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1832 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001833 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001834
Chris Lattner0a8191e2010-01-05 07:50:36 +00001835 return 0;
1836 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001837
Chris Lattner0a8191e2010-01-05 07:50:36 +00001838 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1839 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1840 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001841
Chris Lattner0a8191e2010-01-05 07:50:36 +00001842 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1843 // Swap RHS operands to match LHS.
1844 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1845 std::swap(Op1LHS, Op1RHS);
1846 }
1847 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1848 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1849 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001850 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001851 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001852 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001853 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001854 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001855 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001856 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001857 bool Op0Ordered;
1858 bool Op1Ordered;
1859 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1860 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1861 if (Op0Ordered == Op1Ordered) {
1862 // If both are ordered or unordered, return a new fcmp with
1863 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001864 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001865 }
1866 }
1867 return 0;
1868}
1869
1870/// FoldOrWithConstants - This helper function folds:
1871///
1872/// ((A | B) & C1) | (B & C2)
1873///
1874/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001875///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001876/// (A & C1) | B
1877///
1878/// when the XOR of the two constants is "all ones" (-1).
1879Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1880 Value *A, Value *B, Value *C) {
1881 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1882 if (!CI1) return 0;
1883
1884 Value *V1 = 0;
1885 ConstantInt *CI2 = 0;
1886 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1887
1888 APInt Xor = CI1->getValue() ^ CI2->getValue();
1889 if (!Xor.isAllOnesValue()) return 0;
1890
1891 if (V1 == A || V1 == B) {
1892 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1893 return BinaryOperator::CreateOr(NewOp, V1);
1894 }
1895
1896 return 0;
1897}
1898
1899Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001900 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1902
1903 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1904 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001905
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001906 // (A&B)|(A&C) -> A&(B|C) etc
1907 if (Value *V = SimplifyUsingDistributiveLaws(I))
1908 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001909
Craig Topper9d4171a2012-12-20 07:09:41 +00001910 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001911 // purpose is to compute bits we don't care about.
1912 if (SimplifyDemandedInstructionBits(I))
1913 return &I;
1914
1915 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1916 ConstantInt *C1 = 0; Value *X = 0;
1917 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001918 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001919 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001920 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001921 Op0->hasOneUse()) {
1922 Value *Or = Builder->CreateOr(X, RHS);
1923 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001924 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001925 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926 }
1927
1928 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1929 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1930 Op0->hasOneUse()) {
1931 Value *Or = Builder->CreateOr(X, RHS);
1932 Or->takeName(Op0);
1933 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001934 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001935 }
1936
1937 // Try to fold constant and into select arguments.
1938 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1939 if (Instruction *R = FoldOpIntoSelect(I, SI))
1940 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001941
Chris Lattner0a8191e2010-01-05 07:50:36 +00001942 if (isa<PHINode>(Op0))
1943 if (Instruction *NV = FoldOpIntoPhi(I))
1944 return NV;
1945 }
1946
1947 Value *A = 0, *B = 0;
1948 ConstantInt *C1 = 0, *C2 = 0;
1949
1950 // (A | B) | C and A | (B | C) -> bswap if possible.
1951 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1952 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1953 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00001954 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1955 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001956 if (Instruction *BSwap = MatchBSwap(I))
1957 return BSwap;
1958 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001959
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001960 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001961 if (Op0->hasOneUse() &&
1962 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1963 MaskedValueIsZero(Op1, C1->getValue())) {
1964 Value *NOr = Builder->CreateOr(A, Op1);
1965 NOr->takeName(Op0);
1966 return BinaryOperator::CreateXor(NOr, C1);
1967 }
1968
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001969 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001970 if (Op1->hasOneUse() &&
1971 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1972 MaskedValueIsZero(Op0, C1->getValue())) {
1973 Value *NOr = Builder->CreateOr(A, Op0);
1974 NOr->takeName(Op0);
1975 return BinaryOperator::CreateXor(NOr, C1);
1976 }
1977
1978 // (A & C)|(B & D)
1979 Value *C = 0, *D = 0;
1980 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1981 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001982 Value *V1 = 0, *V2 = 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001983 C1 = dyn_cast<ConstantInt>(C);
1984 C2 = dyn_cast<ConstantInt>(D);
1985 if (C1 && C2) { // (A & C1)|(B & C2)
1986 // If we have: ((V + N) & C1) | (V & C2)
1987 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1988 // replace with V+N.
1989 if (C1->getValue() == ~C2->getValue()) {
1990 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1991 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1992 // Add commutes, try both ways.
1993 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1994 return ReplaceInstUsesWith(I, A);
1995 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1996 return ReplaceInstUsesWith(I, A);
1997 }
1998 // Or commutes, try both ways.
1999 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
2000 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2001 // Add commutes, try both ways.
2002 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2003 return ReplaceInstUsesWith(I, B);
2004 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2005 return ReplaceInstUsesWith(I, B);
2006 }
2007 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002008
Chris Lattner0a8191e2010-01-05 07:50:36 +00002009 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002010 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002011 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002012 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2013 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2014 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2015 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002016 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002017 // Or commutes, try both ways.
2018 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2019 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2020 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2021 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002022 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002023
Chris Lattner95188692010-01-11 06:55:24 +00002024 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002025 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Chris Lattner95188692010-01-11 06:55:24 +00002026 ConstantInt *C3 = 0, *C4 = 0;
2027 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2028 (C3->getValue() & ~C1->getValue()) == 0 &&
2029 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2030 (C4->getValue() & ~C2->getValue()) == 0) {
2031 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2032 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002033 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002034 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002035 }
2036 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037
Chris Lattner8e2c4712010-02-02 02:43:51 +00002038 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2039 // Don't do this for vector select idioms, the code generator doesn't handle
2040 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002041 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002042 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2043 return Match;
2044 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2045 return Match;
2046 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2047 return Match;
2048 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2049 return Match;
2050 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002051
2052 // ((A&~B)|(~A&B)) -> A^B
2053 if ((match(C, m_Not(m_Specific(D))) &&
2054 match(B, m_Not(m_Specific(A)))))
2055 return BinaryOperator::CreateXor(A, D);
2056 // ((~B&A)|(~A&B)) -> A^B
2057 if ((match(A, m_Not(m_Specific(D))) &&
2058 match(B, m_Not(m_Specific(C)))))
2059 return BinaryOperator::CreateXor(C, D);
2060 // ((A&~B)|(B&~A)) -> A^B
2061 if ((match(C, m_Not(m_Specific(B))) &&
2062 match(D, m_Not(m_Specific(A)))))
2063 return BinaryOperator::CreateXor(A, B);
2064 // ((~B&A)|(B&~A)) -> A^B
2065 if ((match(A, m_Not(m_Specific(B))) &&
2066 match(D, m_Not(m_Specific(C)))))
2067 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002068
2069 // ((A|B)&1)|(B&-2) -> (A&1) | B
2070 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2071 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2072 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2073 if (Ret) return Ret;
2074 }
2075 // (B&-2)|((A|B)&1) -> (A&1) | B
2076 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2077 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2078 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2079 if (Ret) return Ret;
2080 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002081 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002082
Chris Lattner0a8191e2010-01-05 07:50:36 +00002083 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
2084 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2085 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00002086 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002087 SI0->getOperand(1) == SI1->getOperand(1) &&
2088 (SI0->hasOneUse() || SI1->hasOneUse())) {
2089 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2090 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002091 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002092 SI1->getOperand(1));
2093 }
2094 }
2095
Chris Lattner0a8191e2010-01-05 07:50:36 +00002096 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2097 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2098 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2099 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2100 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2101 I.getName()+".demorgan");
2102 return BinaryOperator::CreateNot(And);
2103 }
2104
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002105 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002106 bool SwappedForXor = false;
2107 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002108 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002109 SwappedForXor = true;
2110 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002111
2112 // A | ( A ^ B) -> A | B
2113 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002114 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002115 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2116 if (Op0 == A || Op0 == B)
2117 return BinaryOperator::CreateOr(A, B);
2118
Chad Rosier7813dce2012-04-26 23:29:14 +00002119 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2120 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2121 return BinaryOperator::CreateOr(A, B);
2122
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002123 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2124 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2125 return BinaryOperator::CreateOr(Not, Op0);
2126 }
2127 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2128 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2129 return BinaryOperator::CreateOr(Not, Op0);
2130 }
2131 }
2132
2133 // A | ~(A | B) -> A | ~B
2134 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002135 if (match(Op1, m_Not(m_Value(A))))
2136 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002137 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2138 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2139 B->getOpcode() == Instruction::Xor)) {
2140 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2141 B->getOperand(0);
2142 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2143 return BinaryOperator::CreateOr(Not, Op0);
2144 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002145
Eli Friedmane06535b2012-03-16 00:52:42 +00002146 if (SwappedForXor)
2147 std::swap(Op0, Op1);
2148
Chris Lattner0a8191e2010-01-05 07:50:36 +00002149 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2150 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00002151 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2152 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002153
Chris Lattner4e8137d2010-02-11 06:26:33 +00002154 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2155 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2156 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002157 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2158 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002159
Chris Lattner0a8191e2010-01-05 07:50:36 +00002160 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2161 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002162 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2163 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002164 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002165 if (SrcTy == Op1C->getOperand(0)->getType() &&
2166 SrcTy->isIntOrIntVectorTy()) {
2167 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002168
Chris Lattner311aa632011-01-15 05:40:29 +00002169 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2170 // Only do this if the casts both really cause code to be
2171 // generated.
2172 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2173 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2174 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2175 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002176 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002177
Chris Lattner311aa632011-01-15 05:40:29 +00002178 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2179 // cast is otherwise not optimizable. This happens for vector sexts.
2180 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2181 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2182 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2183 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002184
Chris Lattner311aa632011-01-15 05:40:29 +00002185 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2186 // cast is otherwise not optimizable. This happens for vector sexts.
2187 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2188 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2189 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2190 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002191 }
Chris Lattner311aa632011-01-15 05:40:29 +00002192 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002193 }
Eli Friedman23956262011-04-14 22:41:27 +00002194
2195 // or(sext(A), B) -> A ? -1 : B where A is an i1
2196 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2197 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2198 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2199 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2200 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2201
Owen Andersonc237a842010-09-13 17:59:27 +00002202 // Note: If we've gotten to the point of visiting the outer OR, then the
2203 // inner one couldn't be simplified. If it was a constant, then it won't
2204 // be simplified by a later pass either, so we try swapping the inner/outer
2205 // ORs in the hopes that we'll be able to simplify it this way.
2206 // (X|C) | V --> (X|V) | C
2207 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2208 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2209 Value *Inner = Builder->CreateOr(A, Op1);
2210 Inner->takeName(Op0);
2211 return BinaryOperator::CreateOr(Inner, C1);
2212 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002213
Bill Wendling23242092013-02-16 23:41:36 +00002214 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2215 // Since this OR statement hasn't been optimized further yet, we hope
2216 // that this transformation will allow the new ORs to be optimized.
2217 {
2218 Value *X = 0, *Y = 0;
2219 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2220 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2221 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2222 Value *orTrue = Builder->CreateOr(A, C);
2223 Value *orFalse = Builder->CreateOr(B, D);
2224 return SelectInst::Create(X, orTrue, orFalse);
2225 }
2226 }
2227
Chris Lattner0a8191e2010-01-05 07:50:36 +00002228 return Changed ? &I : 0;
2229}
2230
2231Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002232 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002233 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2234
Duncan Sandsc89ac072010-11-17 18:52:15 +00002235 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2236 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002237
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002238 // (A&B)^(A&C) -> A&(B^C) etc
2239 if (Value *V = SimplifyUsingDistributiveLaws(I))
2240 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002241
Craig Topper9d4171a2012-12-20 07:09:41 +00002242 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002243 // purpose is to compute bits we don't care about.
2244 if (SimplifyDemandedInstructionBits(I))
2245 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002246
2247 // Is this a ~ operation?
2248 if (Value *NotOp = dyn_castNotVal(&I)) {
2249 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002250 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002251 Op0I->getOpcode() == Instruction::Or) {
2252 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2253 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2254 if (dyn_castNotVal(Op0I->getOperand(1)))
2255 Op0I->swapOperands();
2256 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2257 Value *NotY =
2258 Builder->CreateNot(Op0I->getOperand(1),
2259 Op0I->getOperand(1)->getName()+".not");
2260 if (Op0I->getOpcode() == Instruction::And)
2261 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2262 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2263 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002264
Chris Lattner0a8191e2010-01-05 07:50:36 +00002265 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2266 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Craig Topper9d4171a2012-12-20 07:09:41 +00002267 if (isFreeToInvert(Op0I->getOperand(0)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002268 isFreeToInvert(Op0I->getOperand(1))) {
2269 Value *NotX =
2270 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2271 Value *NotY =
2272 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2273 if (Op0I->getOpcode() == Instruction::And)
2274 return BinaryOperator::CreateOr(NotX, NotY);
2275 return BinaryOperator::CreateAnd(NotX, NotY);
2276 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002277
2278 } else if (Op0I->getOpcode() == Instruction::AShr) {
2279 // ~(~X >>s Y) --> (X >>s Y)
2280 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2281 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002282 }
2283 }
2284 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002285
2286
Chris Lattner0a8191e2010-01-05 07:50:36 +00002287 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002288 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002289 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002290 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2291 return CmpInst::Create(CI->getOpcode(),
2292 CI->getInversePredicate(),
2293 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002294
2295 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2296 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2297 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2298 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2299 Instruction::CastOps Opcode = Op0C->getOpcode();
2300 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002301 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002302 Op0C->getDestTy()))) {
2303 CI->setPredicate(CI->getInversePredicate());
2304 return CastInst::Create(Opcode, CI, Op0C->getType());
2305 }
2306 }
2307 }
2308 }
2309
2310 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2311 // ~(c-X) == X-c-1 == X+(-c-1)
2312 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2313 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2314 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2315 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2316 ConstantInt::get(I.getType(), 1));
2317 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2318 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002319
Chris Lattner0a8191e2010-01-05 07:50:36 +00002320 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2321 if (Op0I->getOpcode() == Instruction::Add) {
2322 // ~(X-c) --> (-c-1)-X
2323 if (RHS->isAllOnesValue()) {
2324 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2325 return BinaryOperator::CreateSub(
2326 ConstantExpr::getSub(NegOp0CI,
2327 ConstantInt::get(I.getType(), 1)),
2328 Op0I->getOperand(0));
2329 } else if (RHS->getValue().isSignBit()) {
2330 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002331 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002332 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2333
2334 }
2335 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002336 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002337 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2338 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2339 // Anything in both C1 and C2 is known to be zero, remove it from
2340 // NewRHS.
2341 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002342 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002343 ConstantExpr::getNot(CommonBits));
2344 Worklist.Add(Op0I);
2345 I.setOperand(0, Op0I->getOperand(0));
2346 I.setOperand(1, NewRHS);
2347 return &I;
2348 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002349 } else if (Op0I->getOpcode() == Instruction::LShr) {
2350 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2351 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002352 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002353 ConstantInt *C1;
2354 if (Op0I->hasOneUse() &&
2355 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2356 E1->getOpcode() == Instruction::Xor &&
2357 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2358 // fold (C1 >> C2) ^ C3
2359 ConstantInt *C2 = Op0CI, *C3 = RHS;
2360 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2361 FoldConst ^= C3->getValue();
2362 // Prepare the two operands.
2363 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2364 Opnd0->takeName(Op0I);
2365 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2366 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2367
2368 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2369 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002370 }
2371 }
2372 }
2373
2374 // Try to fold constant and into select arguments.
2375 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2376 if (Instruction *R = FoldOpIntoSelect(I, SI))
2377 return R;
2378 if (isa<PHINode>(Op0))
2379 if (Instruction *NV = FoldOpIntoPhi(I))
2380 return NV;
2381 }
2382
Chris Lattner0a8191e2010-01-05 07:50:36 +00002383 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2384 if (Op1I) {
2385 Value *A, *B;
2386 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2387 if (A == Op0) { // B^(B|A) == (A|B)^B
2388 Op1I->swapOperands();
2389 I.swapOperands();
2390 std::swap(Op0, Op1);
2391 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2392 I.swapOperands(); // Simplified below.
2393 std::swap(Op0, Op1);
2394 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002395 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002396 Op1I->hasOneUse()){
2397 if (A == Op0) { // A^(A&B) -> A^(B&A)
2398 Op1I->swapOperands();
2399 std::swap(A, B);
2400 }
2401 if (B == Op0) { // A^(B&A) -> (B&A)^A
2402 I.swapOperands(); // Simplified below.
2403 std::swap(Op0, Op1);
2404 }
2405 }
2406 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002407
Chris Lattner0a8191e2010-01-05 07:50:36 +00002408 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2409 if (Op0I) {
2410 Value *A, *B;
2411 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2412 Op0I->hasOneUse()) {
2413 if (A == Op1) // (B|A)^B == (A|B)^B
2414 std::swap(A, B);
2415 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002416 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002417 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002418 Op0I->hasOneUse()){
2419 if (A == Op1) // (A&B)^A -> (B&A)^A
2420 std::swap(A, B);
2421 if (B == Op1 && // (B&A)^A == ~B & A
2422 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002423 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002424 }
2425 }
2426 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002427
Chris Lattner0a8191e2010-01-05 07:50:36 +00002428 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Craig Topper9d4171a2012-12-20 07:09:41 +00002429 if (Op0I && Op1I && Op0I->isShift() &&
2430 Op0I->getOpcode() == Op1I->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002431 Op0I->getOperand(1) == Op1I->getOperand(1) &&
Benjamin Kramer9d5849f2012-05-28 20:52:48 +00002432 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002433 Value *NewOp =
2434 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2435 Op0I->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002436 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002437 Op1I->getOperand(1));
2438 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002439
Chris Lattner0a8191e2010-01-05 07:50:36 +00002440 if (Op0I && Op1I) {
2441 Value *A, *B, *C, *D;
2442 // (A & B)^(A | B) -> A ^ B
2443 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2444 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002445 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002446 return BinaryOperator::CreateXor(A, B);
2447 }
2448 // (A | B)^(A & B) -> A ^ B
2449 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2450 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002451 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002452 return BinaryOperator::CreateXor(A, B);
2453 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002454 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002455
Chris Lattner0a8191e2010-01-05 07:50:36 +00002456 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2457 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2458 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2459 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2460 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2461 LHS->getOperand(1) == RHS->getOperand(0))
2462 LHS->swapOperands();
2463 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2464 LHS->getOperand(1) == RHS->getOperand(1)) {
2465 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2466 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2467 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002468 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002469 getNewICmpValue(isSigned, Code, Op0, Op1,
2470 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002471 }
2472 }
2473
2474 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2475 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2476 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2477 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002478 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002479 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002480 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002481 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002482 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002483 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002484 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002485 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2486 Op1C->getOperand(0), I.getName());
2487 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2488 }
2489 }
2490 }
2491
2492 return Changed ? &I : 0;
2493}