blob: dc41e16469e7fc87eb487a4538509f04a2ede6d6 [file] [log] [blame]
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.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 visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
16#include "llvm/IntrinsicInst.h"
Duncan Sands82fdab32010-12-21 14:00:22 +000017#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd12c27c2010-01-05 06:09:35 +000018#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattner1add46d2011-05-22 18:18:41 +000022
23/// simplifyValueKnownNonZero - The specific integer value is used in a context
24/// where it is known to be non-zero. If this allows us to simplify the
25/// computation, do so and return the new operand, otherwise return null.
26static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
27 // If V has multiple uses, then we would have to do more analysis to determine
28 // if this is safe. For example, the use could be in dynamically unreached
29 // code.
30 if (!V->hasOneUse()) return 0;
31
Chris Lattner613f1a32011-05-23 00:32:19 +000032 bool MadeChange = false;
33
Chris Lattner1add46d2011-05-22 18:18:41 +000034 // ((1 << A) >>u B) --> (1 << (A-B))
35 // Because V cannot be zero, we know that B is less than A.
Chris Lattner6083bb92011-05-23 00:09:55 +000036 Value *A = 0, *B = 0, *PowerOf2 = 0;
37 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner1add46d2011-05-22 18:18:41 +000038 m_Value(B))) &&
39 // The "1" can be any value known to be a power of 2.
Micah Villmow3574eca2012-10-08 16:38:25 +000040 isPowerOfTwo(PowerOf2, IC.getDataLayout())) {
Benjamin Kramera9390a42011-09-27 20:39:19 +000041 A = IC.Builder->CreateSub(A, B);
Chris Lattner6083bb92011-05-23 00:09:55 +000042 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner1add46d2011-05-22 18:18:41 +000043 }
44
Chris Lattner613f1a32011-05-23 00:32:19 +000045 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
46 // inexact. Similarly for <<.
47 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
48 if (I->isLogicalShift() &&
Micah Villmow3574eca2012-10-08 16:38:25 +000049 isPowerOfTwo(I->getOperand(0), IC.getDataLayout())) {
Chris Lattner613f1a32011-05-23 00:32:19 +000050 // We know that this is an exact/nuw shift and that the input is a
51 // non-zero context as well.
52 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
53 I->setOperand(0, V2);
54 MadeChange = true;
55 }
56
57 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
58 I->setIsExact();
59 MadeChange = true;
60 }
61
62 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
63 I->setHasNoUnsignedWrap();
64 MadeChange = true;
65 }
66 }
67
Chris Lattner6c9b8d32011-05-22 18:26:48 +000068 // TODO: Lots more we could do here:
Chris Lattner6c9b8d32011-05-22 18:26:48 +000069 // If V is a phi node, we can call this on each of its operands.
70 // "select cond, X, 0" can simplify to "X".
71
Chris Lattner613f1a32011-05-23 00:32:19 +000072 return MadeChange ? V : 0;
Chris Lattner1add46d2011-05-22 18:18:41 +000073}
74
75
Chris Lattnerd12c27c2010-01-05 06:09:35 +000076/// MultiplyOverflows - True if the multiply can not be expressed in an int
77/// this size.
78static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
79 uint32_t W = C1->getBitWidth();
80 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
81 if (sign) {
Jay Foad40f8f622010-12-07 08:25:19 +000082 LHSExt = LHSExt.sext(W * 2);
83 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000084 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000085 LHSExt = LHSExt.zext(W * 2);
86 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000087 }
88
89 APInt MulExt = LHSExt * RHSExt;
90
91 if (!sign)
92 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
93
94 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
95 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
96 return MulExt.slt(Min) || MulExt.sgt(Max);
97}
98
99Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000100 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
102
Duncan Sands82fdab32010-12-21 14:00:22 +0000103 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
104 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000105
Duncan Sands37bf92b2010-12-22 13:36:08 +0000106 if (Value *V = SimplifyUsingDistributiveLaws(I))
107 return ReplaceInstUsesWith(I, V);
108
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000109 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
110 return BinaryOperator::CreateNeg(Op0, I.getName());
111
112 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
113
114 // ((X << C1)*C2) == (X * (C2 << C1))
115 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
116 if (SI->getOpcode() == Instruction::Shl)
117 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
118 return BinaryOperator::CreateMul(SI->getOperand(0),
119 ConstantExpr::getShl(CI, ShOp));
120
121 const APInt &Val = CI->getValue();
122 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
123 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
124 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
125 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
126 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
127 return Shl;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000128 }
129
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000130 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
131 { Value *X; ConstantInt *C1;
132 if (Op0->hasOneUse() &&
133 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000134 Value *Add = Builder->CreateMul(X, CI);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000135 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000136 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000137 }
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000138
Stuart Hastingsf1002822011-06-01 16:42:47 +0000139 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
140 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
141 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000142 {
143 const APInt & Val = CI->getValue();
144 const APInt &PosVal = Val.abs();
145 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stuart Hastingsf1002822011-06-01 16:42:47 +0000146 Value *X = 0, *Y = 0;
147 if (Op0->hasOneUse()) {
148 ConstantInt *C1;
149 Value *Sub = 0;
150 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
151 Sub = Builder->CreateSub(X, Y, "suba");
152 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
153 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
154 if (Sub)
155 return
156 BinaryOperator::CreateMul(Sub,
157 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000158 }
159 }
160 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000161 }
162
163 // Simplify mul instructions with a constant RHS.
164 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000165 // Try to fold constant mul into select arguments.
166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
167 if (Instruction *R = FoldOpIntoSelect(I, SI))
168 return R;
169
170 if (isa<PHINode>(Op0))
171 if (Instruction *NV = FoldOpIntoPhi(I))
172 return NV;
173 }
174
175 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
176 if (Value *Op1v = dyn_castNegVal(Op1))
177 return BinaryOperator::CreateMul(Op0v, Op1v);
178
179 // (X / Y) * Y = X - (X % Y)
180 // (X / Y) * -Y = (X % Y) - X
181 {
182 Value *Op1C = Op1;
183 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
184 if (!BO ||
185 (BO->getOpcode() != Instruction::UDiv &&
186 BO->getOpcode() != Instruction::SDiv)) {
187 Op1C = Op0;
188 BO = dyn_cast<BinaryOperator>(Op1);
189 }
190 Value *Neg = dyn_castNegVal(Op1C);
191 if (BO && BO->hasOneUse() &&
192 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
193 (BO->getOpcode() == Instruction::UDiv ||
194 BO->getOpcode() == Instruction::SDiv)) {
195 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
196
Chris Lattner35bda892011-02-06 21:44:57 +0000197 // If the division is exact, X % Y is zero, so we end up with X or -X.
198 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000199 if (SDiv->isExact()) {
200 if (Op1BO == Op1C)
201 return ReplaceInstUsesWith(I, Op0BO);
202 return BinaryOperator::CreateNeg(Op0BO);
203 }
204
205 Value *Rem;
206 if (BO->getOpcode() == Instruction::UDiv)
207 Rem = Builder->CreateURem(Op0BO, Op1BO);
208 else
209 Rem = Builder->CreateSRem(Op0BO, Op1BO);
210 Rem->takeName(BO);
211
212 if (Op1BO == Op1C)
213 return BinaryOperator::CreateSub(Op0BO, Rem);
214 return BinaryOperator::CreateSub(Rem, Op0BO);
215 }
216 }
217
218 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000219 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000220 return BinaryOperator::CreateAnd(Op0, Op1);
221
222 // X*(1 << Y) --> X << Y
223 // (1 << Y)*X --> X << Y
224 {
225 Value *Y;
226 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
227 return BinaryOperator::CreateShl(Op1, Y);
228 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
229 return BinaryOperator::CreateShl(Op0, Y);
230 }
231
232 // If one of the operands of the multiply is a cast from a boolean value, then
233 // we know the bool is either zero or one, so this is a 'masking' multiply.
234 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000235 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000236 // -2 is "-1 << 1" so it is all bits set except the low one.
237 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
238
239 Value *BoolCast = 0, *OtherOp = 0;
240 if (MaskedValueIsZero(Op0, Negative2))
241 BoolCast = Op0, OtherOp = Op1;
242 else if (MaskedValueIsZero(Op1, Negative2))
243 BoolCast = Op1, OtherOp = Op0;
244
245 if (BoolCast) {
246 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000247 BoolCast);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000248 return BinaryOperator::CreateAnd(V, OtherOp);
249 }
250 }
251
252 return Changed ? &I : 0;
253}
254
255Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000256 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
258
Chris Lattner7302d802012-02-06 21:56:39 +0000259 // Simplify mul instructions with a constant RHS.
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000260 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
261 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
262 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
263 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
264 if (Op1F->isExactlyValue(1.0))
Dan Gohmana9445e12010-03-02 01:11:08 +0000265 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
Chris Lattner7302d802012-02-06 21:56:39 +0000266 } else if (ConstantDataVector *Op1V = dyn_cast<ConstantDataVector>(Op1C)) {
267 // As above, vector X*splat(1.0) -> X in all defined cases.
268 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
269 if (F->isExactlyValue(1.0))
270 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000271 }
272
273 // Try to fold constant mul into select arguments.
274 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
275 if (Instruction *R = FoldOpIntoSelect(I, SI))
276 return R;
277
278 if (isa<PHINode>(Op0))
279 if (Instruction *NV = FoldOpIntoPhi(I))
280 return NV;
281 }
282
283 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
284 if (Value *Op1v = dyn_castFNegVal(Op1))
285 return BinaryOperator::CreateFMul(Op0v, Op1v);
286
Pedro Artigas84030dc2012-11-30 19:09:41 +0000287 // Under unsafe algebra do:
288 // X * log2(0.5*Y) = X*log2(Y) - X
289 if (I.hasUnsafeAlgebra()) {
290 Value *OpX = NULL;
291 Value *OpY = NULL;
292 IntrinsicInst *Log2;
293 if (Op0->hasOneUse()) {
294 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
295 if (II->getIntrinsicID() == Intrinsic::log2 &&
296 II->hasUnsafeAlgebra())
297 {
298 Log2 = II;
299 Value *OpLog2Of = II->getArgOperand(0);
300 if (OpLog2Of->hasOneUse()) {
301 if (Instruction *I = dyn_cast<Instruction>(OpLog2Of)) {
302 if (I->getOpcode() == Instruction::FMul &&
303 I->hasUnsafeAlgebra())
304 {
305 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
306 if (CFP && CFP->isExactlyValue(0.5)) {
307 OpY = I->getOperand(1);
308 OpX = Op1;
309 } else {
310 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
311 if (CFP && CFP->isExactlyValue(0.5)) {
312 OpY = I->getOperand(0);
313 OpX = Op1;
314 }
315 }
316 }
317 }
318 }
319 }
320 }
321 }
322 if (Op1->hasOneUse()) {
323 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op1)) {
324 if (II->getIntrinsicID() == Intrinsic::log2 &&
325 II->hasUnsafeAlgebra())
326 {
327 Log2 = II;
328 Value *OpLog2Of = II->getArgOperand(0);
329 if (OpLog2Of->hasOneUse()) {
330 if (Instruction *I = dyn_cast<Instruction>(OpLog2Of)) {
331 if (I->getOpcode() == Instruction::FMul &&
332 I->hasUnsafeAlgebra())
333 {
334 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
335 if (CFP && CFP->isExactlyValue(0.5)) {
336 OpY = I->getOperand(1);
337 OpX = Op0;
338 } else {
339 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
340 if (CFP && CFP->isExactlyValue(0.5)) {
341 OpY = I->getOperand(0);
342 OpX = Op0;
343 }
344 }
345 }
346 }
347 }
348 }
349 }
350 }
351 // if pattern detected emit alternate sequence
352 if (OpX && OpY) {
353 Log2->setArgOperand(0, OpY);
354 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
355 Instruction *FMul = dyn_cast<Instruction>(FMulVal);
356 assert(FMul && "Must be instruction as Log2 is instruction");
357 FMul->copyFastMathFlags(Log2);
358 Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
359 FSub->copyFastMathFlags(Log2);
360 return FSub;
361 }
362 }
363
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000364 return Changed ? &I : 0;
365}
366
367/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
368/// instruction.
369bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
370 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
371
372 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
373 int NonNullOperand = -1;
374 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
375 if (ST->isNullValue())
376 NonNullOperand = 2;
377 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
378 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
379 if (ST->isNullValue())
380 NonNullOperand = 1;
381
382 if (NonNullOperand == -1)
383 return false;
384
385 Value *SelectCond = SI->getOperand(0);
386
387 // Change the div/rem to use 'Y' instead of the select.
388 I.setOperand(1, SI->getOperand(NonNullOperand));
389
390 // Okay, we know we replace the operand of the div/rem with 'Y' with no
391 // problem. However, the select, or the condition of the select may have
392 // multiple uses. Based on our knowledge that the operand must be non-zero,
393 // propagate the known value for the select into other uses of it, and
394 // propagate a known value of the condition into its other users.
395
396 // If the select and condition only have a single use, don't bother with this,
397 // early exit.
398 if (SI->use_empty() && SelectCond->hasOneUse())
399 return true;
400
401 // Scan the current block backward, looking for other uses of SI.
402 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
403
404 while (BBI != BBFront) {
405 --BBI;
406 // If we found a call to a function, we can't assume it will return, so
407 // information from below it cannot be propagated above it.
408 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
409 break;
410
411 // Replace uses of the select or its condition with the known values.
412 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
413 I != E; ++I) {
414 if (*I == SI) {
415 *I = SI->getOperand(NonNullOperand);
416 Worklist.Add(BBI);
417 } else if (*I == SelectCond) {
418 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
419 ConstantInt::getFalse(BBI->getContext());
420 Worklist.Add(BBI);
421 }
422 }
423
424 // If we past the instruction, quit looking for it.
425 if (&*BBI == SI)
426 SI = 0;
427 if (&*BBI == SelectCond)
428 SelectCond = 0;
429
430 // If we ran out of things to eliminate, break out of the loop.
431 if (SelectCond == 0 && SI == 0)
432 break;
433
434 }
435 return true;
436}
437
438
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000439/// This function implements the transforms common to both integer division
440/// instructions (udiv and sdiv). It is called by the visitors to those integer
441/// division instructions.
442/// @brief Common integer divide transforms
443Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
444 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
445
Chris Lattner1add46d2011-05-22 18:18:41 +0000446 // The RHS is known non-zero.
447 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
448 I.setOperand(1, V);
449 return &I;
450 }
451
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000452 // Handle cases involving: [su]div X, (select Cond, Y, Z)
453 // This does not apply for fdiv.
454 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
455 return &I;
456
457 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000458 // (X / C1) / C2 -> X / (C1*C2)
459 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
460 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
461 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
462 if (MultiplyOverflows(RHS, LHSRHS,
463 I.getOpcode()==Instruction::SDiv))
464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000465 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
466 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000467 }
468
469 if (!RHS->isZero()) { // avoid X udiv 0
470 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
471 if (Instruction *R = FoldOpIntoSelect(I, SI))
472 return R;
473 if (isa<PHINode>(Op0))
474 if (Instruction *NV = FoldOpIntoPhi(I))
475 return NV;
476 }
477 }
478
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000479 // See if we can fold away this div instruction.
480 if (SimplifyDemandedInstructionBits(I))
481 return &I;
482
Duncan Sands593faa52011-01-28 16:51:11 +0000483 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
484 Value *X = 0, *Z = 0;
485 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
486 bool isSigned = I.getOpcode() == Instruction::SDiv;
487 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
488 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
489 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000490 }
491
492 return 0;
493}
494
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000495/// dyn_castZExtVal - Checks if V is a zext or constant that can
496/// be truncated to Ty without losing bits.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000497static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000498 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
499 if (Z->getSrcTy() == Ty)
500 return Z->getOperand(0);
501 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
502 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
503 return ConstantExpr::getTrunc(C, Ty);
504 }
505 return 0;
506}
507
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000508Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
510
Duncan Sands593faa52011-01-28 16:51:11 +0000511 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
512 return ReplaceInstUsesWith(I, V);
513
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000514 // Handle the integer div common cases
515 if (Instruction *Common = commonIDivTransforms(I))
516 return Common;
Pete Coopera29fc802011-11-07 23:04:49 +0000517
518 {
Owen Anderson5b396202010-01-17 06:49:03 +0000519 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000520 // Check to see if this is an unsigned division with an exact power of 2,
521 // if so, convert to a right shift.
Pete Coopera29fc802011-11-07 23:04:49 +0000522 const APInt *C;
523 if (match(Op1, m_Power2(C))) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000524 BinaryOperator *LShr =
Pete Coopera29fc802011-11-07 23:04:49 +0000525 BinaryOperator::CreateLShr(Op0,
526 ConstantInt::get(Op0->getType(),
527 C->logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000528 if (I.isExact()) LShr->setIsExact();
529 return LShr;
530 }
Pete Coopera29fc802011-11-07 23:04:49 +0000531 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000532
Pete Coopera29fc802011-11-07 23:04:49 +0000533 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000534 // X udiv C, where C >= signbit
535 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000536 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000537 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
538 ConstantInt::get(I.getType(), 1));
539 }
540 }
541
Benjamin Kramerc81fe9c2012-08-30 15:07:40 +0000542 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Nadav Rotema694e2a2012-08-28 12:23:22 +0000543 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
Benjamin Krameraac7c652012-08-28 13:08:13 +0000544 Value *X;
545 ConstantInt *C1;
546 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer37dca632012-08-28 13:59:23 +0000547 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
Benjamin Krameraac7c652012-08-28 13:08:13 +0000548 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
Nadav Rotem9753f0b2012-08-28 10:01:43 +0000549 }
550 }
551
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000552 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000553 { const APInt *CI; Value *N;
Evan Cheng2a5422b2012-06-21 22:52:49 +0000554 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
555 match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000556 if (*CI != 1)
Benjamin Kramere5bd3cf2012-09-21 16:26:41 +0000557 N = Builder->CreateAdd(N,
558 ConstantInt::get(N->getType(), CI->logBase2()));
Evan Cheng2a5422b2012-06-21 22:52:49 +0000559 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
560 N = Builder->CreateZExt(N, Z->getDestTy());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000561 if (I.isExact())
562 return BinaryOperator::CreateExactLShr(Op0, N);
563 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000564 }
565 }
566
567 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
568 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000569 { Value *Cond; const APInt *C1, *C2;
570 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
571 // Construct the "on true" case of the select
572 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
573 I.isExact());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000574
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000575 // Construct the "on false" case of the select
576 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
577 I.isExact());
578
579 // construct the select instruction and return it.
580 return SelectInst::Create(Cond, TSI, FSI);
581 }
582 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000583
584 // (zext A) udiv (zext B) --> zext (A udiv B)
585 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
586 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
587 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
588 I.isExact()),
589 I.getType());
590
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000591 return 0;
592}
593
594Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
596
Duncan Sands593faa52011-01-28 16:51:11 +0000597 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
598 return ReplaceInstUsesWith(I, V);
599
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000600 // Handle the integer div common cases
601 if (Instruction *Common = commonIDivTransforms(I))
602 return Common;
603
604 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
605 // sdiv X, -1 == -X
606 if (RHS->isAllOnesValue())
607 return BinaryOperator::CreateNeg(Op0);
608
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000609 // sdiv X, C --> ashr exact X, log2(C)
610 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000611 RHS->getValue().isPowerOf2()) {
612 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
613 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000614 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000615 }
616
617 // -X/C --> X/-C provided the negation doesn't overflow.
618 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000619 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000620 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
621 ConstantExpr::getNeg(RHS));
622 }
623
624 // If the sign bits of both operands are zero (i.e. we can prove they are
625 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000626 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000627 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
628 if (MaskedValueIsZero(Op0, Mask)) {
629 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000630 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000631 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
632 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000633
634 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000635 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
636 // Safe because the only negative value (1 << Y) can take on is
637 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
638 // the sign bit set.
639 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
640 }
641 }
642 }
643
644 return 0;
645}
646
Frits van Bommel31726c12011-01-29 17:50:27 +0000647Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
649
650 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
651 return ReplaceInstUsesWith(I, V);
652
Benjamin Kramer54673962011-03-30 15:42:35 +0000653 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
654 const APFloat &Op1F = Op1C->getValueAPF();
655
656 // If the divisor has an exact multiplicative inverse we can turn the fdiv
657 // into a cheaper fmul.
658 APFloat Reciprocal(Op1F.getSemantics());
659 if (Op1F.getExactInverse(&Reciprocal)) {
660 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
661 return BinaryOperator::CreateFMul(Op0, RFP);
662 }
663 }
664
Frits van Bommel31726c12011-01-29 17:50:27 +0000665 return 0;
666}
667
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000668/// This function implements the transforms common to both integer remainder
669/// instructions (urem and srem). It is called by the visitors to those integer
670/// remainder instructions.
671/// @brief Common integer remainder transforms
672Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
673 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
674
Chris Lattner1add46d2011-05-22 18:18:41 +0000675 // The RHS is known non-zero.
676 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
677 I.setOperand(1, V);
678 return &I;
679 }
680
Duncan Sandsf24ed772011-05-02 16:27:02 +0000681 // Handle cases involving: rem X, (select Cond, Y, Z)
682 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
683 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000684
Duncan Sands00676a62011-05-02 18:41:29 +0000685 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000686 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
687 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
688 if (Instruction *R = FoldOpIntoSelect(I, SI))
689 return R;
690 } else if (isa<PHINode>(Op0I)) {
691 if (Instruction *NV = FoldOpIntoPhi(I))
692 return NV;
693 }
694
695 // See if we can fold away this rem instruction.
696 if (SimplifyDemandedInstructionBits(I))
697 return &I;
698 }
699 }
700
701 return 0;
702}
703
704Instruction *InstCombiner::visitURem(BinaryOperator &I) {
705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
706
Duncan Sandsf24ed772011-05-02 16:27:02 +0000707 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
708 return ReplaceInstUsesWith(I, V);
709
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000710 if (Instruction *common = commonIRemTransforms(I))
711 return common;
712
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000713 // X urem C^2 -> X and C-1
714 { const APInt *C;
715 if (match(Op1, m_Power2(C)))
716 return BinaryOperator::CreateAnd(Op0,
717 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000718 }
719
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000720 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
721 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
722 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000723 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000724 return BinaryOperator::CreateAnd(Op0, Add);
725 }
726
727 // urem X, (select Cond, 2^C1, 2^C2) -->
728 // select Cond, (and X, C1-1), (and X, C2-1)
729 // when C1&C2 are powers of two.
730 { Value *Cond; const APInt *C1, *C2;
731 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
732 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
733 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
734 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000735 }
736 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000737
738 // (zext A) urem (zext B) --> zext (A urem B)
739 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
740 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
741 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
742 I.getType());
743
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000744 return 0;
745}
746
747Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
748 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
749
Duncan Sandsf24ed772011-05-02 16:27:02 +0000750 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
751 return ReplaceInstUsesWith(I, V);
752
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000753 // Handle the integer rem common cases
754 if (Instruction *Common = commonIRemTransforms(I))
755 return Common;
756
757 if (Value *RHSNeg = dyn_castNegVal(Op1))
758 if (!isa<Constant>(RHSNeg) ||
759 (isa<ConstantInt>(RHSNeg) &&
760 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
761 // X % -Y -> X % Y
762 Worklist.AddValue(I.getOperand(1));
763 I.setOperand(1, RHSNeg);
764 return &I;
765 }
766
767 // If the sign bits of both operands are zero (i.e. we can prove they are
768 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000769 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000770 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
771 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000772 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000773 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
774 }
775 }
776
777 // If it's a constant vector, flip any negative values positive.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000778 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
779 Constant *C = cast<Constant>(Op1);
780 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000781
782 bool hasNegative = false;
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000783 bool hasMissing = false;
784 for (unsigned i = 0; i != VWidth; ++i) {
785 Constant *Elt = C->getAggregateElement(i);
786 if (Elt == 0) {
787 hasMissing = true;
788 break;
789 }
790
791 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000792 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000793 hasNegative = true;
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000794 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000795
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000796 if (hasNegative && !hasMissing) {
Chris Lattner4ca829e2012-01-25 06:02:56 +0000797 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000798 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner7302d802012-02-06 21:56:39 +0000799 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000800 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000801 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000802 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000803 }
804 }
805
806 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000807 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000808 Worklist.AddValue(I.getOperand(1));
809 I.setOperand(1, NewRHSV);
810 return &I;
811 }
812 }
813 }
814
815 return 0;
816}
817
818Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000819 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000820
Duncan Sandsf24ed772011-05-02 16:27:02 +0000821 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
822 return ReplaceInstUsesWith(I, V);
823
824 // Handle cases involving: rem X, (select Cond, Y, Z)
825 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
826 return &I;
827
828 return 0;
829}