blob: a2fe0cf659e0a4d5e5abe1dfb5c27da847376bfe [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
22/// SubOne - Subtract one from a ConstantInt.
23static Constant *SubOne(ConstantInt *C) {
24 return ConstantInt::get(C->getContext(), C->getValue()-1);
25}
26
27/// MultiplyOverflows - True if the multiply can not be expressed in an int
28/// this size.
29static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
30 uint32_t W = C1->getBitWidth();
31 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
32 if (sign) {
Jay Foad40f8f622010-12-07 08:25:19 +000033 LHSExt = LHSExt.sext(W * 2);
34 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000035 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000036 LHSExt = LHSExt.zext(W * 2);
37 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000038 }
39
40 APInt MulExt = LHSExt * RHSExt;
41
42 if (!sign)
43 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
44
45 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
46 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
47 return MulExt.slt(Min) || MulExt.sgt(Max);
48}
49
50Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000051 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
53
Duncan Sands82fdab32010-12-21 14:00:22 +000054 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
55 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000056
57 // Simplify mul instructions with a constant RHS.
58 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
59 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
60
61 // ((X << C1)*C2) == (X * (C2 << C1))
62 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
63 if (SI->getOpcode() == Instruction::Shl)
64 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
65 return BinaryOperator::CreateMul(SI->getOperand(0),
66 ConstantExpr::getShl(CI, ShOp));
67
Chris Lattnerd12c27c2010-01-05 06:09:35 +000068 if (CI->isAllOnesValue()) // X * -1 == 0 - X
69 return BinaryOperator::CreateNeg(Op0, I.getName());
70
71 const APInt& Val = cast<ConstantInt>(CI)->getValue();
72 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
73 return BinaryOperator::CreateShl(Op0,
74 ConstantInt::get(Op0->getType(), Val.logBase2()));
75 }
Duncan Sands1df98592010-02-16 11:11:14 +000076 } else if (Op1C->getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +000077 if (Op1C->isNullValue())
78 return ReplaceInstUsesWith(I, Op1C);
79
80 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
81 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
82 return BinaryOperator::CreateNeg(Op0, I.getName());
83
84 // As above, vector X*splat(1.0) -> X in all defined cases.
85 if (Constant *Splat = Op1V->getSplatValue()) {
86 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
87 if (CI->equalsInt(1))
88 return ReplaceInstUsesWith(I, Op0);
89 }
90 }
91 }
92
93 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
94 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
95 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
96 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
97 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
98 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
99 return BinaryOperator::CreateAdd(Add, C1C2);
100
101 }
102
103 // Try to fold constant mul into select arguments.
104 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
105 if (Instruction *R = FoldOpIntoSelect(I, SI))
106 return R;
107
108 if (isa<PHINode>(Op0))
109 if (Instruction *NV = FoldOpIntoPhi(I))
110 return NV;
111 }
112
113 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
114 if (Value *Op1v = dyn_castNegVal(Op1))
115 return BinaryOperator::CreateMul(Op0v, Op1v);
116
117 // (X / Y) * Y = X - (X % Y)
118 // (X / Y) * -Y = (X % Y) - X
119 {
120 Value *Op1C = Op1;
121 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
122 if (!BO ||
123 (BO->getOpcode() != Instruction::UDiv &&
124 BO->getOpcode() != Instruction::SDiv)) {
125 Op1C = Op0;
126 BO = dyn_cast<BinaryOperator>(Op1);
127 }
128 Value *Neg = dyn_castNegVal(Op1C);
129 if (BO && BO->hasOneUse() &&
130 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
131 (BO->getOpcode() == Instruction::UDiv ||
132 BO->getOpcode() == Instruction::SDiv)) {
133 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
134
135 // If the division is exact, X % Y is zero.
136 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
137 if (SDiv->isExact()) {
138 if (Op1BO == Op1C)
139 return ReplaceInstUsesWith(I, Op0BO);
140 return BinaryOperator::CreateNeg(Op0BO);
141 }
142
143 Value *Rem;
144 if (BO->getOpcode() == Instruction::UDiv)
145 Rem = Builder->CreateURem(Op0BO, Op1BO);
146 else
147 Rem = Builder->CreateSRem(Op0BO, Op1BO);
148 Rem->takeName(BO);
149
150 if (Op1BO == Op1C)
151 return BinaryOperator::CreateSub(Op0BO, Rem);
152 return BinaryOperator::CreateSub(Rem, Op0BO);
153 }
154 }
155
156 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000157 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000158 return BinaryOperator::CreateAnd(Op0, Op1);
159
160 // X*(1 << Y) --> X << Y
161 // (1 << Y)*X --> X << Y
162 {
163 Value *Y;
164 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
165 return BinaryOperator::CreateShl(Op1, Y);
166 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
167 return BinaryOperator::CreateShl(Op0, Y);
168 }
169
170 // If one of the operands of the multiply is a cast from a boolean value, then
171 // we know the bool is either zero or one, so this is a 'masking' multiply.
172 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000173 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000174 // -2 is "-1 << 1" so it is all bits set except the low one.
175 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
176
177 Value *BoolCast = 0, *OtherOp = 0;
178 if (MaskedValueIsZero(Op0, Negative2))
179 BoolCast = Op0, OtherOp = Op1;
180 else if (MaskedValueIsZero(Op1, Negative2))
181 BoolCast = Op1, OtherOp = Op0;
182
183 if (BoolCast) {
184 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
185 BoolCast, "tmp");
186 return BinaryOperator::CreateAnd(V, OtherOp);
187 }
188 }
189
190 return Changed ? &I : 0;
191}
192
193Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000194 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
196
197 // Simplify mul instructions with a constant RHS...
198 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
199 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
200 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
201 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
202 if (Op1F->isExactlyValue(1.0))
Dan Gohmana9445e12010-03-02 01:11:08 +0000203 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
Duncan Sands1df98592010-02-16 11:11:14 +0000204 } else if (Op1C->getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000205 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
206 // As above, vector X*splat(1.0) -> X in all defined cases.
207 if (Constant *Splat = Op1V->getSplatValue()) {
208 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
209 if (F->isExactlyValue(1.0))
210 return ReplaceInstUsesWith(I, Op0);
211 }
212 }
213 }
214
215 // Try to fold constant mul into select arguments.
216 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
217 if (Instruction *R = FoldOpIntoSelect(I, SI))
218 return R;
219
220 if (isa<PHINode>(Op0))
221 if (Instruction *NV = FoldOpIntoPhi(I))
222 return NV;
223 }
224
225 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
226 if (Value *Op1v = dyn_castFNegVal(Op1))
227 return BinaryOperator::CreateFMul(Op0v, Op1v);
228
229 return Changed ? &I : 0;
230}
231
232/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
233/// instruction.
234bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
235 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
236
237 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
238 int NonNullOperand = -1;
239 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
240 if (ST->isNullValue())
241 NonNullOperand = 2;
242 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
243 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
244 if (ST->isNullValue())
245 NonNullOperand = 1;
246
247 if (NonNullOperand == -1)
248 return false;
249
250 Value *SelectCond = SI->getOperand(0);
251
252 // Change the div/rem to use 'Y' instead of the select.
253 I.setOperand(1, SI->getOperand(NonNullOperand));
254
255 // Okay, we know we replace the operand of the div/rem with 'Y' with no
256 // problem. However, the select, or the condition of the select may have
257 // multiple uses. Based on our knowledge that the operand must be non-zero,
258 // propagate the known value for the select into other uses of it, and
259 // propagate a known value of the condition into its other users.
260
261 // If the select and condition only have a single use, don't bother with this,
262 // early exit.
263 if (SI->use_empty() && SelectCond->hasOneUse())
264 return true;
265
266 // Scan the current block backward, looking for other uses of SI.
267 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
268
269 while (BBI != BBFront) {
270 --BBI;
271 // If we found a call to a function, we can't assume it will return, so
272 // information from below it cannot be propagated above it.
273 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
274 break;
275
276 // Replace uses of the select or its condition with the known values.
277 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
278 I != E; ++I) {
279 if (*I == SI) {
280 *I = SI->getOperand(NonNullOperand);
281 Worklist.Add(BBI);
282 } else if (*I == SelectCond) {
283 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
284 ConstantInt::getFalse(BBI->getContext());
285 Worklist.Add(BBI);
286 }
287 }
288
289 // If we past the instruction, quit looking for it.
290 if (&*BBI == SI)
291 SI = 0;
292 if (&*BBI == SelectCond)
293 SelectCond = 0;
294
295 // If we ran out of things to eliminate, break out of the loop.
296 if (SelectCond == 0 && SI == 0)
297 break;
298
299 }
300 return true;
301}
302
303
304/// This function implements the transforms on div instructions that work
305/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
306/// used by the visitors to those instructions.
307/// @brief Transforms common to all three div instructions
308Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
310
311 // undef / X -> 0 for integer.
312 // undef / X -> undef for FP (the undef could be a snan).
313 if (isa<UndefValue>(Op0)) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000314 if (Op0->getType()->isFPOrFPVectorTy())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000315 return ReplaceInstUsesWith(I, Op0);
316 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
317 }
318
319 // X / undef -> undef
320 if (isa<UndefValue>(Op1))
321 return ReplaceInstUsesWith(I, Op1);
322
323 return 0;
324}
325
326/// This function implements the transforms common to both integer division
327/// instructions (udiv and sdiv). It is called by the visitors to those integer
328/// division instructions.
329/// @brief Common integer divide transforms
330Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
332
333 // (sdiv X, X) --> 1 (udiv X, X) --> 1
334 if (Op0 == Op1) {
335 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
336 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
337 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
338 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
339 }
340
341 Constant *CI = ConstantInt::get(I.getType(), 1);
342 return ReplaceInstUsesWith(I, CI);
343 }
344
345 if (Instruction *Common = commonDivTransforms(I))
346 return Common;
347
348 // Handle cases involving: [su]div X, (select Cond, Y, Z)
349 // This does not apply for fdiv.
350 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
351 return &I;
352
353 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
354 // div X, 1 == X
355 if (RHS->equalsInt(1))
356 return ReplaceInstUsesWith(I, Op0);
357
358 // (X / C1) / C2 -> X / (C1*C2)
359 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
360 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
361 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
362 if (MultiplyOverflows(RHS, LHSRHS,
363 I.getOpcode()==Instruction::SDiv))
364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
365 else
366 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
367 ConstantExpr::getMul(RHS, LHSRHS));
368 }
369
370 if (!RHS->isZero()) { // avoid X udiv 0
371 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
372 if (Instruction *R = FoldOpIntoSelect(I, SI))
373 return R;
374 if (isa<PHINode>(Op0))
375 if (Instruction *NV = FoldOpIntoPhi(I))
376 return NV;
377 }
378 }
379
380 // 0 / X == 0, we don't need to preserve faults!
381 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
382 if (LHS->equalsInt(0))
383 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
384
385 // It can't be division by zero, hence it must be division by one.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000386 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000387 return ReplaceInstUsesWith(I, Op0);
388
389 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
390 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
391 // div X, 1 == X
392 if (X->isOne())
393 return ReplaceInstUsesWith(I, Op0);
394 }
395
396 return 0;
397}
398
399Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
401
402 // Handle the integer div common cases
403 if (Instruction *Common = commonIDivTransforms(I))
404 return Common;
405
406 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5b396202010-01-17 06:49:03 +0000407 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000408 // Check to see if this is an unsigned division with an exact power of 2,
409 // if so, convert to a right shift.
410 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
411 return BinaryOperator::CreateLShr(Op0,
412 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
413
414 // X udiv C, where C >= signbit
415 if (C->getValue().isNegative()) {
416 Value *IC = Builder->CreateICmpULT( Op0, C);
417 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
418 ConstantInt::get(I.getType(), 1));
419 }
420 }
421
422 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
423 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
424 if (RHSI->getOpcode() == Instruction::Shl &&
425 isa<ConstantInt>(RHSI->getOperand(0))) {
426 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
427 if (C1.isPowerOf2()) {
428 Value *N = RHSI->getOperand(1);
429 const Type *NTy = N->getType();
430 if (uint32_t C2 = C1.logBase2())
431 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
432 return BinaryOperator::CreateLShr(Op0, N);
433 }
434 }
435 }
436
437 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
438 // where C1&C2 are powers of two.
439 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
440 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
441 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
442 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
443 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
444 // Compute the shift amounts
445 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
446 // Construct the "on true" case of the select
447 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
448 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
449
450 // Construct the "on false" case of the select
451 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
452 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
453
454 // construct the select instruction and return it.
455 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
456 }
457 }
458 return 0;
459}
460
461Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
463
464 // Handle the integer div common cases
465 if (Instruction *Common = commonIDivTransforms(I))
466 return Common;
467
468 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
469 // sdiv X, -1 == -X
470 if (RHS->isAllOnesValue())
471 return BinaryOperator::CreateNeg(Op0);
472
473 // sdiv X, C --> ashr X, log2(C)
474 if (cast<SDivOperator>(&I)->isExact() &&
475 RHS->getValue().isNonNegative() &&
476 RHS->getValue().isPowerOf2()) {
477 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
478 RHS->getValue().exactLogBase2());
479 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
480 }
481
482 // -X/C --> X/-C provided the negation doesn't overflow.
483 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
484 if (isa<Constant>(Sub->getOperand(0)) &&
485 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
486 Sub->hasNoSignedWrap())
487 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
488 ConstantExpr::getNeg(RHS));
489 }
490
491 // If the sign bits of both operands are zero (i.e. we can prove they are
492 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000493 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000494 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
495 if (MaskedValueIsZero(Op0, Mask)) {
496 if (MaskedValueIsZero(Op1, Mask)) {
497 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
498 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
499 }
500 ConstantInt *ShiftedInt;
501 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
502 ShiftedInt->getValue().isPowerOf2()) {
503 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
504 // Safe because the only negative value (1 << Y) can take on is
505 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
506 // the sign bit set.
507 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
508 }
509 }
510 }
511
512 return 0;
513}
514
515Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
516 return commonDivTransforms(I);
517}
518
519/// This function implements the transforms on rem instructions that work
520/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
521/// is used by the visitors to those instructions.
522/// @brief Transforms common to all three rem instructions
523Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
525
526 if (isa<UndefValue>(Op0)) { // undef % X -> 0
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000527 if (I.getType()->isFPOrFPVectorTy())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000528 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
529 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
530 }
531 if (isa<UndefValue>(Op1))
532 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
533
534 // Handle cases involving: rem X, (select Cond, Y, Z)
535 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
536 return &I;
537
538 return 0;
539}
540
541/// This function implements the transforms common to both integer remainder
542/// instructions (urem and srem). It is called by the visitors to those integer
543/// remainder instructions.
544/// @brief Common integer remainder transforms
545Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
547
548 if (Instruction *common = commonRemTransforms(I))
549 return common;
550
Benjamin Kramer1951a5b2010-11-17 19:11:46 +0000551 // X % X == 0
552 if (Op0 == Op1)
553 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
554
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000555 // 0 % X == 0 for integer, we don't need to preserve faults!
556 if (Constant *LHS = dyn_cast<Constant>(Op0))
557 if (LHS->isNullValue())
558 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
559
560 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
561 // X % 0 == undef, we don't need to preserve faults!
562 if (RHS->equalsInt(0))
563 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
564
565 if (RHS->equalsInt(1)) // X % 1 == 0
566 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
567
568 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
569 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
570 if (Instruction *R = FoldOpIntoSelect(I, SI))
571 return R;
572 } else if (isa<PHINode>(Op0I)) {
573 if (Instruction *NV = FoldOpIntoPhi(I))
574 return NV;
575 }
576
577 // See if we can fold away this rem instruction.
578 if (SimplifyDemandedInstructionBits(I))
579 return &I;
580 }
581 }
582
583 return 0;
584}
585
586Instruction *InstCombiner::visitURem(BinaryOperator &I) {
587 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
588
589 if (Instruction *common = commonIRemTransforms(I))
590 return common;
591
592 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
593 // X urem C^2 -> X and C
594 // Check to see if this is an unsigned remainder with an exact power of 2,
595 // if so, convert to a bitwise and.
596 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
597 if (C->getValue().isPowerOf2())
598 return BinaryOperator::CreateAnd(Op0, SubOne(C));
599 }
600
601 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
602 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
603 if (RHSI->getOpcode() == Instruction::Shl &&
604 isa<ConstantInt>(RHSI->getOperand(0))) {
605 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
606 Constant *N1 = Constant::getAllOnesValue(I.getType());
607 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
608 return BinaryOperator::CreateAnd(Op0, Add);
609 }
610 }
611 }
612
613 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
614 // where C1&C2 are powers of two.
615 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
616 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
617 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
618 // STO == 0 and SFO == 0 handled above.
619 if ((STO->getValue().isPowerOf2()) &&
620 (SFO->getValue().isPowerOf2())) {
621 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
622 SI->getName()+".t");
623 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
624 SI->getName()+".f");
625 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
626 }
627 }
628 }
629
630 return 0;
631}
632
633Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
634 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
635
636 // Handle the integer rem common cases
637 if (Instruction *Common = commonIRemTransforms(I))
638 return Common;
639
640 if (Value *RHSNeg = dyn_castNegVal(Op1))
641 if (!isa<Constant>(RHSNeg) ||
642 (isa<ConstantInt>(RHSNeg) &&
643 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
644 // X % -Y -> X % Y
645 Worklist.AddValue(I.getOperand(1));
646 I.setOperand(1, RHSNeg);
647 return &I;
648 }
649
650 // If the sign bits of both operands are zero (i.e. we can prove they are
651 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000652 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000653 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
654 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
655 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
656 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
657 }
658 }
659
660 // If it's a constant vector, flip any negative values positive.
661 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
662 unsigned VWidth = RHSV->getNumOperands();
663
664 bool hasNegative = false;
665 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
666 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
667 if (RHS->getValue().isNegative())
668 hasNegative = true;
669
670 if (hasNegative) {
671 std::vector<Constant *> Elts(VWidth);
672 for (unsigned i = 0; i != VWidth; ++i) {
673 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
674 if (RHS->getValue().isNegative())
675 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
676 else
677 Elts[i] = RHS;
678 }
679 }
680
681 Constant *NewRHSV = ConstantVector::get(Elts);
682 if (NewRHSV != RHSV) {
683 Worklist.AddValue(I.getOperand(1));
684 I.setOperand(1, NewRHSV);
685 return &I;
686 }
687 }
688 }
689
690 return 0;
691}
692
693Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
694 return commonRemTransforms(I);
695}
696