blob: b860440f6008905e0a8503d243f4b52122de47d9 [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.
Chris Lattner6083bb92011-05-23 00:09:55 +000040 isPowerOfTwo(PowerOf2, IC.getTargetData())) {
Chris Lattner1add46d2011-05-22 18:18:41 +000041 A = IC.Builder->CreateSub(A, B, "tmp");
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() &&
49 isPowerOfTwo(I->getOperand(0), IC.getTargetData())) {
50 // 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)))) {
134 Value *Add = Builder->CreateMul(X, CI, "tmp");
135 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 Hastingsdf48e842011-05-31 19:29:55 +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 Hastingsdf48e842011-05-31 19:29:55 +0000146 Value *X = 0, *Y = 0;
147 ConstantInt *C1 = 0;
148 if (Op0->hasOneUse() &&
149 (match(Op0, m_Sub(m_Value(Y), m_Value(X)))) ||
150 (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))) {
151 Value *Sub;
152 if (C1) // Matched ADD of constant, negate both operands:
153 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
154 else // Matched SUB, swap operands:
155 Sub = Builder->CreateSub(X, Y, "suba");
156 return
157 BinaryOperator::CreateMul(Sub,
158 ConstantInt::get(X->getType(), PosVal));
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000159 }
160 }
161 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000162 }
163
164 // Simplify mul instructions with a constant RHS.
165 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000166 // Try to fold constant mul into select arguments.
167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
168 if (Instruction *R = FoldOpIntoSelect(I, SI))
169 return R;
170
171 if (isa<PHINode>(Op0))
172 if (Instruction *NV = FoldOpIntoPhi(I))
173 return NV;
174 }
175
176 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
177 if (Value *Op1v = dyn_castNegVal(Op1))
178 return BinaryOperator::CreateMul(Op0v, Op1v);
179
180 // (X / Y) * Y = X - (X % Y)
181 // (X / Y) * -Y = (X % Y) - X
182 {
183 Value *Op1C = Op1;
184 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
185 if (!BO ||
186 (BO->getOpcode() != Instruction::UDiv &&
187 BO->getOpcode() != Instruction::SDiv)) {
188 Op1C = Op0;
189 BO = dyn_cast<BinaryOperator>(Op1);
190 }
191 Value *Neg = dyn_castNegVal(Op1C);
192 if (BO && BO->hasOneUse() &&
193 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
194 (BO->getOpcode() == Instruction::UDiv ||
195 BO->getOpcode() == Instruction::SDiv)) {
196 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
197
Chris Lattner35bda892011-02-06 21:44:57 +0000198 // If the division is exact, X % Y is zero, so we end up with X or -X.
199 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000200 if (SDiv->isExact()) {
201 if (Op1BO == Op1C)
202 return ReplaceInstUsesWith(I, Op0BO);
203 return BinaryOperator::CreateNeg(Op0BO);
204 }
205
206 Value *Rem;
207 if (BO->getOpcode() == Instruction::UDiv)
208 Rem = Builder->CreateURem(Op0BO, Op1BO);
209 else
210 Rem = Builder->CreateSRem(Op0BO, Op1BO);
211 Rem->takeName(BO);
212
213 if (Op1BO == Op1C)
214 return BinaryOperator::CreateSub(Op0BO, Rem);
215 return BinaryOperator::CreateSub(Rem, Op0BO);
216 }
217 }
218
219 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000220 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000221 return BinaryOperator::CreateAnd(Op0, Op1);
222
223 // X*(1 << Y) --> X << Y
224 // (1 << Y)*X --> X << Y
225 {
226 Value *Y;
227 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
228 return BinaryOperator::CreateShl(Op1, Y);
229 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
230 return BinaryOperator::CreateShl(Op0, Y);
231 }
232
233 // If one of the operands of the multiply is a cast from a boolean value, then
234 // we know the bool is either zero or one, so this is a 'masking' multiply.
235 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000236 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000237 // -2 is "-1 << 1" so it is all bits set except the low one.
238 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
239
240 Value *BoolCast = 0, *OtherOp = 0;
241 if (MaskedValueIsZero(Op0, Negative2))
242 BoolCast = Op0, OtherOp = Op1;
243 else if (MaskedValueIsZero(Op1, Negative2))
244 BoolCast = Op1, OtherOp = Op0;
245
246 if (BoolCast) {
247 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
248 BoolCast, "tmp");
249 return BinaryOperator::CreateAnd(V, OtherOp);
250 }
251 }
252
253 return Changed ? &I : 0;
254}
255
256Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000257 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
259
260 // Simplify mul instructions with a constant RHS...
261 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
262 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
263 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
264 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
265 if (Op1F->isExactlyValue(1.0))
Dan Gohmana9445e12010-03-02 01:11:08 +0000266 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
Duncan Sands1df98592010-02-16 11:11:14 +0000267 } else if (Op1C->getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000268 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
269 // As above, vector X*splat(1.0) -> X in all defined cases.
270 if (Constant *Splat = Op1V->getSplatValue()) {
271 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
272 if (F->isExactlyValue(1.0))
273 return ReplaceInstUsesWith(I, Op0);
274 }
275 }
276 }
277
278 // Try to fold constant mul into select arguments.
279 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
280 if (Instruction *R = FoldOpIntoSelect(I, SI))
281 return R;
282
283 if (isa<PHINode>(Op0))
284 if (Instruction *NV = FoldOpIntoPhi(I))
285 return NV;
286 }
287
288 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
289 if (Value *Op1v = dyn_castFNegVal(Op1))
290 return BinaryOperator::CreateFMul(Op0v, Op1v);
291
292 return Changed ? &I : 0;
293}
294
295/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
296/// instruction.
297bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
298 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
299
300 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
301 int NonNullOperand = -1;
302 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
303 if (ST->isNullValue())
304 NonNullOperand = 2;
305 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
306 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
307 if (ST->isNullValue())
308 NonNullOperand = 1;
309
310 if (NonNullOperand == -1)
311 return false;
312
313 Value *SelectCond = SI->getOperand(0);
314
315 // Change the div/rem to use 'Y' instead of the select.
316 I.setOperand(1, SI->getOperand(NonNullOperand));
317
318 // Okay, we know we replace the operand of the div/rem with 'Y' with no
319 // problem. However, the select, or the condition of the select may have
320 // multiple uses. Based on our knowledge that the operand must be non-zero,
321 // propagate the known value for the select into other uses of it, and
322 // propagate a known value of the condition into its other users.
323
324 // If the select and condition only have a single use, don't bother with this,
325 // early exit.
326 if (SI->use_empty() && SelectCond->hasOneUse())
327 return true;
328
329 // Scan the current block backward, looking for other uses of SI.
330 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
331
332 while (BBI != BBFront) {
333 --BBI;
334 // If we found a call to a function, we can't assume it will return, so
335 // information from below it cannot be propagated above it.
336 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
337 break;
338
339 // Replace uses of the select or its condition with the known values.
340 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
341 I != E; ++I) {
342 if (*I == SI) {
343 *I = SI->getOperand(NonNullOperand);
344 Worklist.Add(BBI);
345 } else if (*I == SelectCond) {
346 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
347 ConstantInt::getFalse(BBI->getContext());
348 Worklist.Add(BBI);
349 }
350 }
351
352 // If we past the instruction, quit looking for it.
353 if (&*BBI == SI)
354 SI = 0;
355 if (&*BBI == SelectCond)
356 SelectCond = 0;
357
358 // If we ran out of things to eliminate, break out of the loop.
359 if (SelectCond == 0 && SI == 0)
360 break;
361
362 }
363 return true;
364}
365
366
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000367/// This function implements the transforms common to both integer division
368/// instructions (udiv and sdiv). It is called by the visitors to those integer
369/// division instructions.
370/// @brief Common integer divide transforms
371Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
373
Chris Lattner1add46d2011-05-22 18:18:41 +0000374 // The RHS is known non-zero.
375 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
376 I.setOperand(1, V);
377 return &I;
378 }
379
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000380 // Handle cases involving: [su]div X, (select Cond, Y, Z)
381 // This does not apply for fdiv.
382 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
383 return &I;
384
385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000386 // (X / C1) / C2 -> X / (C1*C2)
387 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
388 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
389 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
390 if (MultiplyOverflows(RHS, LHSRHS,
391 I.getOpcode()==Instruction::SDiv))
392 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000393 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
394 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000395 }
396
397 if (!RHS->isZero()) { // avoid X udiv 0
398 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
399 if (Instruction *R = FoldOpIntoSelect(I, SI))
400 return R;
401 if (isa<PHINode>(Op0))
402 if (Instruction *NV = FoldOpIntoPhi(I))
403 return NV;
404 }
405 }
406
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000407 // See if we can fold away this div instruction.
408 if (SimplifyDemandedInstructionBits(I))
409 return &I;
410
Duncan Sands593faa52011-01-28 16:51:11 +0000411 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
412 Value *X = 0, *Z = 0;
413 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
414 bool isSigned = I.getOpcode() == Instruction::SDiv;
415 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
416 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
417 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000418 }
419
420 return 0;
421}
422
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000423/// dyn_castZExtVal - Checks if V is a zext or constant that can
424/// be truncated to Ty without losing bits.
425static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
426 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
427 if (Z->getSrcTy() == Ty)
428 return Z->getOperand(0);
429 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
430 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
431 return ConstantExpr::getTrunc(C, Ty);
432 }
433 return 0;
434}
435
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000436Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
438
Duncan Sands593faa52011-01-28 16:51:11 +0000439 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
440 return ReplaceInstUsesWith(I, V);
441
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000442 // Handle the integer div common cases
443 if (Instruction *Common = commonIDivTransforms(I))
444 return Common;
445
446 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5b396202010-01-17 06:49:03 +0000447 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000448 // Check to see if this is an unsigned division with an exact power of 2,
449 // if so, convert to a right shift.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000450 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
451 BinaryOperator *LShr =
452 BinaryOperator::CreateLShr(Op0,
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000453 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000454 if (I.isExact()) LShr->setIsExact();
455 return LShr;
456 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000457
458 // X udiv C, where C >= signbit
459 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000460 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000461 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
462 ConstantInt::get(I.getType(), 1));
463 }
464 }
465
466 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000467 { const APInt *CI; Value *N;
468 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
469 if (*CI != 1)
470 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
471 "tmp");
472 if (I.isExact())
473 return BinaryOperator::CreateExactLShr(Op0, N);
474 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000475 }
476 }
477
478 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
479 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000480 { Value *Cond; const APInt *C1, *C2;
481 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
482 // Construct the "on true" case of the select
483 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
484 I.isExact());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000485
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000486 // Construct the "on false" case of the select
487 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
488 I.isExact());
489
490 // construct the select instruction and return it.
491 return SelectInst::Create(Cond, TSI, FSI);
492 }
493 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000494
495 // (zext A) udiv (zext B) --> zext (A udiv B)
496 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
497 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
498 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
499 I.isExact()),
500 I.getType());
501
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000502 return 0;
503}
504
505Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
507
Duncan Sands593faa52011-01-28 16:51:11 +0000508 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
509 return ReplaceInstUsesWith(I, V);
510
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000511 // Handle the integer div common cases
512 if (Instruction *Common = commonIDivTransforms(I))
513 return Common;
514
515 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
516 // sdiv X, -1 == -X
517 if (RHS->isAllOnesValue())
518 return BinaryOperator::CreateNeg(Op0);
519
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000520 // sdiv X, C --> ashr exact X, log2(C)
521 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000522 RHS->getValue().isPowerOf2()) {
523 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
524 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000525 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000526 }
527
528 // -X/C --> X/-C provided the negation doesn't overflow.
529 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000530 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000531 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
532 ConstantExpr::getNeg(RHS));
533 }
534
535 // If the sign bits of both operands are zero (i.e. we can prove they are
536 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000537 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000538 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
539 if (MaskedValueIsZero(Op0, Mask)) {
540 if (MaskedValueIsZero(Op1, Mask)) {
541 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
542 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
543 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000544
545 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000546 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
547 // Safe because the only negative value (1 << Y) can take on is
548 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
549 // the sign bit set.
550 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
551 }
552 }
553 }
554
555 return 0;
556}
557
Frits van Bommel31726c12011-01-29 17:50:27 +0000558Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
559 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
560
561 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
562 return ReplaceInstUsesWith(I, V);
563
Benjamin Kramer54673962011-03-30 15:42:35 +0000564 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
565 const APFloat &Op1F = Op1C->getValueAPF();
566
567 // If the divisor has an exact multiplicative inverse we can turn the fdiv
568 // into a cheaper fmul.
569 APFloat Reciprocal(Op1F.getSemantics());
570 if (Op1F.getExactInverse(&Reciprocal)) {
571 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
572 return BinaryOperator::CreateFMul(Op0, RFP);
573 }
574 }
575
Frits van Bommel31726c12011-01-29 17:50:27 +0000576 return 0;
577}
578
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000579/// This function implements the transforms common to both integer remainder
580/// instructions (urem and srem). It is called by the visitors to those integer
581/// remainder instructions.
582/// @brief Common integer remainder transforms
583Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
585
Chris Lattner1add46d2011-05-22 18:18:41 +0000586 // The RHS is known non-zero.
587 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
588 I.setOperand(1, V);
589 return &I;
590 }
591
Duncan Sandsf24ed772011-05-02 16:27:02 +0000592 // Handle cases involving: rem X, (select Cond, Y, Z)
593 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
594 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000595
Duncan Sands00676a62011-05-02 18:41:29 +0000596 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000597 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
598 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
599 if (Instruction *R = FoldOpIntoSelect(I, SI))
600 return R;
601 } else if (isa<PHINode>(Op0I)) {
602 if (Instruction *NV = FoldOpIntoPhi(I))
603 return NV;
604 }
605
606 // See if we can fold away this rem instruction.
607 if (SimplifyDemandedInstructionBits(I))
608 return &I;
609 }
610 }
611
612 return 0;
613}
614
615Instruction *InstCombiner::visitURem(BinaryOperator &I) {
616 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
617
Duncan Sandsf24ed772011-05-02 16:27:02 +0000618 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
619 return ReplaceInstUsesWith(I, V);
620
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000621 if (Instruction *common = commonIRemTransforms(I))
622 return common;
623
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000624 // X urem C^2 -> X and C-1
625 { const APInt *C;
626 if (match(Op1, m_Power2(C)))
627 return BinaryOperator::CreateAnd(Op0,
628 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000629 }
630
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000631 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
632 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
633 Constant *N1 = Constant::getAllOnesValue(I.getType());
634 Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
635 return BinaryOperator::CreateAnd(Op0, Add);
636 }
637
638 // urem X, (select Cond, 2^C1, 2^C2) -->
639 // select Cond, (and X, C1-1), (and X, C2-1)
640 // when C1&C2 are powers of two.
641 { Value *Cond; const APInt *C1, *C2;
642 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
643 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
644 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
645 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000646 }
647 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000648
649 // (zext A) urem (zext B) --> zext (A urem B)
650 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
651 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
652 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
653 I.getType());
654
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000655 return 0;
656}
657
658Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
660
Duncan Sandsf24ed772011-05-02 16:27:02 +0000661 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
662 return ReplaceInstUsesWith(I, V);
663
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000664 // Handle the integer rem common cases
665 if (Instruction *Common = commonIRemTransforms(I))
666 return Common;
667
668 if (Value *RHSNeg = dyn_castNegVal(Op1))
669 if (!isa<Constant>(RHSNeg) ||
670 (isa<ConstantInt>(RHSNeg) &&
671 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
672 // X % -Y -> X % Y
673 Worklist.AddValue(I.getOperand(1));
674 I.setOperand(1, RHSNeg);
675 return &I;
676 }
677
678 // If the sign bits of both operands are zero (i.e. we can prove they are
679 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000680 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000681 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
682 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
683 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
684 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
685 }
686 }
687
688 // If it's a constant vector, flip any negative values positive.
689 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
690 unsigned VWidth = RHSV->getNumOperands();
691
692 bool hasNegative = false;
693 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
694 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
695 if (RHS->getValue().isNegative())
696 hasNegative = true;
697
698 if (hasNegative) {
699 std::vector<Constant *> Elts(VWidth);
700 for (unsigned i = 0; i != VWidth; ++i) {
701 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
702 if (RHS->getValue().isNegative())
703 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
704 else
705 Elts[i] = RHS;
706 }
707 }
708
709 Constant *NewRHSV = ConstantVector::get(Elts);
710 if (NewRHSV != RHSV) {
711 Worklist.AddValue(I.getOperand(1));
712 I.setOperand(1, NewRHSV);
713 return &I;
714 }
715 }
716 }
717
718 return 0;
719}
720
721Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000722 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000723
Duncan Sandsf24ed772011-05-02 16:27:02 +0000724 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
725 return ReplaceInstUsesWith(I, V);
726
727 // Handle cases involving: rem X, (select Cond, Y, Z)
728 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
729 return &I;
730
731 return 0;
732}