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 /// \brief Return true if we can prove that:
127 /// (mul LHS, RHS) === (mul nsw LHS, RHS)
128 bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
130 // Multiplying n * m significant bits yields a result of n + m significant
131 // bits. If the total number of significant bits does not exceed the
132 // result bit width (minus 1), there is no overflow.
133 // This means if we have enough leading sign bits in the operands
134 // we can guarantee that the result does not overflow.
135 // Ref: "Hacker's Delight" by Henry Warren
136 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
138 // Note that underestimating the number of sign bits gives a more
139 // conservative answer.
140 unsigned SignBits = ComputeNumSignBits(LHS, 0, CxtI) +
141 ComputeNumSignBits(RHS, 0, CxtI);
143 // First handle the easy case: if we have enough sign bits there's
144 // definitely no overflow.
145 if (SignBits > BitWidth + 1)
148 // There are two ambiguous cases where there can be no overflow:
149 // SignBits == BitWidth + 1 and
150 // SignBits == BitWidth
151 // The second case is difficult to check, therefore we only handle the
153 if (SignBits == BitWidth + 1) {
154 // It overflows only when both arguments are negative and the true
155 // product is exactly the minimum negative number.
156 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
157 // For simplicity we just check if at least one side is not negative.
158 bool LHSNonNegative, LHSNegative;
159 bool RHSNonNegative, RHSNegative;
160 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, CxtI);
161 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, CxtI);
162 if (LHSNonNegative || RHSNonNegative)
168 /// \brief Return true if we can prove that:
169 /// (mul LHS, RHS) === (mul nuw LHS, RHS)
170 bool InstCombiner::WillNotOverflowUnsignedMul(Value *LHS, Value *RHS,
172 // Multiplying n * m significant bits yields a result of n + m significant
173 // bits. If the total number of significant bits does not exceed the
174 // result bit width (minus 1), there is no overflow.
175 // This means if we have enough leading zero bits in the operands
176 // we can guarantee that the result does not overflow.
177 // Ref: "Hacker's Delight" by Henry Warren
178 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
179 APInt LHSKnownZero(BitWidth, 0);
180 APInt RHSKnownZero(BitWidth, 0);
181 APInt TmpKnownOne(BitWidth, 0);
182 computeKnownBits(LHS, LHSKnownZero, TmpKnownOne, 0, CxtI);
183 computeKnownBits(RHS, RHSKnownZero, TmpKnownOne, 0, CxtI);
184 // Note that underestimating the number of zero bits gives a more
185 // conservative answer.
186 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
187 RHSKnownZero.countLeadingOnes();
188 // First handle the easy case: if we have enough zero bits there's
189 // definitely no overflow.
190 if (ZeroBits >= BitWidth)
193 // There is an ambiguous cases where there can be no overflow:
194 // ZeroBits == BitWidth - 1
195 // However, determining overflow requires calculating the sign bit of
201 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
202 bool Changed = SimplifyAssociativeOrCommutative(I);
203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
205 if (Value *V = SimplifyVectorOp(I))
206 return ReplaceInstUsesWith(I, V);
208 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
209 return ReplaceInstUsesWith(I, V);
211 if (Value *V = SimplifyUsingDistributiveLaws(I))
212 return ReplaceInstUsesWith(I, V);
215 if (match(Op1, m_AllOnes())) {
216 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
217 if (I.hasNoSignedWrap())
218 BO->setHasNoSignedWrap();
222 // Also allow combining multiply instructions on vectors.
227 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
229 match(C1, m_APInt(IVal))) {
230 // ((X << C2)*C1) == (X * (C1 << C2))
231 Constant *Shl = ConstantExpr::getShl(C1, C2);
232 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
233 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
234 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
235 BO->setHasNoUnsignedWrap();
236 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
237 Shl->isNotMinSignedValue())
238 BO->setHasNoSignedWrap();
242 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
243 Constant *NewCst = nullptr;
244 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
245 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
246 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
247 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
248 // Replace X*(2^C) with X << C, where C is a vector of known
249 // constant powers of 2.
250 NewCst = getLogBase2Vector(CV);
253 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
255 if (I.hasNoUnsignedWrap())
256 Shl->setHasNoUnsignedWrap();
257 if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
258 Shl->setHasNoSignedWrap();
265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
266 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
267 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
268 // The "* (2**n)" thus becomes a potential shifting opportunity.
270 const APInt & Val = CI->getValue();
271 const APInt &PosVal = Val.abs();
272 if (Val.isNegative() && PosVal.isPowerOf2()) {
273 Value *X = nullptr, *Y = nullptr;
274 if (Op0->hasOneUse()) {
276 Value *Sub = nullptr;
277 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
278 Sub = Builder->CreateSub(X, Y, "suba");
279 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
280 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
283 BinaryOperator::CreateMul(Sub,
284 ConstantInt::get(Y->getType(), PosVal));
290 // Simplify mul instructions with a constant RHS.
291 if (isa<Constant>(Op1)) {
292 // Try to fold constant mul into select arguments.
293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
294 if (Instruction *R = FoldOpIntoSelect(I, SI))
297 if (isa<PHINode>(Op0))
298 if (Instruction *NV = FoldOpIntoPhi(I))
301 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
305 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
306 Value *Mul = Builder->CreateMul(C1, Op1);
307 // Only go forward with the transform if C1*CI simplifies to a tidier
309 if (!match(Mul, m_Mul(m_Value(), m_Value())))
310 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
315 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
316 if (Value *Op1v = dyn_castNegVal(Op1)) {
317 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
318 if (I.hasNoSignedWrap() &&
319 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
320 match(Op1, m_NSWSub(m_Value(), m_Value())))
321 BO->setHasNoSignedWrap();
326 // (X / Y) * Y = X - (X % Y)
327 // (X / Y) * -Y = (X % Y) - X
330 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
332 (BO->getOpcode() != Instruction::UDiv &&
333 BO->getOpcode() != Instruction::SDiv)) {
335 BO = dyn_cast<BinaryOperator>(Op1);
337 Value *Neg = dyn_castNegVal(Op1C);
338 if (BO && BO->hasOneUse() &&
339 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
340 (BO->getOpcode() == Instruction::UDiv ||
341 BO->getOpcode() == Instruction::SDiv)) {
342 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
344 // If the division is exact, X % Y is zero, so we end up with X or -X.
345 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
346 if (SDiv->isExact()) {
348 return ReplaceInstUsesWith(I, Op0BO);
349 return BinaryOperator::CreateNeg(Op0BO);
353 if (BO->getOpcode() == Instruction::UDiv)
354 Rem = Builder->CreateURem(Op0BO, Op1BO);
356 Rem = Builder->CreateSRem(Op0BO, Op1BO);
360 return BinaryOperator::CreateSub(Op0BO, Rem);
361 return BinaryOperator::CreateSub(Rem, Op0BO);
365 /// i1 mul -> i1 and.
366 if (I.getType()->getScalarType()->isIntegerTy(1))
367 return BinaryOperator::CreateAnd(Op0, Op1);
369 // X*(1 << Y) --> X << Y
370 // (1 << Y)*X --> X << Y
373 BinaryOperator *BO = nullptr;
375 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
376 BO = BinaryOperator::CreateShl(Op1, Y);
377 ShlNSW = cast<BinaryOperator>(Op0)->hasNoSignedWrap();
378 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
379 BO = BinaryOperator::CreateShl(Op0, Y);
380 ShlNSW = cast<BinaryOperator>(Op1)->hasNoSignedWrap();
383 if (I.hasNoUnsignedWrap())
384 BO->setHasNoUnsignedWrap();
385 if (I.hasNoSignedWrap() && ShlNSW)
386 BO->setHasNoSignedWrap();
391 // If one of the operands of the multiply is a cast from a boolean value, then
392 // we know the bool is either zero or one, so this is a 'masking' multiply.
393 // X * Y (where Y is 0 or 1) -> X & (0-Y)
394 if (!I.getType()->isVectorTy()) {
395 // -2 is "-1 << 1" so it is all bits set except the low one.
396 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
398 Value *BoolCast = nullptr, *OtherOp = nullptr;
399 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
400 BoolCast = Op0, OtherOp = Op1;
401 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
402 BoolCast = Op1, OtherOp = Op0;
405 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
407 return BinaryOperator::CreateAnd(V, OtherOp);
411 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, &I)) {
413 I.setHasNoSignedWrap(true);
416 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedMul(Op0, Op1, &I)) {
418 I.setHasNoUnsignedWrap(true);
421 return Changed ? &I : nullptr;
424 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
425 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
426 if (!Op->hasOneUse())
429 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
432 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
436 Value *OpLog2Of = II->getArgOperand(0);
437 if (!OpLog2Of->hasOneUse())
440 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
443 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
446 if (match(I->getOperand(0), m_SpecificFP(0.5)))
447 Y = I->getOperand(1);
448 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
449 Y = I->getOperand(0);
452 static bool isFiniteNonZeroFp(Constant *C) {
453 if (C->getType()->isVectorTy()) {
454 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
456 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
457 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
463 return isa<ConstantFP>(C) &&
464 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
467 static bool isNormalFp(Constant *C) {
468 if (C->getType()->isVectorTy()) {
469 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
471 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
472 if (!CFP || !CFP->getValueAPF().isNormal())
478 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
481 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
482 /// true iff the given value is FMul or FDiv with one and only one operand
483 /// being a normal constant (i.e. not Zero/NaN/Infinity).
484 static bool isFMulOrFDivWithConstant(Value *V) {
485 Instruction *I = dyn_cast<Instruction>(V);
486 if (!I || (I->getOpcode() != Instruction::FMul &&
487 I->getOpcode() != Instruction::FDiv))
490 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
491 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
496 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
499 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
500 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
501 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
502 /// This function is to simplify "FMulOrDiv * C" and returns the
503 /// resulting expression. Note that this function could return NULL in
504 /// case the constants cannot be folded into a normal floating-point.
506 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
507 Instruction *InsertBefore) {
508 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
510 Value *Opnd0 = FMulOrDiv->getOperand(0);
511 Value *Opnd1 = FMulOrDiv->getOperand(1);
513 Constant *C0 = dyn_cast<Constant>(Opnd0);
514 Constant *C1 = dyn_cast<Constant>(Opnd1);
516 BinaryOperator *R = nullptr;
518 // (X * C0) * C => X * (C0*C)
519 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
520 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
522 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
525 // (C0 / X) * C => (C0 * C) / X
526 if (FMulOrDiv->hasOneUse()) {
527 // It would otherwise introduce another div.
528 Constant *F = ConstantExpr::getFMul(C0, C);
530 R = BinaryOperator::CreateFDiv(F, Opnd1);
533 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
534 Constant *F = ConstantExpr::getFDiv(C, C1);
536 R = BinaryOperator::CreateFMul(Opnd0, F);
538 // (X / C1) * C => X / (C1/C)
539 Constant *F = ConstantExpr::getFDiv(C1, C);
541 R = BinaryOperator::CreateFDiv(Opnd0, F);
547 R->setHasUnsafeAlgebra(true);
548 InsertNewInstWith(R, *InsertBefore);
554 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
555 bool Changed = SimplifyAssociativeOrCommutative(I);
556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
558 if (Value *V = SimplifyVectorOp(I))
559 return ReplaceInstUsesWith(I, V);
561 if (isa<Constant>(Op0))
564 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
566 return ReplaceInstUsesWith(I, V);
568 bool AllowReassociate = I.hasUnsafeAlgebra();
570 // Simplify mul instructions with a constant RHS.
571 if (isa<Constant>(Op1)) {
572 // Try to fold constant mul into select arguments.
573 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
574 if (Instruction *R = FoldOpIntoSelect(I, SI))
577 if (isa<PHINode>(Op0))
578 if (Instruction *NV = FoldOpIntoPhi(I))
581 // (fmul X, -1.0) --> (fsub -0.0, X)
582 if (match(Op1, m_SpecificFP(-1.0))) {
583 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
584 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
585 RI->copyFastMathFlags(&I);
589 Constant *C = cast<Constant>(Op1);
590 if (AllowReassociate && isFiniteNonZeroFp(C)) {
591 // Let MDC denote an expression in one of these forms:
592 // X * C, C/X, X/C, where C is a constant.
594 // Try to simplify "MDC * Constant"
595 if (isFMulOrFDivWithConstant(Op0))
596 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
597 return ReplaceInstUsesWith(I, V);
599 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
600 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
602 (FAddSub->getOpcode() == Instruction::FAdd ||
603 FAddSub->getOpcode() == Instruction::FSub)) {
604 Value *Opnd0 = FAddSub->getOperand(0);
605 Value *Opnd1 = FAddSub->getOperand(1);
606 Constant *C0 = dyn_cast<Constant>(Opnd0);
607 Constant *C1 = dyn_cast<Constant>(Opnd1);
611 std::swap(Opnd0, Opnd1);
615 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
616 Value *M1 = ConstantExpr::getFMul(C1, C);
617 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
618 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
621 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
624 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
625 ? BinaryOperator::CreateFAdd(M0, M1)
626 : BinaryOperator::CreateFSub(M0, M1);
627 RI->copyFastMathFlags(&I);
635 // sqrt(X) * sqrt(X) -> X
636 if (AllowReassociate && (Op0 == Op1))
637 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
638 if (II->getIntrinsicID() == Intrinsic::sqrt)
639 return ReplaceInstUsesWith(I, II->getOperand(0));
641 // Under unsafe algebra do:
642 // X * log2(0.5*Y) = X*log2(Y) - X
643 if (AllowReassociate) {
644 Value *OpX = nullptr;
645 Value *OpY = nullptr;
647 detectLog2OfHalf(Op0, OpY, Log2);
651 detectLog2OfHalf(Op1, OpY, Log2);
656 // if pattern detected emit alternate sequence
658 BuilderTy::FastMathFlagGuard Guard(*Builder);
659 Builder->SetFastMathFlags(Log2->getFastMathFlags());
660 Log2->setArgOperand(0, OpY);
661 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
662 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
664 return ReplaceInstUsesWith(I, FSub);
668 // Handle symmetric situation in a 2-iteration loop
671 for (int i = 0; i < 2; i++) {
672 bool IgnoreZeroSign = I.hasNoSignedZeros();
673 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
674 BuilderTy::FastMathFlagGuard Guard(*Builder);
675 Builder->SetFastMathFlags(I.getFastMathFlags());
677 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
678 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
682 Value *FMul = Builder->CreateFMul(N0, N1);
684 return ReplaceInstUsesWith(I, FMul);
687 if (Opnd0->hasOneUse()) {
688 // -X * Y => -(X*Y) (Promote negation as high as possible)
689 Value *T = Builder->CreateFMul(N0, Opnd1);
690 Value *Neg = Builder->CreateFNeg(T);
692 return ReplaceInstUsesWith(I, Neg);
696 // (X*Y) * X => (X*X) * Y where Y != X
697 // The purpose is two-fold:
698 // 1) to form a power expression (of X).
699 // 2) potentially shorten the critical path: After transformation, the
700 // latency of the instruction Y is amortized by the expression of X*X,
701 // and therefore Y is in a "less critical" position compared to what it
702 // was before the transformation.
704 if (AllowReassociate) {
705 Value *Opnd0_0, *Opnd0_1;
706 if (Opnd0->hasOneUse() &&
707 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
709 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
711 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
715 BuilderTy::FastMathFlagGuard Guard(*Builder);
716 Builder->SetFastMathFlags(I.getFastMathFlags());
717 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
719 Value *R = Builder->CreateFMul(T, Y);
721 return ReplaceInstUsesWith(I, R);
726 if (!isa<Constant>(Op1))
727 std::swap(Opnd0, Opnd1);
732 return Changed ? &I : nullptr;
735 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
737 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
738 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
740 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
741 int NonNullOperand = -1;
742 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
743 if (ST->isNullValue())
745 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
746 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
747 if (ST->isNullValue())
750 if (NonNullOperand == -1)
753 Value *SelectCond = SI->getOperand(0);
755 // Change the div/rem to use 'Y' instead of the select.
756 I.setOperand(1, SI->getOperand(NonNullOperand));
758 // Okay, we know we replace the operand of the div/rem with 'Y' with no
759 // problem. However, the select, or the condition of the select may have
760 // multiple uses. Based on our knowledge that the operand must be non-zero,
761 // propagate the known value for the select into other uses of it, and
762 // propagate a known value of the condition into its other users.
764 // If the select and condition only have a single use, don't bother with this,
766 if (SI->use_empty() && SelectCond->hasOneUse())
769 // Scan the current block backward, looking for other uses of SI.
770 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
772 while (BBI != BBFront) {
774 // If we found a call to a function, we can't assume it will return, so
775 // information from below it cannot be propagated above it.
776 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
779 // Replace uses of the select or its condition with the known values.
780 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
783 *I = SI->getOperand(NonNullOperand);
785 } else if (*I == SelectCond) {
786 *I = Builder->getInt1(NonNullOperand == 1);
791 // If we past the instruction, quit looking for it.
794 if (&*BBI == SelectCond)
795 SelectCond = nullptr;
797 // If we ran out of things to eliminate, break out of the loop.
798 if (!SelectCond && !SI)
806 /// This function implements the transforms common to both integer division
807 /// instructions (udiv and sdiv). It is called by the visitors to those integer
808 /// division instructions.
809 /// @brief Common integer divide transforms
810 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
813 // The RHS is known non-zero.
814 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
819 // Handle cases involving: [su]div X, (select Cond, Y, Z)
820 // This does not apply for fdiv.
821 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
824 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
826 if (match(Op1, m_APInt(C2))) {
829 bool IsSigned = I.getOpcode() == Instruction::SDiv;
831 // (X / C1) / C2 -> X / (C1*C2)
832 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
833 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
834 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
835 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
836 return BinaryOperator::Create(I.getOpcode(), X,
837 ConstantInt::get(I.getType(), Product));
840 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
841 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
842 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
844 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
845 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
846 BinaryOperator *BO = BinaryOperator::Create(
847 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
848 BO->setIsExact(I.isExact());
852 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
853 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
854 BinaryOperator *BO = BinaryOperator::Create(
855 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
856 BO->setHasNoUnsignedWrap(
858 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
859 BO->setHasNoSignedWrap(
860 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
865 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
866 *C1 != C1->getBitWidth() - 1) ||
867 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
868 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
869 APInt C1Shifted = APInt::getOneBitSet(
870 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
872 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
873 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
874 BinaryOperator *BO = BinaryOperator::Create(
875 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
876 BO->setIsExact(I.isExact());
880 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
881 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
882 BinaryOperator *BO = BinaryOperator::Create(
883 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
884 BO->setHasNoUnsignedWrap(
886 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
887 BO->setHasNoSignedWrap(
888 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
893 if (*C2 != 0) { // avoid X udiv 0
894 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
895 if (Instruction *R = FoldOpIntoSelect(I, SI))
897 if (isa<PHINode>(Op0))
898 if (Instruction *NV = FoldOpIntoPhi(I))
904 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
905 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
906 bool isSigned = I.getOpcode() == Instruction::SDiv;
908 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
909 // result is one, if Op1 is -1 then the result is minus one, otherwise
911 Value *Inc = Builder->CreateAdd(Op1, One);
912 Value *Cmp = Builder->CreateICmpULT(
913 Inc, ConstantInt::get(I.getType(), 3));
914 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
916 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
917 // result is one, otherwise it's zero.
918 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
923 // See if we can fold away this div instruction.
924 if (SimplifyDemandedInstructionBits(I))
927 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
928 Value *X = nullptr, *Z = nullptr;
929 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
930 bool isSigned = I.getOpcode() == Instruction::SDiv;
931 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
932 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
933 return BinaryOperator::Create(I.getOpcode(), X, Op1);
939 /// dyn_castZExtVal - Checks if V is a zext or constant that can
940 /// be truncated to Ty without losing bits.
941 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
942 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
943 if (Z->getSrcTy() == Ty)
944 return Z->getOperand(0);
945 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
946 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
947 return ConstantExpr::getTrunc(C, Ty);
953 const unsigned MaxDepth = 6;
954 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
955 const BinaryOperator &I,
958 /// \brief Used to maintain state for visitUDivOperand().
959 struct UDivFoldAction {
960 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
961 ///< operand. This can be zero if this action
962 ///< joins two actions together.
964 Value *OperandToFold; ///< Which operand to fold.
966 Instruction *FoldResult; ///< The instruction returned when FoldAction is
969 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
970 ///< joins two actions together.
973 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
974 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
975 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
976 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
980 // X udiv 2^C -> X >> C
981 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
982 const BinaryOperator &I, InstCombiner &IC) {
983 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
984 BinaryOperator *LShr = BinaryOperator::CreateLShr(
985 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
991 // X udiv C, where C >= signbit
992 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
993 const BinaryOperator &I, InstCombiner &IC) {
994 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
996 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
997 ConstantInt::get(I.getType(), 1));
1000 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1001 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1003 Instruction *ShiftLeft = cast<Instruction>(Op1);
1004 if (isa<ZExtInst>(ShiftLeft))
1005 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
1008 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
1009 Value *N = ShiftLeft->getOperand(1);
1011 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
1012 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
1013 N = IC.Builder->CreateZExt(N, Z->getDestTy());
1014 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
1020 // \brief Recursively visits the possible right hand operands of a udiv
1021 // instruction, seeing through select instructions, to determine if we can
1022 // replace the udiv with something simpler. If we find that an operand is not
1023 // able to simplify the udiv, we abort the entire transformation.
1024 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1025 SmallVectorImpl<UDivFoldAction> &Actions,
1026 unsigned Depth = 0) {
1027 // Check to see if this is an unsigned division with an exact power of 2,
1028 // if so, convert to a right shift.
1029 if (match(Op1, m_Power2())) {
1030 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1031 return Actions.size();
1034 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1035 // X udiv C, where C >= signbit
1036 if (C->getValue().isNegative()) {
1037 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1038 return Actions.size();
1041 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1042 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1043 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1044 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1045 return Actions.size();
1048 // The remaining tests are all recursive, so bail out if we hit the limit.
1049 if (Depth++ == MaxDepth)
1052 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1054 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1055 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1056 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1057 return Actions.size();
1063 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1064 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1066 if (Value *V = SimplifyVectorOp(I))
1067 return ReplaceInstUsesWith(I, V);
1069 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
1070 return ReplaceInstUsesWith(I, V);
1072 // Handle the integer div common cases
1073 if (Instruction *Common = commonIDivTransforms(I))
1076 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
1079 const APInt *C1, *C2;
1080 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1081 match(Op1, m_APInt(C2))) {
1083 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1085 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1086 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1087 X, ConstantInt::get(X->getType(), C2ShlC1));
1095 // (zext A) udiv (zext B) --> zext (A udiv B)
1096 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1097 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1098 return new ZExtInst(
1099 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1102 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1103 SmallVector<UDivFoldAction, 6> UDivActions;
1104 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1105 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1106 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1107 Value *ActionOp1 = UDivActions[i].OperandToFold;
1110 Inst = Action(Op0, ActionOp1, I, *this);
1112 // This action joins two actions together. The RHS of this action is
1113 // simply the last action we processed, we saved the LHS action index in
1114 // the joining action.
1115 size_t SelectRHSIdx = i - 1;
1116 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1117 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1118 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1119 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1120 SelectLHS, SelectRHS);
1123 // If this is the last action to process, return it to the InstCombiner.
1124 // Otherwise, we insert it before the UDiv and record it so that we may
1125 // use it as part of a joining action (i.e., a SelectInst).
1127 Inst->insertBefore(&I);
1128 UDivActions[i].FoldResult = Inst;
1136 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1137 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1139 if (Value *V = SimplifyVectorOp(I))
1140 return ReplaceInstUsesWith(I, V);
1142 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1143 return ReplaceInstUsesWith(I, V);
1145 // Handle the integer div common cases
1146 if (Instruction *Common = commonIDivTransforms(I))
1150 if (match(Op1, m_AllOnes()))
1151 return BinaryOperator::CreateNeg(Op0);
1153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1154 // sdiv X, C --> ashr exact X, log2(C)
1155 if (I.isExact() && RHS->getValue().isNonNegative() &&
1156 RHS->getValue().isPowerOf2()) {
1157 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1158 RHS->getValue().exactLogBase2());
1159 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1163 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1164 // X/INT_MIN -> X == INT_MIN
1165 if (RHS->isMinSignedValue())
1166 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1168 // -X/C --> X/-C provided the negation doesn't overflow.
1170 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1171 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1172 BO->setIsExact(I.isExact());
1177 // If the sign bits of both operands are zero (i.e. we can prove they are
1178 // unsigned inputs), turn this into a udiv.
1179 if (I.getType()->isIntegerTy()) {
1180 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1181 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1182 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1183 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1184 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1185 BO->setIsExact(I.isExact());
1189 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1190 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1191 // Safe because the only negative value (1 << Y) can take on is
1192 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1193 // the sign bit set.
1194 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1195 BO->setIsExact(I.isExact());
1204 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1206 /// 1) 1/C is exact, or
1207 /// 2) reciprocal is allowed.
1208 /// If the conversion was successful, the simplified expression "X * 1/C" is
1209 /// returned; otherwise, NULL is returned.
1211 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1212 bool AllowReciprocal) {
1213 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1216 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1217 APFloat Reciprocal(FpVal.getSemantics());
1218 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1220 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1221 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1222 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1223 Cvt = !Reciprocal.isDenormal();
1230 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1231 return BinaryOperator::CreateFMul(Dividend, R);
1234 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1237 if (Value *V = SimplifyVectorOp(I))
1238 return ReplaceInstUsesWith(I, V);
1240 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1241 return ReplaceInstUsesWith(I, V);
1243 if (isa<Constant>(Op0))
1244 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1245 if (Instruction *R = FoldOpIntoSelect(I, SI))
1248 bool AllowReassociate = I.hasUnsafeAlgebra();
1249 bool AllowReciprocal = I.hasAllowReciprocal();
1251 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1252 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1253 if (Instruction *R = FoldOpIntoSelect(I, SI))
1256 if (AllowReassociate) {
1257 Constant *C1 = nullptr;
1258 Constant *C2 = Op1C;
1260 Instruction *Res = nullptr;
1262 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1263 // (X*C1)/C2 => X * (C1/C2)
1265 Constant *C = ConstantExpr::getFDiv(C1, C2);
1267 Res = BinaryOperator::CreateFMul(X, C);
1268 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1269 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1271 Constant *C = ConstantExpr::getFMul(C1, C2);
1272 if (isNormalFp(C)) {
1273 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1275 Res = BinaryOperator::CreateFDiv(X, C);
1280 Res->setFastMathFlags(I.getFastMathFlags());
1286 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1287 T->copyFastMathFlags(&I);
1294 if (AllowReassociate && isa<Constant>(Op0)) {
1295 Constant *C1 = cast<Constant>(Op0), *C2;
1296 Constant *Fold = nullptr;
1298 bool CreateDiv = true;
1300 // C1 / (X*C2) => (C1/C2) / X
1301 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1302 Fold = ConstantExpr::getFDiv(C1, C2);
1303 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1304 // C1 / (X/C2) => (C1*C2) / X
1305 Fold = ConstantExpr::getFMul(C1, C2);
1306 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1307 // C1 / (C2/X) => (C1/C2) * X
1308 Fold = ConstantExpr::getFDiv(C1, C2);
1312 if (Fold && isNormalFp(Fold)) {
1313 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1314 : BinaryOperator::CreateFMul(X, Fold);
1315 R->setFastMathFlags(I.getFastMathFlags());
1321 if (AllowReassociate) {
1323 Value *NewInst = nullptr;
1324 Instruction *SimpR = nullptr;
1326 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1327 // (X/Y) / Z => X / (Y*Z)
1329 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1330 NewInst = Builder->CreateFMul(Y, Op1);
1331 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1332 FastMathFlags Flags = I.getFastMathFlags();
1333 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1334 RI->setFastMathFlags(Flags);
1336 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1338 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1339 // Z / (X/Y) => Z*Y / X
1341 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1342 NewInst = Builder->CreateFMul(Op0, Y);
1343 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1344 FastMathFlags Flags = I.getFastMathFlags();
1345 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1346 RI->setFastMathFlags(Flags);
1348 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1353 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1354 T->setDebugLoc(I.getDebugLoc());
1355 SimpR->setFastMathFlags(I.getFastMathFlags());
1363 /// This function implements the transforms common to both integer remainder
1364 /// instructions (urem and srem). It is called by the visitors to those integer
1365 /// remainder instructions.
1366 /// @brief Common integer remainder transforms
1367 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1370 // The RHS is known non-zero.
1371 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1376 // Handle cases involving: rem X, (select Cond, Y, Z)
1377 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1380 if (isa<Constant>(Op1)) {
1381 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1383 if (Instruction *R = FoldOpIntoSelect(I, SI))
1385 } else if (isa<PHINode>(Op0I)) {
1386 if (Instruction *NV = FoldOpIntoPhi(I))
1390 // See if we can fold away this rem instruction.
1391 if (SimplifyDemandedInstructionBits(I))
1399 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1402 if (Value *V = SimplifyVectorOp(I))
1403 return ReplaceInstUsesWith(I, V);
1405 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1406 return ReplaceInstUsesWith(I, V);
1408 if (Instruction *common = commonIRemTransforms(I))
1411 // (zext A) urem (zext B) --> zext (A urem B)
1412 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1413 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1414 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1417 // X urem Y -> X and Y-1, where Y is a power of 2,
1418 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1419 Constant *N1 = Constant::getAllOnesValue(I.getType());
1420 Value *Add = Builder->CreateAdd(Op1, N1);
1421 return BinaryOperator::CreateAnd(Op0, Add);
1424 // 1 urem X -> zext(X != 1)
1425 if (match(Op0, m_One())) {
1426 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1427 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1428 return ReplaceInstUsesWith(I, Ext);
1434 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1437 if (Value *V = SimplifyVectorOp(I))
1438 return ReplaceInstUsesWith(I, V);
1440 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1441 return ReplaceInstUsesWith(I, V);
1443 // Handle the integer rem common cases
1444 if (Instruction *Common = commonIRemTransforms(I))
1450 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1451 Worklist.AddValue(I.getOperand(1));
1452 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1457 // If the sign bits of both operands are zero (i.e. we can prove they are
1458 // unsigned inputs), turn this into a urem.
1459 if (I.getType()->isIntegerTy()) {
1460 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1461 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1462 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1463 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1464 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1468 // If it's a constant vector, flip any negative values positive.
1469 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1470 Constant *C = cast<Constant>(Op1);
1471 unsigned VWidth = C->getType()->getVectorNumElements();
1473 bool hasNegative = false;
1474 bool hasMissing = false;
1475 for (unsigned i = 0; i != VWidth; ++i) {
1476 Constant *Elt = C->getAggregateElement(i);
1482 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1483 if (RHS->isNegative())
1487 if (hasNegative && !hasMissing) {
1488 SmallVector<Constant *, 16> Elts(VWidth);
1489 for (unsigned i = 0; i != VWidth; ++i) {
1490 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1491 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1492 if (RHS->isNegative())
1493 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1497 Constant *NewRHSV = ConstantVector::get(Elts);
1498 if (NewRHSV != C) { // Don't loop on -MININT
1499 Worklist.AddValue(I.getOperand(1));
1500 I.setOperand(1, NewRHSV);
1509 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1512 if (Value *V = SimplifyVectorOp(I))
1513 return ReplaceInstUsesWith(I, V);
1515 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1516 return ReplaceInstUsesWith(I, V);
1518 // Handle cases involving: rem X, (select Cond, Y, Z)
1519 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))