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/Analysis/InstructionSimplify.h"
17 #include "llvm/IntrinsicInst.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.getDataLayout())) {
41 A = IC.Builder->CreateSub(A, B);
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.getDataLayout())) {
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);
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;
147 if (Op0->hasOneUse()) {
150 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
151 Sub = Builder->CreateSub(X, Y, "suba");
152 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
153 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
156 BinaryOperator::CreateMul(Sub,
157 ConstantInt::get(Y->getType(), PosVal));
163 // Simplify mul instructions with a constant RHS.
164 if (isa<Constant>(Op1)) {
165 // Try to fold constant mul into select arguments.
166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
167 if (Instruction *R = FoldOpIntoSelect(I, SI))
170 if (isa<PHINode>(Op0))
171 if (Instruction *NV = FoldOpIntoPhi(I))
175 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
176 if (Value *Op1v = dyn_castNegVal(Op1))
177 return BinaryOperator::CreateMul(Op0v, Op1v);
179 // (X / Y) * Y = X - (X % Y)
180 // (X / Y) * -Y = (X % Y) - X
183 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
185 (BO->getOpcode() != Instruction::UDiv &&
186 BO->getOpcode() != Instruction::SDiv)) {
188 BO = dyn_cast<BinaryOperator>(Op1);
190 Value *Neg = dyn_castNegVal(Op1C);
191 if (BO && BO->hasOneUse() &&
192 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
193 (BO->getOpcode() == Instruction::UDiv ||
194 BO->getOpcode() == Instruction::SDiv)) {
195 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
197 // If the division is exact, X % Y is zero, so we end up with X or -X.
198 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
199 if (SDiv->isExact()) {
201 return ReplaceInstUsesWith(I, Op0BO);
202 return BinaryOperator::CreateNeg(Op0BO);
206 if (BO->getOpcode() == Instruction::UDiv)
207 Rem = Builder->CreateURem(Op0BO, Op1BO);
209 Rem = Builder->CreateSRem(Op0BO, Op1BO);
213 return BinaryOperator::CreateSub(Op0BO, Rem);
214 return BinaryOperator::CreateSub(Rem, Op0BO);
218 /// i1 mul -> i1 and.
219 if (I.getType()->isIntegerTy(1))
220 return BinaryOperator::CreateAnd(Op0, Op1);
222 // X*(1 << Y) --> X << Y
223 // (1 << Y)*X --> X << Y
226 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
227 return BinaryOperator::CreateShl(Op1, Y);
228 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
229 return BinaryOperator::CreateShl(Op0, Y);
232 // If one of the operands of the multiply is a cast from a boolean value, then
233 // we know the bool is either zero or one, so this is a 'masking' multiply.
234 // X * Y (where Y is 0 or 1) -> X & (0-Y)
235 if (!I.getType()->isVectorTy()) {
236 // -2 is "-1 << 1" so it is all bits set except the low one.
237 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
239 Value *BoolCast = 0, *OtherOp = 0;
240 if (MaskedValueIsZero(Op0, Negative2))
241 BoolCast = Op0, OtherOp = Op1;
242 else if (MaskedValueIsZero(Op1, Negative2))
243 BoolCast = Op1, OtherOp = Op0;
246 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
248 return BinaryOperator::CreateAnd(V, OtherOp);
252 return Changed ? &I : 0;
260 // And check for corresponding fast math flags
263 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
265 if (!Op->hasOneUse())
268 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
271 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
275 Value *OpLog2Of = II->getArgOperand(0);
276 if (!OpLog2Of->hasOneUse())
279 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
282 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
285 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
286 if (CFP && CFP->isExactlyValue(0.5)) {
287 Y = I->getOperand(1);
290 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
291 if (CFP && CFP->isExactlyValue(0.5))
292 Y = I->getOperand(0);
295 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
296 bool Changed = SimplifyAssociativeOrCommutative(I);
297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
299 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
300 return ReplaceInstUsesWith(I, V);
302 // Simplify mul instructions with a constant RHS.
303 if (isa<Constant>(Op1)) {
304 // Try to fold constant mul into select arguments.
305 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
306 if (Instruction *R = FoldOpIntoSelect(I, SI))
309 if (isa<PHINode>(Op0))
310 if (Instruction *NV = FoldOpIntoPhi(I))
314 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
315 if (Value *Op1v = dyn_castFNegVal(Op1))
316 return BinaryOperator::CreateFMul(Op0v, Op1v);
318 // Under unsafe algebra do:
319 // X * log2(0.5*Y) = X*log2(Y) - X
320 if (I.hasUnsafeAlgebra()) {
324 detectLog2OfHalf(Op0, OpY, Log2);
328 detectLog2OfHalf(Op1, OpY, Log2);
333 // if pattern detected emit alternate sequence
335 Log2->setArgOperand(0, OpY);
336 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
337 Instruction *FMul = cast<Instruction>(FMulVal);
338 FMul->copyFastMathFlags(Log2);
339 Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
340 FSub->copyFastMathFlags(Log2);
345 return Changed ? &I : 0;
348 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
350 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
351 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
353 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
354 int NonNullOperand = -1;
355 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
356 if (ST->isNullValue())
358 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
359 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
360 if (ST->isNullValue())
363 if (NonNullOperand == -1)
366 Value *SelectCond = SI->getOperand(0);
368 // Change the div/rem to use 'Y' instead of the select.
369 I.setOperand(1, SI->getOperand(NonNullOperand));
371 // Okay, we know we replace the operand of the div/rem with 'Y' with no
372 // problem. However, the select, or the condition of the select may have
373 // multiple uses. Based on our knowledge that the operand must be non-zero,
374 // propagate the known value for the select into other uses of it, and
375 // propagate a known value of the condition into its other users.
377 // If the select and condition only have a single use, don't bother with this,
379 if (SI->use_empty() && SelectCond->hasOneUse())
382 // Scan the current block backward, looking for other uses of SI.
383 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
385 while (BBI != BBFront) {
387 // If we found a call to a function, we can't assume it will return, so
388 // information from below it cannot be propagated above it.
389 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
392 // Replace uses of the select or its condition with the known values.
393 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
396 *I = SI->getOperand(NonNullOperand);
398 } else if (*I == SelectCond) {
399 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
400 ConstantInt::getFalse(BBI->getContext());
405 // If we past the instruction, quit looking for it.
408 if (&*BBI == SelectCond)
411 // If we ran out of things to eliminate, break out of the loop.
412 if (SelectCond == 0 && SI == 0)
420 /// This function implements the transforms common to both integer division
421 /// instructions (udiv and sdiv). It is called by the visitors to those integer
422 /// division instructions.
423 /// @brief Common integer divide transforms
424 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
427 // The RHS is known non-zero.
428 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
433 // Handle cases involving: [su]div X, (select Cond, Y, Z)
434 // This does not apply for fdiv.
435 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
438 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
439 // (X / C1) / C2 -> X / (C1*C2)
440 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
441 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
442 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
443 if (MultiplyOverflows(RHS, LHSRHS,
444 I.getOpcode()==Instruction::SDiv))
445 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
446 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
447 ConstantExpr::getMul(RHS, LHSRHS));
450 if (!RHS->isZero()) { // avoid X udiv 0
451 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
452 if (Instruction *R = FoldOpIntoSelect(I, SI))
454 if (isa<PHINode>(Op0))
455 if (Instruction *NV = FoldOpIntoPhi(I))
460 // See if we can fold away this div instruction.
461 if (SimplifyDemandedInstructionBits(I))
464 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
465 Value *X = 0, *Z = 0;
466 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
467 bool isSigned = I.getOpcode() == Instruction::SDiv;
468 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
469 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
470 return BinaryOperator::Create(I.getOpcode(), X, Op1);
476 /// dyn_castZExtVal - Checks if V is a zext or constant that can
477 /// be truncated to Ty without losing bits.
478 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
479 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
480 if (Z->getSrcTy() == Ty)
481 return Z->getOperand(0);
482 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
483 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
484 return ConstantExpr::getTrunc(C, Ty);
489 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
490 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
492 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
493 return ReplaceInstUsesWith(I, V);
495 // Handle the integer div common cases
496 if (Instruction *Common = commonIDivTransforms(I))
500 // X udiv 2^C -> X >> C
501 // Check to see if this is an unsigned division with an exact power of 2,
502 // if so, convert to a right shift.
504 if (match(Op1, m_Power2(C))) {
505 BinaryOperator *LShr =
506 BinaryOperator::CreateLShr(Op0,
507 ConstantInt::get(Op0->getType(),
509 if (I.isExact()) LShr->setIsExact();
514 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
515 // X udiv C, where C >= signbit
516 if (C->getValue().isNegative()) {
517 Value *IC = Builder->CreateICmpULT(Op0, C);
518 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
519 ConstantInt::get(I.getType(), 1));
523 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
524 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
527 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
528 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
529 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
533 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
534 { const APInt *CI; Value *N;
535 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
536 match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
538 N = Builder->CreateAdd(N,
539 ConstantInt::get(N->getType(), CI->logBase2()));
540 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
541 N = Builder->CreateZExt(N, Z->getDestTy());
543 return BinaryOperator::CreateExactLShr(Op0, N);
544 return BinaryOperator::CreateLShr(Op0, N);
548 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
549 // where C1&C2 are powers of two.
550 { Value *Cond; const APInt *C1, *C2;
551 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
552 // Construct the "on true" case of the select
553 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
556 // Construct the "on false" case of the select
557 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
560 // construct the select instruction and return it.
561 return SelectInst::Create(Cond, TSI, FSI);
565 // (zext A) udiv (zext B) --> zext (A udiv B)
566 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
567 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
568 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
575 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
578 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
579 return ReplaceInstUsesWith(I, V);
581 // Handle the integer div common cases
582 if (Instruction *Common = commonIDivTransforms(I))
585 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
587 if (RHS->isAllOnesValue())
588 return BinaryOperator::CreateNeg(Op0);
590 // sdiv X, C --> ashr exact X, log2(C)
591 if (I.isExact() && RHS->getValue().isNonNegative() &&
592 RHS->getValue().isPowerOf2()) {
593 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
594 RHS->getValue().exactLogBase2());
595 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
598 // -X/C --> X/-C provided the negation doesn't overflow.
599 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
600 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
601 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
602 ConstantExpr::getNeg(RHS));
605 // If the sign bits of both operands are zero (i.e. we can prove they are
606 // unsigned inputs), turn this into a udiv.
607 if (I.getType()->isIntegerTy()) {
608 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
609 if (MaskedValueIsZero(Op0, Mask)) {
610 if (MaskedValueIsZero(Op1, Mask)) {
611 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
612 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
615 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
616 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
617 // Safe because the only negative value (1 << Y) can take on is
618 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
620 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
628 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
629 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
631 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
632 return ReplaceInstUsesWith(I, V);
634 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
635 const APFloat &Op1F = Op1C->getValueAPF();
637 // If the divisor has an exact multiplicative inverse we can turn the fdiv
638 // into a cheaper fmul.
639 APFloat Reciprocal(Op1F.getSemantics());
640 if (Op1F.getExactInverse(&Reciprocal)) {
641 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
642 return BinaryOperator::CreateFMul(Op0, RFP);
649 /// This function implements the transforms common to both integer remainder
650 /// instructions (urem and srem). It is called by the visitors to those integer
651 /// remainder instructions.
652 /// @brief Common integer remainder transforms
653 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
654 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
656 // The RHS is known non-zero.
657 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
662 // Handle cases involving: rem X, (select Cond, Y, Z)
663 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
666 if (isa<ConstantInt>(Op1)) {
667 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
668 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
669 if (Instruction *R = FoldOpIntoSelect(I, SI))
671 } else if (isa<PHINode>(Op0I)) {
672 if (Instruction *NV = FoldOpIntoPhi(I))
676 // See if we can fold away this rem instruction.
677 if (SimplifyDemandedInstructionBits(I))
685 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
688 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
689 return ReplaceInstUsesWith(I, V);
691 if (Instruction *common = commonIRemTransforms(I))
694 // X urem C^2 -> X and C-1
696 if (match(Op1, m_Power2(C)))
697 return BinaryOperator::CreateAnd(Op0,
698 ConstantInt::get(I.getType(), *C-1));
701 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
702 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
703 Constant *N1 = Constant::getAllOnesValue(I.getType());
704 Value *Add = Builder->CreateAdd(Op1, N1);
705 return BinaryOperator::CreateAnd(Op0, Add);
708 // urem X, (select Cond, 2^C1, 2^C2) -->
709 // select Cond, (and X, C1-1), (and X, C2-1)
710 // when C1&C2 are powers of two.
711 { Value *Cond; const APInt *C1, *C2;
712 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
713 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
714 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
715 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
719 // (zext A) urem (zext B) --> zext (A urem B)
720 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
721 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
722 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
728 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
731 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
732 return ReplaceInstUsesWith(I, V);
734 // Handle the integer rem common cases
735 if (Instruction *Common = commonIRemTransforms(I))
738 if (Value *RHSNeg = dyn_castNegVal(Op1))
739 if (!isa<Constant>(RHSNeg) ||
740 (isa<ConstantInt>(RHSNeg) &&
741 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
743 Worklist.AddValue(I.getOperand(1));
744 I.setOperand(1, RHSNeg);
748 // If the sign bits of both operands are zero (i.e. we can prove they are
749 // unsigned inputs), turn this into a urem.
750 if (I.getType()->isIntegerTy()) {
751 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
752 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
753 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
754 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
758 // If it's a constant vector, flip any negative values positive.
759 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
760 Constant *C = cast<Constant>(Op1);
761 unsigned VWidth = C->getType()->getVectorNumElements();
763 bool hasNegative = false;
764 bool hasMissing = false;
765 for (unsigned i = 0; i != VWidth; ++i) {
766 Constant *Elt = C->getAggregateElement(i);
772 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
773 if (RHS->isNegative())
777 if (hasNegative && !hasMissing) {
778 SmallVector<Constant *, 16> Elts(VWidth);
779 for (unsigned i = 0; i != VWidth; ++i) {
780 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
781 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
782 if (RHS->isNegative())
783 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
787 Constant *NewRHSV = ConstantVector::get(Elts);
788 if (NewRHSV != C) { // Don't loop on -MININT
789 Worklist.AddValue(I.getOperand(1));
790 I.setOperand(1, NewRHSV);
799 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
800 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
802 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
803 return ReplaceInstUsesWith(I, V);
805 // Handle cases involving: rem X, (select Cond, Y, Z)
806 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))