blob: 6a4e721db462061b01537c4bd280cd144979d791 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Chris Lattner0a8191e2010-01-05 07:50:36 +000025/// isFreeToInvert - Return true if the specified value is free to invert (apply
26/// ~ to). This happens in cases where the ~ can be eliminated.
27static inline bool isFreeToInvert(Value *V) {
28 // ~(~(X)) -> X.
29 if (BinaryOperator::isNot(V))
30 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000031
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 // Constants can be considered to be not'ed values.
33 if (isa<ConstantInt>(V))
34 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000035
Chris Lattner0a8191e2010-01-05 07:50:36 +000036 // Compares can be inverted if they have a single use.
37 if (CmpInst *CI = dyn_cast<CmpInst>(V))
38 return CI->hasOneUse();
Craig Topper9d4171a2012-12-20 07:09:41 +000039
Chris Lattner0a8191e2010-01-05 07:50:36 +000040 return false;
41}
42
43static inline Value *dyn_castNotVal(Value *V) {
44 // If this is not(not(x)) don't return that this is a not: we want the two
45 // not's to be folded first.
46 if (BinaryOperator::isNot(V)) {
47 Value *Operand = BinaryOperator::getNotArgument(V);
48 if (!isFreeToInvert(Operand))
49 return Operand;
50 }
Craig Topper9d4171a2012-12-20 07:09:41 +000051
Chris Lattner0a8191e2010-01-05 07:50:36 +000052 // Constants can be considered to be not'ed values...
53 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
54 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000055 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000056}
57
Chris Lattner0a8191e2010-01-05 07:50:36 +000058/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
59/// predicate into a three bit mask. It also returns whether it is an ordered
60/// predicate by reference.
61static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
62 isOrdered = false;
63 switch (CC) {
64 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
65 case FCmpInst::FCMP_UNO: return 0; // 000
66 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
67 case FCmpInst::FCMP_UGT: return 1; // 001
68 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
69 case FCmpInst::FCMP_UEQ: return 2; // 010
70 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
71 case FCmpInst::FCMP_UGE: return 3; // 011
72 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
73 case FCmpInst::FCMP_ULT: return 4; // 100
74 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
75 case FCmpInst::FCMP_UNE: return 5; // 101
76 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
77 case FCmpInst::FCMP_ULE: return 6; // 110
78 // True -> 7
79 default:
80 // Not expecting FCMP_FALSE and FCMP_TRUE;
81 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000082 }
83}
84
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000085/// getNewICmpValue - This is the complement of getICmpCode, which turns an
Craig Topper9d4171a2012-12-20 07:09:41 +000086/// opcode and two operands into either a constant true or false, or a brand
Chris Lattner0a8191e2010-01-05 07:50:36 +000087/// new ICmp instruction. The sign is passed in to determine which kind
88/// of predicate to use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000089static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
90 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000091 ICmpInst::Predicate NewPred;
92 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
93 return NewConstant;
94 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000095}
96
97/// getFCmpValue - This is the complement of getFCmpCode, which turns an
98/// opcode and two operands into either a FCmp instruction. isordered is passed
99/// in to determine which kind of predicate to use in the new fcmp instruction.
100static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +0000101 Value *LHS, Value *RHS,
102 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000103 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000104 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +0000105 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +0000106 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
107 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
108 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
109 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
110 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
111 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
112 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +0000113 case 7:
Owen Andersona8342002011-01-21 19:39:42 +0000114 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
115 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000116 }
Chris Lattner067459c2010-03-05 08:46:26 +0000117 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000118}
119
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000120/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
121/// \param I Binary operator to transform.
122/// \return Pointer to node that must replace the original binary operator, or
123/// null pointer if no transformation was made.
124Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
125 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
126
127 // Can't do vectors.
128 if (I.getType()->isVectorTy()) return nullptr;
129
130 // Can only do bitwise ops.
131 unsigned Op = I.getOpcode();
132 if (Op != Instruction::And && Op != Instruction::Or &&
133 Op != Instruction::Xor)
134 return nullptr;
135
136 Value *OldLHS = I.getOperand(0);
137 Value *OldRHS = I.getOperand(1);
138 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
139 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
140 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
141 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
142 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
143 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
144
145 if (!IsBswapLHS && !IsBswapRHS)
146 return nullptr;
147
148 if (!IsBswapLHS && !ConstLHS)
149 return nullptr;
150
151 if (!IsBswapRHS && !ConstRHS)
152 return nullptr;
153
154 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
155 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
156 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
157 Builder->getInt(ConstLHS->getValue().byteSwap());
158
159 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
160 Builder->getInt(ConstRHS->getValue().byteSwap());
161
162 Value *BinOp = nullptr;
163 if (Op == Instruction::And)
164 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
165 else if (Op == Instruction::Or)
166 BinOp = Builder->CreateOr(NewLHS, NewRHS);
167 else //if (Op == Instruction::Xor)
168 BinOp = Builder->CreateXor(NewLHS, NewRHS);
169
170 Module *M = I.getParent()->getParent()->getParent();
171 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
172 return Builder->CreateCall(F, BinOp);
173}
174
Chris Lattner0a8191e2010-01-05 07:50:36 +0000175// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
176// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
177// guaranteed to be a binary operator.
178Instruction *InstCombiner::OptAndOp(Instruction *Op,
179 ConstantInt *OpRHS,
180 ConstantInt *AndRHS,
181 BinaryOperator &TheAnd) {
182 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000183 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000184 if (!Op->isShift())
185 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
186
187 switch (Op->getOpcode()) {
188 case Instruction::Xor:
189 if (Op->hasOneUse()) {
190 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
191 Value *And = Builder->CreateAnd(X, AndRHS);
192 And->takeName(Op);
193 return BinaryOperator::CreateXor(And, Together);
194 }
195 break;
196 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000197 if (Op->hasOneUse()){
198 if (Together != OpRHS) {
199 // (X | C1) & C2 --> (X | (C1&C2)) & C2
200 Value *Or = Builder->CreateOr(X, Together);
201 Or->takeName(Op);
202 return BinaryOperator::CreateAnd(Or, AndRHS);
203 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000204
Owen Andersonc237a842010-09-13 17:59:27 +0000205 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
206 if (TogetherCI && !TogetherCI->isZero()){
207 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
208 // NOTE: This reduces the number of bits set in the & mask, which
209 // can expose opportunities for store narrowing.
210 Together = ConstantExpr::getXor(AndRHS, Together);
211 Value *And = Builder->CreateAnd(X, Together);
212 And->takeName(Op);
213 return BinaryOperator::CreateOr(And, OpRHS);
214 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000215 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000216
Chris Lattner0a8191e2010-01-05 07:50:36 +0000217 break;
218 case Instruction::Add:
219 if (Op->hasOneUse()) {
220 // Adding a one to a single bit bit-field should be turned into an XOR
221 // of the bit. First thing to check is to see if this AND is with a
222 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000223 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000224
225 // If there is only one bit set.
226 if (AndRHSV.isPowerOf2()) {
227 // Ok, at this point, we know that we are masking the result of the
228 // ADD down to exactly one bit. If the constant we are adding has
229 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000230 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000231
232 // Check to see if any bits below the one bit set in AndRHSV are set.
233 if ((AddRHS & (AndRHSV-1)) == 0) {
234 // If not, the only thing that can effect the output of the AND is
235 // the bit specified by AndRHSV. If that bit is set, the effect of
236 // the XOR is to toggle the bit. If it is clear, then the ADD has
237 // no effect.
238 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
239 TheAnd.setOperand(0, X);
240 return &TheAnd;
241 } else {
242 // Pull the XOR out of the AND.
243 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
244 NewAnd->takeName(Op);
245 return BinaryOperator::CreateXor(NewAnd, AndRHS);
246 }
247 }
248 }
249 }
250 break;
251
252 case Instruction::Shl: {
253 // We know that the AND will not produce any of the bits shifted in, so if
254 // the anded constant includes them, clear them now!
255 //
256 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
257 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
258 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000259 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000260
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000261 if (CI->getValue() == ShlMask)
262 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000263 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000264
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000265 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000266 TheAnd.setOperand(1, CI);
267 return &TheAnd;
268 }
269 break;
270 }
271 case Instruction::LShr: {
272 // We know that the AND will not produce any of the bits shifted in, so if
273 // the anded constant includes them, clear them now! This only applies to
274 // unsigned shifts, because a signed shr may bring in set bits!
275 //
276 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
277 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
278 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000279 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000280
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000281 if (CI->getValue() == ShrMask)
282 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000283 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000284
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000285 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000286 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
287 return &TheAnd;
288 }
289 break;
290 }
291 case Instruction::AShr:
292 // Signed shr.
293 // See if this is shifting in some sign extension, then masking it out
294 // with an and.
295 if (Op->hasOneUse()) {
296 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
297 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
298 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000299 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000300 if (C == AndRHS) { // Masking out bits shifted in.
301 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
302 // Make the argument unsigned.
303 Value *ShVal = Op->getOperand(0);
304 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
305 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
306 }
307 }
308 break;
309 }
Craig Topperf40110f2014-04-25 05:29:35 +0000310 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000311}
312
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000313/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
314/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000315/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000316/// whether to treat the V, Lo and HI as signed or not. IB is the location to
317/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000318Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
319 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000320 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000321 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
322 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000323
Chris Lattner0a8191e2010-01-05 07:50:36 +0000324 if (Inside) {
325 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000326 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327
328 // V >= Min && V < Hi --> V < Hi
329 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000330 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000331 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000332 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000333 }
334
335 // Emit V-Lo <u Hi-Lo
336 Constant *NegLo = ConstantExpr::getNeg(Lo);
337 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
338 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000339 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000340 }
341
342 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000343 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000344
345 // V < Min || V >= Hi -> V > Hi-1
346 Hi = SubOne(cast<ConstantInt>(Hi));
347 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000348 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000349 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000350 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000351 }
352
353 // Emit V-Lo >u Hi-1-Lo
354 // Note that Hi has already had one subtracted from it, above.
355 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
356 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
357 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000358 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000359}
360
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000361// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000362// any number of 0s on either side. The 1s are allowed to wrap from LSB to
363// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
364// not, since all 1s are not contiguous.
365static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
366 const APInt& V = Val->getValue();
367 uint32_t BitWidth = Val->getType()->getBitWidth();
368 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
369
370 // look for the first zero bit after the run of ones
371 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
372 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000373 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000374 return true;
375}
376
377/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
378/// where isSub determines whether the operator is a sub. If we can fold one of
379/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000380///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000381/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
382/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
383/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000384///
385/// return (A +/- B).
386///
387Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
388 ConstantInt *Mask, bool isSub,
389 Instruction &I) {
390 Instruction *LHSI = dyn_cast<Instruction>(LHS);
391 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000392 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000393
394 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
395
396 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000397 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000398 case Instruction::And:
399 if (ConstantExpr::getAnd(N, Mask) == Mask) {
400 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000401 if ((Mask->getValue().countLeadingZeros() +
402 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000403 Mask->getValue().getBitWidth())
404 break;
405
406 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
407 // part, we don't need any explicit masks to take them out of A. If that
408 // is all N is, ignore it.
409 uint32_t MB = 0, ME = 0;
410 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
411 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
412 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000413 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000414 break;
415 }
416 }
Craig Topperf40110f2014-04-25 05:29:35 +0000417 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000418 case Instruction::Or:
419 case Instruction::Xor:
420 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000421 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000422 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
423 && ConstantExpr::getAnd(N, Mask)->isNullValue())
424 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000425 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000426 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000427
Chris Lattner0a8191e2010-01-05 07:50:36 +0000428 if (isSub)
429 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
430 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
431}
432
Owen Anderson3fe002d2010-09-08 22:16:17 +0000433/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000434/// One of A and B is considered the mask, the other the value. This is
435/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000436/// contains only "Mask", then both A and B can be considered masks.
437/// If A is the mask, then it was proven, that (A & C) == C. This
438/// is trivial if C == A, or C == 0. If both A and C are constants, this
439/// proof is also easy.
440/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000441/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000442/// if (A & B) == A, or all bits of A are set in B.
443/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000444/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000445/// if (A & B) == 0, or all bits of A are cleared in B.
446/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000447/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000448/// contain any number of one bits and zero bits.
449/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
450/// The Part "Not" means, that in above descriptions "==" should be replaced
451/// by "!=".
452/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
453/// If the mask A contains a single bit, then the following is equivalent:
454/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
455/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
456enum MaskedICmpType {
457 FoldMskICmp_AMask_AllOnes = 1,
458 FoldMskICmp_AMask_NotAllOnes = 2,
459 FoldMskICmp_BMask_AllOnes = 4,
460 FoldMskICmp_BMask_NotAllOnes = 8,
461 FoldMskICmp_Mask_AllZeroes = 16,
462 FoldMskICmp_Mask_NotAllZeroes = 32,
463 FoldMskICmp_AMask_Mixed = 64,
464 FoldMskICmp_AMask_NotMixed = 128,
465 FoldMskICmp_BMask_Mixed = 256,
466 FoldMskICmp_BMask_NotMixed = 512
467};
468
469/// return the set of pattern classes (from MaskedICmpType)
470/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000471static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000472 ICmpInst::Predicate SCC)
473{
474 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
475 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
476 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
477 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000478 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000479 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000480 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000481 BCst->getValue().isPowerOf2());
482 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000483 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000484 // if C is zero, then both A and B qualify as mask
485 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
486 FoldMskICmp_Mask_AllZeroes |
487 FoldMskICmp_AMask_Mixed |
488 FoldMskICmp_BMask_Mixed)
489 : (FoldMskICmp_Mask_NotAllZeroes |
490 FoldMskICmp_Mask_NotAllZeroes |
491 FoldMskICmp_AMask_NotMixed |
492 FoldMskICmp_BMask_NotMixed));
493 if (icmp_abit)
494 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000495 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000496 : (FoldMskICmp_AMask_AllOnes |
497 FoldMskICmp_AMask_Mixed));
498 if (icmp_bbit)
499 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000500 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000501 : (FoldMskICmp_BMask_AllOnes |
502 FoldMskICmp_BMask_Mixed));
503 return result;
504 }
505 if (A == C) {
506 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
507 FoldMskICmp_AMask_Mixed)
508 : (FoldMskICmp_AMask_NotAllOnes |
509 FoldMskICmp_AMask_NotMixed));
510 if (icmp_abit)
511 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
512 FoldMskICmp_AMask_NotMixed)
513 : (FoldMskICmp_Mask_AllZeroes |
514 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000515 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000516 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000517 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
518 : FoldMskICmp_AMask_NotMixed);
519 }
Craig Topperae48cb22012-12-20 07:15:54 +0000520 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000521 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
522 FoldMskICmp_BMask_Mixed)
523 : (FoldMskICmp_BMask_NotAllOnes |
524 FoldMskICmp_BMask_NotMixed));
525 if (icmp_bbit)
526 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000527 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000528 : (FoldMskICmp_Mask_AllZeroes |
529 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000530 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000531 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000532 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
533 : FoldMskICmp_BMask_NotMixed);
534 }
535 return result;
536}
537
Tim Northoverc0756c42013-09-04 11:57:13 +0000538/// Convert an analysis of a masked ICmp into its equivalent if all boolean
539/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
540/// is adjacent to the corresponding normal flag (recording ==), this just
541/// involves swapping those bits over.
542static unsigned conjugateICmpMask(unsigned Mask) {
543 unsigned NewMask;
544 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
545 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
546 FoldMskICmp_BMask_Mixed))
547 << 1;
548
549 NewMask |=
550 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
551 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
552 FoldMskICmp_BMask_NotMixed))
553 >> 1;
554
555 return NewMask;
556}
557
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000558/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
559/// if possible. The returned predicate is either == or !=. Returns false if
560/// decomposition fails.
561static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
562 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000563 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
564 if (!C)
565 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000566
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000567 switch (I->getPredicate()) {
568 default:
569 return false;
570 case ICmpInst::ICMP_SLT:
571 // X < 0 is equivalent to (X & SignBit) != 0.
572 if (!C->isZero())
573 return false;
574 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
575 Pred = ICmpInst::ICMP_NE;
576 break;
577 case ICmpInst::ICMP_SGT:
578 // X > -1 is equivalent to (X & SignBit) == 0.
579 if (!C->isAllOnesValue())
580 return false;
581 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
582 Pred = ICmpInst::ICMP_EQ;
583 break;
584 case ICmpInst::ICMP_ULT:
585 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
586 if (!C->getValue().isPowerOf2())
587 return false;
588 Y = ConstantInt::get(I->getContext(), -C->getValue());
589 Pred = ICmpInst::ICMP_EQ;
590 break;
591 case ICmpInst::ICMP_UGT:
592 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
593 if (!(C->getValue() + 1).isPowerOf2())
594 return false;
595 Y = ConstantInt::get(I->getContext(), ~C->getValue());
596 Pred = ICmpInst::ICMP_NE;
597 break;
598 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000599
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000600 X = I->getOperand(0);
601 Z = ConstantInt::getNullValue(C->getType());
602 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000603}
604
Owen Anderson3fe002d2010-09-08 22:16:17 +0000605/// foldLogOpOfMaskedICmpsHelper:
606/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
607/// return the set of pattern classes (from MaskedICmpType)
608/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000609static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000610 Value*& B, Value*& C,
611 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000612 ICmpInst *LHS, ICmpInst *RHS,
613 ICmpInst::Predicate &LHSCC,
614 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000615 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
616 // vectors are not (yet?) supported
617 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
618
619 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000620 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000621 // and L11 & L12 == L21 & L22. The same goes for RHS.
622 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000623 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000624 // above.
625 Value *L1 = LHS->getOperand(0);
626 Value *L2 = LHS->getOperand(1);
627 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000628 // Check whether the icmp can be decomposed into a bit test.
629 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000630 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000631 } else {
632 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000633 if (!L1->getType()->isIntegerTy()) {
634 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000635 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000636 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
637 // Any icmp can be viewed as being trivially masked; if it allows us to
638 // remove one, it's worth it.
639 L11 = L1;
640 L12 = Constant::getAllOnesValue(L1->getType());
641 }
642
643 if (!L2->getType()->isIntegerTy()) {
644 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000645 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000646 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
647 L21 = L2;
648 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000649 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000650 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000651
652 // Bail if LHS was a icmp that can't be decomposed into an equality.
653 if (!ICmpInst::isEquality(LHSCC))
654 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000655
656 Value *R1 = RHS->getOperand(0);
657 Value *R2 = RHS->getOperand(1);
658 Value *R11,*R12;
659 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000660 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
661 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
662 A = R11; D = R12;
663 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
664 A = R12; D = R11;
665 } else {
666 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000667 }
Craig Topperf40110f2014-04-25 05:29:35 +0000668 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000669 } else if (R1->getType()->isIntegerTy()) {
670 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
671 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000672 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000673 R11 = R1;
674 R12 = Constant::getAllOnesValue(R1->getType());
675 }
676
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000677 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
678 A = R11; D = R12; E = R2; ok = true;
679 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000680 A = R12; D = R11; E = R2; ok = true;
681 }
682 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000683
684 // Bail if RHS was a icmp that can't be decomposed into an equality.
685 if (!ICmpInst::isEquality(RHSCC))
686 return 0;
687
688 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000689 if (!ok && R2->getType()->isIntegerTy()) {
690 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
691 R11 = R2;
692 R12 = Constant::getAllOnesValue(R2->getType());
693 }
694
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000695 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
696 A = R11; D = R12; E = R1; ok = true;
697 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000698 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000699 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000700 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000701 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000702 }
703 if (!ok)
704 return 0;
705
706 if (L11 == A) {
707 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000708 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000709 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000710 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000711 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000712 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000713 B = L21; C = L1;
714 }
715
716 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
717 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
718 return left_type & right_type;
719}
720/// foldLogOpOfMaskedICmps:
721/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
722/// into a single (icmp(A & X) ==/!= Y)
David Majnemer1a3327b2014-11-18 09:31:36 +0000723static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
724 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000725 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000726 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
727 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
728 LHSCC, RHSCC);
Craig Topperf40110f2014-04-25 05:29:35 +0000729 if (mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000730 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
731 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000732
Tim Northoverc0756c42013-09-04 11:57:13 +0000733 // In full generality:
734 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
735 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
736 //
737 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
738 // equivalent to (icmp (A & X) !Op Y).
739 //
740 // Therefore, we can pretend for the rest of this function that we're dealing
741 // with the conjunction, provided we flip the sense of any comparisons (both
742 // input and output).
743
744 // In most cases we're going to produce an EQ for the "&&" case.
745 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
746 if (!IsAnd) {
747 // Convert the masking analysis into its equivalent with negated
748 // comparisons.
749 mask = conjugateICmpMask(mask);
750 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000751
752 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000753 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000754 // -> (icmp eq (A & (B|D)), 0)
David Majnemer1a3327b2014-11-18 09:31:36 +0000755 Value *newOr = Builder->CreateOr(B, D);
756 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000757 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000758 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000759 // with B and D, having a single bit set
David Majnemer1a3327b2014-11-18 09:31:36 +0000760 Value *zero = Constant::getNullValue(A->getType());
Owen Anderson3fe002d2010-09-08 22:16:17 +0000761 return Builder->CreateICmp(NEWCC, newAnd, zero);
762 }
Craig Topperae48cb22012-12-20 07:15:54 +0000763 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000764 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000765 // -> (icmp eq (A & (B|D)), (B|D))
David Majnemer1a3327b2014-11-18 09:31:36 +0000766 Value *newOr = Builder->CreateOr(B, D);
767 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000768 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000769 }
Craig Topperae48cb22012-12-20 07:15:54 +0000770 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000771 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000772 // -> (icmp eq (A & (B&D)), A)
David Majnemer1a3327b2014-11-18 09:31:36 +0000773 Value *newAnd1 = Builder->CreateAnd(B, D);
774 Value *newAnd = Builder->CreateAnd(A, newAnd1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000775 return Builder->CreateICmp(NEWCC, newAnd, A);
776 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000777
778 // Remaining cases assume at least that B and D are constant, and depend on
779 // their actual values. This isn't strictly, necessary, just a "handle the
780 // easy cases for now" decision.
781 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000782 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000783 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000784 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000785
786 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
787 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
788 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
789 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
790 // Only valid if one of the masks is a superset of the other (check "B&D" is
791 // the same as either B or D).
792 APInt NewMask = BCst->getValue() & DCst->getValue();
793
794 if (NewMask == BCst->getValue())
795 return LHS;
796 else if (NewMask == DCst->getValue())
797 return RHS;
798 }
799 if (mask & FoldMskICmp_AMask_NotAllOnes) {
800 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
801 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
802 // Only valid if one of the masks is a superset of the other (check "B|D" is
803 // the same as either B or D).
804 APInt NewMask = BCst->getValue() | DCst->getValue();
805
806 if (NewMask == BCst->getValue())
807 return LHS;
808 else if (NewMask == DCst->getValue())
809 return RHS;
810 }
Craig Topperae48cb22012-12-20 07:15:54 +0000811 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000812 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000813 // We already know that B & C == C && D & E == E.
814 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
815 // C and E, which are shared by both the mask B and the mask D, don't
816 // contradict, then we can transform to
817 // -> (icmp eq (A & (B|D)), (C|E))
818 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000819 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000820 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000821 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000822 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000823 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000824 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000825 if (!ECst) return nullptr;
David Majnemer1a3327b2014-11-18 09:31:36 +0000826 if (LHSCC != NEWCC)
827 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000828 if (RHSCC != NEWCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000829 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Owen Anderson3fe002d2010-09-08 22:16:17 +0000830 // if there is a conflict we should actually return a false for the
831 // whole construct
David Majnemer1a3327b2014-11-18 09:31:36 +0000832 if (((BCst->getValue() & DCst->getValue()) &
833 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000834 return ConstantInt::get(LHS->getType(), !IsAnd);
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000835 Value *newOr1 = Builder->CreateOr(B, D);
836 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
837 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000838 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
839 }
Craig Topperf40110f2014-04-25 05:29:35 +0000840 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000841}
842
Erik Ecksteind1817522014-12-03 10:39:15 +0000843/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
844/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
845/// If \p Inverted is true then the check is for the inverted range, e.g.
846/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
847Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
848 bool Inverted) {
849 // Check the lower range comparison, e.g. x >= 0
850 // InstCombine already ensured that if there is a constant it's on the RHS.
851 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
852 if (!RangeStart)
853 return nullptr;
854
855 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
856 Cmp0->getPredicate());
857
858 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
859 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
860 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
861 return nullptr;
862
863 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
864 Cmp1->getPredicate());
865
866 Value *Input = Cmp0->getOperand(0);
867 Value *RangeEnd;
868 if (Cmp1->getOperand(0) == Input) {
869 // For the upper range compare we have: icmp x, n
870 RangeEnd = Cmp1->getOperand(1);
871 } else if (Cmp1->getOperand(1) == Input) {
872 // For the upper range compare we have: icmp n, x
873 RangeEnd = Cmp1->getOperand(0);
874 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
875 } else {
876 return nullptr;
877 }
878
879 // Check the upper range comparison, e.g. x < n
880 ICmpInst::Predicate NewPred;
881 switch (Pred1) {
882 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
883 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
884 default: return nullptr;
885 }
886
887 // This simplification is only valid if the upper range is not negative.
888 bool IsNegative, IsNotNegative;
889 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, DL, 0, AT,
890 Cmp1, DT);
891 if (!IsNotNegative)
892 return nullptr;
893
894 if (Inverted)
895 NewPred = ICmpInst::getInversePredicate(NewPred);
896
897 return Builder->CreateICmp(NewPred, Input, RangeEnd);
898}
899
Chris Lattner0a8191e2010-01-05 07:50:36 +0000900/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000901Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000902 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
903
904 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
905 if (PredicatesFoldable(LHSCC, RHSCC)) {
906 if (LHS->getOperand(0) == RHS->getOperand(1) &&
907 LHS->getOperand(1) == RHS->getOperand(0))
908 LHS->swapOperands();
909 if (LHS->getOperand(0) == RHS->getOperand(0) &&
910 LHS->getOperand(1) == RHS->getOperand(1)) {
911 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
912 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
913 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000914 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915 }
916 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000917
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000918 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000919 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000920 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000921
Erik Ecksteind1817522014-12-03 10:39:15 +0000922 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
923 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
924 return V;
925
926 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
927 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
928 return V;
929
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
931 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
932 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
933 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000934 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000935
Chris Lattner0a8191e2010-01-05 07:50:36 +0000936 if (LHSCst == RHSCst && LHSCC == RHSCC) {
937 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
938 // where C is a power of 2
939 if (LHSCC == ICmpInst::ICMP_ULT &&
940 LHSCst->getValue().isPowerOf2()) {
941 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000942 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000943 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000944
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
946 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
947 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000948 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949 }
950 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000951
Benjamin Kramer101720f2011-04-28 20:09:57 +0000952 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000953 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000954 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000955 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000956 LHS->hasOneUse() && RHS->hasOneUse()) {
957 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000958 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000959
960 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000961 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000962 if (match(Val2, m_Trunc(m_Value(V))) &&
963 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
964 SmallCst = RHSCst;
965 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000966 } else if (match(Val, m_Trunc(m_Value(V))) &&
967 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000968 SmallCst = LHSCst;
969 BigCst = RHSCst;
970 }
971
972 if (SmallCst && BigCst) {
973 unsigned BigBitSize = BigCst->getType()->getBitWidth();
974 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
975
976 // Check that the low bits are zero.
977 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000978 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000979 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
980 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
981 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
982 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
983 }
984 }
985 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000986
Chris Lattner0a8191e2010-01-05 07:50:36 +0000987 // From here on, we only handle:
988 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000989 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000990
Chris Lattner0a8191e2010-01-05 07:50:36 +0000991 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
992 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
993 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
994 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
995 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000996 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000997
998 // Make a constant range that's the intersection of the two icmp ranges.
999 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +00001000 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +00001001 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001002 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +00001003 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
1004
1005 if (LHSRange.intersectWith(RHSRange).isEmptySet())
1006 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1007
Chris Lattner0a8191e2010-01-05 07:50:36 +00001008 // We can't fold (ugt x, C) & (sgt x, C2).
1009 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001010 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001011
Chris Lattner0a8191e2010-01-05 07:50:36 +00001012 // Ensure that the larger constant is on the RHS.
1013 bool ShouldSwap;
1014 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001015 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001016 CmpInst::isSigned(RHSCC)))
1017 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1018 else
1019 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001020
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 if (ShouldSwap) {
1022 std::swap(LHS, RHS);
1023 std::swap(LHSCst, RHSCst);
1024 std::swap(LHSCC, RHSCC);
1025 }
1026
Dan Gohman4a618822010-02-10 16:03:48 +00001027 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028 // comparing a value against two constants and and'ing the result
1029 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001030 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1031 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001032 // are not equal and that the larger constant is on the RHS
1033 assert(LHSCst != RHSCst && "Compares not folded above?");
1034
1035 switch (LHSCC) {
1036 default: llvm_unreachable("Unknown integer condition code!");
1037 case ICmpInst::ICMP_EQ:
1038 switch (RHSCC) {
1039 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001040 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1041 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1042 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +00001043 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001044 }
1045 case ICmpInst::ICMP_NE:
1046 switch (RHSCC) {
1047 default: llvm_unreachable("Unknown integer condition code!");
1048 case ICmpInst::ICMP_ULT:
1049 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001050 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001051 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1052 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001053 break; // (X != 13 & X u< 15) -> no change
1054 case ICmpInst::ICMP_SLT:
1055 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001056 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001057 break; // (X != 13 & X s< 15) -> no change
1058 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1059 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1060 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001061 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001062 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001063 // Special case to get the ordering right when the values wrap around
1064 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001065 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001066 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001067 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1068 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1069 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001070 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1071 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001072 }
1073 break; // (X != 13 & X != 15) -> no change
1074 }
1075 break;
1076 case ICmpInst::ICMP_ULT:
1077 switch (RHSCC) {
1078 default: llvm_unreachable("Unknown integer condition code!");
1079 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1080 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001081 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001082 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1083 break;
1084 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1085 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001086 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001087 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1088 break;
1089 }
1090 break;
1091 case ICmpInst::ICMP_SLT:
1092 switch (RHSCC) {
1093 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001094 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1095 break;
1096 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1097 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001098 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001099 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1100 break;
1101 }
1102 break;
1103 case ICmpInst::ICMP_UGT:
1104 switch (RHSCC) {
1105 default: llvm_unreachable("Unknown integer condition code!");
1106 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1107 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001108 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001109 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1110 break;
1111 case ICmpInst::ICMP_NE:
1112 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001113 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001114 break; // (X u> 13 & X != 15) -> no change
1115 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001116 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001117 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1118 break;
1119 }
1120 break;
1121 case ICmpInst::ICMP_SGT:
1122 switch (RHSCC) {
1123 default: llvm_unreachable("Unknown integer condition code!");
1124 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1125 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001126 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001127 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1128 break;
1129 case ICmpInst::ICMP_NE:
1130 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001131 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001132 break; // (X s> 13 & X != 15) -> no change
1133 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001134 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001135 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1136 break;
1137 }
1138 break;
1139 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001140
Craig Topperf40110f2014-04-25 05:29:35 +00001141 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001142}
1143
Chris Lattner067459c2010-03-05 08:46:26 +00001144/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1145/// instcombine, this returns a Value which should already be inserted into the
1146/// function.
1147Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001148 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1149 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001150 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001151 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001152
Chris Lattner0a8191e2010-01-05 07:50:36 +00001153 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1154 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1155 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1156 // If either of the constants are nans, then the whole thing returns
1157 // false.
1158 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001159 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001160 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001161 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001162
Chris Lattner0a8191e2010-01-05 07:50:36 +00001163 // Handle vector zeros. This occurs because the canonical form of
1164 // "fcmp ord x,x" is "fcmp ord x, 0".
1165 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1166 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001167 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001168 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001169 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001170
Chris Lattner0a8191e2010-01-05 07:50:36 +00001171 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1172 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1173 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001174
1175
Chris Lattner0a8191e2010-01-05 07:50:36 +00001176 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1177 // Swap RHS operands to match LHS.
1178 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1179 std::swap(Op1LHS, Op1RHS);
1180 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001181
Chris Lattner0a8191e2010-01-05 07:50:36 +00001182 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1183 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1184 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001185 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001186 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001187 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001188 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001189 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001190 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001191 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001192
Chris Lattner0a8191e2010-01-05 07:50:36 +00001193 bool Op0Ordered;
1194 bool Op1Ordered;
1195 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1196 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001197 // uno && ord -> false
1198 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1199 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001200 if (Op1Pred == 0) {
1201 std::swap(LHS, RHS);
1202 std::swap(Op0Pred, Op1Pred);
1203 std::swap(Op0Ordered, Op1Ordered);
1204 }
1205 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001206 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001207 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001208 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1209 return LHS;
1210 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001211 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001212
Chris Lattner0a8191e2010-01-05 07:50:36 +00001213 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001214 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001215 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001216 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001217 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001218 }
1219 }
1220
Craig Topperf40110f2014-04-25 05:29:35 +00001221 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001222}
1223
Chris Lattner0a8191e2010-01-05 07:50:36 +00001224Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001225 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1227
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001228 if (Value *V = SimplifyVectorOp(I))
1229 return ReplaceInstUsesWith(I, V);
1230
Hal Finkel60db0582014-09-07 18:57:58 +00001231 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AT))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001232 return ReplaceInstUsesWith(I, V);
1233
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001234 // (A|B)&(A|C) -> A|(B&C) etc
1235 if (Value *V = SimplifyUsingDistributiveLaws(I))
1236 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001237
Craig Topper9d4171a2012-12-20 07:09:41 +00001238 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001239 // purpose is to compute bits we don't care about.
1240 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001241 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001242
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001243 if (Value *V = SimplifyBSwap(I))
1244 return ReplaceInstUsesWith(I, V);
1245
Chris Lattner0a8191e2010-01-05 07:50:36 +00001246 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1247 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001248
1249 // Optimize a variety of ((val OP C1) & C2) combinations...
1250 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1251 Value *Op0LHS = Op0I->getOperand(0);
1252 Value *Op0RHS = Op0I->getOperand(1);
1253 switch (Op0I->getOpcode()) {
1254 default: break;
1255 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001256 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001257 // If the mask is only needed on one incoming arm, push it up.
1258 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001259
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001260 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001261 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262 // Not masking anything out for the LHS, move to RHS.
1263 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1264 Op0RHS->getName()+".masked");
1265 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1266 }
1267 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001268 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001269 // Not masking anything out for the RHS, move to LHS.
1270 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1271 Op0LHS->getName()+".masked");
1272 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1273 }
1274
1275 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001276 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001277 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001278 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1279 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1280 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001281 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1282 return BinaryOperator::CreateAnd(V, AndRHS);
1283 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1284 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1285 break;
1286
1287 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001288 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1289 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1290 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001291 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1292 return BinaryOperator::CreateAnd(V, AndRHS);
1293
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001294 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001295 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001296 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001297 uint32_t BitWidth = AndRHSMask.getBitWidth();
1298 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1299 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1300
Hal Finkel60db0582014-09-07 18:57:58 +00001301 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001302 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1303 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1304 }
1305 }
1306 break;
1307
1308 case Instruction::Shl:
1309 case Instruction::LShr:
1310 // (1 << x) & 1 --> zext(x == 0)
1311 // (1 >> x) & 1 --> zext(x == 0)
1312 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1313 Value *NewICmp =
1314 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1315 return new ZExtInst(NewICmp, I.getType());
1316 }
1317 break;
1318 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001319
Chris Lattner0a8191e2010-01-05 07:50:36 +00001320 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1321 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1322 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001323 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001324
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001325 // If this is an integer truncation, and if the source is an 'and' with
1326 // immediate, transform it. This frequently occurs for bitfield accesses.
1327 {
Craig Topperf40110f2014-04-25 05:29:35 +00001328 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001329 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1330 // Change: and (trunc (and X, YC) to T), C2
1331 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001332 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001333 // other simplifications.
1334 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1335 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1336 C3 = ConstantExpr::getAnd(C3, AndRHS);
1337 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001338 }
1339 }
1340
1341 // Try to fold constant and into select arguments.
1342 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1343 if (Instruction *R = FoldOpIntoSelect(I, SI))
1344 return R;
1345 if (isa<PHINode>(Op0))
1346 if (Instruction *NV = FoldOpIntoPhi(I))
1347 return NV;
1348 }
1349
1350
1351 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1352 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1353 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1354 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1355 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1356 I.getName()+".demorgan");
1357 return BinaryOperator::CreateNot(Or);
1358 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001359
Chris Lattner0a8191e2010-01-05 07:50:36 +00001360 {
Craig Topperf40110f2014-04-25 05:29:35 +00001361 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001362 // (A|B) & ~(A&B) -> A^B
1363 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1364 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1365 ((A == C && B == D) || (A == D && B == C)))
1366 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001367
Chris Lattner0a8191e2010-01-05 07:50:36 +00001368 // ~(A&B) & (A|B) -> A^B
1369 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1370 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1371 ((A == C && B == D) || (A == D && B == C)))
1372 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001373
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001374 // A&(A^B) => A & ~B
1375 {
1376 Value *tmpOp0 = Op0;
1377 Value *tmpOp1 = Op1;
1378 if (Op0->hasOneUse() &&
1379 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1380 if (A == Op1 || B == Op1 ) {
1381 tmpOp1 = Op0;
1382 tmpOp0 = Op1;
1383 // Simplify below
1384 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001386
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001387 if (tmpOp1->hasOneUse() &&
1388 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1389 if (B == tmpOp0) {
1390 std::swap(A, B);
1391 }
1392 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1393 // A is originally -1 (or a vector of -1 and undefs), then we enter
1394 // an endless loop. By checking that A is non-constant we ensure that
1395 // we will never get to the loop.
1396 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001397 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001398 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001399 }
1400
1401 // (A&((~A)|B)) -> A&B
1402 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1403 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1404 return BinaryOperator::CreateAnd(A, Op1);
1405 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1406 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1407 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001408
1409 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1410 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1411 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1412 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1413 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1414
1415 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1416 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1417 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1418 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1419 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001420
1421 // (A | B) & ((~A) ^ B) -> (A & B)
1422 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1423 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1424 return BinaryOperator::CreateAnd(A, B);
1425
1426 // ((~A) ^ B) & (A | B) -> (A & B)
1427 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1428 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1429 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001430 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001431
David Majnemer5e96f1b2014-08-30 06:18:20 +00001432 {
1433 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1434 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1435 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001436 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1437 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001438
David Majnemer5e96f1b2014-08-30 06:18:20 +00001439 // TODO: Make this recursive; it's a little tricky because an arbitrary
1440 // number of 'and' instructions might have to be created.
1441 Value *X, *Y;
1442 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1443 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1444 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1445 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1446 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1447 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1448 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1449 }
1450 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1451 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1452 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1453 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1454 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1455 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1456 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1457 }
1458 }
1459
Chris Lattner4e8137d2010-02-11 06:26:33 +00001460 // If and'ing two fcmp, try combine them into one.
1461 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1462 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001463 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1464 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001465
1466
Chris Lattner0a8191e2010-01-05 07:50:36 +00001467 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1468 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001469 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001470 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001471 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1472 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001473 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001474 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001475
Chris Lattner4e8137d2010-02-11 06:26:33 +00001476 // Only do this if the casts both really cause code to be generated.
1477 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1478 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1479 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001480 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1481 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001482
Chris Lattner4e8137d2010-02-11 06:26:33 +00001483 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1484 // cast is otherwise not optimizable. This happens for vector sexts.
1485 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1486 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001487 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001488 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001489
Chris Lattner4e8137d2010-02-11 06:26:33 +00001490 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1491 // cast is otherwise not optimizable. This happens for vector sexts.
1492 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1493 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001494 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001495 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001496 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001497 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001498
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001499 {
Craig Topperf40110f2014-04-25 05:29:35 +00001500 Value *X = nullptr;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001501 bool OpsSwapped = false;
1502 // Canonicalize SExt or Not to the LHS
1503 if (match(Op1, m_SExt(m_Value())) ||
1504 match(Op1, m_Not(m_Value()))) {
1505 std::swap(Op0, Op1);
1506 OpsSwapped = true;
1507 }
1508
1509 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1510 if (match(Op0, m_SExt(m_Value(X))) &&
1511 X->getType()->getScalarType()->isIntegerTy(1)) {
1512 Value *Zero = Constant::getNullValue(Op1->getType());
1513 return SelectInst::Create(X, Op1, Zero);
1514 }
1515
1516 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1517 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1518 X->getType()->getScalarType()->isIntegerTy(1)) {
1519 Value *Zero = Constant::getNullValue(Op0->getType());
1520 return SelectInst::Create(X, Zero, Op1);
1521 }
1522
1523 if (OpsSwapped)
1524 std::swap(Op0, Op1);
1525 }
1526
Craig Topperf40110f2014-04-25 05:29:35 +00001527 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001528}
1529
1530/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1531/// capable of providing pieces of a bswap. The subexpression provides pieces
1532/// of a bswap if it is proven that each of the non-zero bytes in the output of
1533/// the expression came from the corresponding "byte swapped" byte in some other
1534/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1535/// we know that the expression deposits the low byte of %X into the high byte
1536/// of the bswap result and that all other bytes are zero. This expression is
1537/// accepted, the high byte of ByteValues is set to X to indicate a correct
1538/// match.
1539///
1540/// This function returns true if the match was unsuccessful and false if so.
1541/// On entry to the function the "OverallLeftShift" is a signed integer value
1542/// indicating the number of bytes that the subexpression is later shifted. For
1543/// example, if the expression is later right shifted by 16 bits, the
1544/// OverallLeftShift value would be -2 on entry. This is used to specify which
1545/// byte of ByteValues is actually being set.
1546///
1547/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1548/// byte is masked to zero by a user. For example, in (X & 255), X will be
1549/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1550/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1551/// always in the local (OverallLeftShift) coordinate space.
1552///
1553static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
Craig Topperb94011f2013-07-14 04:42:23 +00001554 SmallVectorImpl<Value *> &ByteValues) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001555 if (Instruction *I = dyn_cast<Instruction>(V)) {
1556 // If this is an or instruction, it may be an inner node of the bswap.
1557 if (I->getOpcode() == Instruction::Or) {
1558 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1559 ByteValues) ||
1560 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1561 ByteValues);
1562 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001563
Chris Lattner0a8191e2010-01-05 07:50:36 +00001564 // If this is a logical shift by a constant multiple of 8, recurse with
1565 // OverallLeftShift and ByteMask adjusted.
1566 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001567 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001568 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1569 // Ensure the shift amount is defined and of a byte value.
1570 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1571 return true;
1572
1573 unsigned ByteShift = ShAmt >> 3;
1574 if (I->getOpcode() == Instruction::Shl) {
1575 // X << 2 -> collect(X, +2)
1576 OverallLeftShift += ByteShift;
1577 ByteMask >>= ByteShift;
1578 } else {
1579 // X >>u 2 -> collect(X, -2)
1580 OverallLeftShift -= ByteShift;
1581 ByteMask <<= ByteShift;
1582 ByteMask &= (~0U >> (32-ByteValues.size()));
1583 }
1584
1585 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1586 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1587
Craig Topper9d4171a2012-12-20 07:09:41 +00001588 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001589 ByteValues);
1590 }
1591
1592 // If this is a logical 'and' with a mask that clears bytes, clear the
1593 // corresponding bytes in ByteMask.
1594 if (I->getOpcode() == Instruction::And &&
1595 isa<ConstantInt>(I->getOperand(1))) {
1596 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1597 unsigned NumBytes = ByteValues.size();
1598 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1599 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001600
Chris Lattner0a8191e2010-01-05 07:50:36 +00001601 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1602 // If this byte is masked out by a later operation, we don't care what
1603 // the and mask is.
1604 if ((ByteMask & (1 << i)) == 0)
1605 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001606
Chris Lattner0a8191e2010-01-05 07:50:36 +00001607 // If the AndMask is all zeros for this byte, clear the bit.
1608 APInt MaskB = AndMask & Byte;
1609 if (MaskB == 0) {
1610 ByteMask &= ~(1U << i);
1611 continue;
1612 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001613
Chris Lattner0a8191e2010-01-05 07:50:36 +00001614 // If the AndMask is not all ones for this byte, it's not a bytezap.
1615 if (MaskB != Byte)
1616 return true;
1617
1618 // Otherwise, this byte is kept.
1619 }
1620
Craig Topper9d4171a2012-12-20 07:09:41 +00001621 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001622 ByteValues);
1623 }
1624 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001625
Chris Lattner0a8191e2010-01-05 07:50:36 +00001626 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1627 // the input value to the bswap. Some observations: 1) if more than one byte
1628 // is demanded from this input, then it could not be successfully assembled
1629 // into a byteswap. At least one of the two bytes would not be aligned with
1630 // their ultimate destination.
1631 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001632 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001633
Chris Lattner0a8191e2010-01-05 07:50:36 +00001634 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1635 // is demanded, it needs to go into byte 0 of the result. This means that the
1636 // byte needs to be shifted until it lands in the right byte bucket. The
1637 // shift amount depends on the position: if the byte is coming from the high
1638 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1639 // low part, it must be shifted left.
1640 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001641 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1642 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001643
Chris Lattner0a8191e2010-01-05 07:50:36 +00001644 // If the destination byte value is already defined, the values are or'd
1645 // together, which isn't a bswap (unless it's an or of the same bits).
1646 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1647 return true;
1648 ByteValues[DestByteNo] = V;
1649 return false;
1650}
1651
1652/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1653/// If so, insert the new bswap intrinsic and return it.
1654Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001655 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001656 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001657 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001658 ITy->getBitWidth() > 32*8)
Craig Topperf40110f2014-04-25 05:29:35 +00001659 return nullptr; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001660
Chris Lattner0a8191e2010-01-05 07:50:36 +00001661 /// ByteValues - For each byte of the result, we keep track of which value
1662 /// defines each byte.
1663 SmallVector<Value*, 8> ByteValues;
1664 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001665
Chris Lattner0a8191e2010-01-05 07:50:36 +00001666 // Try to find all the pieces corresponding to the bswap.
1667 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1668 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Craig Topperf40110f2014-04-25 05:29:35 +00001669 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001670
Chris Lattner0a8191e2010-01-05 07:50:36 +00001671 // Check to see if all of the bytes come from the same value.
1672 Value *V = ByteValues[0];
Craig Topperf40110f2014-04-25 05:29:35 +00001673 if (!V) return nullptr; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001674
Chris Lattner0a8191e2010-01-05 07:50:36 +00001675 // Check to make sure that all of the bytes come from the same value.
1676 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1677 if (ByteValues[i] != V)
Craig Topperf40110f2014-04-25 05:29:35 +00001678 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001679 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001680 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001681 return CallInst::Create(F, V);
1682}
1683
1684/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1685/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1686/// we can simplify this expression to "cond ? C : D or B".
1687static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1688 Value *C, Value *D) {
1689 // If A is not a select of -1/0, this cannot match.
Craig Topperf40110f2014-04-25 05:29:35 +00001690 Value *Cond = nullptr;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001691 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001692 !Cond->getType()->isIntegerTy(1))
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001694
1695 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001696 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001697 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001698 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001699 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001700
Chris Lattner0a8191e2010-01-05 07:50:36 +00001701 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001702 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001703 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001704 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001705 return SelectInst::Create(Cond, C, D);
Craig Topperf40110f2014-04-25 05:29:35 +00001706 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001707}
1708
Chris Lattner067459c2010-03-05 08:46:26 +00001709/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001710Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1711 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001712 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1713
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001714 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1715 // if K1 and K2 are a one-bit mask.
1716 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1717 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1718
1719 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1720 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1721
1722 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1723 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1724 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1725 LAnd->getOpcode() == Instruction::And &&
1726 RAnd->getOpcode() == Instruction::And) {
1727
Craig Topperf40110f2014-04-25 05:29:35 +00001728 Value *Mask = nullptr;
1729 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001730 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001731 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), false, 0, AT, CxtI, DT) &&
1732 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), false, 0, AT, CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001733 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1734 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1735 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001736 isKnownToBeAPowerOfTwo(LAnd->getOperand(0),
1737 false, 0, AT, CxtI, DT) &&
1738 isKnownToBeAPowerOfTwo(RAnd->getOperand(0),
1739 false, 0, AT, CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001740 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1741 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1742 }
1743
1744 if (Masked)
1745 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1746 }
1747 }
1748
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001749 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1750 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1751 // The original condition actually refers to the following two ranges:
1752 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1753 // We can fold these two ranges if:
1754 // 1) C1 and C2 is unsigned greater than C3.
1755 // 2) The two ranges are separated.
1756 // 3) C1 ^ C2 is one-bit mask.
1757 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1758 // This implies all values in the two ranges differ by exactly one bit.
1759
1760 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1761 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1762 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1763 LHSCst->getValue() == (RHSCst->getValue())) {
1764
1765 Value *LAdd = LHS->getOperand(0);
1766 Value *RAdd = RHS->getOperand(0);
1767
1768 Value *LAddOpnd, *RAddOpnd;
1769 ConstantInt *LAddCst, *RAddCst;
1770 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1771 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1772 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1773 RAddCst->getValue().ugt(LHSCst->getValue())) {
1774
1775 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1776 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1777 ConstantInt *MaxAddCst = nullptr;
1778 if (LAddCst->getValue().ult(RAddCst->getValue()))
1779 MaxAddCst = RAddCst;
1780 else
1781 MaxAddCst = LAddCst;
1782
1783 APInt RRangeLow = -RAddCst->getValue();
1784 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1785 APInt LRangeLow = -LAddCst->getValue();
1786 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1787 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1788 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1789 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1790 : RRangeLow - LRangeLow;
1791
1792 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1793 RangeDiff.ugt(LHSCst->getValue())) {
1794 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1795
1796 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1797 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1798 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1799 }
1800 }
1801 }
1802 }
1803
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1805 if (PredicatesFoldable(LHSCC, RHSCC)) {
1806 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1807 LHS->getOperand(1) == RHS->getOperand(0))
1808 LHS->swapOperands();
1809 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1810 LHS->getOperand(1) == RHS->getOperand(1)) {
1811 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1812 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1813 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001814 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001815 }
1816 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001817
1818 // handle (roughly):
1819 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001820 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001821 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001822
Chris Lattner0a8191e2010-01-05 07:50:36 +00001823 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001824 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1825 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1826 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001827 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001828 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1829 B = Val;
1830 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1831 A = Val2;
1832 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1833 A = RHS->getOperand(1);
1834 }
1835 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1836 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1837 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1838 B = Val2;
1839 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1840 A = Val;
1841 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1842 A = LHS->getOperand(1);
1843 }
1844 if (A && B)
1845 return Builder->CreateICmp(
1846 ICmpInst::ICMP_UGE,
1847 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1848 }
1849
Erik Ecksteind1817522014-12-03 10:39:15 +00001850 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1851 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1852 return V;
1853
1854 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1855 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1856 return V;
1857
David Majnemerc2a990b2013-07-05 00:31:17 +00001858 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001859 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001860
Owen Anderson8f306a72010-08-02 09:32:13 +00001861 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1862 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1863 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1864 Value *NewOr = Builder->CreateOr(Val, Val2);
1865 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1866 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001867 }
1868
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001869 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001870 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001871 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001872 ConstantInt *AddCst;
1873 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1874 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001875 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001876 }
1877
Chris Lattner0a8191e2010-01-05 07:50:36 +00001878 // From here on, we only handle:
1879 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001880 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001881
Chris Lattner0a8191e2010-01-05 07:50:36 +00001882 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1883 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1884 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1885 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1886 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001887 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001888
Chris Lattner0a8191e2010-01-05 07:50:36 +00001889 // We can't fold (ugt x, C) | (sgt x, C2).
1890 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001891 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001892
Chris Lattner0a8191e2010-01-05 07:50:36 +00001893 // Ensure that the larger constant is on the RHS.
1894 bool ShouldSwap;
1895 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001896 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897 CmpInst::isSigned(RHSCC)))
1898 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1899 else
1900 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001901
Chris Lattner0a8191e2010-01-05 07:50:36 +00001902 if (ShouldSwap) {
1903 std::swap(LHS, RHS);
1904 std::swap(LHSCst, RHSCst);
1905 std::swap(LHSCC, RHSCC);
1906 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001907
Dan Gohman4a618822010-02-10 16:03:48 +00001908 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909 // comparing a value against two constants and or'ing the result
1910 // together. Because of the above check, we know that we only have
1911 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1912 // icmp folding check above), that the two constants are not
1913 // equal.
1914 assert(LHSCst != RHSCst && "Compares not folded above?");
1915
1916 switch (LHSCC) {
1917 default: llvm_unreachable("Unknown integer condition code!");
1918 case ICmpInst::ICMP_EQ:
1919 switch (RHSCC) {
1920 default: llvm_unreachable("Unknown integer condition code!");
1921 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001922 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001923 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001924 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001925 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1926
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001927 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1928 if (Xor.isPowerOf2()) {
1929 Value *NegCst = Builder->getInt(~Xor);
1930 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1931 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1932 }
1933 }
1934
David Majnemer1fae1952013-04-14 21:15:43 +00001935 if (LHSCst == SubOne(RHSCst)) {
1936 // (X == 13 | X == 14) -> X-13 <u 2
1937 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1938 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1939 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1940 return Builder->CreateICmpULT(Add, AddCST);
1941 }
1942
Chris Lattner0a8191e2010-01-05 07:50:36 +00001943 break; // (X == 13 | X == 15) -> no change
1944 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1945 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1946 break;
1947 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1948 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1949 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001950 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001951 }
1952 break;
1953 case ICmpInst::ICMP_NE:
1954 switch (RHSCC) {
1955 default: llvm_unreachable("Unknown integer condition code!");
1956 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1957 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1958 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001959 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001960 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1961 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1962 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001963 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001964 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001965 case ICmpInst::ICMP_ULT:
1966 switch (RHSCC) {
1967 default: llvm_unreachable("Unknown integer condition code!");
1968 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1969 break;
1970 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1971 // If RHSCst is [us]MAXINT, it is always false. Not handling
1972 // this can cause overflow.
1973 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001974 return LHS;
1975 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001976 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1977 break;
1978 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1979 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001980 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001981 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1982 break;
1983 }
1984 break;
1985 case ICmpInst::ICMP_SLT:
1986 switch (RHSCC) {
1987 default: llvm_unreachable("Unknown integer condition code!");
1988 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1989 break;
1990 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1991 // If RHSCst is [us]MAXINT, it is always false. Not handling
1992 // this can cause overflow.
1993 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001994 return LHS;
1995 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001996 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1997 break;
1998 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1999 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00002000 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002001 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2002 break;
2003 }
2004 break;
2005 case ICmpInst::ICMP_UGT:
2006 switch (RHSCC) {
2007 default: llvm_unreachable("Unknown integer condition code!");
2008 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2009 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00002010 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002011 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2012 break;
2013 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2014 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002015 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002016 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2017 break;
2018 }
2019 break;
2020 case ICmpInst::ICMP_SGT:
2021 switch (RHSCC) {
2022 default: llvm_unreachable("Unknown integer condition code!");
2023 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2024 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00002025 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002026 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2027 break;
2028 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2029 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002030 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002031 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2032 break;
2033 }
2034 break;
2035 }
Craig Topperf40110f2014-04-25 05:29:35 +00002036 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037}
2038
Chris Lattner067459c2010-03-05 08:46:26 +00002039/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
2040/// instcombine, this returns a Value which should already be inserted into the
2041/// function.
2042Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002043 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002044 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002045 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2046 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2047 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2048 // If either of the constants are nans, then the whole thing returns
2049 // true.
2050 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002051 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002052
Chris Lattner0a8191e2010-01-05 07:50:36 +00002053 // Otherwise, no need to compare the two constants, compare the
2054 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002055 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002056 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002057
Chris Lattner0a8191e2010-01-05 07:50:36 +00002058 // Handle vector zeros. This occurs because the canonical form of
2059 // "fcmp uno x,x" is "fcmp uno x, 0".
2060 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2061 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002062 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002063
Craig Topperf40110f2014-04-25 05:29:35 +00002064 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002065 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002066
Chris Lattner0a8191e2010-01-05 07:50:36 +00002067 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2068 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2069 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00002070
Chris Lattner0a8191e2010-01-05 07:50:36 +00002071 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2072 // Swap RHS operands to match LHS.
2073 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2074 std::swap(Op1LHS, Op1RHS);
2075 }
2076 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2077 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2078 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00002079 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002080 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00002081 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002082 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002083 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002084 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002085 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086 bool Op0Ordered;
2087 bool Op1Ordered;
2088 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2089 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2090 if (Op0Ordered == Op1Ordered) {
2091 // If both are ordered or unordered, return a new fcmp with
2092 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00002093 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002094 }
2095 }
Craig Topperf40110f2014-04-25 05:29:35 +00002096 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097}
2098
2099/// FoldOrWithConstants - This helper function folds:
2100///
2101/// ((A | B) & C1) | (B & C2)
2102///
2103/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002104///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002105/// (A & C1) | B
2106///
2107/// when the XOR of the two constants is "all ones" (-1).
2108Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2109 Value *A, Value *B, Value *C) {
2110 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002111 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002112
Craig Topperf40110f2014-04-25 05:29:35 +00002113 Value *V1 = nullptr;
2114 ConstantInt *CI2 = nullptr;
2115 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002116
2117 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002118 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002119
2120 if (V1 == A || V1 == B) {
2121 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2122 return BinaryOperator::CreateOr(NewOp, V1);
2123 }
2124
Craig Topperf40110f2014-04-25 05:29:35 +00002125 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002126}
2127
David Majnemer5d1aeba2014-08-21 05:14:48 +00002128/// \brief This helper function folds:
2129///
2130/// ((A | B) & C1) ^ (B & C2)
2131///
2132/// into:
2133///
2134/// (A & C1) ^ B
2135///
2136/// when the XOR of the two constants is "all ones" (-1).
2137Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2138 Value *A, Value *B, Value *C) {
2139 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2140 if (!CI1)
2141 return nullptr;
2142
2143 Value *V1 = nullptr;
2144 ConstantInt *CI2 = nullptr;
2145 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2146 return nullptr;
2147
2148 APInt Xor = CI1->getValue() ^ CI2->getValue();
2149 if (!Xor.isAllOnesValue())
2150 return nullptr;
2151
2152 if (V1 == A || V1 == B) {
2153 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2154 return BinaryOperator::CreateXor(NewOp, V1);
2155 }
2156
2157 return nullptr;
2158}
2159
Chris Lattner0a8191e2010-01-05 07:50:36 +00002160Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002161 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2163
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002164 if (Value *V = SimplifyVectorOp(I))
2165 return ReplaceInstUsesWith(I, V);
2166
Hal Finkel60db0582014-09-07 18:57:58 +00002167 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AT))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002168 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002169
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002170 // (A&B)|(A&C) -> A&(B|C) etc
2171 if (Value *V = SimplifyUsingDistributiveLaws(I))
2172 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002173
Craig Topper9d4171a2012-12-20 07:09:41 +00002174 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002175 // purpose is to compute bits we don't care about.
2176 if (SimplifyDemandedInstructionBits(I))
2177 return &I;
2178
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002179 if (Value *V = SimplifyBSwap(I))
2180 return ReplaceInstUsesWith(I, V);
2181
Chris Lattner0a8191e2010-01-05 07:50:36 +00002182 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002183 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002184 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002185 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002186 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002187 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002188 Op0->hasOneUse()) {
2189 Value *Or = Builder->CreateOr(X, RHS);
2190 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002191 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002192 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002193 }
2194
2195 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2196 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2197 Op0->hasOneUse()) {
2198 Value *Or = Builder->CreateOr(X, RHS);
2199 Or->takeName(Op0);
2200 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002201 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002202 }
2203
2204 // Try to fold constant and into select arguments.
2205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2206 if (Instruction *R = FoldOpIntoSelect(I, SI))
2207 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002208
Chris Lattner0a8191e2010-01-05 07:50:36 +00002209 if (isa<PHINode>(Op0))
2210 if (Instruction *NV = FoldOpIntoPhi(I))
2211 return NV;
2212 }
2213
Craig Topperf40110f2014-04-25 05:29:35 +00002214 Value *A = nullptr, *B = nullptr;
2215 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002216
2217 // (A | B) | C and A | (B | C) -> bswap if possible.
2218 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
2219 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2220 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00002221 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2222 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002223 if (Instruction *BSwap = MatchBSwap(I))
2224 return BSwap;
2225 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002226
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002227 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002228 if (Op0->hasOneUse() &&
2229 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002230 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002231 Value *NOr = Builder->CreateOr(A, Op1);
2232 NOr->takeName(Op0);
2233 return BinaryOperator::CreateXor(NOr, C1);
2234 }
2235
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002236 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002237 if (Op1->hasOneUse() &&
2238 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002239 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002240 Value *NOr = Builder->CreateOr(A, Op0);
2241 NOr->takeName(Op0);
2242 return BinaryOperator::CreateXor(NOr, C1);
2243 }
2244
Suyog Sardad64faf62014-07-22 18:09:41 +00002245 // ((~A & B) | A) -> (A | B)
2246 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2247 match(Op1, m_Specific(A)))
2248 return BinaryOperator::CreateOr(A, B);
2249
2250 // ((A & B) | ~A) -> (~A | B)
2251 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2252 match(Op1, m_Not(m_Specific(A))))
2253 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2254
Suyog Sarda52324c82014-08-01 04:50:31 +00002255 // (A & (~B)) | (A ^ B) -> (A ^ B)
2256 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2257 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2258 return BinaryOperator::CreateXor(A, B);
2259
2260 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2261 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2262 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2263 return BinaryOperator::CreateXor(A, B);
2264
Chris Lattner0a8191e2010-01-05 07:50:36 +00002265 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002266 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002267 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2268 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002269 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002270 C1 = dyn_cast<ConstantInt>(C);
2271 C2 = dyn_cast<ConstantInt>(D);
2272 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002273 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002274 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002275 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002276 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002277 ((V1 == B &&
2278 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2279 (V2 == B &&
2280 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002281 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002282 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002283 // Or commutes, try both ways.
2284 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002285 ((V1 == A &&
2286 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2287 (V2 == A &&
2288 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002289 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002290 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002291
Chris Lattner95188692010-01-11 06:55:24 +00002292 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002293 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002294 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002295 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2296 (C3->getValue() & ~C1->getValue()) == 0 &&
2297 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2298 (C4->getValue() & ~C2->getValue()) == 0) {
2299 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2300 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002301 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002302 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002303 }
2304 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002305
Chris Lattner8e2c4712010-02-02 02:43:51 +00002306 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2307 // Don't do this for vector select idioms, the code generator doesn't handle
2308 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002309 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002310 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2311 return Match;
2312 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2313 return Match;
2314 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2315 return Match;
2316 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2317 return Match;
2318 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002319
2320 // ((A&~B)|(~A&B)) -> A^B
2321 if ((match(C, m_Not(m_Specific(D))) &&
2322 match(B, m_Not(m_Specific(A)))))
2323 return BinaryOperator::CreateXor(A, D);
2324 // ((~B&A)|(~A&B)) -> A^B
2325 if ((match(A, m_Not(m_Specific(D))) &&
2326 match(B, m_Not(m_Specific(C)))))
2327 return BinaryOperator::CreateXor(C, D);
2328 // ((A&~B)|(B&~A)) -> A^B
2329 if ((match(C, m_Not(m_Specific(B))) &&
2330 match(D, m_Not(m_Specific(A)))))
2331 return BinaryOperator::CreateXor(A, B);
2332 // ((~B&A)|(B&~A)) -> A^B
2333 if ((match(A, m_Not(m_Specific(B))) &&
2334 match(D, m_Not(m_Specific(C)))))
2335 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002336
2337 // ((A|B)&1)|(B&-2) -> (A&1) | B
2338 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2339 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2340 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2341 if (Ret) return Ret;
2342 }
2343 // (B&-2)|((A|B)&1) -> (A&1) | B
2344 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2345 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2346 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2347 if (Ret) return Ret;
2348 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002349 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2350 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2351 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2352 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2353 if (Ret) return Ret;
2354 }
2355 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2356 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2357 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2358 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2359 if (Ret) return Ret;
2360 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002361 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002362
David Majnemer42af3602014-07-30 21:26:37 +00002363 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2364 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2365 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2366 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2367 return BinaryOperator::CreateOr(Op0, C);
2368
2369 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2370 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2371 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2372 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2373 return BinaryOperator::CreateOr(Op1, C);
2374
David Majnemerf1eda232014-08-14 06:41:38 +00002375 // ((B | C) & A) | B -> B | (A & C)
2376 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2377 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2378
Chris Lattner0a8191e2010-01-05 07:50:36 +00002379 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2380 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2381 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2382 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2383 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2384 I.getName()+".demorgan");
2385 return BinaryOperator::CreateNot(And);
2386 }
2387
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002388 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002389 bool SwappedForXor = false;
2390 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002391 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002392 SwappedForXor = true;
2393 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002394
2395 // A | ( A ^ B) -> A | B
2396 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002397 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002398 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2399 if (Op0 == A || Op0 == B)
2400 return BinaryOperator::CreateOr(A, B);
2401
Chad Rosier7813dce2012-04-26 23:29:14 +00002402 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2403 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2404 return BinaryOperator::CreateOr(A, B);
2405
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002406 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2407 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2408 return BinaryOperator::CreateOr(Not, Op0);
2409 }
2410 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2411 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2412 return BinaryOperator::CreateOr(Not, Op0);
2413 }
2414 }
2415
2416 // A | ~(A | B) -> A | ~B
2417 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002418 if (match(Op1, m_Not(m_Value(A))))
2419 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002420 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2421 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2422 B->getOpcode() == Instruction::Xor)) {
2423 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2424 B->getOperand(0);
2425 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2426 return BinaryOperator::CreateOr(Not, Op0);
2427 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002428
Suyog Sarda16d64652014-08-01 04:41:43 +00002429 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2430 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2431 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2432 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2433
2434 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2435 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2436 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2437 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2438
Eli Friedmane06535b2012-03-16 00:52:42 +00002439 if (SwappedForXor)
2440 std::swap(Op0, Op1);
2441
David Majnemer3d6f80b2014-11-28 19:58:29 +00002442 {
2443 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2444 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2445 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002446 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner067459c2010-03-05 08:46:26 +00002447 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002448
David Majnemer3d6f80b2014-11-28 19:58:29 +00002449 // TODO: Make this recursive; it's a little tricky because an arbitrary
2450 // number of 'or' instructions might have to be created.
2451 Value *X, *Y;
2452 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2453 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2454 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2455 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2456 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2457 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2458 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2459 }
2460 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2461 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2462 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2463 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2464 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2465 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2466 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2467 }
2468 }
2469
Chris Lattner4e8137d2010-02-11 06:26:33 +00002470 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2471 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2472 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002473 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2474 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002475
Chris Lattner0a8191e2010-01-05 07:50:36 +00002476 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2477 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002478 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2479 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002480 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002481 if (SrcTy == Op1C->getOperand(0)->getType() &&
2482 SrcTy->isIntOrIntVectorTy()) {
2483 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002484
Chris Lattner311aa632011-01-15 05:40:29 +00002485 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2486 // Only do this if the casts both really cause code to be
2487 // generated.
2488 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2489 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2490 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2491 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002492 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002493
Chris Lattner311aa632011-01-15 05:40:29 +00002494 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2495 // cast is otherwise not optimizable. This happens for vector sexts.
2496 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2497 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Hal Finkel60db0582014-09-07 18:57:58 +00002498 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner311aa632011-01-15 05:40:29 +00002499 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002500
Chris Lattner311aa632011-01-15 05:40:29 +00002501 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2502 // cast is otherwise not optimizable. This happens for vector sexts.
2503 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2504 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2505 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2506 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002507 }
Chris Lattner311aa632011-01-15 05:40:29 +00002508 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509 }
Eli Friedman23956262011-04-14 22:41:27 +00002510
2511 // or(sext(A), B) -> A ? -1 : B where A is an i1
2512 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2513 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2514 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2515 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2516 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2517
Owen Andersonc237a842010-09-13 17:59:27 +00002518 // Note: If we've gotten to the point of visiting the outer OR, then the
2519 // inner one couldn't be simplified. If it was a constant, then it won't
2520 // be simplified by a later pass either, so we try swapping the inner/outer
2521 // ORs in the hopes that we'll be able to simplify it this way.
2522 // (X|C) | V --> (X|V) | C
2523 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2524 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2525 Value *Inner = Builder->CreateOr(A, Op1);
2526 Inner->takeName(Op0);
2527 return BinaryOperator::CreateOr(Inner, C1);
2528 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002529
Bill Wendling23242092013-02-16 23:41:36 +00002530 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2531 // Since this OR statement hasn't been optimized further yet, we hope
2532 // that this transformation will allow the new ORs to be optimized.
2533 {
Craig Topperf40110f2014-04-25 05:29:35 +00002534 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002535 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2536 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2537 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2538 Value *orTrue = Builder->CreateOr(A, C);
2539 Value *orFalse = Builder->CreateOr(B, D);
2540 return SelectInst::Create(X, orTrue, orFalse);
2541 }
2542 }
2543
Craig Topperf40110f2014-04-25 05:29:35 +00002544 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002545}
2546
2547Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002548 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002549 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2550
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002551 if (Value *V = SimplifyVectorOp(I))
2552 return ReplaceInstUsesWith(I, V);
2553
Hal Finkel60db0582014-09-07 18:57:58 +00002554 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002555 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002556
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002557 // (A&B)^(A&C) -> A&(B^C) etc
2558 if (Value *V = SimplifyUsingDistributiveLaws(I))
2559 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002560
Craig Topper9d4171a2012-12-20 07:09:41 +00002561 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002562 // purpose is to compute bits we don't care about.
2563 if (SimplifyDemandedInstructionBits(I))
2564 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002565
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002566 if (Value *V = SimplifyBSwap(I))
2567 return ReplaceInstUsesWith(I, V);
2568
Chris Lattner0a8191e2010-01-05 07:50:36 +00002569 // Is this a ~ operation?
2570 if (Value *NotOp = dyn_castNotVal(&I)) {
2571 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002572 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002573 Op0I->getOpcode() == Instruction::Or) {
2574 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2575 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2576 if (dyn_castNotVal(Op0I->getOperand(1)))
2577 Op0I->swapOperands();
2578 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2579 Value *NotY =
2580 Builder->CreateNot(Op0I->getOperand(1),
2581 Op0I->getOperand(1)->getName()+".not");
2582 if (Op0I->getOpcode() == Instruction::And)
2583 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2584 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2585 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002586
Chris Lattner0a8191e2010-01-05 07:50:36 +00002587 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2588 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Craig Topper9d4171a2012-12-20 07:09:41 +00002589 if (isFreeToInvert(Op0I->getOperand(0)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002590 isFreeToInvert(Op0I->getOperand(1))) {
2591 Value *NotX =
2592 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2593 Value *NotY =
2594 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2595 if (Op0I->getOpcode() == Instruction::And)
2596 return BinaryOperator::CreateOr(NotX, NotY);
2597 return BinaryOperator::CreateAnd(NotX, NotY);
2598 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002599
2600 } else if (Op0I->getOpcode() == Instruction::AShr) {
2601 // ~(~X >>s Y) --> (X >>s Y)
2602 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2603 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002604 }
2605 }
2606 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002607
2608
Chris Lattner0a8191e2010-01-05 07:50:36 +00002609 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002610 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002611 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002612 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2613 return CmpInst::Create(CI->getOpcode(),
2614 CI->getInversePredicate(),
2615 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002616
2617 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2618 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2619 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2620 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2621 Instruction::CastOps Opcode = Op0C->getOpcode();
2622 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002623 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002624 Op0C->getDestTy()))) {
2625 CI->setPredicate(CI->getInversePredicate());
2626 return CastInst::Create(Opcode, CI, Op0C->getType());
2627 }
2628 }
2629 }
2630 }
2631
2632 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2633 // ~(c-X) == X-c-1 == X+(-c-1)
2634 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2635 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2636 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2637 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2638 ConstantInt::get(I.getType(), 1));
2639 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2640 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002641
Chris Lattner0a8191e2010-01-05 07:50:36 +00002642 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2643 if (Op0I->getOpcode() == Instruction::Add) {
2644 // ~(X-c) --> (-c-1)-X
2645 if (RHS->isAllOnesValue()) {
2646 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2647 return BinaryOperator::CreateSub(
2648 ConstantExpr::getSub(NegOp0CI,
2649 ConstantInt::get(I.getType(), 1)),
2650 Op0I->getOperand(0));
2651 } else if (RHS->getValue().isSignBit()) {
2652 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002653 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002654 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2655
2656 }
2657 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002658 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002659 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2660 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002661 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2662 // Anything in both C1 and C2 is known to be zero, remove it from
2663 // NewRHS.
2664 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002665 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002666 ConstantExpr::getNot(CommonBits));
2667 Worklist.Add(Op0I);
2668 I.setOperand(0, Op0I->getOperand(0));
2669 I.setOperand(1, NewRHS);
2670 return &I;
2671 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002672 } else if (Op0I->getOpcode() == Instruction::LShr) {
2673 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2674 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002675 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002676 ConstantInt *C1;
2677 if (Op0I->hasOneUse() &&
2678 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2679 E1->getOpcode() == Instruction::Xor &&
2680 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2681 // fold (C1 >> C2) ^ C3
2682 ConstantInt *C2 = Op0CI, *C3 = RHS;
2683 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2684 FoldConst ^= C3->getValue();
2685 // Prepare the two operands.
2686 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2687 Opnd0->takeName(Op0I);
2688 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2689 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2690
2691 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2692 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002693 }
2694 }
2695 }
2696
2697 // Try to fold constant and into select arguments.
2698 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2699 if (Instruction *R = FoldOpIntoSelect(I, SI))
2700 return R;
2701 if (isa<PHINode>(Op0))
2702 if (Instruction *NV = FoldOpIntoPhi(I))
2703 return NV;
2704 }
2705
Chris Lattner0a8191e2010-01-05 07:50:36 +00002706 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2707 if (Op1I) {
2708 Value *A, *B;
2709 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2710 if (A == Op0) { // B^(B|A) == (A|B)^B
2711 Op1I->swapOperands();
2712 I.swapOperands();
2713 std::swap(Op0, Op1);
2714 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2715 I.swapOperands(); // Simplified below.
2716 std::swap(Op0, Op1);
2717 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002718 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002719 Op1I->hasOneUse()){
2720 if (A == Op0) { // A^(A&B) -> A^(B&A)
2721 Op1I->swapOperands();
2722 std::swap(A, B);
2723 }
2724 if (B == Op0) { // A^(B&A) -> (B&A)^A
2725 I.swapOperands(); // Simplified below.
2726 std::swap(Op0, Op1);
2727 }
2728 }
2729 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002730
Chris Lattner0a8191e2010-01-05 07:50:36 +00002731 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2732 if (Op0I) {
2733 Value *A, *B;
2734 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2735 Op0I->hasOneUse()) {
2736 if (A == Op1) // (B|A)^B == (A|B)^B
2737 std::swap(A, B);
2738 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002739 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002740 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002741 Op0I->hasOneUse()){
2742 if (A == Op1) // (A&B)^A -> (B&A)^A
2743 std::swap(A, B);
2744 if (B == Op1 && // (B&A)^A == ~B & A
2745 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002746 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002747 }
2748 }
2749 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002750
Chris Lattner0a8191e2010-01-05 07:50:36 +00002751 if (Op0I && Op1I) {
2752 Value *A, *B, *C, *D;
2753 // (A & B)^(A | B) -> A ^ B
2754 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2755 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002756 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002757 return BinaryOperator::CreateXor(A, B);
2758 }
2759 // (A | B)^(A & B) -> A ^ B
2760 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2761 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002762 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002763 return BinaryOperator::CreateXor(A, B);
2764 }
David Majnemer698dca02014-08-14 06:46:25 +00002765 // (A | ~B) ^ (~A | B) -> A ^ B
2766 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2767 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2768 return BinaryOperator::CreateXor(A, B);
2769 }
2770 // (~A | B) ^ (A | ~B) -> A ^ B
2771 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2772 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2773 return BinaryOperator::CreateXor(A, B);
2774 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002775 // (A & ~B) ^ (~A & B) -> A ^ B
2776 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2777 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2778 return BinaryOperator::CreateXor(A, B);
2779 }
2780 // (~A & B) ^ (A & ~B) -> A ^ B
2781 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2782 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2783 return BinaryOperator::CreateXor(A, B);
2784 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002785 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2786 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2787 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2788 if (D == A)
2789 return BinaryOperator::CreateXor(
2790 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2791 if (D == B)
2792 return BinaryOperator::CreateXor(
2793 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002794 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002795 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002796 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002797 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2798 if (D == A)
2799 return BinaryOperator::CreateXor(
2800 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2801 if (D == B)
2802 return BinaryOperator::CreateXor(
2803 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002804 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002805 // (A & B) ^ (A ^ B) -> (A | B)
2806 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2807 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2808 return BinaryOperator::CreateOr(A, B);
2809 // (A ^ B) ^ (A & B) -> (A | B)
2810 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2811 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2812 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002813 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002814
Suyog Sarda521237c2014-07-22 15:37:39 +00002815 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002816 // (A & ~B) ^ (~A) -> ~(A & B)
2817 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2818 match(Op1, m_Not(m_Specific(A))))
2819 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2820
Chris Lattner0a8191e2010-01-05 07:50:36 +00002821 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2822 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2823 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2824 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2825 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2826 LHS->getOperand(1) == RHS->getOperand(0))
2827 LHS->swapOperands();
2828 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2829 LHS->getOperand(1) == RHS->getOperand(1)) {
2830 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2831 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2832 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002833 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002834 getNewICmpValue(isSigned, Code, Op0, Op1,
2835 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002836 }
2837 }
2838
2839 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2840 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2841 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2842 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002843 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002844 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002845 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002846 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002847 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002848 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002849 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002850 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2851 Op1C->getOperand(0), I.getName());
2852 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2853 }
2854 }
2855 }
2856
Craig Topperf40110f2014-04-25 05:29:35 +00002857 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002858}