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/IR/PatternMatch.h"
20 using namespace PatternMatch;
22 #define DEBUG_TYPE "instcombine"
25 /// simplifyValueKnownNonZero - The specific integer value is used in a context
26 /// where it is known to be non-zero. If this allows us to simplify the
27 /// computation, do so and return the new operand, otherwise return null.
28 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
30 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
33 if (!V->hasOneUse()) return nullptr;
35 bool MadeChange = false;
37 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
39 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
42 A = IC.Builder->CreateSub(A, B);
43 return IC.Builder->CreateShl(One, A);
46 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
49 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
50 0, IC.getAssumptionTracker(),
52 IC.getDominatorTree())) {
53 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
55 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
60 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
65 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
71 // TODO: Lots more we could do here:
72 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
75 return MadeChange ? V : nullptr;
79 /// MultiplyOverflows - True if the multiply can not be expressed in an int
81 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
85 Product = C1.smul_ov(C2, Overflow);
87 Product = C1.umul_ov(C2, Overflow);
92 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
102 APInt::udivrem(C1, C2, Quotient, Remainder);
104 return Remainder.isMinValue();
107 /// \brief A helper routine of InstCombiner::visitMul().
109 /// If C is a vector of known powers of 2, then this function returns
110 /// a new vector obtained from C replacing each element with its logBase2.
111 /// Return a null pointer otherwise.
112 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
114 SmallVector<Constant *, 4> Elts;
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
123 return ConstantVector::get(Elts);
126 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
127 bool Changed = SimplifyAssociativeOrCommutative(I);
128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
130 if (Value *V = SimplifyVectorOp(I))
131 return ReplaceInstUsesWith(I, V);
133 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
134 return ReplaceInstUsesWith(I, V);
136 if (Value *V = SimplifyUsingDistributiveLaws(I))
137 return ReplaceInstUsesWith(I, V);
139 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
140 return BinaryOperator::CreateNeg(Op0, I.getName());
142 // Also allow combining multiply instructions on vectors.
147 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
149 match(C1, m_APInt(IVal)))
150 // ((X << C1)*C2) == (X * (C2 << C1))
151 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
153 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
154 Constant *NewCst = nullptr;
155 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
156 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
157 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
158 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
159 // Replace X*(2^C) with X << C, where C is a vector of known
160 // constant powers of 2.
161 NewCst = getLogBase2Vector(CV);
164 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
166 if (I.hasNoUnsignedWrap())
167 Shl->setHasNoUnsignedWrap();
174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
175 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
176 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
177 // The "* (2**n)" thus becomes a potential shifting opportunity.
179 const APInt & Val = CI->getValue();
180 const APInt &PosVal = Val.abs();
181 if (Val.isNegative() && PosVal.isPowerOf2()) {
182 Value *X = nullptr, *Y = nullptr;
183 if (Op0->hasOneUse()) {
185 Value *Sub = nullptr;
186 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
187 Sub = Builder->CreateSub(X, Y, "suba");
188 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
189 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
192 BinaryOperator::CreateMul(Sub,
193 ConstantInt::get(Y->getType(), PosVal));
199 // Simplify mul instructions with a constant RHS.
200 if (isa<Constant>(Op1)) {
201 // Try to fold constant mul into select arguments.
202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
203 if (Instruction *R = FoldOpIntoSelect(I, SI))
206 if (isa<PHINode>(Op0))
207 if (Instruction *NV = FoldOpIntoPhi(I))
210 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
214 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
215 Value *Mul = Builder->CreateMul(C1, Op1);
216 // Only go forward with the transform if C1*CI simplifies to a tidier
218 if (!match(Mul, m_Mul(m_Value(), m_Value())))
219 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
224 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
225 if (Value *Op1v = dyn_castNegVal(Op1))
226 return BinaryOperator::CreateMul(Op0v, Op1v);
228 // (X / Y) * Y = X - (X % Y)
229 // (X / Y) * -Y = (X % Y) - X
232 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
234 (BO->getOpcode() != Instruction::UDiv &&
235 BO->getOpcode() != Instruction::SDiv)) {
237 BO = dyn_cast<BinaryOperator>(Op1);
239 Value *Neg = dyn_castNegVal(Op1C);
240 if (BO && BO->hasOneUse() &&
241 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
242 (BO->getOpcode() == Instruction::UDiv ||
243 BO->getOpcode() == Instruction::SDiv)) {
244 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
246 // If the division is exact, X % Y is zero, so we end up with X or -X.
247 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
248 if (SDiv->isExact()) {
250 return ReplaceInstUsesWith(I, Op0BO);
251 return BinaryOperator::CreateNeg(Op0BO);
255 if (BO->getOpcode() == Instruction::UDiv)
256 Rem = Builder->CreateURem(Op0BO, Op1BO);
258 Rem = Builder->CreateSRem(Op0BO, Op1BO);
262 return BinaryOperator::CreateSub(Op0BO, Rem);
263 return BinaryOperator::CreateSub(Rem, Op0BO);
267 /// i1 mul -> i1 and.
268 if (I.getType()->getScalarType()->isIntegerTy(1))
269 return BinaryOperator::CreateAnd(Op0, Op1);
271 // X*(1 << Y) --> X << Y
272 // (1 << Y)*X --> X << Y
275 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
276 return BinaryOperator::CreateShl(Op1, Y);
277 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
278 return BinaryOperator::CreateShl(Op0, Y);
281 // If one of the operands of the multiply is a cast from a boolean value, then
282 // we know the bool is either zero or one, so this is a 'masking' multiply.
283 // X * Y (where Y is 0 or 1) -> X & (0-Y)
284 if (!I.getType()->isVectorTy()) {
285 // -2 is "-1 << 1" so it is all bits set except the low one.
286 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
288 Value *BoolCast = nullptr, *OtherOp = nullptr;
289 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
290 BoolCast = Op0, OtherOp = Op1;
291 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
292 BoolCast = Op1, OtherOp = Op0;
295 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
297 return BinaryOperator::CreateAnd(V, OtherOp);
301 return Changed ? &I : nullptr;
304 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
305 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
306 if (!Op->hasOneUse())
309 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
312 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
316 Value *OpLog2Of = II->getArgOperand(0);
317 if (!OpLog2Of->hasOneUse())
320 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
323 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
326 if (match(I->getOperand(0), m_SpecificFP(0.5)))
327 Y = I->getOperand(1);
328 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
329 Y = I->getOperand(0);
332 static bool isFiniteNonZeroFp(Constant *C) {
333 if (C->getType()->isVectorTy()) {
334 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
336 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
337 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
343 return isa<ConstantFP>(C) &&
344 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
347 static bool isNormalFp(Constant *C) {
348 if (C->getType()->isVectorTy()) {
349 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
351 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
352 if (!CFP || !CFP->getValueAPF().isNormal())
358 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
361 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
362 /// true iff the given value is FMul or FDiv with one and only one operand
363 /// being a normal constant (i.e. not Zero/NaN/Infinity).
364 static bool isFMulOrFDivWithConstant(Value *V) {
365 Instruction *I = dyn_cast<Instruction>(V);
366 if (!I || (I->getOpcode() != Instruction::FMul &&
367 I->getOpcode() != Instruction::FDiv))
370 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
371 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
376 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
379 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
380 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
381 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
382 /// This function is to simplify "FMulOrDiv * C" and returns the
383 /// resulting expression. Note that this function could return NULL in
384 /// case the constants cannot be folded into a normal floating-point.
386 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
387 Instruction *InsertBefore) {
388 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
390 Value *Opnd0 = FMulOrDiv->getOperand(0);
391 Value *Opnd1 = FMulOrDiv->getOperand(1);
393 Constant *C0 = dyn_cast<Constant>(Opnd0);
394 Constant *C1 = dyn_cast<Constant>(Opnd1);
396 BinaryOperator *R = nullptr;
398 // (X * C0) * C => X * (C0*C)
399 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
400 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
402 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
405 // (C0 / X) * C => (C0 * C) / X
406 if (FMulOrDiv->hasOneUse()) {
407 // It would otherwise introduce another div.
408 Constant *F = ConstantExpr::getFMul(C0, C);
410 R = BinaryOperator::CreateFDiv(F, Opnd1);
413 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
414 Constant *F = ConstantExpr::getFDiv(C, C1);
416 R = BinaryOperator::CreateFMul(Opnd0, F);
418 // (X / C1) * C => X / (C1/C)
419 Constant *F = ConstantExpr::getFDiv(C1, C);
421 R = BinaryOperator::CreateFDiv(Opnd0, F);
427 R->setHasUnsafeAlgebra(true);
428 InsertNewInstWith(R, *InsertBefore);
434 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
435 bool Changed = SimplifyAssociativeOrCommutative(I);
436 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
438 if (Value *V = SimplifyVectorOp(I))
439 return ReplaceInstUsesWith(I, V);
441 if (isa<Constant>(Op0))
444 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
446 return ReplaceInstUsesWith(I, V);
448 bool AllowReassociate = I.hasUnsafeAlgebra();
450 // Simplify mul instructions with a constant RHS.
451 if (isa<Constant>(Op1)) {
452 // Try to fold constant mul into select arguments.
453 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
454 if (Instruction *R = FoldOpIntoSelect(I, SI))
457 if (isa<PHINode>(Op0))
458 if (Instruction *NV = FoldOpIntoPhi(I))
461 // (fmul X, -1.0) --> (fsub -0.0, X)
462 if (match(Op1, m_SpecificFP(-1.0))) {
463 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
464 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
465 RI->copyFastMathFlags(&I);
469 Constant *C = cast<Constant>(Op1);
470 if (AllowReassociate && isFiniteNonZeroFp(C)) {
471 // Let MDC denote an expression in one of these forms:
472 // X * C, C/X, X/C, where C is a constant.
474 // Try to simplify "MDC * Constant"
475 if (isFMulOrFDivWithConstant(Op0))
476 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
477 return ReplaceInstUsesWith(I, V);
479 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
480 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
482 (FAddSub->getOpcode() == Instruction::FAdd ||
483 FAddSub->getOpcode() == Instruction::FSub)) {
484 Value *Opnd0 = FAddSub->getOperand(0);
485 Value *Opnd1 = FAddSub->getOperand(1);
486 Constant *C0 = dyn_cast<Constant>(Opnd0);
487 Constant *C1 = dyn_cast<Constant>(Opnd1);
491 std::swap(Opnd0, Opnd1);
495 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
496 Value *M1 = ConstantExpr::getFMul(C1, C);
497 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
498 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
501 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
504 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
505 ? BinaryOperator::CreateFAdd(M0, M1)
506 : BinaryOperator::CreateFSub(M0, M1);
507 RI->copyFastMathFlags(&I);
515 // sqrt(X) * sqrt(X) -> X
516 if (AllowReassociate && (Op0 == Op1))
517 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
518 if (II->getIntrinsicID() == Intrinsic::sqrt)
519 return ReplaceInstUsesWith(I, II->getOperand(0));
521 // Under unsafe algebra do:
522 // X * log2(0.5*Y) = X*log2(Y) - X
523 if (AllowReassociate) {
524 Value *OpX = nullptr;
525 Value *OpY = nullptr;
527 detectLog2OfHalf(Op0, OpY, Log2);
531 detectLog2OfHalf(Op1, OpY, Log2);
536 // if pattern detected emit alternate sequence
538 BuilderTy::FastMathFlagGuard Guard(*Builder);
539 Builder->SetFastMathFlags(Log2->getFastMathFlags());
540 Log2->setArgOperand(0, OpY);
541 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
542 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
544 return ReplaceInstUsesWith(I, FSub);
548 // Handle symmetric situation in a 2-iteration loop
551 for (int i = 0; i < 2; i++) {
552 bool IgnoreZeroSign = I.hasNoSignedZeros();
553 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
554 BuilderTy::FastMathFlagGuard Guard(*Builder);
555 Builder->SetFastMathFlags(I.getFastMathFlags());
557 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
558 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
562 Value *FMul = Builder->CreateFMul(N0, N1);
564 return ReplaceInstUsesWith(I, FMul);
567 if (Opnd0->hasOneUse()) {
568 // -X * Y => -(X*Y) (Promote negation as high as possible)
569 Value *T = Builder->CreateFMul(N0, Opnd1);
570 Value *Neg = Builder->CreateFNeg(T);
572 return ReplaceInstUsesWith(I, Neg);
576 // (X*Y) * X => (X*X) * Y where Y != X
577 // The purpose is two-fold:
578 // 1) to form a power expression (of X).
579 // 2) potentially shorten the critical path: After transformation, the
580 // latency of the instruction Y is amortized by the expression of X*X,
581 // and therefore Y is in a "less critical" position compared to what it
582 // was before the transformation.
584 if (AllowReassociate) {
585 Value *Opnd0_0, *Opnd0_1;
586 if (Opnd0->hasOneUse() &&
587 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
589 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
591 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
595 BuilderTy::FastMathFlagGuard Guard(*Builder);
596 Builder->SetFastMathFlags(I.getFastMathFlags());
597 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
599 Value *R = Builder->CreateFMul(T, Y);
601 return ReplaceInstUsesWith(I, R);
606 if (!isa<Constant>(Op1))
607 std::swap(Opnd0, Opnd1);
612 return Changed ? &I : nullptr;
615 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
617 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
618 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
620 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
621 int NonNullOperand = -1;
622 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
623 if (ST->isNullValue())
625 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
626 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
627 if (ST->isNullValue())
630 if (NonNullOperand == -1)
633 Value *SelectCond = SI->getOperand(0);
635 // Change the div/rem to use 'Y' instead of the select.
636 I.setOperand(1, SI->getOperand(NonNullOperand));
638 // Okay, we know we replace the operand of the div/rem with 'Y' with no
639 // problem. However, the select, or the condition of the select may have
640 // multiple uses. Based on our knowledge that the operand must be non-zero,
641 // propagate the known value for the select into other uses of it, and
642 // propagate a known value of the condition into its other users.
644 // If the select and condition only have a single use, don't bother with this,
646 if (SI->use_empty() && SelectCond->hasOneUse())
649 // Scan the current block backward, looking for other uses of SI.
650 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
652 while (BBI != BBFront) {
654 // If we found a call to a function, we can't assume it will return, so
655 // information from below it cannot be propagated above it.
656 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
659 // Replace uses of the select or its condition with the known values.
660 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
663 *I = SI->getOperand(NonNullOperand);
665 } else if (*I == SelectCond) {
666 *I = Builder->getInt1(NonNullOperand == 1);
671 // If we past the instruction, quit looking for it.
674 if (&*BBI == SelectCond)
675 SelectCond = nullptr;
677 // If we ran out of things to eliminate, break out of the loop.
678 if (!SelectCond && !SI)
686 /// This function implements the transforms common to both integer division
687 /// instructions (udiv and sdiv). It is called by the visitors to those integer
688 /// division instructions.
689 /// @brief Common integer divide transforms
690 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
693 // The RHS is known non-zero.
694 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
699 // Handle cases involving: [su]div X, (select Cond, Y, Z)
700 // This does not apply for fdiv.
701 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
704 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
706 if (match(Op1, m_APInt(C2))) {
709 bool IsSigned = I.getOpcode() == Instruction::SDiv;
711 // (X / C1) / C2 -> X / (C1*C2)
712 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
713 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
714 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
715 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
716 return BinaryOperator::Create(I.getOpcode(), X,
717 ConstantInt::get(I.getType(), Product));
720 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
721 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
722 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
724 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
725 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
726 BinaryOperator *BO = BinaryOperator::Create(
727 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
728 BO->setIsExact(I.isExact());
732 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
733 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
734 BinaryOperator *BO = BinaryOperator::Create(
735 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
736 BO->setHasNoUnsignedWrap(
738 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
739 BO->setHasNoSignedWrap(
740 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
745 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
746 *C1 != C1->getBitWidth() - 1) ||
747 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
748 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
749 APInt C1Shifted = APInt::getOneBitSet(
750 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
752 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
753 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
754 BinaryOperator *BO = BinaryOperator::Create(
755 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
756 BO->setIsExact(I.isExact());
760 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
761 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
762 BinaryOperator *BO = BinaryOperator::Create(
763 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
764 BO->setHasNoUnsignedWrap(
766 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
767 BO->setHasNoSignedWrap(
768 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
773 if (*C2 != 0) { // avoid X udiv 0
774 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
775 if (Instruction *R = FoldOpIntoSelect(I, SI))
777 if (isa<PHINode>(Op0))
778 if (Instruction *NV = FoldOpIntoPhi(I))
784 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
785 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
786 bool isSigned = I.getOpcode() == Instruction::SDiv;
788 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
789 // result is one, if Op1 is -1 then the result is minus one, otherwise
791 Value *Inc = Builder->CreateAdd(Op1, One);
792 Value *Cmp = Builder->CreateICmpULT(
793 Inc, ConstantInt::get(I.getType(), 3));
794 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
796 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
797 // result is one, otherwise it's zero.
798 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
803 // See if we can fold away this div instruction.
804 if (SimplifyDemandedInstructionBits(I))
807 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
808 Value *X = nullptr, *Z = nullptr;
809 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
810 bool isSigned = I.getOpcode() == Instruction::SDiv;
811 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
812 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
813 return BinaryOperator::Create(I.getOpcode(), X, Op1);
819 /// dyn_castZExtVal - Checks if V is a zext or constant that can
820 /// be truncated to Ty without losing bits.
821 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
822 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
823 if (Z->getSrcTy() == Ty)
824 return Z->getOperand(0);
825 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
826 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
827 return ConstantExpr::getTrunc(C, Ty);
833 const unsigned MaxDepth = 6;
834 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
835 const BinaryOperator &I,
838 /// \brief Used to maintain state for visitUDivOperand().
839 struct UDivFoldAction {
840 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
841 ///< operand. This can be zero if this action
842 ///< joins two actions together.
844 Value *OperandToFold; ///< Which operand to fold.
846 Instruction *FoldResult; ///< The instruction returned when FoldAction is
849 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
850 ///< joins two actions together.
853 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
854 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
855 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
856 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
860 // X udiv 2^C -> X >> C
861 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
862 const BinaryOperator &I, InstCombiner &IC) {
863 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
864 BinaryOperator *LShr = BinaryOperator::CreateLShr(
865 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
871 // X udiv C, where C >= signbit
872 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
873 const BinaryOperator &I, InstCombiner &IC) {
874 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
876 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
877 ConstantInt::get(I.getType(), 1));
880 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
881 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
883 Instruction *ShiftLeft = cast<Instruction>(Op1);
884 if (isa<ZExtInst>(ShiftLeft))
885 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
888 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
889 Value *N = ShiftLeft->getOperand(1);
891 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
892 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
893 N = IC.Builder->CreateZExt(N, Z->getDestTy());
894 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
900 // \brief Recursively visits the possible right hand operands of a udiv
901 // instruction, seeing through select instructions, to determine if we can
902 // replace the udiv with something simpler. If we find that an operand is not
903 // able to simplify the udiv, we abort the entire transformation.
904 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
905 SmallVectorImpl<UDivFoldAction> &Actions,
906 unsigned Depth = 0) {
907 // Check to see if this is an unsigned division with an exact power of 2,
908 // if so, convert to a right shift.
909 if (match(Op1, m_Power2())) {
910 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
911 return Actions.size();
914 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
915 // X udiv C, where C >= signbit
916 if (C->getValue().isNegative()) {
917 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
918 return Actions.size();
921 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
922 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
923 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
924 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
925 return Actions.size();
928 // The remaining tests are all recursive, so bail out if we hit the limit.
929 if (Depth++ == MaxDepth)
932 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
934 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
935 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
936 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
937 return Actions.size();
943 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
944 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
946 if (Value *V = SimplifyVectorOp(I))
947 return ReplaceInstUsesWith(I, V);
949 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
950 return ReplaceInstUsesWith(I, V);
952 // Handle the integer div common cases
953 if (Instruction *Common = commonIDivTransforms(I))
956 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
959 const APInt *C1, *C2;
960 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
961 match(Op1, m_APInt(C2))) {
963 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
965 return BinaryOperator::CreateUDiv(
966 X, ConstantInt::get(X->getType(), C2ShlC1));
970 // (zext A) udiv (zext B) --> zext (A udiv B)
971 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
972 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
974 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
977 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
978 SmallVector<UDivFoldAction, 6> UDivActions;
979 if (visitUDivOperand(Op0, Op1, I, UDivActions))
980 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
981 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
982 Value *ActionOp1 = UDivActions[i].OperandToFold;
985 Inst = Action(Op0, ActionOp1, I, *this);
987 // This action joins two actions together. The RHS of this action is
988 // simply the last action we processed, we saved the LHS action index in
989 // the joining action.
990 size_t SelectRHSIdx = i - 1;
991 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
992 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
993 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
994 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
995 SelectLHS, SelectRHS);
998 // If this is the last action to process, return it to the InstCombiner.
999 // Otherwise, we insert it before the UDiv and record it so that we may
1000 // use it as part of a joining action (i.e., a SelectInst).
1002 Inst->insertBefore(&I);
1003 UDivActions[i].FoldResult = Inst;
1011 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1014 if (Value *V = SimplifyVectorOp(I))
1015 return ReplaceInstUsesWith(I, V);
1017 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1018 return ReplaceInstUsesWith(I, V);
1020 // Handle the integer div common cases
1021 if (Instruction *Common = commonIDivTransforms(I))
1025 if (match(Op1, m_AllOnes()))
1026 return BinaryOperator::CreateNeg(Op0);
1028 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1029 // sdiv X, C --> ashr exact X, log2(C)
1030 if (I.isExact() && RHS->getValue().isNonNegative() &&
1031 RHS->getValue().isPowerOf2()) {
1032 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1033 RHS->getValue().exactLogBase2());
1034 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1038 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1039 // X/INT_MIN -> X == INT_MIN
1040 if (RHS->isMinSignedValue())
1041 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1043 // -X/C --> X/-C provided the negation doesn't overflow.
1044 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1045 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1046 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1047 ConstantExpr::getNeg(RHS));
1050 // If the sign bits of both operands are zero (i.e. we can prove they are
1051 // unsigned inputs), turn this into a udiv.
1052 if (I.getType()->isIntegerTy()) {
1053 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1054 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1055 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1056 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1057 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1060 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1061 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1062 // Safe because the only negative value (1 << Y) can take on is
1063 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1064 // the sign bit set.
1065 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1073 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1075 /// 1) 1/C is exact, or
1076 /// 2) reciprocal is allowed.
1077 /// If the conversion was successful, the simplified expression "X * 1/C" is
1078 /// returned; otherwise, NULL is returned.
1080 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1081 bool AllowReciprocal) {
1082 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1085 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1086 APFloat Reciprocal(FpVal.getSemantics());
1087 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1089 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1090 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1091 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1092 Cvt = !Reciprocal.isDenormal();
1099 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1100 return BinaryOperator::CreateFMul(Dividend, R);
1103 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1106 if (Value *V = SimplifyVectorOp(I))
1107 return ReplaceInstUsesWith(I, V);
1109 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1110 return ReplaceInstUsesWith(I, V);
1112 if (isa<Constant>(Op0))
1113 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1114 if (Instruction *R = FoldOpIntoSelect(I, SI))
1117 bool AllowReassociate = I.hasUnsafeAlgebra();
1118 bool AllowReciprocal = I.hasAllowReciprocal();
1120 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1121 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1122 if (Instruction *R = FoldOpIntoSelect(I, SI))
1125 if (AllowReassociate) {
1126 Constant *C1 = nullptr;
1127 Constant *C2 = Op1C;
1129 Instruction *Res = nullptr;
1131 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1132 // (X*C1)/C2 => X * (C1/C2)
1134 Constant *C = ConstantExpr::getFDiv(C1, C2);
1136 Res = BinaryOperator::CreateFMul(X, C);
1137 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1138 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1140 Constant *C = ConstantExpr::getFMul(C1, C2);
1141 if (isNormalFp(C)) {
1142 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1144 Res = BinaryOperator::CreateFDiv(X, C);
1149 Res->setFastMathFlags(I.getFastMathFlags());
1155 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1156 T->copyFastMathFlags(&I);
1163 if (AllowReassociate && isa<Constant>(Op0)) {
1164 Constant *C1 = cast<Constant>(Op0), *C2;
1165 Constant *Fold = nullptr;
1167 bool CreateDiv = true;
1169 // C1 / (X*C2) => (C1/C2) / X
1170 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1171 Fold = ConstantExpr::getFDiv(C1, C2);
1172 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1173 // C1 / (X/C2) => (C1*C2) / X
1174 Fold = ConstantExpr::getFMul(C1, C2);
1175 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1176 // C1 / (C2/X) => (C1/C2) * X
1177 Fold = ConstantExpr::getFDiv(C1, C2);
1181 if (Fold && isNormalFp(Fold)) {
1182 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1183 : BinaryOperator::CreateFMul(X, Fold);
1184 R->setFastMathFlags(I.getFastMathFlags());
1190 if (AllowReassociate) {
1192 Value *NewInst = nullptr;
1193 Instruction *SimpR = nullptr;
1195 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1196 // (X/Y) / Z => X / (Y*Z)
1198 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1199 NewInst = Builder->CreateFMul(Y, Op1);
1200 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1201 FastMathFlags Flags = I.getFastMathFlags();
1202 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1203 RI->setFastMathFlags(Flags);
1205 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1207 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1208 // Z / (X/Y) => Z*Y / X
1210 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1211 NewInst = Builder->CreateFMul(Op0, Y);
1212 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1213 FastMathFlags Flags = I.getFastMathFlags();
1214 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1215 RI->setFastMathFlags(Flags);
1217 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1222 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1223 T->setDebugLoc(I.getDebugLoc());
1224 SimpR->setFastMathFlags(I.getFastMathFlags());
1232 /// This function implements the transforms common to both integer remainder
1233 /// instructions (urem and srem). It is called by the visitors to those integer
1234 /// remainder instructions.
1235 /// @brief Common integer remainder transforms
1236 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1237 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1239 // The RHS is known non-zero.
1240 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1245 // Handle cases involving: rem X, (select Cond, Y, Z)
1246 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1249 if (isa<Constant>(Op1)) {
1250 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1251 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1252 if (Instruction *R = FoldOpIntoSelect(I, SI))
1254 } else if (isa<PHINode>(Op0I)) {
1255 if (Instruction *NV = FoldOpIntoPhi(I))
1259 // See if we can fold away this rem instruction.
1260 if (SimplifyDemandedInstructionBits(I))
1268 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1271 if (Value *V = SimplifyVectorOp(I))
1272 return ReplaceInstUsesWith(I, V);
1274 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1275 return ReplaceInstUsesWith(I, V);
1277 if (Instruction *common = commonIRemTransforms(I))
1280 // (zext A) urem (zext B) --> zext (A urem B)
1281 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1282 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1283 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1286 // X urem Y -> X and Y-1, where Y is a power of 2,
1287 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1288 Constant *N1 = Constant::getAllOnesValue(I.getType());
1289 Value *Add = Builder->CreateAdd(Op1, N1);
1290 return BinaryOperator::CreateAnd(Op0, Add);
1293 // 1 urem X -> zext(X != 1)
1294 if (match(Op0, m_One())) {
1295 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1296 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1297 return ReplaceInstUsesWith(I, Ext);
1303 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1304 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1306 if (Value *V = SimplifyVectorOp(I))
1307 return ReplaceInstUsesWith(I, V);
1309 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1310 return ReplaceInstUsesWith(I, V);
1312 // Handle the integer rem common cases
1313 if (Instruction *Common = commonIRemTransforms(I))
1319 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1320 Worklist.AddValue(I.getOperand(1));
1321 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1326 // If the sign bits of both operands are zero (i.e. we can prove they are
1327 // unsigned inputs), turn this into a urem.
1328 if (I.getType()->isIntegerTy()) {
1329 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1330 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1331 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1332 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1333 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1337 // If it's a constant vector, flip any negative values positive.
1338 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1339 Constant *C = cast<Constant>(Op1);
1340 unsigned VWidth = C->getType()->getVectorNumElements();
1342 bool hasNegative = false;
1343 bool hasMissing = false;
1344 for (unsigned i = 0; i != VWidth; ++i) {
1345 Constant *Elt = C->getAggregateElement(i);
1351 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1352 if (RHS->isNegative())
1356 if (hasNegative && !hasMissing) {
1357 SmallVector<Constant *, 16> Elts(VWidth);
1358 for (unsigned i = 0; i != VWidth; ++i) {
1359 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1360 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1361 if (RHS->isNegative())
1362 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1366 Constant *NewRHSV = ConstantVector::get(Elts);
1367 if (NewRHSV != C) { // Don't loop on -MININT
1368 Worklist.AddValue(I.getOperand(1));
1369 I.setOperand(1, NewRHSV);
1378 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1381 if (Value *V = SimplifyVectorOp(I))
1382 return ReplaceInstUsesWith(I, V);
1384 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1385 return ReplaceInstUsesWith(I, V);
1387 // Handle cases involving: rem X, (select Cond, Y, Z)
1388 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))