blob: c96741aacd210a122232fdde79b9e02bebe1b81a [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
32 // ((1 << A) >>u B) --> (1 << (A-B))
33 // Because V cannot be zero, we know that B is less than A.
34 Value *A = 0, *B = 0; ConstantInt *One = 0;
35 if (match(V, m_LShr(m_OneUse(m_Shl(m_ConstantInt(One), m_Value(A))),
36 m_Value(B))) &&
37 // The "1" can be any value known to be a power of 2.
38 One->getValue().isPowerOf2()) {
39 A = IC.Builder->CreateSub(A, B, "tmp");
40 return IC.Builder->CreateShl(One, A);
41 }
42
43 return 0;
44}
45
46
Chris Lattnerd12c27c2010-01-05 06:09:35 +000047/// MultiplyOverflows - True if the multiply can not be expressed in an int
48/// this size.
49static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
50 uint32_t W = C1->getBitWidth();
51 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
52 if (sign) {
Jay Foad40f8f622010-12-07 08:25:19 +000053 LHSExt = LHSExt.sext(W * 2);
54 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000055 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000056 LHSExt = LHSExt.zext(W * 2);
57 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000058 }
59
60 APInt MulExt = LHSExt * RHSExt;
61
62 if (!sign)
63 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
64
65 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
66 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
67 return MulExt.slt(Min) || MulExt.sgt(Max);
68}
69
70Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000071 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
73
Duncan Sands82fdab32010-12-21 14:00:22 +000074 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
75 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000076
Duncan Sands37bf92b2010-12-22 13:36:08 +000077 if (Value *V = SimplifyUsingDistributiveLaws(I))
78 return ReplaceInstUsesWith(I, V);
79
Chris Lattner7a6aa1a2011-02-10 05:36:31 +000080 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
81 return BinaryOperator::CreateNeg(Op0, I.getName());
82
83 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
84
85 // ((X << C1)*C2) == (X * (C2 << C1))
86 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
87 if (SI->getOpcode() == Instruction::Shl)
88 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
89 return BinaryOperator::CreateMul(SI->getOperand(0),
90 ConstantExpr::getShl(CI, ShOp));
91
92 const APInt &Val = CI->getValue();
93 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
94 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
95 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
96 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
97 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
98 return Shl;
Chris Lattnerd12c27c2010-01-05 06:09:35 +000099 }
100
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000101 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
102 { Value *X; ConstantInt *C1;
103 if (Op0->hasOneUse() &&
104 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
105 Value *Add = Builder->CreateMul(X, CI, "tmp");
106 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000107 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000108 }
109 }
110
111 // Simplify mul instructions with a constant RHS.
112 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000113 // Try to fold constant mul into select arguments.
114 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
115 if (Instruction *R = FoldOpIntoSelect(I, SI))
116 return R;
117
118 if (isa<PHINode>(Op0))
119 if (Instruction *NV = FoldOpIntoPhi(I))
120 return NV;
121 }
122
123 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
124 if (Value *Op1v = dyn_castNegVal(Op1))
125 return BinaryOperator::CreateMul(Op0v, Op1v);
126
127 // (X / Y) * Y = X - (X % Y)
128 // (X / Y) * -Y = (X % Y) - X
129 {
130 Value *Op1C = Op1;
131 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
132 if (!BO ||
133 (BO->getOpcode() != Instruction::UDiv &&
134 BO->getOpcode() != Instruction::SDiv)) {
135 Op1C = Op0;
136 BO = dyn_cast<BinaryOperator>(Op1);
137 }
138 Value *Neg = dyn_castNegVal(Op1C);
139 if (BO && BO->hasOneUse() &&
140 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
141 (BO->getOpcode() == Instruction::UDiv ||
142 BO->getOpcode() == Instruction::SDiv)) {
143 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
144
Chris Lattner35bda892011-02-06 21:44:57 +0000145 // If the division is exact, X % Y is zero, so we end up with X or -X.
146 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000147 if (SDiv->isExact()) {
148 if (Op1BO == Op1C)
149 return ReplaceInstUsesWith(I, Op0BO);
150 return BinaryOperator::CreateNeg(Op0BO);
151 }
152
153 Value *Rem;
154 if (BO->getOpcode() == Instruction::UDiv)
155 Rem = Builder->CreateURem(Op0BO, Op1BO);
156 else
157 Rem = Builder->CreateSRem(Op0BO, Op1BO);
158 Rem->takeName(BO);
159
160 if (Op1BO == Op1C)
161 return BinaryOperator::CreateSub(Op0BO, Rem);
162 return BinaryOperator::CreateSub(Rem, Op0BO);
163 }
164 }
165
166 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000167 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000168 return BinaryOperator::CreateAnd(Op0, Op1);
169
170 // X*(1 << Y) --> X << Y
171 // (1 << Y)*X --> X << Y
172 {
173 Value *Y;
174 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
175 return BinaryOperator::CreateShl(Op1, Y);
176 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
177 return BinaryOperator::CreateShl(Op0, Y);
178 }
179
180 // If one of the operands of the multiply is a cast from a boolean value, then
181 // we know the bool is either zero or one, so this is a 'masking' multiply.
182 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000183 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000184 // -2 is "-1 << 1" so it is all bits set except the low one.
185 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
186
187 Value *BoolCast = 0, *OtherOp = 0;
188 if (MaskedValueIsZero(Op0, Negative2))
189 BoolCast = Op0, OtherOp = Op1;
190 else if (MaskedValueIsZero(Op1, Negative2))
191 BoolCast = Op1, OtherOp = Op0;
192
193 if (BoolCast) {
194 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
195 BoolCast, "tmp");
196 return BinaryOperator::CreateAnd(V, OtherOp);
197 }
198 }
199
200 return Changed ? &I : 0;
201}
202
203Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000204 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
206
207 // Simplify mul instructions with a constant RHS...
208 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
209 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
210 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
211 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
212 if (Op1F->isExactlyValue(1.0))
Dan Gohmana9445e12010-03-02 01:11:08 +0000213 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
Duncan Sands1df98592010-02-16 11:11:14 +0000214 } else if (Op1C->getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000215 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
216 // As above, vector X*splat(1.0) -> X in all defined cases.
217 if (Constant *Splat = Op1V->getSplatValue()) {
218 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
219 if (F->isExactlyValue(1.0))
220 return ReplaceInstUsesWith(I, Op0);
221 }
222 }
223 }
224
225 // Try to fold constant mul into select arguments.
226 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
227 if (Instruction *R = FoldOpIntoSelect(I, SI))
228 return R;
229
230 if (isa<PHINode>(Op0))
231 if (Instruction *NV = FoldOpIntoPhi(I))
232 return NV;
233 }
234
235 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
236 if (Value *Op1v = dyn_castFNegVal(Op1))
237 return BinaryOperator::CreateFMul(Op0v, Op1v);
238
239 return Changed ? &I : 0;
240}
241
242/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
243/// instruction.
244bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
245 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
246
247 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
248 int NonNullOperand = -1;
249 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
250 if (ST->isNullValue())
251 NonNullOperand = 2;
252 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
253 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
254 if (ST->isNullValue())
255 NonNullOperand = 1;
256
257 if (NonNullOperand == -1)
258 return false;
259
260 Value *SelectCond = SI->getOperand(0);
261
262 // Change the div/rem to use 'Y' instead of the select.
263 I.setOperand(1, SI->getOperand(NonNullOperand));
264
265 // Okay, we know we replace the operand of the div/rem with 'Y' with no
266 // problem. However, the select, or the condition of the select may have
267 // multiple uses. Based on our knowledge that the operand must be non-zero,
268 // propagate the known value for the select into other uses of it, and
269 // propagate a known value of the condition into its other users.
270
271 // If the select and condition only have a single use, don't bother with this,
272 // early exit.
273 if (SI->use_empty() && SelectCond->hasOneUse())
274 return true;
275
276 // Scan the current block backward, looking for other uses of SI.
277 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
278
279 while (BBI != BBFront) {
280 --BBI;
281 // If we found a call to a function, we can't assume it will return, so
282 // information from below it cannot be propagated above it.
283 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
284 break;
285
286 // Replace uses of the select or its condition with the known values.
287 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
288 I != E; ++I) {
289 if (*I == SI) {
290 *I = SI->getOperand(NonNullOperand);
291 Worklist.Add(BBI);
292 } else if (*I == SelectCond) {
293 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
294 ConstantInt::getFalse(BBI->getContext());
295 Worklist.Add(BBI);
296 }
297 }
298
299 // If we past the instruction, quit looking for it.
300 if (&*BBI == SI)
301 SI = 0;
302 if (&*BBI == SelectCond)
303 SelectCond = 0;
304
305 // If we ran out of things to eliminate, break out of the loop.
306 if (SelectCond == 0 && SI == 0)
307 break;
308
309 }
310 return true;
311}
312
313
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000314/// This function implements the transforms common to both integer division
315/// instructions (udiv and sdiv). It is called by the visitors to those integer
316/// division instructions.
317/// @brief Common integer divide transforms
318Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
320
Chris Lattner1add46d2011-05-22 18:18:41 +0000321 // The RHS is known non-zero.
322 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
323 I.setOperand(1, V);
324 return &I;
325 }
326
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000327 // Handle cases involving: [su]div X, (select Cond, Y, Z)
328 // This does not apply for fdiv.
329 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
330 return &I;
331
332 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000333 // (X / C1) / C2 -> X / (C1*C2)
334 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
335 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
336 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
337 if (MultiplyOverflows(RHS, LHSRHS,
338 I.getOpcode()==Instruction::SDiv))
339 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000340 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
341 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000342 }
343
344 if (!RHS->isZero()) { // avoid X udiv 0
345 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
346 if (Instruction *R = FoldOpIntoSelect(I, SI))
347 return R;
348 if (isa<PHINode>(Op0))
349 if (Instruction *NV = FoldOpIntoPhi(I))
350 return NV;
351 }
352 }
353
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000354 // See if we can fold away this div instruction.
355 if (SimplifyDemandedInstructionBits(I))
356 return &I;
357
Duncan Sands593faa52011-01-28 16:51:11 +0000358 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
359 Value *X = 0, *Z = 0;
360 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
361 bool isSigned = I.getOpcode() == Instruction::SDiv;
362 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
363 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
364 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000365 }
366
367 return 0;
368}
369
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000370/// dyn_castZExtVal - Checks if V is a zext or constant that can
371/// be truncated to Ty without losing bits.
372static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
373 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
374 if (Z->getSrcTy() == Ty)
375 return Z->getOperand(0);
376 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
377 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
378 return ConstantExpr::getTrunc(C, Ty);
379 }
380 return 0;
381}
382
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000383Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
385
Duncan Sands593faa52011-01-28 16:51:11 +0000386 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
387 return ReplaceInstUsesWith(I, V);
388
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000389 // Handle the integer div common cases
390 if (Instruction *Common = commonIDivTransforms(I))
391 return Common;
392
393 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5b396202010-01-17 06:49:03 +0000394 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000395 // Check to see if this is an unsigned division with an exact power of 2,
396 // if so, convert to a right shift.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000397 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
398 BinaryOperator *LShr =
399 BinaryOperator::CreateLShr(Op0,
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000400 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000401 if (I.isExact()) LShr->setIsExact();
402 return LShr;
403 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000404
405 // X udiv C, where C >= signbit
406 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000407 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000408 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
409 ConstantInt::get(I.getType(), 1));
410 }
411 }
412
413 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000414 { const APInt *CI; Value *N;
415 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
416 if (*CI != 1)
417 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
418 "tmp");
419 if (I.isExact())
420 return BinaryOperator::CreateExactLShr(Op0, N);
421 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000422 }
423 }
424
425 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
426 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000427 { Value *Cond; const APInt *C1, *C2;
428 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
429 // Construct the "on true" case of the select
430 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
431 I.isExact());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000432
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000433 // Construct the "on false" case of the select
434 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
435 I.isExact());
436
437 // construct the select instruction and return it.
438 return SelectInst::Create(Cond, TSI, FSI);
439 }
440 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000441
442 // (zext A) udiv (zext B) --> zext (A udiv B)
443 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
444 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
445 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
446 I.isExact()),
447 I.getType());
448
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000449 return 0;
450}
451
452Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
454
Duncan Sands593faa52011-01-28 16:51:11 +0000455 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
456 return ReplaceInstUsesWith(I, V);
457
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000458 // Handle the integer div common cases
459 if (Instruction *Common = commonIDivTransforms(I))
460 return Common;
461
462 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
463 // sdiv X, -1 == -X
464 if (RHS->isAllOnesValue())
465 return BinaryOperator::CreateNeg(Op0);
466
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000467 // sdiv X, C --> ashr exact X, log2(C)
468 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000469 RHS->getValue().isPowerOf2()) {
470 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
471 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000472 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000473 }
474
475 // -X/C --> X/-C provided the negation doesn't overflow.
476 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000477 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000478 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
479 ConstantExpr::getNeg(RHS));
480 }
481
482 // If the sign bits of both operands are zero (i.e. we can prove they are
483 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000484 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000485 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
486 if (MaskedValueIsZero(Op0, Mask)) {
487 if (MaskedValueIsZero(Op1, Mask)) {
488 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
489 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
490 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000491
492 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000493 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
494 // Safe because the only negative value (1 << Y) can take on is
495 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
496 // the sign bit set.
497 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
498 }
499 }
500 }
501
502 return 0;
503}
504
Frits van Bommel31726c12011-01-29 17:50:27 +0000505Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
507
508 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
509 return ReplaceInstUsesWith(I, V);
510
Benjamin Kramer54673962011-03-30 15:42:35 +0000511 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
512 const APFloat &Op1F = Op1C->getValueAPF();
513
514 // If the divisor has an exact multiplicative inverse we can turn the fdiv
515 // into a cheaper fmul.
516 APFloat Reciprocal(Op1F.getSemantics());
517 if (Op1F.getExactInverse(&Reciprocal)) {
518 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
519 return BinaryOperator::CreateFMul(Op0, RFP);
520 }
521 }
522
Frits van Bommel31726c12011-01-29 17:50:27 +0000523 return 0;
524}
525
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000526/// This function implements the transforms common to both integer remainder
527/// instructions (urem and srem). It is called by the visitors to those integer
528/// remainder instructions.
529/// @brief Common integer remainder transforms
530Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
532
Chris Lattner1add46d2011-05-22 18:18:41 +0000533 // The RHS is known non-zero.
534 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
535 I.setOperand(1, V);
536 return &I;
537 }
538
Duncan Sandsf24ed772011-05-02 16:27:02 +0000539 // Handle cases involving: rem X, (select Cond, Y, Z)
540 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
541 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000542
Duncan Sands00676a62011-05-02 18:41:29 +0000543 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000544 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
545 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
546 if (Instruction *R = FoldOpIntoSelect(I, SI))
547 return R;
548 } else if (isa<PHINode>(Op0I)) {
549 if (Instruction *NV = FoldOpIntoPhi(I))
550 return NV;
551 }
552
553 // See if we can fold away this rem instruction.
554 if (SimplifyDemandedInstructionBits(I))
555 return &I;
556 }
557 }
558
559 return 0;
560}
561
562Instruction *InstCombiner::visitURem(BinaryOperator &I) {
563 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
564
Duncan Sandsf24ed772011-05-02 16:27:02 +0000565 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
566 return ReplaceInstUsesWith(I, V);
567
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000568 if (Instruction *common = commonIRemTransforms(I))
569 return common;
570
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000571 // X urem C^2 -> X and C-1
572 { const APInt *C;
573 if (match(Op1, m_Power2(C)))
574 return BinaryOperator::CreateAnd(Op0,
575 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000576 }
577
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000578 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
579 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
580 Constant *N1 = Constant::getAllOnesValue(I.getType());
581 Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
582 return BinaryOperator::CreateAnd(Op0, Add);
583 }
584
585 // urem X, (select Cond, 2^C1, 2^C2) -->
586 // select Cond, (and X, C1-1), (and X, C2-1)
587 // when C1&C2 are powers of two.
588 { Value *Cond; const APInt *C1, *C2;
589 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
590 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
591 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
592 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000593 }
594 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000595
596 // (zext A) urem (zext B) --> zext (A urem B)
597 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
598 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
599 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
600 I.getType());
601
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000602 return 0;
603}
604
605Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
606 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
607
Duncan Sandsf24ed772011-05-02 16:27:02 +0000608 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
609 return ReplaceInstUsesWith(I, V);
610
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000611 // Handle the integer rem common cases
612 if (Instruction *Common = commonIRemTransforms(I))
613 return Common;
614
615 if (Value *RHSNeg = dyn_castNegVal(Op1))
616 if (!isa<Constant>(RHSNeg) ||
617 (isa<ConstantInt>(RHSNeg) &&
618 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
619 // X % -Y -> X % Y
620 Worklist.AddValue(I.getOperand(1));
621 I.setOperand(1, RHSNeg);
622 return &I;
623 }
624
625 // If the sign bits of both operands are zero (i.e. we can prove they are
626 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000627 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000628 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
629 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
630 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
631 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
632 }
633 }
634
635 // If it's a constant vector, flip any negative values positive.
636 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
637 unsigned VWidth = RHSV->getNumOperands();
638
639 bool hasNegative = false;
640 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
641 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
642 if (RHS->getValue().isNegative())
643 hasNegative = true;
644
645 if (hasNegative) {
646 std::vector<Constant *> Elts(VWidth);
647 for (unsigned i = 0; i != VWidth; ++i) {
648 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
649 if (RHS->getValue().isNegative())
650 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
651 else
652 Elts[i] = RHS;
653 }
654 }
655
656 Constant *NewRHSV = ConstantVector::get(Elts);
657 if (NewRHSV != RHSV) {
658 Worklist.AddValue(I.getOperand(1));
659 I.setOperand(1, NewRHSV);
660 return &I;
661 }
662 }
663 }
664
665 return 0;
666}
667
668Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000669 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000670
Duncan Sandsf24ed772011-05-02 16:27:02 +0000671 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
672 return ReplaceInstUsesWith(I, V);
673
674 // Handle cases involving: rem X, (select Cond, Y, Z)
675 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
676 return &I;
677
678 return 0;
679}