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);
140 if (match(Op1, m_AllOnes())) {
141 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
142 if (I.hasNoSignedWrap())
143 BO->setHasNoSignedWrap();
147 // Also allow combining multiply instructions on vectors.
152 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
154 match(C1, m_APInt(IVal))) {
155 // ((X << C2)*C1) == (X * (C1 << C2))
156 Constant *Shl = ConstantExpr::getShl(C1, C2);
157 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
158 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
159 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
160 BO->setHasNoUnsignedWrap();
161 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
162 Shl->isNotMinSignedValue())
163 BO->setHasNoSignedWrap();
167 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
168 Constant *NewCst = nullptr;
169 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
170 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
171 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
172 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
173 // Replace X*(2^C) with X << C, where C is a vector of known
174 // constant powers of 2.
175 NewCst = getLogBase2Vector(CV);
178 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
180 if (I.hasNoUnsignedWrap())
181 Shl->setHasNoUnsignedWrap();
182 if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
183 Shl->setHasNoSignedWrap();
190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
191 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
192 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
193 // The "* (2**n)" thus becomes a potential shifting opportunity.
195 const APInt & Val = CI->getValue();
196 const APInt &PosVal = Val.abs();
197 if (Val.isNegative() && PosVal.isPowerOf2()) {
198 Value *X = nullptr, *Y = nullptr;
199 if (Op0->hasOneUse()) {
201 Value *Sub = nullptr;
202 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
203 Sub = Builder->CreateSub(X, Y, "suba");
204 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
205 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
208 BinaryOperator::CreateMul(Sub,
209 ConstantInt::get(Y->getType(), PosVal));
215 // Simplify mul instructions with a constant RHS.
216 if (isa<Constant>(Op1)) {
217 // Try to fold constant mul into select arguments.
218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
219 if (Instruction *R = FoldOpIntoSelect(I, SI))
222 if (isa<PHINode>(Op0))
223 if (Instruction *NV = FoldOpIntoPhi(I))
226 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
230 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
231 Value *Mul = Builder->CreateMul(C1, Op1);
232 // Only go forward with the transform if C1*CI simplifies to a tidier
234 if (!match(Mul, m_Mul(m_Value(), m_Value())))
235 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
240 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
241 if (Value *Op1v = dyn_castNegVal(Op1))
242 return BinaryOperator::CreateMul(Op0v, Op1v);
244 // (X / Y) * Y = X - (X % Y)
245 // (X / Y) * -Y = (X % Y) - X
248 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
250 (BO->getOpcode() != Instruction::UDiv &&
251 BO->getOpcode() != Instruction::SDiv)) {
253 BO = dyn_cast<BinaryOperator>(Op1);
255 Value *Neg = dyn_castNegVal(Op1C);
256 if (BO && BO->hasOneUse() &&
257 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
258 (BO->getOpcode() == Instruction::UDiv ||
259 BO->getOpcode() == Instruction::SDiv)) {
260 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
262 // If the division is exact, X % Y is zero, so we end up with X or -X.
263 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
264 if (SDiv->isExact()) {
266 return ReplaceInstUsesWith(I, Op0BO);
267 return BinaryOperator::CreateNeg(Op0BO);
271 if (BO->getOpcode() == Instruction::UDiv)
272 Rem = Builder->CreateURem(Op0BO, Op1BO);
274 Rem = Builder->CreateSRem(Op0BO, Op1BO);
278 return BinaryOperator::CreateSub(Op0BO, Rem);
279 return BinaryOperator::CreateSub(Rem, Op0BO);
283 /// i1 mul -> i1 and.
284 if (I.getType()->getScalarType()->isIntegerTy(1))
285 return BinaryOperator::CreateAnd(Op0, Op1);
287 // X*(1 << Y) --> X << Y
288 // (1 << Y)*X --> X << Y
291 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
292 return BinaryOperator::CreateShl(Op1, Y);
293 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
294 return BinaryOperator::CreateShl(Op0, Y);
297 // If one of the operands of the multiply is a cast from a boolean value, then
298 // we know the bool is either zero or one, so this is a 'masking' multiply.
299 // X * Y (where Y is 0 or 1) -> X & (0-Y)
300 if (!I.getType()->isVectorTy()) {
301 // -2 is "-1 << 1" so it is all bits set except the low one.
302 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
304 Value *BoolCast = nullptr, *OtherOp = nullptr;
305 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
306 BoolCast = Op0, OtherOp = Op1;
307 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
308 BoolCast = Op1, OtherOp = Op0;
311 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
313 return BinaryOperator::CreateAnd(V, OtherOp);
317 return Changed ? &I : nullptr;
320 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
321 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
322 if (!Op->hasOneUse())
325 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
328 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
332 Value *OpLog2Of = II->getArgOperand(0);
333 if (!OpLog2Of->hasOneUse())
336 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
339 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
342 if (match(I->getOperand(0), m_SpecificFP(0.5)))
343 Y = I->getOperand(1);
344 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
345 Y = I->getOperand(0);
348 static bool isFiniteNonZeroFp(Constant *C) {
349 if (C->getType()->isVectorTy()) {
350 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
352 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
353 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
359 return isa<ConstantFP>(C) &&
360 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
363 static bool isNormalFp(Constant *C) {
364 if (C->getType()->isVectorTy()) {
365 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
367 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
368 if (!CFP || !CFP->getValueAPF().isNormal())
374 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
377 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
378 /// true iff the given value is FMul or FDiv with one and only one operand
379 /// being a normal constant (i.e. not Zero/NaN/Infinity).
380 static bool isFMulOrFDivWithConstant(Value *V) {
381 Instruction *I = dyn_cast<Instruction>(V);
382 if (!I || (I->getOpcode() != Instruction::FMul &&
383 I->getOpcode() != Instruction::FDiv))
386 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
387 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
392 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
395 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
396 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
397 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
398 /// This function is to simplify "FMulOrDiv * C" and returns the
399 /// resulting expression. Note that this function could return NULL in
400 /// case the constants cannot be folded into a normal floating-point.
402 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
403 Instruction *InsertBefore) {
404 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
406 Value *Opnd0 = FMulOrDiv->getOperand(0);
407 Value *Opnd1 = FMulOrDiv->getOperand(1);
409 Constant *C0 = dyn_cast<Constant>(Opnd0);
410 Constant *C1 = dyn_cast<Constant>(Opnd1);
412 BinaryOperator *R = nullptr;
414 // (X * C0) * C => X * (C0*C)
415 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
416 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
418 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
421 // (C0 / X) * C => (C0 * C) / X
422 if (FMulOrDiv->hasOneUse()) {
423 // It would otherwise introduce another div.
424 Constant *F = ConstantExpr::getFMul(C0, C);
426 R = BinaryOperator::CreateFDiv(F, Opnd1);
429 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
430 Constant *F = ConstantExpr::getFDiv(C, C1);
432 R = BinaryOperator::CreateFMul(Opnd0, F);
434 // (X / C1) * C => X / (C1/C)
435 Constant *F = ConstantExpr::getFDiv(C1, C);
437 R = BinaryOperator::CreateFDiv(Opnd0, F);
443 R->setHasUnsafeAlgebra(true);
444 InsertNewInstWith(R, *InsertBefore);
450 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
451 bool Changed = SimplifyAssociativeOrCommutative(I);
452 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
454 if (Value *V = SimplifyVectorOp(I))
455 return ReplaceInstUsesWith(I, V);
457 if (isa<Constant>(Op0))
460 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
462 return ReplaceInstUsesWith(I, V);
464 bool AllowReassociate = I.hasUnsafeAlgebra();
466 // Simplify mul instructions with a constant RHS.
467 if (isa<Constant>(Op1)) {
468 // Try to fold constant mul into select arguments.
469 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
470 if (Instruction *R = FoldOpIntoSelect(I, SI))
473 if (isa<PHINode>(Op0))
474 if (Instruction *NV = FoldOpIntoPhi(I))
477 // (fmul X, -1.0) --> (fsub -0.0, X)
478 if (match(Op1, m_SpecificFP(-1.0))) {
479 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
480 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
481 RI->copyFastMathFlags(&I);
485 Constant *C = cast<Constant>(Op1);
486 if (AllowReassociate && isFiniteNonZeroFp(C)) {
487 // Let MDC denote an expression in one of these forms:
488 // X * C, C/X, X/C, where C is a constant.
490 // Try to simplify "MDC * Constant"
491 if (isFMulOrFDivWithConstant(Op0))
492 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
493 return ReplaceInstUsesWith(I, V);
495 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
496 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
498 (FAddSub->getOpcode() == Instruction::FAdd ||
499 FAddSub->getOpcode() == Instruction::FSub)) {
500 Value *Opnd0 = FAddSub->getOperand(0);
501 Value *Opnd1 = FAddSub->getOperand(1);
502 Constant *C0 = dyn_cast<Constant>(Opnd0);
503 Constant *C1 = dyn_cast<Constant>(Opnd1);
507 std::swap(Opnd0, Opnd1);
511 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
512 Value *M1 = ConstantExpr::getFMul(C1, C);
513 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
514 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
517 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
520 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
521 ? BinaryOperator::CreateFAdd(M0, M1)
522 : BinaryOperator::CreateFSub(M0, M1);
523 RI->copyFastMathFlags(&I);
531 // sqrt(X) * sqrt(X) -> X
532 if (AllowReassociate && (Op0 == Op1))
533 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
534 if (II->getIntrinsicID() == Intrinsic::sqrt)
535 return ReplaceInstUsesWith(I, II->getOperand(0));
537 // Under unsafe algebra do:
538 // X * log2(0.5*Y) = X*log2(Y) - X
539 if (AllowReassociate) {
540 Value *OpX = nullptr;
541 Value *OpY = nullptr;
543 detectLog2OfHalf(Op0, OpY, Log2);
547 detectLog2OfHalf(Op1, OpY, Log2);
552 // if pattern detected emit alternate sequence
554 BuilderTy::FastMathFlagGuard Guard(*Builder);
555 Builder->SetFastMathFlags(Log2->getFastMathFlags());
556 Log2->setArgOperand(0, OpY);
557 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
558 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
560 return ReplaceInstUsesWith(I, FSub);
564 // Handle symmetric situation in a 2-iteration loop
567 for (int i = 0; i < 2; i++) {
568 bool IgnoreZeroSign = I.hasNoSignedZeros();
569 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
570 BuilderTy::FastMathFlagGuard Guard(*Builder);
571 Builder->SetFastMathFlags(I.getFastMathFlags());
573 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
574 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
578 Value *FMul = Builder->CreateFMul(N0, N1);
580 return ReplaceInstUsesWith(I, FMul);
583 if (Opnd0->hasOneUse()) {
584 // -X * Y => -(X*Y) (Promote negation as high as possible)
585 Value *T = Builder->CreateFMul(N0, Opnd1);
586 Value *Neg = Builder->CreateFNeg(T);
588 return ReplaceInstUsesWith(I, Neg);
592 // (X*Y) * X => (X*X) * Y where Y != X
593 // The purpose is two-fold:
594 // 1) to form a power expression (of X).
595 // 2) potentially shorten the critical path: After transformation, the
596 // latency of the instruction Y is amortized by the expression of X*X,
597 // and therefore Y is in a "less critical" position compared to what it
598 // was before the transformation.
600 if (AllowReassociate) {
601 Value *Opnd0_0, *Opnd0_1;
602 if (Opnd0->hasOneUse() &&
603 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
605 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
607 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
611 BuilderTy::FastMathFlagGuard Guard(*Builder);
612 Builder->SetFastMathFlags(I.getFastMathFlags());
613 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
615 Value *R = Builder->CreateFMul(T, Y);
617 return ReplaceInstUsesWith(I, R);
622 if (!isa<Constant>(Op1))
623 std::swap(Opnd0, Opnd1);
628 return Changed ? &I : nullptr;
631 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
633 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
634 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
636 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
637 int NonNullOperand = -1;
638 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
639 if (ST->isNullValue())
641 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
642 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
643 if (ST->isNullValue())
646 if (NonNullOperand == -1)
649 Value *SelectCond = SI->getOperand(0);
651 // Change the div/rem to use 'Y' instead of the select.
652 I.setOperand(1, SI->getOperand(NonNullOperand));
654 // Okay, we know we replace the operand of the div/rem with 'Y' with no
655 // problem. However, the select, or the condition of the select may have
656 // multiple uses. Based on our knowledge that the operand must be non-zero,
657 // propagate the known value for the select into other uses of it, and
658 // propagate a known value of the condition into its other users.
660 // If the select and condition only have a single use, don't bother with this,
662 if (SI->use_empty() && SelectCond->hasOneUse())
665 // Scan the current block backward, looking for other uses of SI.
666 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
668 while (BBI != BBFront) {
670 // If we found a call to a function, we can't assume it will return, so
671 // information from below it cannot be propagated above it.
672 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
675 // Replace uses of the select or its condition with the known values.
676 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
679 *I = SI->getOperand(NonNullOperand);
681 } else if (*I == SelectCond) {
682 *I = Builder->getInt1(NonNullOperand == 1);
687 // If we past the instruction, quit looking for it.
690 if (&*BBI == SelectCond)
691 SelectCond = nullptr;
693 // If we ran out of things to eliminate, break out of the loop.
694 if (!SelectCond && !SI)
702 /// This function implements the transforms common to both integer division
703 /// instructions (udiv and sdiv). It is called by the visitors to those integer
704 /// division instructions.
705 /// @brief Common integer divide transforms
706 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
709 // The RHS is known non-zero.
710 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
715 // Handle cases involving: [su]div X, (select Cond, Y, Z)
716 // This does not apply for fdiv.
717 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
720 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
722 if (match(Op1, m_APInt(C2))) {
725 bool IsSigned = I.getOpcode() == Instruction::SDiv;
727 // (X / C1) / C2 -> X / (C1*C2)
728 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
729 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
730 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
731 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
732 return BinaryOperator::Create(I.getOpcode(), X,
733 ConstantInt::get(I.getType(), Product));
736 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
737 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
738 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
740 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
741 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
742 BinaryOperator *BO = BinaryOperator::Create(
743 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
744 BO->setIsExact(I.isExact());
748 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
749 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
750 BinaryOperator *BO = BinaryOperator::Create(
751 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
752 BO->setHasNoUnsignedWrap(
754 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
755 BO->setHasNoSignedWrap(
756 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
761 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
762 *C1 != C1->getBitWidth() - 1) ||
763 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
764 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
765 APInt C1Shifted = APInt::getOneBitSet(
766 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
768 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
769 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
770 BinaryOperator *BO = BinaryOperator::Create(
771 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
772 BO->setIsExact(I.isExact());
776 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
777 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
778 BinaryOperator *BO = BinaryOperator::Create(
779 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
780 BO->setHasNoUnsignedWrap(
782 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
783 BO->setHasNoSignedWrap(
784 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
789 if (*C2 != 0) { // avoid X udiv 0
790 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
791 if (Instruction *R = FoldOpIntoSelect(I, SI))
793 if (isa<PHINode>(Op0))
794 if (Instruction *NV = FoldOpIntoPhi(I))
800 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
801 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
802 bool isSigned = I.getOpcode() == Instruction::SDiv;
804 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
805 // result is one, if Op1 is -1 then the result is minus one, otherwise
807 Value *Inc = Builder->CreateAdd(Op1, One);
808 Value *Cmp = Builder->CreateICmpULT(
809 Inc, ConstantInt::get(I.getType(), 3));
810 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
812 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
813 // result is one, otherwise it's zero.
814 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
819 // See if we can fold away this div instruction.
820 if (SimplifyDemandedInstructionBits(I))
823 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
824 Value *X = nullptr, *Z = nullptr;
825 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
826 bool isSigned = I.getOpcode() == Instruction::SDiv;
827 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
828 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
829 return BinaryOperator::Create(I.getOpcode(), X, Op1);
835 /// dyn_castZExtVal - Checks if V is a zext or constant that can
836 /// be truncated to Ty without losing bits.
837 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
838 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
839 if (Z->getSrcTy() == Ty)
840 return Z->getOperand(0);
841 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
842 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
843 return ConstantExpr::getTrunc(C, Ty);
849 const unsigned MaxDepth = 6;
850 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
851 const BinaryOperator &I,
854 /// \brief Used to maintain state for visitUDivOperand().
855 struct UDivFoldAction {
856 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
857 ///< operand. This can be zero if this action
858 ///< joins two actions together.
860 Value *OperandToFold; ///< Which operand to fold.
862 Instruction *FoldResult; ///< The instruction returned when FoldAction is
865 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
866 ///< joins two actions together.
869 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
870 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
871 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
872 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
876 // X udiv 2^C -> X >> C
877 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
878 const BinaryOperator &I, InstCombiner &IC) {
879 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
880 BinaryOperator *LShr = BinaryOperator::CreateLShr(
881 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
887 // X udiv C, where C >= signbit
888 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
889 const BinaryOperator &I, InstCombiner &IC) {
890 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
892 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
893 ConstantInt::get(I.getType(), 1));
896 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
897 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
899 Instruction *ShiftLeft = cast<Instruction>(Op1);
900 if (isa<ZExtInst>(ShiftLeft))
901 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
904 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
905 Value *N = ShiftLeft->getOperand(1);
907 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
908 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
909 N = IC.Builder->CreateZExt(N, Z->getDestTy());
910 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
916 // \brief Recursively visits the possible right hand operands of a udiv
917 // instruction, seeing through select instructions, to determine if we can
918 // replace the udiv with something simpler. If we find that an operand is not
919 // able to simplify the udiv, we abort the entire transformation.
920 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
921 SmallVectorImpl<UDivFoldAction> &Actions,
922 unsigned Depth = 0) {
923 // Check to see if this is an unsigned division with an exact power of 2,
924 // if so, convert to a right shift.
925 if (match(Op1, m_Power2())) {
926 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
927 return Actions.size();
930 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
931 // X udiv C, where C >= signbit
932 if (C->getValue().isNegative()) {
933 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
934 return Actions.size();
937 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
938 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
939 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
940 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
941 return Actions.size();
944 // The remaining tests are all recursive, so bail out if we hit the limit.
945 if (Depth++ == MaxDepth)
948 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
950 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
951 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
952 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
953 return Actions.size();
959 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
962 if (Value *V = SimplifyVectorOp(I))
963 return ReplaceInstUsesWith(I, V);
965 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
966 return ReplaceInstUsesWith(I, V);
968 // Handle the integer div common cases
969 if (Instruction *Common = commonIDivTransforms(I))
972 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
975 const APInt *C1, *C2;
976 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
977 match(Op1, m_APInt(C2))) {
979 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
981 return BinaryOperator::CreateUDiv(
982 X, ConstantInt::get(X->getType(), C2ShlC1));
986 // (zext A) udiv (zext B) --> zext (A udiv B)
987 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
988 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
990 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
993 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
994 SmallVector<UDivFoldAction, 6> UDivActions;
995 if (visitUDivOperand(Op0, Op1, I, UDivActions))
996 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
997 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
998 Value *ActionOp1 = UDivActions[i].OperandToFold;
1001 Inst = Action(Op0, ActionOp1, I, *this);
1003 // This action joins two actions together. The RHS of this action is
1004 // simply the last action we processed, we saved the LHS action index in
1005 // the joining action.
1006 size_t SelectRHSIdx = i - 1;
1007 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1008 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1009 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1010 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1011 SelectLHS, SelectRHS);
1014 // If this is the last action to process, return it to the InstCombiner.
1015 // Otherwise, we insert it before the UDiv and record it so that we may
1016 // use it as part of a joining action (i.e., a SelectInst).
1018 Inst->insertBefore(&I);
1019 UDivActions[i].FoldResult = Inst;
1027 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1030 if (Value *V = SimplifyVectorOp(I))
1031 return ReplaceInstUsesWith(I, V);
1033 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1034 return ReplaceInstUsesWith(I, V);
1036 // Handle the integer div common cases
1037 if (Instruction *Common = commonIDivTransforms(I))
1041 if (match(Op1, m_AllOnes()))
1042 return BinaryOperator::CreateNeg(Op0);
1044 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1045 // sdiv X, C --> ashr exact X, log2(C)
1046 if (I.isExact() && RHS->getValue().isNonNegative() &&
1047 RHS->getValue().isPowerOf2()) {
1048 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1049 RHS->getValue().exactLogBase2());
1050 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1054 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1055 // X/INT_MIN -> X == INT_MIN
1056 if (RHS->isMinSignedValue())
1057 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1059 // -X/C --> X/-C provided the negation doesn't overflow.
1060 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1061 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1062 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1063 ConstantExpr::getNeg(RHS));
1066 // If the sign bits of both operands are zero (i.e. we can prove they are
1067 // unsigned inputs), turn this into a udiv.
1068 if (I.getType()->isIntegerTy()) {
1069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1070 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1071 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1072 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1073 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1076 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1077 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1078 // Safe because the only negative value (1 << Y) can take on is
1079 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1080 // the sign bit set.
1081 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1089 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1091 /// 1) 1/C is exact, or
1092 /// 2) reciprocal is allowed.
1093 /// If the conversion was successful, the simplified expression "X * 1/C" is
1094 /// returned; otherwise, NULL is returned.
1096 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1097 bool AllowReciprocal) {
1098 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1101 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1102 APFloat Reciprocal(FpVal.getSemantics());
1103 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1105 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1106 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1107 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1108 Cvt = !Reciprocal.isDenormal();
1115 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1116 return BinaryOperator::CreateFMul(Dividend, R);
1119 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1122 if (Value *V = SimplifyVectorOp(I))
1123 return ReplaceInstUsesWith(I, V);
1125 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1126 return ReplaceInstUsesWith(I, V);
1128 if (isa<Constant>(Op0))
1129 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1130 if (Instruction *R = FoldOpIntoSelect(I, SI))
1133 bool AllowReassociate = I.hasUnsafeAlgebra();
1134 bool AllowReciprocal = I.hasAllowReciprocal();
1136 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1137 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1138 if (Instruction *R = FoldOpIntoSelect(I, SI))
1141 if (AllowReassociate) {
1142 Constant *C1 = nullptr;
1143 Constant *C2 = Op1C;
1145 Instruction *Res = nullptr;
1147 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1148 // (X*C1)/C2 => X * (C1/C2)
1150 Constant *C = ConstantExpr::getFDiv(C1, C2);
1152 Res = BinaryOperator::CreateFMul(X, C);
1153 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1154 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1156 Constant *C = ConstantExpr::getFMul(C1, C2);
1157 if (isNormalFp(C)) {
1158 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1160 Res = BinaryOperator::CreateFDiv(X, C);
1165 Res->setFastMathFlags(I.getFastMathFlags());
1171 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1172 T->copyFastMathFlags(&I);
1179 if (AllowReassociate && isa<Constant>(Op0)) {
1180 Constant *C1 = cast<Constant>(Op0), *C2;
1181 Constant *Fold = nullptr;
1183 bool CreateDiv = true;
1185 // C1 / (X*C2) => (C1/C2) / X
1186 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1187 Fold = ConstantExpr::getFDiv(C1, C2);
1188 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1189 // C1 / (X/C2) => (C1*C2) / X
1190 Fold = ConstantExpr::getFMul(C1, C2);
1191 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1192 // C1 / (C2/X) => (C1/C2) * X
1193 Fold = ConstantExpr::getFDiv(C1, C2);
1197 if (Fold && isNormalFp(Fold)) {
1198 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1199 : BinaryOperator::CreateFMul(X, Fold);
1200 R->setFastMathFlags(I.getFastMathFlags());
1206 if (AllowReassociate) {
1208 Value *NewInst = nullptr;
1209 Instruction *SimpR = nullptr;
1211 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1212 // (X/Y) / Z => X / (Y*Z)
1214 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1215 NewInst = Builder->CreateFMul(Y, Op1);
1216 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1217 FastMathFlags Flags = I.getFastMathFlags();
1218 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1219 RI->setFastMathFlags(Flags);
1221 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1223 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1224 // Z / (X/Y) => Z*Y / X
1226 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1227 NewInst = Builder->CreateFMul(Op0, Y);
1228 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1229 FastMathFlags Flags = I.getFastMathFlags();
1230 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1231 RI->setFastMathFlags(Flags);
1233 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1238 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1239 T->setDebugLoc(I.getDebugLoc());
1240 SimpR->setFastMathFlags(I.getFastMathFlags());
1248 /// This function implements the transforms common to both integer remainder
1249 /// instructions (urem and srem). It is called by the visitors to those integer
1250 /// remainder instructions.
1251 /// @brief Common integer remainder transforms
1252 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1255 // The RHS is known non-zero.
1256 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1261 // Handle cases involving: rem X, (select Cond, Y, Z)
1262 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1265 if (isa<Constant>(Op1)) {
1266 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1267 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1268 if (Instruction *R = FoldOpIntoSelect(I, SI))
1270 } else if (isa<PHINode>(Op0I)) {
1271 if (Instruction *NV = FoldOpIntoPhi(I))
1275 // See if we can fold away this rem instruction.
1276 if (SimplifyDemandedInstructionBits(I))
1284 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1287 if (Value *V = SimplifyVectorOp(I))
1288 return ReplaceInstUsesWith(I, V);
1290 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1291 return ReplaceInstUsesWith(I, V);
1293 if (Instruction *common = commonIRemTransforms(I))
1296 // (zext A) urem (zext B) --> zext (A urem B)
1297 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1298 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1299 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1302 // X urem Y -> X and Y-1, where Y is a power of 2,
1303 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1304 Constant *N1 = Constant::getAllOnesValue(I.getType());
1305 Value *Add = Builder->CreateAdd(Op1, N1);
1306 return BinaryOperator::CreateAnd(Op0, Add);
1309 // 1 urem X -> zext(X != 1)
1310 if (match(Op0, m_One())) {
1311 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1312 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1313 return ReplaceInstUsesWith(I, Ext);
1319 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1322 if (Value *V = SimplifyVectorOp(I))
1323 return ReplaceInstUsesWith(I, V);
1325 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1326 return ReplaceInstUsesWith(I, V);
1328 // Handle the integer rem common cases
1329 if (Instruction *Common = commonIRemTransforms(I))
1335 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1336 Worklist.AddValue(I.getOperand(1));
1337 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1342 // If the sign bits of both operands are zero (i.e. we can prove they are
1343 // unsigned inputs), turn this into a urem.
1344 if (I.getType()->isIntegerTy()) {
1345 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1346 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1347 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1348 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1349 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1353 // If it's a constant vector, flip any negative values positive.
1354 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1355 Constant *C = cast<Constant>(Op1);
1356 unsigned VWidth = C->getType()->getVectorNumElements();
1358 bool hasNegative = false;
1359 bool hasMissing = false;
1360 for (unsigned i = 0; i != VWidth; ++i) {
1361 Constant *Elt = C->getAggregateElement(i);
1367 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1368 if (RHS->isNegative())
1372 if (hasNegative && !hasMissing) {
1373 SmallVector<Constant *, 16> Elts(VWidth);
1374 for (unsigned i = 0; i != VWidth; ++i) {
1375 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1376 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1377 if (RHS->isNegative())
1378 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1382 Constant *NewRHSV = ConstantVector::get(Elts);
1383 if (NewRHSV != C) { // Don't loop on -MININT
1384 Worklist.AddValue(I.getOperand(1));
1385 I.setOperand(1, NewRHSV);
1394 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1397 if (Value *V = SimplifyVectorOp(I))
1398 return ReplaceInstUsesWith(I, V);
1400 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1401 return ReplaceInstUsesWith(I, V);
1403 // Handle cases involving: rem X, (select Cond, Y, Z)
1404 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))