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 "InstCombineInternal.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() &&
50 isKnownToBeAPowerOfTwo(I->getOperand(0), IC.getDataLayout(), false, 0,
51 IC.getAssumptionCache(), &CxtI,
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.
141 ComputeNumSignBits(LHS, 0, &CxtI) + 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 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
169 bool Changed = SimplifyAssociativeOrCommutative(I);
170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
172 if (Value *V = SimplifyVectorOp(I))
173 return ReplaceInstUsesWith(I, V);
175 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AC))
176 return ReplaceInstUsesWith(I, V);
178 if (Value *V = SimplifyUsingDistributiveLaws(I))
179 return ReplaceInstUsesWith(I, V);
182 if (match(Op1, m_AllOnes())) {
183 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
184 if (I.hasNoSignedWrap())
185 BO->setHasNoSignedWrap();
189 // Also allow combining multiply instructions on vectors.
194 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
196 match(C1, m_APInt(IVal))) {
197 // ((X << C2)*C1) == (X * (C1 << C2))
198 Constant *Shl = ConstantExpr::getShl(C1, C2);
199 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
200 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
201 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
202 BO->setHasNoUnsignedWrap();
203 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
204 Shl->isNotMinSignedValue())
205 BO->setHasNoSignedWrap();
209 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
210 Constant *NewCst = nullptr;
211 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
212 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
213 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
214 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
215 // Replace X*(2^C) with X << C, where C is a vector of known
216 // constant powers of 2.
217 NewCst = getLogBase2Vector(CV);
220 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
221 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
223 if (I.hasNoUnsignedWrap())
224 Shl->setHasNoUnsignedWrap();
225 if (I.hasNoSignedWrap()) {
227 if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
228 Shl->setHasNoSignedWrap();
236 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
237 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
238 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
239 // The "* (2**n)" thus becomes a potential shifting opportunity.
241 const APInt & Val = CI->getValue();
242 const APInt &PosVal = Val.abs();
243 if (Val.isNegative() && PosVal.isPowerOf2()) {
244 Value *X = nullptr, *Y = nullptr;
245 if (Op0->hasOneUse()) {
247 Value *Sub = nullptr;
248 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
249 Sub = Builder->CreateSub(X, Y, "suba");
250 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
251 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
254 BinaryOperator::CreateMul(Sub,
255 ConstantInt::get(Y->getType(), PosVal));
261 // Simplify mul instructions with a constant RHS.
262 if (isa<Constant>(Op1)) {
263 // Try to fold constant mul into select arguments.
264 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
265 if (Instruction *R = FoldOpIntoSelect(I, SI))
268 if (isa<PHINode>(Op0))
269 if (Instruction *NV = FoldOpIntoPhi(I))
272 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
276 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
277 Value *Mul = Builder->CreateMul(C1, Op1);
278 // Only go forward with the transform if C1*CI simplifies to a tidier
280 if (!match(Mul, m_Mul(m_Value(), m_Value())))
281 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
286 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
287 if (Value *Op1v = dyn_castNegVal(Op1)) {
288 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
289 if (I.hasNoSignedWrap() &&
290 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
291 match(Op1, m_NSWSub(m_Value(), m_Value())))
292 BO->setHasNoSignedWrap();
297 // (X / Y) * Y = X - (X % Y)
298 // (X / Y) * -Y = (X % Y) - X
301 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
303 (BO->getOpcode() != Instruction::UDiv &&
304 BO->getOpcode() != Instruction::SDiv)) {
306 BO = dyn_cast<BinaryOperator>(Op1);
308 Value *Neg = dyn_castNegVal(Op1C);
309 if (BO && BO->hasOneUse() &&
310 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
311 (BO->getOpcode() == Instruction::UDiv ||
312 BO->getOpcode() == Instruction::SDiv)) {
313 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
315 // If the division is exact, X % Y is zero, so we end up with X or -X.
316 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
317 if (SDiv->isExact()) {
319 return ReplaceInstUsesWith(I, Op0BO);
320 return BinaryOperator::CreateNeg(Op0BO);
324 if (BO->getOpcode() == Instruction::UDiv)
325 Rem = Builder->CreateURem(Op0BO, Op1BO);
327 Rem = Builder->CreateSRem(Op0BO, Op1BO);
331 return BinaryOperator::CreateSub(Op0BO, Rem);
332 return BinaryOperator::CreateSub(Rem, Op0BO);
336 /// i1 mul -> i1 and.
337 if (I.getType()->getScalarType()->isIntegerTy(1))
338 return BinaryOperator::CreateAnd(Op0, Op1);
340 // X*(1 << Y) --> X << Y
341 // (1 << Y)*X --> X << Y
344 BinaryOperator *BO = nullptr;
346 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
347 BO = BinaryOperator::CreateShl(Op1, Y);
348 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
349 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
350 BO = BinaryOperator::CreateShl(Op0, Y);
351 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
354 if (I.hasNoUnsignedWrap())
355 BO->setHasNoUnsignedWrap();
356 if (I.hasNoSignedWrap() && ShlNSW)
357 BO->setHasNoSignedWrap();
362 // If one of the operands of the multiply is a cast from a boolean value, then
363 // we know the bool is either zero or one, so this is a 'masking' multiply.
364 // X * Y (where Y is 0 or 1) -> X & (0-Y)
365 if (!I.getType()->isVectorTy()) {
366 // -2 is "-1 << 1" so it is all bits set except the low one.
367 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
369 Value *BoolCast = nullptr, *OtherOp = nullptr;
370 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
371 BoolCast = Op0, OtherOp = Op1;
372 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
373 BoolCast = Op1, OtherOp = Op0;
376 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
378 return BinaryOperator::CreateAnd(V, OtherOp);
382 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
384 I.setHasNoSignedWrap(true);
387 if (!I.hasNoUnsignedWrap() &&
388 computeOverflowForUnsignedMul(Op0, Op1, &I) ==
389 OverflowResult::NeverOverflows) {
391 I.setHasNoUnsignedWrap(true);
394 return Changed ? &I : nullptr;
397 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
398 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
399 if (!Op->hasOneUse())
402 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
405 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
409 Value *OpLog2Of = II->getArgOperand(0);
410 if (!OpLog2Of->hasOneUse())
413 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
416 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
419 if (match(I->getOperand(0), m_SpecificFP(0.5)))
420 Y = I->getOperand(1);
421 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
422 Y = I->getOperand(0);
425 static bool isFiniteNonZeroFp(Constant *C) {
426 if (C->getType()->isVectorTy()) {
427 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
429 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
430 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
436 return isa<ConstantFP>(C) &&
437 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
440 static bool isNormalFp(Constant *C) {
441 if (C->getType()->isVectorTy()) {
442 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
444 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
445 if (!CFP || !CFP->getValueAPF().isNormal())
451 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
454 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
455 /// true iff the given value is FMul or FDiv with one and only one operand
456 /// being a normal constant (i.e. not Zero/NaN/Infinity).
457 static bool isFMulOrFDivWithConstant(Value *V) {
458 Instruction *I = dyn_cast<Instruction>(V);
459 if (!I || (I->getOpcode() != Instruction::FMul &&
460 I->getOpcode() != Instruction::FDiv))
463 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
464 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
469 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
472 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
473 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
474 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
475 /// This function is to simplify "FMulOrDiv * C" and returns the
476 /// resulting expression. Note that this function could return NULL in
477 /// case the constants cannot be folded into a normal floating-point.
479 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
480 Instruction *InsertBefore) {
481 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
483 Value *Opnd0 = FMulOrDiv->getOperand(0);
484 Value *Opnd1 = FMulOrDiv->getOperand(1);
486 Constant *C0 = dyn_cast<Constant>(Opnd0);
487 Constant *C1 = dyn_cast<Constant>(Opnd1);
489 BinaryOperator *R = nullptr;
491 // (X * C0) * C => X * (C0*C)
492 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
493 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
495 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
498 // (C0 / X) * C => (C0 * C) / X
499 if (FMulOrDiv->hasOneUse()) {
500 // It would otherwise introduce another div.
501 Constant *F = ConstantExpr::getFMul(C0, C);
503 R = BinaryOperator::CreateFDiv(F, Opnd1);
506 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
507 Constant *F = ConstantExpr::getFDiv(C, C1);
509 R = BinaryOperator::CreateFMul(Opnd0, F);
511 // (X / C1) * C => X / (C1/C)
512 Constant *F = ConstantExpr::getFDiv(C1, C);
514 R = BinaryOperator::CreateFDiv(Opnd0, F);
520 R->setHasUnsafeAlgebra(true);
521 InsertNewInstWith(R, *InsertBefore);
527 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
528 bool Changed = SimplifyAssociativeOrCommutative(I);
529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
531 if (Value *V = SimplifyVectorOp(I))
532 return ReplaceInstUsesWith(I, V);
534 if (isa<Constant>(Op0))
538 SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
539 return ReplaceInstUsesWith(I, V);
541 bool AllowReassociate = I.hasUnsafeAlgebra();
543 // Simplify mul instructions with a constant RHS.
544 if (isa<Constant>(Op1)) {
545 // Try to fold constant mul into select arguments.
546 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
547 if (Instruction *R = FoldOpIntoSelect(I, SI))
550 if (isa<PHINode>(Op0))
551 if (Instruction *NV = FoldOpIntoPhi(I))
554 // (fmul X, -1.0) --> (fsub -0.0, X)
555 if (match(Op1, m_SpecificFP(-1.0))) {
556 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
557 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
558 RI->copyFastMathFlags(&I);
562 Constant *C = cast<Constant>(Op1);
563 if (AllowReassociate && isFiniteNonZeroFp(C)) {
564 // Let MDC denote an expression in one of these forms:
565 // X * C, C/X, X/C, where C is a constant.
567 // Try to simplify "MDC * Constant"
568 if (isFMulOrFDivWithConstant(Op0))
569 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
570 return ReplaceInstUsesWith(I, V);
572 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
573 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
575 (FAddSub->getOpcode() == Instruction::FAdd ||
576 FAddSub->getOpcode() == Instruction::FSub)) {
577 Value *Opnd0 = FAddSub->getOperand(0);
578 Value *Opnd1 = FAddSub->getOperand(1);
579 Constant *C0 = dyn_cast<Constant>(Opnd0);
580 Constant *C1 = dyn_cast<Constant>(Opnd1);
584 std::swap(Opnd0, Opnd1);
588 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
589 Value *M1 = ConstantExpr::getFMul(C1, C);
590 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
591 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
594 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
597 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
598 ? BinaryOperator::CreateFAdd(M0, M1)
599 : BinaryOperator::CreateFSub(M0, M1);
600 RI->copyFastMathFlags(&I);
608 // sqrt(X) * sqrt(X) -> X
609 if (AllowReassociate && (Op0 == Op1))
610 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
611 if (II->getIntrinsicID() == Intrinsic::sqrt)
612 return ReplaceInstUsesWith(I, II->getOperand(0));
614 // Under unsafe algebra do:
615 // X * log2(0.5*Y) = X*log2(Y) - X
616 if (AllowReassociate) {
617 Value *OpX = nullptr;
618 Value *OpY = nullptr;
620 detectLog2OfHalf(Op0, OpY, Log2);
624 detectLog2OfHalf(Op1, OpY, Log2);
629 // if pattern detected emit alternate sequence
631 BuilderTy::FastMathFlagGuard Guard(*Builder);
632 Builder->SetFastMathFlags(Log2->getFastMathFlags());
633 Log2->setArgOperand(0, OpY);
634 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
635 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
637 return ReplaceInstUsesWith(I, FSub);
641 // Handle symmetric situation in a 2-iteration loop
644 for (int i = 0; i < 2; i++) {
645 bool IgnoreZeroSign = I.hasNoSignedZeros();
646 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
647 BuilderTy::FastMathFlagGuard Guard(*Builder);
648 Builder->SetFastMathFlags(I.getFastMathFlags());
650 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
651 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
655 Value *FMul = Builder->CreateFMul(N0, N1);
657 return ReplaceInstUsesWith(I, FMul);
660 if (Opnd0->hasOneUse()) {
661 // -X * Y => -(X*Y) (Promote negation as high as possible)
662 Value *T = Builder->CreateFMul(N0, Opnd1);
663 Value *Neg = Builder->CreateFNeg(T);
665 return ReplaceInstUsesWith(I, Neg);
669 // (X*Y) * X => (X*X) * Y where Y != X
670 // The purpose is two-fold:
671 // 1) to form a power expression (of X).
672 // 2) potentially shorten the critical path: After transformation, the
673 // latency of the instruction Y is amortized by the expression of X*X,
674 // and therefore Y is in a "less critical" position compared to what it
675 // was before the transformation.
677 if (AllowReassociate) {
678 Value *Opnd0_0, *Opnd0_1;
679 if (Opnd0->hasOneUse() &&
680 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
682 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
684 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
688 BuilderTy::FastMathFlagGuard Guard(*Builder);
689 Builder->SetFastMathFlags(I.getFastMathFlags());
690 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
692 Value *R = Builder->CreateFMul(T, Y);
694 return ReplaceInstUsesWith(I, R);
699 if (!isa<Constant>(Op1))
700 std::swap(Opnd0, Opnd1);
705 return Changed ? &I : nullptr;
708 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
710 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
711 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
713 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
714 int NonNullOperand = -1;
715 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
716 if (ST->isNullValue())
718 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
719 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
720 if (ST->isNullValue())
723 if (NonNullOperand == -1)
726 Value *SelectCond = SI->getOperand(0);
728 // Change the div/rem to use 'Y' instead of the select.
729 I.setOperand(1, SI->getOperand(NonNullOperand));
731 // Okay, we know we replace the operand of the div/rem with 'Y' with no
732 // problem. However, the select, or the condition of the select may have
733 // multiple uses. Based on our knowledge that the operand must be non-zero,
734 // propagate the known value for the select into other uses of it, and
735 // propagate a known value of the condition into its other users.
737 // If the select and condition only have a single use, don't bother with this,
739 if (SI->use_empty() && SelectCond->hasOneUse())
742 // Scan the current block backward, looking for other uses of SI.
743 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
745 while (BBI != BBFront) {
747 // If we found a call to a function, we can't assume it will return, so
748 // information from below it cannot be propagated above it.
749 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
752 // Replace uses of the select or its condition with the known values.
753 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
756 *I = SI->getOperand(NonNullOperand);
758 } else if (*I == SelectCond) {
759 *I = Builder->getInt1(NonNullOperand == 1);
764 // If we past the instruction, quit looking for it.
767 if (&*BBI == SelectCond)
768 SelectCond = nullptr;
770 // If we ran out of things to eliminate, break out of the loop.
771 if (!SelectCond && !SI)
779 /// This function implements the transforms common to both integer division
780 /// instructions (udiv and sdiv). It is called by the visitors to those integer
781 /// division instructions.
782 /// @brief Common integer divide transforms
783 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
786 // The RHS is known non-zero.
787 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
792 // Handle cases involving: [su]div X, (select Cond, Y, Z)
793 // This does not apply for fdiv.
794 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
797 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
799 if (match(Op1, m_APInt(C2))) {
802 bool IsSigned = I.getOpcode() == Instruction::SDiv;
804 // (X / C1) / C2 -> X / (C1*C2)
805 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
806 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
807 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
808 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
809 return BinaryOperator::Create(I.getOpcode(), X,
810 ConstantInt::get(I.getType(), Product));
813 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
814 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
815 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
817 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
818 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
819 BinaryOperator *BO = BinaryOperator::Create(
820 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
821 BO->setIsExact(I.isExact());
825 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
826 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
827 BinaryOperator *BO = BinaryOperator::Create(
828 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
829 BO->setHasNoUnsignedWrap(
831 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
832 BO->setHasNoSignedWrap(
833 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
838 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
839 *C1 != C1->getBitWidth() - 1) ||
840 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
841 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
842 APInt C1Shifted = APInt::getOneBitSet(
843 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
845 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
846 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
847 BinaryOperator *BO = BinaryOperator::Create(
848 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
849 BO->setIsExact(I.isExact());
853 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
854 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
855 BinaryOperator *BO = BinaryOperator::Create(
856 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
857 BO->setHasNoUnsignedWrap(
859 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
860 BO->setHasNoSignedWrap(
861 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
866 if (*C2 != 0) { // avoid X udiv 0
867 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
868 if (Instruction *R = FoldOpIntoSelect(I, SI))
870 if (isa<PHINode>(Op0))
871 if (Instruction *NV = FoldOpIntoPhi(I))
877 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
878 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
879 bool isSigned = I.getOpcode() == Instruction::SDiv;
881 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
882 // result is one, if Op1 is -1 then the result is minus one, otherwise
884 Value *Inc = Builder->CreateAdd(Op1, One);
885 Value *Cmp = Builder->CreateICmpULT(
886 Inc, ConstantInt::get(I.getType(), 3));
887 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
889 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
890 // result is one, otherwise it's zero.
891 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
896 // See if we can fold away this div instruction.
897 if (SimplifyDemandedInstructionBits(I))
900 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
901 Value *X = nullptr, *Z = nullptr;
902 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
903 bool isSigned = I.getOpcode() == Instruction::SDiv;
904 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
905 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
906 return BinaryOperator::Create(I.getOpcode(), X, Op1);
912 /// dyn_castZExtVal - Checks if V is a zext or constant that can
913 /// be truncated to Ty without losing bits.
914 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
915 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
916 if (Z->getSrcTy() == Ty)
917 return Z->getOperand(0);
918 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
919 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
920 return ConstantExpr::getTrunc(C, Ty);
926 const unsigned MaxDepth = 6;
927 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
928 const BinaryOperator &I,
931 /// \brief Used to maintain state for visitUDivOperand().
932 struct UDivFoldAction {
933 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
934 ///< operand. This can be zero if this action
935 ///< joins two actions together.
937 Value *OperandToFold; ///< Which operand to fold.
939 Instruction *FoldResult; ///< The instruction returned when FoldAction is
942 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
943 ///< joins two actions together.
946 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
947 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
948 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
949 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
953 // X udiv 2^C -> X >> C
954 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
955 const BinaryOperator &I, InstCombiner &IC) {
956 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
957 BinaryOperator *LShr = BinaryOperator::CreateLShr(
958 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
964 // X udiv C, where C >= signbit
965 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
966 const BinaryOperator &I, InstCombiner &IC) {
967 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
969 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
970 ConstantInt::get(I.getType(), 1));
973 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
974 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
976 Instruction *ShiftLeft = cast<Instruction>(Op1);
977 if (isa<ZExtInst>(ShiftLeft))
978 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
981 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
982 Value *N = ShiftLeft->getOperand(1);
984 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
985 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
986 N = IC.Builder->CreateZExt(N, Z->getDestTy());
987 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
993 // \brief Recursively visits the possible right hand operands of a udiv
994 // instruction, seeing through select instructions, to determine if we can
995 // replace the udiv with something simpler. If we find that an operand is not
996 // able to simplify the udiv, we abort the entire transformation.
997 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
998 SmallVectorImpl<UDivFoldAction> &Actions,
999 unsigned Depth = 0) {
1000 // Check to see if this is an unsigned division with an exact power of 2,
1001 // if so, convert to a right shift.
1002 if (match(Op1, m_Power2())) {
1003 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1004 return Actions.size();
1007 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1008 // X udiv C, where C >= signbit
1009 if (C->getValue().isNegative()) {
1010 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1011 return Actions.size();
1014 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1015 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1016 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1017 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1018 return Actions.size();
1021 // The remaining tests are all recursive, so bail out if we hit the limit.
1022 if (Depth++ == MaxDepth)
1025 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1027 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1028 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1029 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1030 return Actions.size();
1036 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1039 if (Value *V = SimplifyVectorOp(I))
1040 return ReplaceInstUsesWith(I, V);
1042 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AC))
1043 return ReplaceInstUsesWith(I, V);
1045 // Handle the integer div common cases
1046 if (Instruction *Common = commonIDivTransforms(I))
1049 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
1052 const APInt *C1, *C2;
1053 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1054 match(Op1, m_APInt(C2))) {
1056 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1058 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1059 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1060 X, ConstantInt::get(X->getType(), C2ShlC1));
1068 // (zext A) udiv (zext B) --> zext (A udiv B)
1069 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1070 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1071 return new ZExtInst(
1072 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1075 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1076 SmallVector<UDivFoldAction, 6> UDivActions;
1077 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1078 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1079 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1080 Value *ActionOp1 = UDivActions[i].OperandToFold;
1083 Inst = Action(Op0, ActionOp1, I, *this);
1085 // This action joins two actions together. The RHS of this action is
1086 // simply the last action we processed, we saved the LHS action index in
1087 // the joining action.
1088 size_t SelectRHSIdx = i - 1;
1089 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1090 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1091 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1092 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1093 SelectLHS, SelectRHS);
1096 // If this is the last action to process, return it to the InstCombiner.
1097 // Otherwise, we insert it before the UDiv and record it so that we may
1098 // use it as part of a joining action (i.e., a SelectInst).
1100 Inst->insertBefore(&I);
1101 UDivActions[i].FoldResult = Inst;
1109 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1112 if (Value *V = SimplifyVectorOp(I))
1113 return ReplaceInstUsesWith(I, V);
1115 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AC))
1116 return ReplaceInstUsesWith(I, V);
1118 // Handle the integer div common cases
1119 if (Instruction *Common = commonIDivTransforms(I))
1123 if (match(Op1, m_AllOnes()))
1124 return BinaryOperator::CreateNeg(Op0);
1126 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1127 // sdiv X, C --> ashr exact X, log2(C)
1128 if (I.isExact() && RHS->getValue().isNonNegative() &&
1129 RHS->getValue().isPowerOf2()) {
1130 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1131 RHS->getValue().exactLogBase2());
1132 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1136 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1137 // X/INT_MIN -> X == INT_MIN
1138 if (RHS->isMinSignedValue())
1139 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1141 // -X/C --> X/-C provided the negation doesn't overflow.
1143 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1144 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1145 BO->setIsExact(I.isExact());
1150 // If the sign bits of both operands are zero (i.e. we can prove they are
1151 // unsigned inputs), turn this into a udiv.
1152 if (I.getType()->isIntegerTy()) {
1153 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1154 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1155 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1156 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1157 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1158 BO->setIsExact(I.isExact());
1162 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
1163 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1164 // Safe because the only negative value (1 << Y) can take on is
1165 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1166 // the sign bit set.
1167 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1168 BO->setIsExact(I.isExact());
1177 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1179 /// 1) 1/C is exact, or
1180 /// 2) reciprocal is allowed.
1181 /// If the conversion was successful, the simplified expression "X * 1/C" is
1182 /// returned; otherwise, NULL is returned.
1184 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1185 bool AllowReciprocal) {
1186 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1189 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1190 APFloat Reciprocal(FpVal.getSemantics());
1191 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1193 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1194 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1195 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1196 Cvt = !Reciprocal.isDenormal();
1203 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1204 return BinaryOperator::CreateFMul(Dividend, R);
1207 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1208 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1210 if (Value *V = SimplifyVectorOp(I))
1211 return ReplaceInstUsesWith(I, V);
1213 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1215 return ReplaceInstUsesWith(I, V);
1217 if (isa<Constant>(Op0))
1218 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1219 if (Instruction *R = FoldOpIntoSelect(I, SI))
1222 bool AllowReassociate = I.hasUnsafeAlgebra();
1223 bool AllowReciprocal = I.hasAllowReciprocal();
1225 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1226 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1227 if (Instruction *R = FoldOpIntoSelect(I, SI))
1230 if (AllowReassociate) {
1231 Constant *C1 = nullptr;
1232 Constant *C2 = Op1C;
1234 Instruction *Res = nullptr;
1236 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1237 // (X*C1)/C2 => X * (C1/C2)
1239 Constant *C = ConstantExpr::getFDiv(C1, C2);
1241 Res = BinaryOperator::CreateFMul(X, C);
1242 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1243 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1245 Constant *C = ConstantExpr::getFMul(C1, C2);
1246 if (isNormalFp(C)) {
1247 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1249 Res = BinaryOperator::CreateFDiv(X, C);
1254 Res->setFastMathFlags(I.getFastMathFlags());
1260 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1261 T->copyFastMathFlags(&I);
1268 if (AllowReassociate && isa<Constant>(Op0)) {
1269 Constant *C1 = cast<Constant>(Op0), *C2;
1270 Constant *Fold = nullptr;
1272 bool CreateDiv = true;
1274 // C1 / (X*C2) => (C1/C2) / X
1275 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1276 Fold = ConstantExpr::getFDiv(C1, C2);
1277 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1278 // C1 / (X/C2) => (C1*C2) / X
1279 Fold = ConstantExpr::getFMul(C1, C2);
1280 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1281 // C1 / (C2/X) => (C1/C2) * X
1282 Fold = ConstantExpr::getFDiv(C1, C2);
1286 if (Fold && isNormalFp(Fold)) {
1287 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1288 : BinaryOperator::CreateFMul(X, Fold);
1289 R->setFastMathFlags(I.getFastMathFlags());
1295 if (AllowReassociate) {
1297 Value *NewInst = nullptr;
1298 Instruction *SimpR = nullptr;
1300 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1301 // (X/Y) / Z => X / (Y*Z)
1303 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1304 NewInst = Builder->CreateFMul(Y, Op1);
1305 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1306 FastMathFlags Flags = I.getFastMathFlags();
1307 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1308 RI->setFastMathFlags(Flags);
1310 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1312 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1313 // Z / (X/Y) => Z*Y / X
1315 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1316 NewInst = Builder->CreateFMul(Op0, Y);
1317 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1318 FastMathFlags Flags = I.getFastMathFlags();
1319 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1320 RI->setFastMathFlags(Flags);
1322 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1327 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1328 T->setDebugLoc(I.getDebugLoc());
1329 SimpR->setFastMathFlags(I.getFastMathFlags());
1337 /// This function implements the transforms common to both integer remainder
1338 /// instructions (urem and srem). It is called by the visitors to those integer
1339 /// remainder instructions.
1340 /// @brief Common integer remainder transforms
1341 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1344 // The RHS is known non-zero.
1345 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
1350 // Handle cases involving: rem X, (select Cond, Y, Z)
1351 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1354 if (isa<Constant>(Op1)) {
1355 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1356 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1357 if (Instruction *R = FoldOpIntoSelect(I, SI))
1359 } else if (isa<PHINode>(Op0I)) {
1360 if (Instruction *NV = FoldOpIntoPhi(I))
1364 // See if we can fold away this rem instruction.
1365 if (SimplifyDemandedInstructionBits(I))
1373 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1374 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1376 if (Value *V = SimplifyVectorOp(I))
1377 return ReplaceInstUsesWith(I, V);
1379 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AC))
1380 return ReplaceInstUsesWith(I, V);
1382 if (Instruction *common = commonIRemTransforms(I))
1385 // (zext A) urem (zext B) --> zext (A urem B)
1386 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1387 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1388 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1391 // X urem Y -> X and Y-1, where Y is a power of 2,
1392 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
1393 Constant *N1 = Constant::getAllOnesValue(I.getType());
1394 Value *Add = Builder->CreateAdd(Op1, N1);
1395 return BinaryOperator::CreateAnd(Op0, Add);
1398 // 1 urem X -> zext(X != 1)
1399 if (match(Op0, m_One())) {
1400 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1401 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1402 return ReplaceInstUsesWith(I, Ext);
1408 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1411 if (Value *V = SimplifyVectorOp(I))
1412 return ReplaceInstUsesWith(I, V);
1414 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AC))
1415 return ReplaceInstUsesWith(I, V);
1417 // Handle the integer rem common cases
1418 if (Instruction *Common = commonIRemTransforms(I))
1424 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1425 Worklist.AddValue(I.getOperand(1));
1426 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1431 // If the sign bits of both operands are zero (i.e. we can prove they are
1432 // unsigned inputs), turn this into a urem.
1433 if (I.getType()->isIntegerTy()) {
1434 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1435 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1436 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1437 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1438 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1442 // If it's a constant vector, flip any negative values positive.
1443 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1444 Constant *C = cast<Constant>(Op1);
1445 unsigned VWidth = C->getType()->getVectorNumElements();
1447 bool hasNegative = false;
1448 bool hasMissing = false;
1449 for (unsigned i = 0; i != VWidth; ++i) {
1450 Constant *Elt = C->getAggregateElement(i);
1456 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1457 if (RHS->isNegative())
1461 if (hasNegative && !hasMissing) {
1462 SmallVector<Constant *, 16> Elts(VWidth);
1463 for (unsigned i = 0; i != VWidth; ++i) {
1464 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1465 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1466 if (RHS->isNegative())
1467 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1471 Constant *NewRHSV = ConstantVector::get(Elts);
1472 if (NewRHSV != C) { // Don't loop on -MININT
1473 Worklist.AddValue(I.getOperand(1));
1474 I.setOperand(1, NewRHSV);
1483 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1484 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1486 if (Value *V = SimplifyVectorOp(I))
1487 return ReplaceInstUsesWith(I, V);
1489 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1491 return ReplaceInstUsesWith(I, V);
1493 // Handle cases involving: rem X, (select Cond, Y, Z)
1494 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))