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/IR/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 isKnownToBeAPowerOfTwo(PowerOf2)) {
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() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
49 // We know that this is an exact/nuw shift and that the input is a
50 // non-zero context as well.
51 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
56 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
62 I->setHasNoUnsignedWrap();
67 // TODO: Lots more we could do here:
68 // If V is a phi node, we can call this on each of its operands.
69 // "select cond, X, 0" can simplify to "X".
71 return MadeChange ? V : 0;
75 /// MultiplyOverflows - True if the multiply can not be expressed in an int
77 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
78 uint32_t W = C1->getBitWidth();
79 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
81 LHSExt = LHSExt.sext(W * 2);
82 RHSExt = RHSExt.sext(W * 2);
84 LHSExt = LHSExt.zext(W * 2);
85 RHSExt = RHSExt.zext(W * 2);
88 APInt MulExt = LHSExt * RHSExt;
91 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
93 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
94 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
95 return MulExt.slt(Min) || MulExt.sgt(Max);
98 /// \brief A helper routine of InstCombiner::visitMul().
100 /// If C is a vector of known powers of 2, then this function returns
101 /// a new vector obtained from C replacing each element with its logBase2.
102 /// Return a null pointer otherwise.
103 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
105 SmallVector<Constant *, 4> Elts;
107 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
108 Constant *Elt = CV->getElementAsConstant(I);
109 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
111 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
114 return ConstantVector::get(Elts);
117 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
118 bool Changed = SimplifyAssociativeOrCommutative(I);
119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
121 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
122 return ReplaceInstUsesWith(I, V);
124 if (Value *V = SimplifyUsingDistributiveLaws(I))
125 return ReplaceInstUsesWith(I, V);
127 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
128 return BinaryOperator::CreateNeg(Op0, I.getName());
130 // Also allow combining multiply instructions on vectors.
135 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
137 match(C1, m_APInt(IVal)))
138 // ((X << C1)*C2) == (X * (C2 << C1))
139 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
141 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
142 Constant *NewCst = 0;
143 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
144 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
145 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
146 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
147 // Replace X*(2^C) with X << C, where C is a vector of known
148 // constant powers of 2.
149 NewCst = getLogBase2Vector(CV);
152 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
153 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
154 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
160 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
161 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
162 { Value *X; ConstantInt *C1;
163 if (Op0->hasOneUse() &&
164 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
165 Value *Add = Builder->CreateMul(X, CI);
166 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
170 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
171 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
172 // The "* (2**n)" thus becomes a potential shifting opportunity.
174 const APInt & Val = CI->getValue();
175 const APInt &PosVal = Val.abs();
176 if (Val.isNegative() && PosVal.isPowerOf2()) {
177 Value *X = 0, *Y = 0;
178 if (Op0->hasOneUse()) {
181 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
182 Sub = Builder->CreateSub(X, Y, "suba");
183 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
184 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
187 BinaryOperator::CreateMul(Sub,
188 ConstantInt::get(Y->getType(), PosVal));
194 // Simplify mul instructions with a constant RHS.
195 if (isa<Constant>(Op1)) {
196 // Try to fold constant mul into select arguments.
197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
198 if (Instruction *R = FoldOpIntoSelect(I, SI))
201 if (isa<PHINode>(Op0))
202 if (Instruction *NV = FoldOpIntoPhi(I))
206 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
207 if (Value *Op1v = dyn_castNegVal(Op1))
208 return BinaryOperator::CreateMul(Op0v, Op1v);
210 // (X / Y) * Y = X - (X % Y)
211 // (X / Y) * -Y = (X % Y) - X
214 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
216 (BO->getOpcode() != Instruction::UDiv &&
217 BO->getOpcode() != Instruction::SDiv)) {
219 BO = dyn_cast<BinaryOperator>(Op1);
221 Value *Neg = dyn_castNegVal(Op1C);
222 if (BO && BO->hasOneUse() &&
223 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
224 (BO->getOpcode() == Instruction::UDiv ||
225 BO->getOpcode() == Instruction::SDiv)) {
226 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
228 // If the division is exact, X % Y is zero, so we end up with X or -X.
229 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
230 if (SDiv->isExact()) {
232 return ReplaceInstUsesWith(I, Op0BO);
233 return BinaryOperator::CreateNeg(Op0BO);
237 if (BO->getOpcode() == Instruction::UDiv)
238 Rem = Builder->CreateURem(Op0BO, Op1BO);
240 Rem = Builder->CreateSRem(Op0BO, Op1BO);
244 return BinaryOperator::CreateSub(Op0BO, Rem);
245 return BinaryOperator::CreateSub(Rem, Op0BO);
249 /// i1 mul -> i1 and.
250 if (I.getType()->isIntegerTy(1))
251 return BinaryOperator::CreateAnd(Op0, Op1);
253 // X*(1 << Y) --> X << Y
254 // (1 << Y)*X --> X << Y
257 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
258 return BinaryOperator::CreateShl(Op1, Y);
259 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
260 return BinaryOperator::CreateShl(Op0, Y);
263 // If one of the operands of the multiply is a cast from a boolean value, then
264 // we know the bool is either zero or one, so this is a 'masking' multiply.
265 // X * Y (where Y is 0 or 1) -> X & (0-Y)
266 if (!I.getType()->isVectorTy()) {
267 // -2 is "-1 << 1" so it is all bits set except the low one.
268 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
270 Value *BoolCast = 0, *OtherOp = 0;
271 if (MaskedValueIsZero(Op0, Negative2))
272 BoolCast = Op0, OtherOp = Op1;
273 else if (MaskedValueIsZero(Op1, Negative2))
274 BoolCast = Op1, OtherOp = Op0;
277 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
279 return BinaryOperator::CreateAnd(V, OtherOp);
283 return Changed ? &I : 0;
291 // And check for corresponding fast math flags
294 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
296 if (!Op->hasOneUse())
299 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
302 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
306 Value *OpLog2Of = II->getArgOperand(0);
307 if (!OpLog2Of->hasOneUse())
310 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
313 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
316 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
317 if (CFP && CFP->isExactlyValue(0.5)) {
318 Y = I->getOperand(1);
321 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
322 if (CFP && CFP->isExactlyValue(0.5))
323 Y = I->getOperand(0);
326 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
327 /// true iff the given value is FMul or FDiv with one and only one operand
328 /// being a normal constant (i.e. not Zero/NaN/Infinity).
329 static bool isFMulOrFDivWithConstant(Value *V) {
330 Instruction *I = dyn_cast<Instruction>(V);
331 if (!I || (I->getOpcode() != Instruction::FMul &&
332 I->getOpcode() != Instruction::FDiv))
335 ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
336 ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
341 return (C0 && C0->getValueAPF().isFiniteNonZero()) ||
342 (C1 && C1->getValueAPF().isFiniteNonZero());
345 static bool isNormalFp(const ConstantFP *C) {
346 const APFloat &Flt = C->getValueAPF();
347 return Flt.isFiniteNonZero() && !Flt.isDenormal();
350 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
351 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
352 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
353 /// This function is to simplify "FMulOrDiv * C" and returns the
354 /// resulting expression. Note that this function could return NULL in
355 /// case the constants cannot be folded into a normal floating-point.
357 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, ConstantFP *C,
358 Instruction *InsertBefore) {
359 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
361 Value *Opnd0 = FMulOrDiv->getOperand(0);
362 Value *Opnd1 = FMulOrDiv->getOperand(1);
364 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
365 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
367 BinaryOperator *R = 0;
369 // (X * C0) * C => X * (C0*C)
370 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
371 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
372 if (isNormalFp(cast<ConstantFP>(F)))
373 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
376 // (C0 / X) * C => (C0 * C) / X
377 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C));
379 R = BinaryOperator::CreateFDiv(F, Opnd1);
381 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
382 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1));
384 R = BinaryOperator::CreateFMul(Opnd0, F);
386 // (X / C1) * C => X / (C1/C)
387 Constant *F = ConstantExpr::getFDiv(C1, C);
388 if (isNormalFp(cast<ConstantFP>(F)))
389 R = BinaryOperator::CreateFDiv(Opnd0, F);
395 R->setHasUnsafeAlgebra(true);
396 InsertNewInstWith(R, *InsertBefore);
402 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
403 bool Changed = SimplifyAssociativeOrCommutative(I);
404 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
406 if (isa<Constant>(Op0))
409 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
410 return ReplaceInstUsesWith(I, V);
412 bool AllowReassociate = I.hasUnsafeAlgebra();
414 // Simplify mul instructions with a constant RHS.
415 if (isa<Constant>(Op1)) {
416 // Try to fold constant mul into select arguments.
417 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
418 if (Instruction *R = FoldOpIntoSelect(I, SI))
421 if (isa<PHINode>(Op0))
422 if (Instruction *NV = FoldOpIntoPhi(I))
425 ConstantFP *C = dyn_cast<ConstantFP>(Op1);
426 if (C && AllowReassociate && C->getValueAPF().isFiniteNonZero()) {
427 // Let MDC denote an expression in one of these forms:
428 // X * C, C/X, X/C, where C is a constant.
430 // Try to simplify "MDC * Constant"
431 if (isFMulOrFDivWithConstant(Op0)) {
432 Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I);
434 return ReplaceInstUsesWith(I, V);
437 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
438 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
440 (FAddSub->getOpcode() == Instruction::FAdd ||
441 FAddSub->getOpcode() == Instruction::FSub)) {
442 Value *Opnd0 = FAddSub->getOperand(0);
443 Value *Opnd1 = FAddSub->getOperand(1);
444 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
445 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
449 std::swap(Opnd0, Opnd1);
453 if (C1 && C1->getValueAPF().isFiniteNonZero() &&
454 isFMulOrFDivWithConstant(Opnd0)) {
455 Value *M1 = ConstantExpr::getFMul(C1, C);
456 Value *M0 = isNormalFp(cast<ConstantFP>(M1)) ?
457 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
460 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
463 Value *R = (FAddSub->getOpcode() == Instruction::FAdd) ?
464 BinaryOperator::CreateFAdd(M0, M1) :
465 BinaryOperator::CreateFSub(M0, M1);
466 Instruction *RI = cast<Instruction>(R);
467 RI->copyFastMathFlags(&I);
476 // Under unsafe algebra do:
477 // X * log2(0.5*Y) = X*log2(Y) - X
478 if (I.hasUnsafeAlgebra()) {
482 detectLog2OfHalf(Op0, OpY, Log2);
486 detectLog2OfHalf(Op1, OpY, Log2);
491 // if pattern detected emit alternate sequence
493 Log2->setArgOperand(0, OpY);
494 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
495 Instruction *FMul = cast<Instruction>(FMulVal);
496 FMul->copyFastMathFlags(Log2);
497 Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
498 FSub->copyFastMathFlags(Log2);
503 // Handle symmetric situation in a 2-iteration loop
506 for (int i = 0; i < 2; i++) {
507 bool IgnoreZeroSign = I.hasNoSignedZeros();
508 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
509 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
510 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
514 return BinaryOperator::CreateFMul(N0, N1);
516 if (Opnd0->hasOneUse()) {
517 // -X * Y => -(X*Y) (Promote negation as high as possible)
518 Value *T = Builder->CreateFMul(N0, Opnd1);
519 cast<Instruction>(T)->setDebugLoc(I.getDebugLoc());
520 Instruction *Neg = BinaryOperator::CreateFNeg(T);
521 if (I.getFastMathFlags().any()) {
522 cast<Instruction>(T)->copyFastMathFlags(&I);
523 Neg->copyFastMathFlags(&I);
529 // (X*Y) * X => (X*X) * Y where Y != X
530 // The purpose is two-fold:
531 // 1) to form a power expression (of X).
532 // 2) potentially shorten the critical path: After transformation, the
533 // latency of the instruction Y is amortized by the expression of X*X,
534 // and therefore Y is in a "less critical" position compared to what it
535 // was before the transformation.
537 if (AllowReassociate) {
538 Value *Opnd0_0, *Opnd0_1;
539 if (Opnd0->hasOneUse() &&
540 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
542 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
544 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
548 Instruction *T = cast<Instruction>(Builder->CreateFMul(Opnd1, Opnd1));
549 T->copyFastMathFlags(&I);
550 T->setDebugLoc(I.getDebugLoc());
552 Instruction *R = BinaryOperator::CreateFMul(T, Y);
553 R->copyFastMathFlags(&I);
559 if (!isa<Constant>(Op1))
560 std::swap(Opnd0, Opnd1);
565 return Changed ? &I : 0;
568 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
570 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
571 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
573 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
574 int NonNullOperand = -1;
575 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
576 if (ST->isNullValue())
578 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
579 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
580 if (ST->isNullValue())
583 if (NonNullOperand == -1)
586 Value *SelectCond = SI->getOperand(0);
588 // Change the div/rem to use 'Y' instead of the select.
589 I.setOperand(1, SI->getOperand(NonNullOperand));
591 // Okay, we know we replace the operand of the div/rem with 'Y' with no
592 // problem. However, the select, or the condition of the select may have
593 // multiple uses. Based on our knowledge that the operand must be non-zero,
594 // propagate the known value for the select into other uses of it, and
595 // propagate a known value of the condition into its other users.
597 // If the select and condition only have a single use, don't bother with this,
599 if (SI->use_empty() && SelectCond->hasOneUse())
602 // Scan the current block backward, looking for other uses of SI.
603 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
605 while (BBI != BBFront) {
607 // If we found a call to a function, we can't assume it will return, so
608 // information from below it cannot be propagated above it.
609 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
612 // Replace uses of the select or its condition with the known values.
613 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
616 *I = SI->getOperand(NonNullOperand);
618 } else if (*I == SelectCond) {
619 *I = Builder->getInt1(NonNullOperand == 1);
624 // If we past the instruction, quit looking for it.
627 if (&*BBI == SelectCond)
630 // If we ran out of things to eliminate, break out of the loop.
631 if (SelectCond == 0 && SI == 0)
639 /// This function implements the transforms common to both integer division
640 /// instructions (udiv and sdiv). It is called by the visitors to those integer
641 /// division instructions.
642 /// @brief Common integer divide transforms
643 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
646 // The RHS is known non-zero.
647 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
652 // Handle cases involving: [su]div X, (select Cond, Y, Z)
653 // This does not apply for fdiv.
654 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
657 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
658 // (X / C1) / C2 -> X / (C1*C2)
659 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
660 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
661 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
662 if (MultiplyOverflows(RHS, LHSRHS,
663 I.getOpcode()==Instruction::SDiv))
664 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
665 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
666 ConstantExpr::getMul(RHS, LHSRHS));
669 if (!RHS->isZero()) { // avoid X udiv 0
670 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
671 if (Instruction *R = FoldOpIntoSelect(I, SI))
673 if (isa<PHINode>(Op0))
674 if (Instruction *NV = FoldOpIntoPhi(I))
679 // See if we can fold away this div instruction.
680 if (SimplifyDemandedInstructionBits(I))
683 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
684 Value *X = 0, *Z = 0;
685 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
686 bool isSigned = I.getOpcode() == Instruction::SDiv;
687 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
688 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
689 return BinaryOperator::Create(I.getOpcode(), X, Op1);
695 /// dyn_castZExtVal - Checks if V is a zext or constant that can
696 /// be truncated to Ty without losing bits.
697 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
698 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
699 if (Z->getSrcTy() == Ty)
700 return Z->getOperand(0);
701 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
702 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
703 return ConstantExpr::getTrunc(C, Ty);
708 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
709 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
711 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
712 return ReplaceInstUsesWith(I, V);
714 // Handle the integer div common cases
715 if (Instruction *Common = commonIDivTransforms(I))
719 // X udiv 2^C -> X >> C
720 // Check to see if this is an unsigned division with an exact power of 2,
721 // if so, convert to a right shift.
723 if (match(Op1, m_Power2(C))) {
724 BinaryOperator *LShr =
725 BinaryOperator::CreateLShr(Op0,
726 ConstantInt::get(Op0->getType(),
728 if (I.isExact()) LShr->setIsExact();
733 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
734 // X udiv C, where C >= signbit
735 if (C->getValue().isNegative()) {
736 Value *IC = Builder->CreateICmpULT(Op0, C);
737 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
738 ConstantInt::get(I.getType(), 1));
742 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
743 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
746 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
747 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
748 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
752 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
753 { const APInt *CI; Value *N;
754 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
755 match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
757 N = Builder->CreateAdd(N,
758 ConstantInt::get(N->getType(), CI->logBase2()));
759 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
760 N = Builder->CreateZExt(N, Z->getDestTy());
762 return BinaryOperator::CreateExactLShr(Op0, N);
763 return BinaryOperator::CreateLShr(Op0, N);
767 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
768 // where C1&C2 are powers of two.
769 { Value *Cond; const APInt *C1, *C2;
770 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
771 // Construct the "on true" case of the select
772 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
775 // Construct the "on false" case of the select
776 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
779 // construct the select instruction and return it.
780 return SelectInst::Create(Cond, TSI, FSI);
784 // (zext A) udiv (zext B) --> zext (A udiv B)
785 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
786 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
787 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
794 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
795 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
797 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
798 return ReplaceInstUsesWith(I, V);
800 // Handle the integer div common cases
801 if (Instruction *Common = commonIDivTransforms(I))
804 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
806 if (RHS->isAllOnesValue())
807 return BinaryOperator::CreateNeg(Op0);
809 // sdiv X, C --> ashr exact X, log2(C)
810 if (I.isExact() && RHS->getValue().isNonNegative() &&
811 RHS->getValue().isPowerOf2()) {
812 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
813 RHS->getValue().exactLogBase2());
814 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
817 // -X/C --> X/-C provided the negation doesn't overflow.
818 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
819 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
820 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
821 ConstantExpr::getNeg(RHS));
824 // If the sign bits of both operands are zero (i.e. we can prove they are
825 // unsigned inputs), turn this into a udiv.
826 if (I.getType()->isIntegerTy()) {
827 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
828 if (MaskedValueIsZero(Op0, Mask)) {
829 if (MaskedValueIsZero(Op1, Mask)) {
830 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
831 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
834 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
835 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
836 // Safe because the only negative value (1 << Y) can take on is
837 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
839 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
847 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
849 /// 1) 1/C is exact, or
850 /// 2) reciprocal is allowed.
851 /// If the conversion was successful, the simplified expression "X * 1/C" is
852 /// returned; otherwise, NULL is returned.
854 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
856 bool AllowReciprocal) {
857 const APFloat &FpVal = Divisor->getValueAPF();
858 APFloat Reciprocal(FpVal.getSemantics());
859 bool Cvt = FpVal.getExactInverse(&Reciprocal);
861 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
862 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
863 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
864 Cvt = !Reciprocal.isDenormal();
871 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
872 return BinaryOperator::CreateFMul(Dividend, R);
875 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
878 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
879 return ReplaceInstUsesWith(I, V);
881 bool AllowReassociate = I.hasUnsafeAlgebra();
882 bool AllowReciprocal = I.hasAllowReciprocal();
884 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
885 if (AllowReassociate) {
887 ConstantFP *C2 = Op1C;
889 Instruction *Res = 0;
891 if (match(Op0, m_FMul(m_Value(X), m_ConstantFP(C1)))) {
892 // (X*C1)/C2 => X * (C1/C2)
894 Constant *C = ConstantExpr::getFDiv(C1, C2);
895 const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
896 if (F.isFiniteNonZero() && !F.isDenormal())
897 Res = BinaryOperator::CreateFMul(X, C);
898 } else if (match(Op0, m_FDiv(m_Value(X), m_ConstantFP(C1)))) {
899 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
901 Constant *C = ConstantExpr::getFMul(C1, C2);
902 const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
903 if (F.isFiniteNonZero() && !F.isDenormal()) {
904 Res = CvtFDivConstToReciprocal(X, cast<ConstantFP>(C),
907 Res = BinaryOperator::CreateFDiv(X, C);
912 Res->setFastMathFlags(I.getFastMathFlags());
918 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal))
924 if (AllowReassociate && isa<ConstantFP>(Op0)) {
925 ConstantFP *C1 = cast<ConstantFP>(Op0), *C2;
928 bool CreateDiv = true;
930 // C1 / (X*C2) => (C1/C2) / X
931 if (match(Op1, m_FMul(m_Value(X), m_ConstantFP(C2))))
932 Fold = ConstantExpr::getFDiv(C1, C2);
933 else if (match(Op1, m_FDiv(m_Value(X), m_ConstantFP(C2)))) {
934 // C1 / (X/C2) => (C1*C2) / X
935 Fold = ConstantExpr::getFMul(C1, C2);
936 } else if (match(Op1, m_FDiv(m_ConstantFP(C2), m_Value(X)))) {
937 // C1 / (C2/X) => (C1/C2) * X
938 Fold = ConstantExpr::getFDiv(C1, C2);
943 const APFloat &FoldC = cast<ConstantFP>(Fold)->getValueAPF();
944 if (FoldC.isFiniteNonZero() && !FoldC.isDenormal()) {
945 Instruction *R = CreateDiv ?
946 BinaryOperator::CreateFDiv(Fold, X) :
947 BinaryOperator::CreateFMul(X, Fold);
948 R->setFastMathFlags(I.getFastMathFlags());
955 if (AllowReassociate) {
958 Instruction *SimpR = 0;
960 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
961 // (X/Y) / Z => X / (Y*Z)
963 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op1)) {
964 NewInst = Builder->CreateFMul(Y, Op1);
965 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
967 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
968 // Z / (X/Y) => Z*Y / X
970 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op0)) {
971 NewInst = Builder->CreateFMul(Op0, Y);
972 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
977 if (Instruction *T = dyn_cast<Instruction>(NewInst))
978 T->setDebugLoc(I.getDebugLoc());
979 SimpR->setFastMathFlags(I.getFastMathFlags());
987 /// This function implements the transforms common to both integer remainder
988 /// instructions (urem and srem). It is called by the visitors to those integer
989 /// remainder instructions.
990 /// @brief Common integer remainder transforms
991 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
994 // The RHS is known non-zero.
995 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1000 // Handle cases involving: rem X, (select Cond, Y, Z)
1001 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1004 if (isa<ConstantInt>(Op1)) {
1005 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1006 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1007 if (Instruction *R = FoldOpIntoSelect(I, SI))
1009 } else if (isa<PHINode>(Op0I)) {
1010 if (Instruction *NV = FoldOpIntoPhi(I))
1014 // See if we can fold away this rem instruction.
1015 if (SimplifyDemandedInstructionBits(I))
1023 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1024 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1026 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
1027 return ReplaceInstUsesWith(I, V);
1029 if (Instruction *common = commonIRemTransforms(I))
1032 // (zext A) urem (zext B) --> zext (A urem B)
1033 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1034 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1035 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1038 // X urem Y -> X and Y-1, where Y is a power of 2,
1039 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1040 Constant *N1 = Constant::getAllOnesValue(I.getType());
1041 Value *Add = Builder->CreateAdd(Op1, N1);
1042 return BinaryOperator::CreateAnd(Op0, Add);
1048 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1051 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
1052 return ReplaceInstUsesWith(I, V);
1054 // Handle the integer rem common cases
1055 if (Instruction *Common = commonIRemTransforms(I))
1058 if (Value *RHSNeg = dyn_castNegVal(Op1))
1059 if (!isa<Constant>(RHSNeg) ||
1060 (isa<ConstantInt>(RHSNeg) &&
1061 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1063 Worklist.AddValue(I.getOperand(1));
1064 I.setOperand(1, RHSNeg);
1068 // If the sign bits of both operands are zero (i.e. we can prove they are
1069 // unsigned inputs), turn this into a urem.
1070 if (I.getType()->isIntegerTy()) {
1071 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1072 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1073 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1074 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1078 // If it's a constant vector, flip any negative values positive.
1079 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1080 Constant *C = cast<Constant>(Op1);
1081 unsigned VWidth = C->getType()->getVectorNumElements();
1083 bool hasNegative = false;
1084 bool hasMissing = false;
1085 for (unsigned i = 0; i != VWidth; ++i) {
1086 Constant *Elt = C->getAggregateElement(i);
1092 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1093 if (RHS->isNegative())
1097 if (hasNegative && !hasMissing) {
1098 SmallVector<Constant *, 16> Elts(VWidth);
1099 for (unsigned i = 0; i != VWidth; ++i) {
1100 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1101 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1102 if (RHS->isNegative())
1103 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1107 Constant *NewRHSV = ConstantVector::get(Elts);
1108 if (NewRHSV != C) { // Don't loop on -MININT
1109 Worklist.AddValue(I.getOperand(1));
1110 I.setOperand(1, NewRHSV);
1119 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1122 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
1123 return ReplaceInstUsesWith(I, V);
1125 // Handle cases involving: rem X, (select Cond, Y, Z)
1126 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))