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 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
243 if (I.hasNoSignedWrap() &&
244 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
245 match(Op1, m_NSWSub(m_Value(), m_Value())))
246 BO->setHasNoSignedWrap();
251 // (X / Y) * Y = X - (X % Y)
252 // (X / Y) * -Y = (X % Y) - X
255 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
257 (BO->getOpcode() != Instruction::UDiv &&
258 BO->getOpcode() != Instruction::SDiv)) {
260 BO = dyn_cast<BinaryOperator>(Op1);
262 Value *Neg = dyn_castNegVal(Op1C);
263 if (BO && BO->hasOneUse() &&
264 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
265 (BO->getOpcode() == Instruction::UDiv ||
266 BO->getOpcode() == Instruction::SDiv)) {
267 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
269 // If the division is exact, X % Y is zero, so we end up with X or -X.
270 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
271 if (SDiv->isExact()) {
273 return ReplaceInstUsesWith(I, Op0BO);
274 return BinaryOperator::CreateNeg(Op0BO);
278 if (BO->getOpcode() == Instruction::UDiv)
279 Rem = Builder->CreateURem(Op0BO, Op1BO);
281 Rem = Builder->CreateSRem(Op0BO, Op1BO);
285 return BinaryOperator::CreateSub(Op0BO, Rem);
286 return BinaryOperator::CreateSub(Rem, Op0BO);
290 /// i1 mul -> i1 and.
291 if (I.getType()->getScalarType()->isIntegerTy(1))
292 return BinaryOperator::CreateAnd(Op0, Op1);
294 // X*(1 << Y) --> X << Y
295 // (1 << Y)*X --> X << Y
298 BinaryOperator *BO = nullptr;
300 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
301 BO = BinaryOperator::CreateShl(Op1, Y);
302 ShlNSW = cast<BinaryOperator>(Op0)->hasNoSignedWrap();
303 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
304 BO = BinaryOperator::CreateShl(Op0, Y);
305 ShlNSW = cast<BinaryOperator>(Op1)->hasNoSignedWrap();
308 if (I.hasNoUnsignedWrap())
309 BO->setHasNoUnsignedWrap();
310 if (I.hasNoSignedWrap() && ShlNSW)
311 BO->setHasNoSignedWrap();
316 // If one of the operands of the multiply is a cast from a boolean value, then
317 // we know the bool is either zero or one, so this is a 'masking' multiply.
318 // X * Y (where Y is 0 or 1) -> X & (0-Y)
319 if (!I.getType()->isVectorTy()) {
320 // -2 is "-1 << 1" so it is all bits set except the low one.
321 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
323 Value *BoolCast = nullptr, *OtherOp = nullptr;
324 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
325 BoolCast = Op0, OtherOp = Op1;
326 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
327 BoolCast = Op1, OtherOp = Op0;
330 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
332 return BinaryOperator::CreateAnd(V, OtherOp);
336 return Changed ? &I : nullptr;
339 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
340 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
341 if (!Op->hasOneUse())
344 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
347 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
351 Value *OpLog2Of = II->getArgOperand(0);
352 if (!OpLog2Of->hasOneUse())
355 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
358 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
361 if (match(I->getOperand(0), m_SpecificFP(0.5)))
362 Y = I->getOperand(1);
363 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
364 Y = I->getOperand(0);
367 static bool isFiniteNonZeroFp(Constant *C) {
368 if (C->getType()->isVectorTy()) {
369 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
371 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
372 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
378 return isa<ConstantFP>(C) &&
379 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
382 static bool isNormalFp(Constant *C) {
383 if (C->getType()->isVectorTy()) {
384 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
386 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
387 if (!CFP || !CFP->getValueAPF().isNormal())
393 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
396 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
397 /// true iff the given value is FMul or FDiv with one and only one operand
398 /// being a normal constant (i.e. not Zero/NaN/Infinity).
399 static bool isFMulOrFDivWithConstant(Value *V) {
400 Instruction *I = dyn_cast<Instruction>(V);
401 if (!I || (I->getOpcode() != Instruction::FMul &&
402 I->getOpcode() != Instruction::FDiv))
405 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
406 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
411 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
414 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
415 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
416 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
417 /// This function is to simplify "FMulOrDiv * C" and returns the
418 /// resulting expression. Note that this function could return NULL in
419 /// case the constants cannot be folded into a normal floating-point.
421 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
422 Instruction *InsertBefore) {
423 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
425 Value *Opnd0 = FMulOrDiv->getOperand(0);
426 Value *Opnd1 = FMulOrDiv->getOperand(1);
428 Constant *C0 = dyn_cast<Constant>(Opnd0);
429 Constant *C1 = dyn_cast<Constant>(Opnd1);
431 BinaryOperator *R = nullptr;
433 // (X * C0) * C => X * (C0*C)
434 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
435 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
437 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
440 // (C0 / X) * C => (C0 * C) / X
441 if (FMulOrDiv->hasOneUse()) {
442 // It would otherwise introduce another div.
443 Constant *F = ConstantExpr::getFMul(C0, C);
445 R = BinaryOperator::CreateFDiv(F, Opnd1);
448 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
449 Constant *F = ConstantExpr::getFDiv(C, C1);
451 R = BinaryOperator::CreateFMul(Opnd0, F);
453 // (X / C1) * C => X / (C1/C)
454 Constant *F = ConstantExpr::getFDiv(C1, C);
456 R = BinaryOperator::CreateFDiv(Opnd0, F);
462 R->setHasUnsafeAlgebra(true);
463 InsertNewInstWith(R, *InsertBefore);
469 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
470 bool Changed = SimplifyAssociativeOrCommutative(I);
471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
473 if (Value *V = SimplifyVectorOp(I))
474 return ReplaceInstUsesWith(I, V);
476 if (isa<Constant>(Op0))
479 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
481 return ReplaceInstUsesWith(I, V);
483 bool AllowReassociate = I.hasUnsafeAlgebra();
485 // Simplify mul instructions with a constant RHS.
486 if (isa<Constant>(Op1)) {
487 // Try to fold constant mul into select arguments.
488 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
489 if (Instruction *R = FoldOpIntoSelect(I, SI))
492 if (isa<PHINode>(Op0))
493 if (Instruction *NV = FoldOpIntoPhi(I))
496 // (fmul X, -1.0) --> (fsub -0.0, X)
497 if (match(Op1, m_SpecificFP(-1.0))) {
498 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
499 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
500 RI->copyFastMathFlags(&I);
504 Constant *C = cast<Constant>(Op1);
505 if (AllowReassociate && isFiniteNonZeroFp(C)) {
506 // Let MDC denote an expression in one of these forms:
507 // X * C, C/X, X/C, where C is a constant.
509 // Try to simplify "MDC * Constant"
510 if (isFMulOrFDivWithConstant(Op0))
511 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
512 return ReplaceInstUsesWith(I, V);
514 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
515 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
517 (FAddSub->getOpcode() == Instruction::FAdd ||
518 FAddSub->getOpcode() == Instruction::FSub)) {
519 Value *Opnd0 = FAddSub->getOperand(0);
520 Value *Opnd1 = FAddSub->getOperand(1);
521 Constant *C0 = dyn_cast<Constant>(Opnd0);
522 Constant *C1 = dyn_cast<Constant>(Opnd1);
526 std::swap(Opnd0, Opnd1);
530 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
531 Value *M1 = ConstantExpr::getFMul(C1, C);
532 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
533 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
536 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
539 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
540 ? BinaryOperator::CreateFAdd(M0, M1)
541 : BinaryOperator::CreateFSub(M0, M1);
542 RI->copyFastMathFlags(&I);
550 // sqrt(X) * sqrt(X) -> X
551 if (AllowReassociate && (Op0 == Op1))
552 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
553 if (II->getIntrinsicID() == Intrinsic::sqrt)
554 return ReplaceInstUsesWith(I, II->getOperand(0));
556 // Under unsafe algebra do:
557 // X * log2(0.5*Y) = X*log2(Y) - X
558 if (AllowReassociate) {
559 Value *OpX = nullptr;
560 Value *OpY = nullptr;
562 detectLog2OfHalf(Op0, OpY, Log2);
566 detectLog2OfHalf(Op1, OpY, Log2);
571 // if pattern detected emit alternate sequence
573 BuilderTy::FastMathFlagGuard Guard(*Builder);
574 Builder->SetFastMathFlags(Log2->getFastMathFlags());
575 Log2->setArgOperand(0, OpY);
576 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
577 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
579 return ReplaceInstUsesWith(I, FSub);
583 // Handle symmetric situation in a 2-iteration loop
586 for (int i = 0; i < 2; i++) {
587 bool IgnoreZeroSign = I.hasNoSignedZeros();
588 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
589 BuilderTy::FastMathFlagGuard Guard(*Builder);
590 Builder->SetFastMathFlags(I.getFastMathFlags());
592 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
593 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
597 Value *FMul = Builder->CreateFMul(N0, N1);
599 return ReplaceInstUsesWith(I, FMul);
602 if (Opnd0->hasOneUse()) {
603 // -X * Y => -(X*Y) (Promote negation as high as possible)
604 Value *T = Builder->CreateFMul(N0, Opnd1);
605 Value *Neg = Builder->CreateFNeg(T);
607 return ReplaceInstUsesWith(I, Neg);
611 // (X*Y) * X => (X*X) * Y where Y != X
612 // The purpose is two-fold:
613 // 1) to form a power expression (of X).
614 // 2) potentially shorten the critical path: After transformation, the
615 // latency of the instruction Y is amortized by the expression of X*X,
616 // and therefore Y is in a "less critical" position compared to what it
617 // was before the transformation.
619 if (AllowReassociate) {
620 Value *Opnd0_0, *Opnd0_1;
621 if (Opnd0->hasOneUse() &&
622 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
624 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
626 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
630 BuilderTy::FastMathFlagGuard Guard(*Builder);
631 Builder->SetFastMathFlags(I.getFastMathFlags());
632 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
634 Value *R = Builder->CreateFMul(T, Y);
636 return ReplaceInstUsesWith(I, R);
641 if (!isa<Constant>(Op1))
642 std::swap(Opnd0, Opnd1);
647 return Changed ? &I : nullptr;
650 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
652 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
653 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
655 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
656 int NonNullOperand = -1;
657 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
658 if (ST->isNullValue())
660 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
661 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
662 if (ST->isNullValue())
665 if (NonNullOperand == -1)
668 Value *SelectCond = SI->getOperand(0);
670 // Change the div/rem to use 'Y' instead of the select.
671 I.setOperand(1, SI->getOperand(NonNullOperand));
673 // Okay, we know we replace the operand of the div/rem with 'Y' with no
674 // problem. However, the select, or the condition of the select may have
675 // multiple uses. Based on our knowledge that the operand must be non-zero,
676 // propagate the known value for the select into other uses of it, and
677 // propagate a known value of the condition into its other users.
679 // If the select and condition only have a single use, don't bother with this,
681 if (SI->use_empty() && SelectCond->hasOneUse())
684 // Scan the current block backward, looking for other uses of SI.
685 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
687 while (BBI != BBFront) {
689 // If we found a call to a function, we can't assume it will return, so
690 // information from below it cannot be propagated above it.
691 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
694 // Replace uses of the select or its condition with the known values.
695 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
698 *I = SI->getOperand(NonNullOperand);
700 } else if (*I == SelectCond) {
701 *I = Builder->getInt1(NonNullOperand == 1);
706 // If we past the instruction, quit looking for it.
709 if (&*BBI == SelectCond)
710 SelectCond = nullptr;
712 // If we ran out of things to eliminate, break out of the loop.
713 if (!SelectCond && !SI)
721 /// This function implements the transforms common to both integer division
722 /// instructions (udiv and sdiv). It is called by the visitors to those integer
723 /// division instructions.
724 /// @brief Common integer divide transforms
725 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
728 // The RHS is known non-zero.
729 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
734 // Handle cases involving: [su]div X, (select Cond, Y, Z)
735 // This does not apply for fdiv.
736 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
739 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
741 if (match(Op1, m_APInt(C2))) {
744 bool IsSigned = I.getOpcode() == Instruction::SDiv;
746 // (X / C1) / C2 -> X / (C1*C2)
747 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
748 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
749 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
750 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
751 return BinaryOperator::Create(I.getOpcode(), X,
752 ConstantInt::get(I.getType(), Product));
755 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
756 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
757 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
759 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
760 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
761 BinaryOperator *BO = BinaryOperator::Create(
762 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
763 BO->setIsExact(I.isExact());
767 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
768 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
769 BinaryOperator *BO = BinaryOperator::Create(
770 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
771 BO->setHasNoUnsignedWrap(
773 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
774 BO->setHasNoSignedWrap(
775 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
780 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
781 *C1 != C1->getBitWidth() - 1) ||
782 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
783 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
784 APInt C1Shifted = APInt::getOneBitSet(
785 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
787 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
788 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
789 BinaryOperator *BO = BinaryOperator::Create(
790 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
791 BO->setIsExact(I.isExact());
795 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
796 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
797 BinaryOperator *BO = BinaryOperator::Create(
798 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
799 BO->setHasNoUnsignedWrap(
801 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
802 BO->setHasNoSignedWrap(
803 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
808 if (*C2 != 0) { // avoid X udiv 0
809 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
810 if (Instruction *R = FoldOpIntoSelect(I, SI))
812 if (isa<PHINode>(Op0))
813 if (Instruction *NV = FoldOpIntoPhi(I))
819 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
820 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
821 bool isSigned = I.getOpcode() == Instruction::SDiv;
823 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
824 // result is one, if Op1 is -1 then the result is minus one, otherwise
826 Value *Inc = Builder->CreateAdd(Op1, One);
827 Value *Cmp = Builder->CreateICmpULT(
828 Inc, ConstantInt::get(I.getType(), 3));
829 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
831 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
832 // result is one, otherwise it's zero.
833 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
838 // See if we can fold away this div instruction.
839 if (SimplifyDemandedInstructionBits(I))
842 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
843 Value *X = nullptr, *Z = nullptr;
844 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
845 bool isSigned = I.getOpcode() == Instruction::SDiv;
846 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
847 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
848 return BinaryOperator::Create(I.getOpcode(), X, Op1);
854 /// dyn_castZExtVal - Checks if V is a zext or constant that can
855 /// be truncated to Ty without losing bits.
856 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
857 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
858 if (Z->getSrcTy() == Ty)
859 return Z->getOperand(0);
860 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
861 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
862 return ConstantExpr::getTrunc(C, Ty);
868 const unsigned MaxDepth = 6;
869 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
870 const BinaryOperator &I,
873 /// \brief Used to maintain state for visitUDivOperand().
874 struct UDivFoldAction {
875 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
876 ///< operand. This can be zero if this action
877 ///< joins two actions together.
879 Value *OperandToFold; ///< Which operand to fold.
881 Instruction *FoldResult; ///< The instruction returned when FoldAction is
884 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
885 ///< joins two actions together.
888 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
889 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
890 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
891 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
895 // X udiv 2^C -> X >> C
896 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
897 const BinaryOperator &I, InstCombiner &IC) {
898 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
899 BinaryOperator *LShr = BinaryOperator::CreateLShr(
900 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
906 // X udiv C, where C >= signbit
907 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
908 const BinaryOperator &I, InstCombiner &IC) {
909 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
911 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
912 ConstantInt::get(I.getType(), 1));
915 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
916 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
918 Instruction *ShiftLeft = cast<Instruction>(Op1);
919 if (isa<ZExtInst>(ShiftLeft))
920 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
923 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
924 Value *N = ShiftLeft->getOperand(1);
926 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
927 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
928 N = IC.Builder->CreateZExt(N, Z->getDestTy());
929 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
935 // \brief Recursively visits the possible right hand operands of a udiv
936 // instruction, seeing through select instructions, to determine if we can
937 // replace the udiv with something simpler. If we find that an operand is not
938 // able to simplify the udiv, we abort the entire transformation.
939 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
940 SmallVectorImpl<UDivFoldAction> &Actions,
941 unsigned Depth = 0) {
942 // Check to see if this is an unsigned division with an exact power of 2,
943 // if so, convert to a right shift.
944 if (match(Op1, m_Power2())) {
945 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
946 return Actions.size();
949 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
950 // X udiv C, where C >= signbit
951 if (C->getValue().isNegative()) {
952 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
953 return Actions.size();
956 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
957 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
958 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
959 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
960 return Actions.size();
963 // The remaining tests are all recursive, so bail out if we hit the limit.
964 if (Depth++ == MaxDepth)
967 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
969 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
970 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
971 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
972 return Actions.size();
978 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
979 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
981 if (Value *V = SimplifyVectorOp(I))
982 return ReplaceInstUsesWith(I, V);
984 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
985 return ReplaceInstUsesWith(I, V);
987 // Handle the integer div common cases
988 if (Instruction *Common = commonIDivTransforms(I))
991 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
994 const APInt *C1, *C2;
995 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
996 match(Op1, m_APInt(C2))) {
998 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1000 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1001 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1002 X, ConstantInt::get(X->getType(), C2ShlC1));
1010 // (zext A) udiv (zext B) --> zext (A udiv B)
1011 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1012 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1013 return new ZExtInst(
1014 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1017 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1018 SmallVector<UDivFoldAction, 6> UDivActions;
1019 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1020 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1021 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1022 Value *ActionOp1 = UDivActions[i].OperandToFold;
1025 Inst = Action(Op0, ActionOp1, I, *this);
1027 // This action joins two actions together. The RHS of this action is
1028 // simply the last action we processed, we saved the LHS action index in
1029 // the joining action.
1030 size_t SelectRHSIdx = i - 1;
1031 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1032 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1033 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1034 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1035 SelectLHS, SelectRHS);
1038 // If this is the last action to process, return it to the InstCombiner.
1039 // Otherwise, we insert it before the UDiv and record it so that we may
1040 // use it as part of a joining action (i.e., a SelectInst).
1042 Inst->insertBefore(&I);
1043 UDivActions[i].FoldResult = Inst;
1051 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1054 if (Value *V = SimplifyVectorOp(I))
1055 return ReplaceInstUsesWith(I, V);
1057 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1058 return ReplaceInstUsesWith(I, V);
1060 // Handle the integer div common cases
1061 if (Instruction *Common = commonIDivTransforms(I))
1065 if (match(Op1, m_AllOnes()))
1066 return BinaryOperator::CreateNeg(Op0);
1068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1069 // sdiv X, C --> ashr exact X, log2(C)
1070 if (I.isExact() && RHS->getValue().isNonNegative() &&
1071 RHS->getValue().isPowerOf2()) {
1072 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1073 RHS->getValue().exactLogBase2());
1074 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1078 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1079 // X/INT_MIN -> X == INT_MIN
1080 if (RHS->isMinSignedValue())
1081 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1083 // -X/C --> X/-C provided the negation doesn't overflow.
1085 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1086 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1087 BO->setIsExact(I.isExact());
1092 // If the sign bits of both operands are zero (i.e. we can prove they are
1093 // unsigned inputs), turn this into a udiv.
1094 if (I.getType()->isIntegerTy()) {
1095 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1096 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1097 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1098 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1099 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1100 BO->setIsExact(I.isExact());
1104 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1105 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1106 // Safe because the only negative value (1 << Y) can take on is
1107 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1108 // the sign bit set.
1109 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1110 BO->setIsExact(I.isExact());
1119 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1121 /// 1) 1/C is exact, or
1122 /// 2) reciprocal is allowed.
1123 /// If the conversion was successful, the simplified expression "X * 1/C" is
1124 /// returned; otherwise, NULL is returned.
1126 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1127 bool AllowReciprocal) {
1128 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1131 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1132 APFloat Reciprocal(FpVal.getSemantics());
1133 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1135 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1136 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1137 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1138 Cvt = !Reciprocal.isDenormal();
1145 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1146 return BinaryOperator::CreateFMul(Dividend, R);
1149 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1150 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1152 if (Value *V = SimplifyVectorOp(I))
1153 return ReplaceInstUsesWith(I, V);
1155 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1156 return ReplaceInstUsesWith(I, V);
1158 if (isa<Constant>(Op0))
1159 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1160 if (Instruction *R = FoldOpIntoSelect(I, SI))
1163 bool AllowReassociate = I.hasUnsafeAlgebra();
1164 bool AllowReciprocal = I.hasAllowReciprocal();
1166 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1168 if (Instruction *R = FoldOpIntoSelect(I, SI))
1171 if (AllowReassociate) {
1172 Constant *C1 = nullptr;
1173 Constant *C2 = Op1C;
1175 Instruction *Res = nullptr;
1177 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1178 // (X*C1)/C2 => X * (C1/C2)
1180 Constant *C = ConstantExpr::getFDiv(C1, C2);
1182 Res = BinaryOperator::CreateFMul(X, C);
1183 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1184 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1186 Constant *C = ConstantExpr::getFMul(C1, C2);
1187 if (isNormalFp(C)) {
1188 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1190 Res = BinaryOperator::CreateFDiv(X, C);
1195 Res->setFastMathFlags(I.getFastMathFlags());
1201 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1202 T->copyFastMathFlags(&I);
1209 if (AllowReassociate && isa<Constant>(Op0)) {
1210 Constant *C1 = cast<Constant>(Op0), *C2;
1211 Constant *Fold = nullptr;
1213 bool CreateDiv = true;
1215 // C1 / (X*C2) => (C1/C2) / X
1216 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1217 Fold = ConstantExpr::getFDiv(C1, C2);
1218 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1219 // C1 / (X/C2) => (C1*C2) / X
1220 Fold = ConstantExpr::getFMul(C1, C2);
1221 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1222 // C1 / (C2/X) => (C1/C2) * X
1223 Fold = ConstantExpr::getFDiv(C1, C2);
1227 if (Fold && isNormalFp(Fold)) {
1228 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1229 : BinaryOperator::CreateFMul(X, Fold);
1230 R->setFastMathFlags(I.getFastMathFlags());
1236 if (AllowReassociate) {
1238 Value *NewInst = nullptr;
1239 Instruction *SimpR = nullptr;
1241 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1242 // (X/Y) / Z => X / (Y*Z)
1244 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1245 NewInst = Builder->CreateFMul(Y, Op1);
1246 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1247 FastMathFlags Flags = I.getFastMathFlags();
1248 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1249 RI->setFastMathFlags(Flags);
1251 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1253 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1254 // Z / (X/Y) => Z*Y / X
1256 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1257 NewInst = Builder->CreateFMul(Op0, Y);
1258 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1259 FastMathFlags Flags = I.getFastMathFlags();
1260 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1261 RI->setFastMathFlags(Flags);
1263 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1268 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1269 T->setDebugLoc(I.getDebugLoc());
1270 SimpR->setFastMathFlags(I.getFastMathFlags());
1278 /// This function implements the transforms common to both integer remainder
1279 /// instructions (urem and srem). It is called by the visitors to those integer
1280 /// remainder instructions.
1281 /// @brief Common integer remainder transforms
1282 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1285 // The RHS is known non-zero.
1286 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1291 // Handle cases involving: rem X, (select Cond, Y, Z)
1292 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1295 if (isa<Constant>(Op1)) {
1296 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1297 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1298 if (Instruction *R = FoldOpIntoSelect(I, SI))
1300 } else if (isa<PHINode>(Op0I)) {
1301 if (Instruction *NV = FoldOpIntoPhi(I))
1305 // See if we can fold away this rem instruction.
1306 if (SimplifyDemandedInstructionBits(I))
1314 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1315 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1317 if (Value *V = SimplifyVectorOp(I))
1318 return ReplaceInstUsesWith(I, V);
1320 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1321 return ReplaceInstUsesWith(I, V);
1323 if (Instruction *common = commonIRemTransforms(I))
1326 // (zext A) urem (zext B) --> zext (A urem B)
1327 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1328 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1329 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1332 // X urem Y -> X and Y-1, where Y is a power of 2,
1333 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1334 Constant *N1 = Constant::getAllOnesValue(I.getType());
1335 Value *Add = Builder->CreateAdd(Op1, N1);
1336 return BinaryOperator::CreateAnd(Op0, Add);
1339 // 1 urem X -> zext(X != 1)
1340 if (match(Op0, m_One())) {
1341 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1342 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1343 return ReplaceInstUsesWith(I, Ext);
1349 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1352 if (Value *V = SimplifyVectorOp(I))
1353 return ReplaceInstUsesWith(I, V);
1355 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1356 return ReplaceInstUsesWith(I, V);
1358 // Handle the integer rem common cases
1359 if (Instruction *Common = commonIRemTransforms(I))
1365 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1366 Worklist.AddValue(I.getOperand(1));
1367 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1372 // If the sign bits of both operands are zero (i.e. we can prove they are
1373 // unsigned inputs), turn this into a urem.
1374 if (I.getType()->isIntegerTy()) {
1375 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1376 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1377 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1378 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1379 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1383 // If it's a constant vector, flip any negative values positive.
1384 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1385 Constant *C = cast<Constant>(Op1);
1386 unsigned VWidth = C->getType()->getVectorNumElements();
1388 bool hasNegative = false;
1389 bool hasMissing = false;
1390 for (unsigned i = 0; i != VWidth; ++i) {
1391 Constant *Elt = C->getAggregateElement(i);
1397 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1398 if (RHS->isNegative())
1402 if (hasNegative && !hasMissing) {
1403 SmallVector<Constant *, 16> Elts(VWidth);
1404 for (unsigned i = 0; i != VWidth; ++i) {
1405 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1406 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1407 if (RHS->isNegative())
1408 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1412 Constant *NewRHSV = ConstantVector::get(Elts);
1413 if (NewRHSV != C) { // Don't loop on -MININT
1414 Worklist.AddValue(I.getOperand(1));
1415 I.setOperand(1, NewRHSV);
1424 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1427 if (Value *V = SimplifyVectorOp(I))
1428 return ReplaceInstUsesWith(I, V);
1430 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1431 return ReplaceInstUsesWith(I, V);
1433 // Handle cases involving: rem X, (select Cond, Y, Z)
1434 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))