1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
13 //===----------------------------------------------------------------------===//
15 #include "InstCombine.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/PatternMatch.h"
20 using namespace PatternMatch;
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.
26 static 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
30 if (!V->hasOneUse()) return 0;
32 bool MadeChange = false;
34 // ((1 << A) >>u B) --> (1 << (A-B))
35 // Because V cannot be zero, we know that B is less than A.
36 Value *A = 0, *B = 0, *PowerOf2 = 0;
37 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
39 // The "1" can be any value known to be a power of 2.
40 isPowerOfTwo(PowerOf2, IC.getTargetData())) {
41 A = IC.Builder->CreateSub(A, B, "tmp");
42 return IC.Builder->CreateShl(PowerOf2, A);
45 // (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)) {
57 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
62 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
63 I->setHasNoUnsignedWrap();
68 // TODO: Lots more we could do here:
69 // If V is a phi node, we can call this on each of its operands.
70 // "select cond, X, 0" can simplify to "X".
72 return MadeChange ? V : 0;
76 /// MultiplyOverflows - True if the multiply can not be expressed in an int
78 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
79 uint32_t W = C1->getBitWidth();
80 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 LHSExt = LHSExt.sext(W * 2);
83 RHSExt = RHSExt.sext(W * 2);
85 LHSExt = LHSExt.zext(W * 2);
86 RHSExt = RHSExt.zext(W * 2);
89 APInt MulExt = LHSExt * RHSExt;
92 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
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);
99 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
100 bool Changed = SimplifyAssociativeOrCommutative(I);
101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
103 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
104 return ReplaceInstUsesWith(I, V);
106 if (Value *V = SimplifyUsingDistributiveLaws(I))
107 return ReplaceInstUsesWith(I, V);
109 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
110 return BinaryOperator::CreateNeg(Op0, I.getName());
112 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
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));
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();
130 // 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));
139 // (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.
143 const APInt & Val = CI->getValue();
144 const APInt &PosVal = Val.abs();
145 if (Val.isNegative() && PosVal.isPowerOf2()) {
146 Value *X = 0, *Y = 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))))) {
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");
157 BinaryOperator::CreateMul(Sub,
158 ConstantInt::get(X->getType(), PosVal));
164 // Simplify mul instructions with a constant RHS.
165 if (isa<Constant>(Op1)) {
166 // Try to fold constant mul into select arguments.
167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
168 if (Instruction *R = FoldOpIntoSelect(I, SI))
171 if (isa<PHINode>(Op0))
172 if (Instruction *NV = FoldOpIntoPhi(I))
176 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
177 if (Value *Op1v = dyn_castNegVal(Op1))
178 return BinaryOperator::CreateMul(Op0v, Op1v);
180 // (X / Y) * Y = X - (X % Y)
181 // (X / Y) * -Y = (X % Y) - X
184 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
186 (BO->getOpcode() != Instruction::UDiv &&
187 BO->getOpcode() != Instruction::SDiv)) {
189 BO = dyn_cast<BinaryOperator>(Op1);
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);
198 // 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))
200 if (SDiv->isExact()) {
202 return ReplaceInstUsesWith(I, Op0BO);
203 return BinaryOperator::CreateNeg(Op0BO);
207 if (BO->getOpcode() == Instruction::UDiv)
208 Rem = Builder->CreateURem(Op0BO, Op1BO);
210 Rem = Builder->CreateSRem(Op0BO, Op1BO);
214 return BinaryOperator::CreateSub(Op0BO, Rem);
215 return BinaryOperator::CreateSub(Rem, Op0BO);
219 /// i1 mul -> i1 and.
220 if (I.getType()->isIntegerTy(1))
221 return BinaryOperator::CreateAnd(Op0, Op1);
223 // X*(1 << Y) --> X << Y
224 // (1 << Y)*X --> X << 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);
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)
236 if (!I.getType()->isVectorTy()) {
237 // -2 is "-1 << 1" so it is all bits set except the low one.
238 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
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;
247 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
249 return BinaryOperator::CreateAnd(V, OtherOp);
253 return Changed ? &I : 0;
256 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
257 bool Changed = SimplifyAssociativeOrCommutative(I);
258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
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))
266 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
267 } else if (Op1C->getType()->isVectorTy()) {
268 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);
278 // Try to fold constant mul into select arguments.
279 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
280 if (Instruction *R = FoldOpIntoSelect(I, SI))
283 if (isa<PHINode>(Op0))
284 if (Instruction *NV = FoldOpIntoPhi(I))
288 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
289 if (Value *Op1v = dyn_castFNegVal(Op1))
290 return BinaryOperator::CreateFMul(Op0v, Op1v);
292 return Changed ? &I : 0;
295 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
297 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
298 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
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())
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())
310 if (NonNullOperand == -1)
313 Value *SelectCond = SI->getOperand(0);
315 // Change the div/rem to use 'Y' instead of the select.
316 I.setOperand(1, SI->getOperand(NonNullOperand));
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.
324 // If the select and condition only have a single use, don't bother with this,
326 if (SI->use_empty() && SelectCond->hasOneUse())
329 // Scan the current block backward, looking for other uses of SI.
330 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
332 while (BBI != BBFront) {
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))
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();
343 *I = SI->getOperand(NonNullOperand);
345 } else if (*I == SelectCond) {
346 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
347 ConstantInt::getFalse(BBI->getContext());
352 // If we past the instruction, quit looking for it.
355 if (&*BBI == SelectCond)
358 // If we ran out of things to eliminate, break out of the loop.
359 if (SelectCond == 0 && SI == 0)
367 /// 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
371 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
374 // The RHS is known non-zero.
375 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
380 // Handle cases involving: [su]div X, (select Cond, Y, Z)
381 // This does not apply for fdiv.
382 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
386 // (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()));
393 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
394 ConstantExpr::getMul(RHS, LHSRHS));
397 if (!RHS->isZero()) { // avoid X udiv 0
398 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
399 if (Instruction *R = FoldOpIntoSelect(I, SI))
401 if (isa<PHINode>(Op0))
402 if (Instruction *NV = FoldOpIntoPhi(I))
407 // See if we can fold away this div instruction.
408 if (SimplifyDemandedInstructionBits(I))
411 // (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);
423 /// dyn_castZExtVal - Checks if V is a zext or constant that can
424 /// be truncated to Ty without losing bits.
425 static 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);
436 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
439 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
440 return ReplaceInstUsesWith(I, V);
442 // Handle the integer div common cases
443 if (Instruction *Common = commonIDivTransforms(I))
446 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
447 // X udiv 2^C -> X >> C
448 // Check to see if this is an unsigned division with an exact power of 2,
449 // if so, convert to a right shift.
450 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
451 BinaryOperator *LShr =
452 BinaryOperator::CreateLShr(Op0,
453 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
454 if (I.isExact()) LShr->setIsExact();
458 // X udiv C, where C >= signbit
459 if (C->getValue().isNegative()) {
460 Value *IC = Builder->CreateICmpULT(Op0, C);
461 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
462 ConstantInt::get(I.getType(), 1));
466 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
467 { const APInt *CI; Value *N;
468 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
470 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
473 return BinaryOperator::CreateExactLShr(Op0, N);
474 return BinaryOperator::CreateLShr(Op0, N);
478 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
479 // where C1&C2 are powers of two.
480 { 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",
486 // Construct the "on false" case of the select
487 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
490 // construct the select instruction and return it.
491 return SelectInst::Create(Cond, TSI, FSI);
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",
505 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
506 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
508 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
509 return ReplaceInstUsesWith(I, V);
511 // Handle the integer div common cases
512 if (Instruction *Common = commonIDivTransforms(I))
515 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
517 if (RHS->isAllOnesValue())
518 return BinaryOperator::CreateNeg(Op0);
520 // sdiv X, C --> ashr exact X, log2(C)
521 if (I.isExact() && RHS->getValue().isNonNegative() &&
522 RHS->getValue().isPowerOf2()) {
523 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
524 RHS->getValue().exactLogBase2());
525 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
528 // -X/C --> X/-C provided the negation doesn't overflow.
529 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
530 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
531 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
532 ConstantExpr::getNeg(RHS));
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.
537 if (I.getType()->isIntegerTy()) {
538 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());
545 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
546 // 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
550 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
558 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
559 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
561 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
562 return ReplaceInstUsesWith(I, V);
564 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
565 const APFloat &Op1F = Op1C->getValueAPF();
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);
579 /// 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
583 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
586 // The RHS is known non-zero.
587 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
592 // Handle cases involving: rem X, (select Cond, Y, Z)
593 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
596 if (isa<ConstantInt>(Op1)) {
597 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
598 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
599 if (Instruction *R = FoldOpIntoSelect(I, SI))
601 } else if (isa<PHINode>(Op0I)) {
602 if (Instruction *NV = FoldOpIntoPhi(I))
606 // See if we can fold away this rem instruction.
607 if (SimplifyDemandedInstructionBits(I))
615 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
616 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
618 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
619 return ReplaceInstUsesWith(I, V);
621 if (Instruction *common = commonIRemTransforms(I))
624 // X urem C^2 -> X and C-1
626 if (match(Op1, m_Power2(C)))
627 return BinaryOperator::CreateAnd(Op0,
628 ConstantInt::get(I.getType(), *C-1));
631 // 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);
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);
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),
658 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
661 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
662 return ReplaceInstUsesWith(I, V);
664 // Handle the integer rem common cases
665 if (Instruction *Common = commonIRemTransforms(I))
668 if (Value *RHSNeg = dyn_castNegVal(Op1))
669 if (!isa<Constant>(RHSNeg) ||
670 (isa<ConstantInt>(RHSNeg) &&
671 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
673 Worklist.AddValue(I.getOperand(1));
674 I.setOperand(1, RHSNeg);
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.
680 if (I.getType()->isIntegerTy()) {
681 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());
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();
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())
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));
709 Constant *NewRHSV = ConstantVector::get(Elts);
710 if (NewRHSV != RHSV) {
711 Worklist.AddValue(I.getOperand(1));
712 I.setOperand(1, NewRHSV);
721 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
722 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
724 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
725 return ReplaceInstUsesWith(I, V);
727 // Handle cases involving: rem X, (select Cond, Y, Z)
728 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))