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 /// The specific integer value is used in a context where it is known to be
26 /// non-zero. If this allows us to simplify the computation, do so and return
27 /// 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 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
49 if (I && 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 /// True if the multiply can not be expressed in an int this size.
80 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
84 Product = C1.smul_ov(C2, Overflow);
86 Product = C1.umul_ov(C2, Overflow);
91 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
92 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94 assert(C1.getBitWidth() == C2.getBitWidth() &&
95 "Inconsistent width of constants!");
97 // Bail if we will divide by zero.
101 // Bail if we would divide INT_MIN by -1.
102 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
105 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
107 APInt::sdivrem(C1, C2, Quotient, Remainder);
109 APInt::udivrem(C1, C2, Quotient, Remainder);
111 return Remainder.isMinValue();
114 /// \brief A helper routine of InstCombiner::visitMul().
116 /// If C is a vector of known powers of 2, then this function returns
117 /// a new vector obtained from C replacing each element with its logBase2.
118 /// Return a null pointer otherwise.
119 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
121 SmallVector<Constant *, 4> Elts;
123 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
124 Constant *Elt = CV->getElementAsConstant(I);
125 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
127 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
130 return ConstantVector::get(Elts);
133 /// \brief Return true if we can prove that:
134 /// (mul LHS, RHS) === (mul nsw LHS, RHS)
135 bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
137 // Multiplying n * m significant bits yields a result of n + m significant
138 // bits. If the total number of significant bits does not exceed the
139 // result bit width (minus 1), there is no overflow.
140 // This means if we have enough leading sign bits in the operands
141 // we can guarantee that the result does not overflow.
142 // Ref: "Hacker's Delight" by Henry Warren
143 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
145 // Note that underestimating the number of sign bits gives a more
146 // conservative answer.
148 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
150 // First handle the easy case: if we have enough sign bits there's
151 // definitely no overflow.
152 if (SignBits > BitWidth + 1)
155 // There are two ambiguous cases where there can be no overflow:
156 // SignBits == BitWidth + 1 and
157 // SignBits == BitWidth
158 // The second case is difficult to check, therefore we only handle the
160 if (SignBits == BitWidth + 1) {
161 // It overflows only when both arguments are negative and the true
162 // product is exactly the minimum negative number.
163 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
164 // For simplicity we just check if at least one side is not negative.
165 bool LHSNonNegative, LHSNegative;
166 bool RHSNonNegative, RHSNegative;
167 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
168 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
169 if (LHSNonNegative || RHSNonNegative)
175 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
176 bool Changed = SimplifyAssociativeOrCommutative(I);
177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
179 if (Value *V = SimplifyVectorOp(I))
180 return replaceInstUsesWith(I, V);
182 if (Value *V = SimplifyMulInst(Op0, Op1, DL, &TLI, &DT, &AC))
183 return replaceInstUsesWith(I, V);
185 if (Value *V = SimplifyUsingDistributiveLaws(I))
186 return replaceInstUsesWith(I, V);
189 if (match(Op1, m_AllOnes())) {
190 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
191 if (I.hasNoSignedWrap())
192 BO->setHasNoSignedWrap();
196 // Also allow combining multiply instructions on vectors.
201 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
203 match(C1, m_APInt(IVal))) {
204 // ((X << C2)*C1) == (X * (C1 << C2))
205 Constant *Shl = ConstantExpr::getShl(C1, C2);
206 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
207 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
208 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
209 BO->setHasNoUnsignedWrap();
210 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
211 Shl->isNotMinSignedValue())
212 BO->setHasNoSignedWrap();
216 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
217 Constant *NewCst = nullptr;
218 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
219 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
220 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
221 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
222 // Replace X*(2^C) with X << C, where C is a vector of known
223 // constant powers of 2.
224 NewCst = getLogBase2Vector(CV);
227 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
228 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
230 if (I.hasNoUnsignedWrap())
231 Shl->setHasNoUnsignedWrap();
232 if (I.hasNoSignedWrap()) {
234 if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
235 Shl->setHasNoSignedWrap();
243 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
244 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
245 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
246 // The "* (2**n)" thus becomes a potential shifting opportunity.
248 const APInt & Val = CI->getValue();
249 const APInt &PosVal = Val.abs();
250 if (Val.isNegative() && PosVal.isPowerOf2()) {
251 Value *X = nullptr, *Y = nullptr;
252 if (Op0->hasOneUse()) {
254 Value *Sub = nullptr;
255 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
256 Sub = Builder->CreateSub(X, Y, "suba");
257 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
258 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
261 BinaryOperator::CreateMul(Sub,
262 ConstantInt::get(Y->getType(), PosVal));
268 // Simplify mul instructions with a constant RHS.
269 if (isa<Constant>(Op1)) {
270 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
273 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
277 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
278 Value *Mul = Builder->CreateMul(C1, Op1);
279 // Only go forward with the transform if C1*CI simplifies to a tidier
281 if (!match(Mul, m_Mul(m_Value(), m_Value())))
282 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
287 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
288 if (Value *Op1v = dyn_castNegVal(Op1)) {
289 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
290 if (I.hasNoSignedWrap() &&
291 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
292 match(Op1, m_NSWSub(m_Value(), m_Value())))
293 BO->setHasNoSignedWrap();
298 // (X / Y) * Y = X - (X % Y)
299 // (X / Y) * -Y = (X % Y) - X
302 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
303 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
304 Div->getOpcode() != Instruction::SDiv)) {
306 Div = dyn_cast<BinaryOperator>(Op1);
308 Value *Neg = dyn_castNegVal(Y);
309 if (Div && Div->hasOneUse() &&
310 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
311 (Div->getOpcode() == Instruction::UDiv ||
312 Div->getOpcode() == Instruction::SDiv)) {
313 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
315 // If the division is exact, X % Y is zero, so we end up with X or -X.
316 if (Div->isExact()) {
318 return replaceInstUsesWith(I, X);
319 return BinaryOperator::CreateNeg(X);
322 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
324 Value *Rem = Builder->CreateBinOp(RemOpc, X, DivOp1);
326 return BinaryOperator::CreateSub(X, Rem);
327 return BinaryOperator::CreateSub(Rem, X);
331 /// i1 mul -> i1 and.
332 if (I.getType()->getScalarType()->isIntegerTy(1))
333 return BinaryOperator::CreateAnd(Op0, Op1);
335 // X*(1 << Y) --> X << Y
336 // (1 << Y)*X --> X << Y
339 BinaryOperator *BO = nullptr;
341 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
342 BO = BinaryOperator::CreateShl(Op1, Y);
343 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
344 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
345 BO = BinaryOperator::CreateShl(Op0, Y);
346 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
349 if (I.hasNoUnsignedWrap())
350 BO->setHasNoUnsignedWrap();
351 if (I.hasNoSignedWrap() && ShlNSW)
352 BO->setHasNoSignedWrap();
357 // If one of the operands of the multiply is a cast from a boolean value, then
358 // we know the bool is either zero or one, so this is a 'masking' multiply.
359 // X * Y (where Y is 0 or 1) -> X & (0-Y)
360 if (!I.getType()->isVectorTy()) {
361 // -2 is "-1 << 1" so it is all bits set except the low one.
362 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
364 Value *BoolCast = nullptr, *OtherOp = nullptr;
365 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
368 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
374 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
376 return BinaryOperator::CreateAnd(V, OtherOp);
380 // Check for (mul (sext x), y), see if we can merge this into an
381 // integer mul followed by a sext.
382 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
383 // (mul (sext x), cst) --> (sext (mul x, cst'))
384 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
385 if (Op0Conv->hasOneUse()) {
387 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
388 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
389 WillNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
390 // Insert the new, smaller mul.
392 Builder->CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
393 return new SExtInst(NewMul, I.getType());
398 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
399 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
400 // Only do this if x/y have the same type, if at last one of them has a
401 // single use (so we don't increase the number of sexts), and if the
402 // integer mul will not overflow.
403 if (Op0Conv->getOperand(0)->getType() ==
404 Op1Conv->getOperand(0)->getType() &&
405 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
406 WillNotOverflowSignedMul(Op0Conv->getOperand(0),
407 Op1Conv->getOperand(0), I)) {
408 // Insert the new integer mul.
409 Value *NewMul = Builder->CreateNSWMul(
410 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
411 return new SExtInst(NewMul, I.getType());
416 // Check for (mul (zext x), y), see if we can merge this into an
417 // integer mul followed by a zext.
418 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
419 // (mul (zext x), cst) --> (zext (mul x, cst'))
420 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
421 if (Op0Conv->hasOneUse()) {
423 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
424 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
425 computeOverflowForUnsignedMul(Op0Conv->getOperand(0), CI, &I) ==
426 OverflowResult::NeverOverflows) {
427 // Insert the new, smaller mul.
429 Builder->CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
430 return new ZExtInst(NewMul, I.getType());
435 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
436 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
437 // Only do this if x/y have the same type, if at last one of them has a
438 // single use (so we don't increase the number of zexts), and if the
439 // integer mul will not overflow.
440 if (Op0Conv->getOperand(0)->getType() ==
441 Op1Conv->getOperand(0)->getType() &&
442 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
443 computeOverflowForUnsignedMul(Op0Conv->getOperand(0),
444 Op1Conv->getOperand(0),
445 &I) == OverflowResult::NeverOverflows) {
446 // Insert the new integer mul.
447 Value *NewMul = Builder->CreateNUWMul(
448 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
449 return new ZExtInst(NewMul, I.getType());
454 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
456 I.setHasNoSignedWrap(true);
459 if (!I.hasNoUnsignedWrap() &&
460 computeOverflowForUnsignedMul(Op0, Op1, &I) ==
461 OverflowResult::NeverOverflows) {
463 I.setHasNoUnsignedWrap(true);
466 return Changed ? &I : nullptr;
469 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
470 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
471 if (!Op->hasOneUse())
474 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
477 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
481 Value *OpLog2Of = II->getArgOperand(0);
482 if (!OpLog2Of->hasOneUse())
485 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
488 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
491 if (match(I->getOperand(0), m_SpecificFP(0.5)))
492 Y = I->getOperand(1);
493 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
494 Y = I->getOperand(0);
497 static bool isFiniteNonZeroFp(Constant *C) {
498 if (C->getType()->isVectorTy()) {
499 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
501 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
502 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
508 return isa<ConstantFP>(C) &&
509 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
512 static bool isNormalFp(Constant *C) {
513 if (C->getType()->isVectorTy()) {
514 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
516 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
517 if (!CFP || !CFP->getValueAPF().isNormal())
523 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
526 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
527 /// true iff the given value is FMul or FDiv with one and only one operand
528 /// being a normal constant (i.e. not Zero/NaN/Infinity).
529 static bool isFMulOrFDivWithConstant(Value *V) {
530 Instruction *I = dyn_cast<Instruction>(V);
531 if (!I || (I->getOpcode() != Instruction::FMul &&
532 I->getOpcode() != Instruction::FDiv))
535 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
536 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
541 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
544 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
545 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
546 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
547 /// This function is to simplify "FMulOrDiv * C" and returns the
548 /// resulting expression. Note that this function could return NULL in
549 /// case the constants cannot be folded into a normal floating-point.
551 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
552 Instruction *InsertBefore) {
553 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
555 Value *Opnd0 = FMulOrDiv->getOperand(0);
556 Value *Opnd1 = FMulOrDiv->getOperand(1);
558 Constant *C0 = dyn_cast<Constant>(Opnd0);
559 Constant *C1 = dyn_cast<Constant>(Opnd1);
561 BinaryOperator *R = nullptr;
563 // (X * C0) * C => X * (C0*C)
564 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
565 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
567 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
570 // (C0 / X) * C => (C0 * C) / X
571 if (FMulOrDiv->hasOneUse()) {
572 // It would otherwise introduce another div.
573 Constant *F = ConstantExpr::getFMul(C0, C);
575 R = BinaryOperator::CreateFDiv(F, Opnd1);
578 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
579 Constant *F = ConstantExpr::getFDiv(C, C1);
581 R = BinaryOperator::CreateFMul(Opnd0, F);
583 // (X / C1) * C => X / (C1/C)
584 Constant *F = ConstantExpr::getFDiv(C1, C);
586 R = BinaryOperator::CreateFDiv(Opnd0, F);
592 R->setHasUnsafeAlgebra(true);
593 InsertNewInstWith(R, *InsertBefore);
599 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
600 bool Changed = SimplifyAssociativeOrCommutative(I);
601 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
603 if (Value *V = SimplifyVectorOp(I))
604 return replaceInstUsesWith(I, V);
606 if (isa<Constant>(Op0))
610 SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, &TLI, &DT, &AC))
611 return replaceInstUsesWith(I, V);
613 bool AllowReassociate = I.hasUnsafeAlgebra();
615 // Simplify mul instructions with a constant RHS.
616 if (isa<Constant>(Op1)) {
617 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
620 // (fmul X, -1.0) --> (fsub -0.0, X)
621 if (match(Op1, m_SpecificFP(-1.0))) {
622 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
623 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
624 RI->copyFastMathFlags(&I);
628 Constant *C = cast<Constant>(Op1);
629 if (AllowReassociate && isFiniteNonZeroFp(C)) {
630 // Let MDC denote an expression in one of these forms:
631 // X * C, C/X, X/C, where C is a constant.
633 // Try to simplify "MDC * Constant"
634 if (isFMulOrFDivWithConstant(Op0))
635 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
636 return replaceInstUsesWith(I, V);
638 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
639 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
641 (FAddSub->getOpcode() == Instruction::FAdd ||
642 FAddSub->getOpcode() == Instruction::FSub)) {
643 Value *Opnd0 = FAddSub->getOperand(0);
644 Value *Opnd1 = FAddSub->getOperand(1);
645 Constant *C0 = dyn_cast<Constant>(Opnd0);
646 Constant *C1 = dyn_cast<Constant>(Opnd1);
650 std::swap(Opnd0, Opnd1);
654 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
655 Value *M1 = ConstantExpr::getFMul(C1, C);
656 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
657 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
660 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
663 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
664 ? BinaryOperator::CreateFAdd(M0, M1)
665 : BinaryOperator::CreateFSub(M0, M1);
666 RI->copyFastMathFlags(&I);
675 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
676 // sqrt(X) * sqrt(X) -> X
677 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
678 return replaceInstUsesWith(I, II->getOperand(0));
680 // fabs(X) * fabs(X) -> X * X
681 if (II->getIntrinsicID() == Intrinsic::fabs) {
682 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
685 FMulVal->copyFastMathFlags(&I);
691 // Under unsafe algebra do:
692 // X * log2(0.5*Y) = X*log2(Y) - X
693 if (AllowReassociate) {
694 Value *OpX = nullptr;
695 Value *OpY = nullptr;
697 detectLog2OfHalf(Op0, OpY, Log2);
701 detectLog2OfHalf(Op1, OpY, Log2);
706 // if pattern detected emit alternate sequence
708 BuilderTy::FastMathFlagGuard Guard(*Builder);
709 Builder->setFastMathFlags(Log2->getFastMathFlags());
710 Log2->setArgOperand(0, OpY);
711 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
712 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
714 return replaceInstUsesWith(I, FSub);
718 // Handle symmetric situation in a 2-iteration loop
721 for (int i = 0; i < 2; i++) {
722 bool IgnoreZeroSign = I.hasNoSignedZeros();
723 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
724 BuilderTy::FastMathFlagGuard Guard(*Builder);
725 Builder->setFastMathFlags(I.getFastMathFlags());
727 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
728 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
732 Value *FMul = Builder->CreateFMul(N0, N1);
734 return replaceInstUsesWith(I, FMul);
737 if (Opnd0->hasOneUse()) {
738 // -X * Y => -(X*Y) (Promote negation as high as possible)
739 Value *T = Builder->CreateFMul(N0, Opnd1);
740 Value *Neg = Builder->CreateFNeg(T);
742 return replaceInstUsesWith(I, Neg);
746 // (X*Y) * X => (X*X) * Y where Y != X
747 // The purpose is two-fold:
748 // 1) to form a power expression (of X).
749 // 2) potentially shorten the critical path: After transformation, the
750 // latency of the instruction Y is amortized by the expression of X*X,
751 // and therefore Y is in a "less critical" position compared to what it
752 // was before the transformation.
754 if (AllowReassociate) {
755 Value *Opnd0_0, *Opnd0_1;
756 if (Opnd0->hasOneUse() &&
757 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
759 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
761 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
765 BuilderTy::FastMathFlagGuard Guard(*Builder);
766 Builder->setFastMathFlags(I.getFastMathFlags());
767 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
768 Value *R = Builder->CreateFMul(T, Y);
770 return replaceInstUsesWith(I, R);
775 if (!isa<Constant>(Op1))
776 std::swap(Opnd0, Opnd1);
781 return Changed ? &I : nullptr;
784 /// Try to fold a divide or remainder of a select instruction.
785 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
786 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
788 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
789 int NonNullOperand = -1;
790 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
791 if (ST->isNullValue())
793 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
794 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
795 if (ST->isNullValue())
798 if (NonNullOperand == -1)
801 Value *SelectCond = SI->getOperand(0);
803 // Change the div/rem to use 'Y' instead of the select.
804 I.setOperand(1, SI->getOperand(NonNullOperand));
806 // Okay, we know we replace the operand of the div/rem with 'Y' with no
807 // problem. However, the select, or the condition of the select may have
808 // multiple uses. Based on our knowledge that the operand must be non-zero,
809 // propagate the known value for the select into other uses of it, and
810 // propagate a known value of the condition into its other users.
812 // If the select and condition only have a single use, don't bother with this,
814 if (SI->use_empty() && SelectCond->hasOneUse())
817 // Scan the current block backward, looking for other uses of SI.
818 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
820 while (BBI != BBFront) {
822 // If we found a call to a function, we can't assume it will return, so
823 // information from below it cannot be propagated above it.
824 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
827 // Replace uses of the select or its condition with the known values.
828 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
831 *I = SI->getOperand(NonNullOperand);
833 } else if (*I == SelectCond) {
834 *I = Builder->getInt1(NonNullOperand == 1);
839 // If we past the instruction, quit looking for it.
842 if (&*BBI == SelectCond)
843 SelectCond = nullptr;
845 // If we ran out of things to eliminate, break out of the loop.
846 if (!SelectCond && !SI)
854 /// This function implements the transforms common to both integer division
855 /// instructions (udiv and sdiv). It is called by the visitors to those integer
856 /// division instructions.
857 /// @brief Common integer divide transforms
858 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
859 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
861 // The RHS is known non-zero.
862 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
867 // Handle cases involving: [su]div X, (select Cond, Y, Z)
868 // This does not apply for fdiv.
869 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
872 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
874 if (match(Op1, m_APInt(C2))) {
877 bool IsSigned = I.getOpcode() == Instruction::SDiv;
879 // (X / C1) / C2 -> X / (C1*C2)
880 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
881 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
882 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
883 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
884 return BinaryOperator::Create(I.getOpcode(), X,
885 ConstantInt::get(I.getType(), Product));
888 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
889 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
890 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
892 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
893 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
894 BinaryOperator *BO = BinaryOperator::Create(
895 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
896 BO->setIsExact(I.isExact());
900 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
901 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
902 BinaryOperator *BO = BinaryOperator::Create(
903 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
904 BO->setHasNoUnsignedWrap(
906 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
907 BO->setHasNoSignedWrap(
908 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
913 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
914 *C1 != C1->getBitWidth() - 1) ||
915 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
916 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
917 APInt C1Shifted = APInt::getOneBitSet(
918 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
920 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
921 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
922 BinaryOperator *BO = BinaryOperator::Create(
923 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
924 BO->setIsExact(I.isExact());
928 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
929 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
930 BinaryOperator *BO = BinaryOperator::Create(
931 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
932 BO->setHasNoUnsignedWrap(
934 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
935 BO->setHasNoSignedWrap(
936 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
941 if (*C2 != 0) // avoid X udiv 0
942 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
947 if (match(Op0, m_One())) {
948 assert(!I.getType()->getScalarType()->isIntegerTy(1) &&
949 "i1 divide not removed?");
950 if (I.getOpcode() == Instruction::SDiv) {
951 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
952 // result is one, if Op1 is -1 then the result is minus one, otherwise
954 Value *Inc = Builder->CreateAdd(Op1, Op0);
955 Value *Cmp = Builder->CreateICmpULT(
956 Inc, ConstantInt::get(I.getType(), 3));
957 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
959 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
960 // result is one, otherwise it's zero.
961 return new ZExtInst(Builder->CreateICmpEQ(Op1, Op0), I.getType());
965 // See if we can fold away this div instruction.
966 if (SimplifyDemandedInstructionBits(I))
969 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
970 Value *X = nullptr, *Z = nullptr;
971 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
972 bool isSigned = I.getOpcode() == Instruction::SDiv;
973 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
974 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
975 return BinaryOperator::Create(I.getOpcode(), X, Op1);
981 /// dyn_castZExtVal - Checks if V is a zext or constant that can
982 /// be truncated to Ty without losing bits.
983 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
984 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
985 if (Z->getSrcTy() == Ty)
986 return Z->getOperand(0);
987 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
988 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
989 return ConstantExpr::getTrunc(C, Ty);
995 const unsigned MaxDepth = 6;
996 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
997 const BinaryOperator &I,
1000 /// \brief Used to maintain state for visitUDivOperand().
1001 struct UDivFoldAction {
1002 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
1003 ///< operand. This can be zero if this action
1004 ///< joins two actions together.
1006 Value *OperandToFold; ///< Which operand to fold.
1008 Instruction *FoldResult; ///< The instruction returned when FoldAction is
1011 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
1012 ///< joins two actions together.
1015 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
1016 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
1017 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1018 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1022 // X udiv 2^C -> X >> C
1023 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1024 const BinaryOperator &I, InstCombiner &IC) {
1025 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1026 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1027 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
1033 // X udiv C, where C >= signbit
1034 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1035 const BinaryOperator &I, InstCombiner &IC) {
1036 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
1038 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1039 ConstantInt::get(I.getType(), 1));
1042 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1043 // X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
1044 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1047 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1052 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1053 llvm_unreachable("match should never fail here!");
1055 N = IC.Builder->CreateAdd(N,
1056 ConstantInt::get(N->getType(), CI->logBase2()));
1057 if (Op1 != ShiftLeft)
1058 N = IC.Builder->CreateZExt(N, Op1->getType());
1059 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
1065 // \brief Recursively visits the possible right hand operands of a udiv
1066 // instruction, seeing through select instructions, to determine if we can
1067 // replace the udiv with something simpler. If we find that an operand is not
1068 // able to simplify the udiv, we abort the entire transformation.
1069 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1070 SmallVectorImpl<UDivFoldAction> &Actions,
1071 unsigned Depth = 0) {
1072 // Check to see if this is an unsigned division with an exact power of 2,
1073 // if so, convert to a right shift.
1074 if (match(Op1, m_Power2())) {
1075 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1076 return Actions.size();
1079 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1080 // X udiv C, where C >= signbit
1081 if (C->getValue().isNegative()) {
1082 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1083 return Actions.size();
1086 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1087 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1088 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1089 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1090 return Actions.size();
1093 // The remaining tests are all recursive, so bail out if we hit the limit.
1094 if (Depth++ == MaxDepth)
1097 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1099 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1100 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1101 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1102 return Actions.size();
1108 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1111 if (Value *V = SimplifyVectorOp(I))
1112 return replaceInstUsesWith(I, V);
1114 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, &TLI, &DT, &AC))
1115 return replaceInstUsesWith(I, V);
1117 // Handle the integer div common cases
1118 if (Instruction *Common = commonIDivTransforms(I))
1121 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
1124 const APInt *C1, *C2;
1125 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1126 match(Op1, m_APInt(C2))) {
1128 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1130 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1131 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1132 X, ConstantInt::get(X->getType(), C2ShlC1));
1140 // (zext A) udiv (zext B) --> zext (A udiv B)
1141 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1142 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1143 return new ZExtInst(
1144 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1147 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1148 SmallVector<UDivFoldAction, 6> UDivActions;
1149 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1150 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1151 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1152 Value *ActionOp1 = UDivActions[i].OperandToFold;
1155 Inst = Action(Op0, ActionOp1, I, *this);
1157 // This action joins two actions together. The RHS of this action is
1158 // simply the last action we processed, we saved the LHS action index in
1159 // the joining action.
1160 size_t SelectRHSIdx = i - 1;
1161 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1162 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1163 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1164 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1165 SelectLHS, SelectRHS);
1168 // If this is the last action to process, return it to the InstCombiner.
1169 // Otherwise, we insert it before the UDiv and record it so that we may
1170 // use it as part of a joining action (i.e., a SelectInst).
1172 Inst->insertBefore(&I);
1173 UDivActions[i].FoldResult = Inst;
1181 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1182 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1184 if (Value *V = SimplifyVectorOp(I))
1185 return replaceInstUsesWith(I, V);
1187 if (Value *V = SimplifySDivInst(Op0, Op1, DL, &TLI, &DT, &AC))
1188 return replaceInstUsesWith(I, V);
1190 // Handle the integer div common cases
1191 if (Instruction *Common = commonIDivTransforms(I))
1195 if (match(Op1, m_APInt(Op1C))) {
1197 if (Op1C->isAllOnesValue())
1198 return BinaryOperator::CreateNeg(Op0);
1200 // sdiv exact X, C --> ashr exact X, log2(C)
1201 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1202 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1203 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1206 // If the dividend is sign-extended and the constant divisor is small enough
1207 // to fit in the source type, shrink the division to the narrower type:
1208 // (sext X) sdiv C --> sext (X sdiv C)
1210 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1211 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1213 // In the general case, we need to make sure that the dividend is not the
1214 // minimum signed value because dividing that by -1 is UB. But here, we
1215 // know that the -1 divisor case is already handled above.
1217 Constant *NarrowDivisor =
1218 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1219 Value *NarrowOp = Builder->CreateSDiv(Op0Src, NarrowDivisor);
1220 return new SExtInst(NarrowOp, Op0->getType());
1224 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1225 // X/INT_MIN -> X == INT_MIN
1226 if (RHS->isMinSignedValue())
1227 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1229 // -X/C --> X/-C provided the negation doesn't overflow.
1231 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1232 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1233 BO->setIsExact(I.isExact());
1238 // If the sign bits of both operands are zero (i.e. we can prove they are
1239 // unsigned inputs), turn this into a udiv.
1240 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1241 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1242 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1243 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1244 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1245 BO->setIsExact(I.isExact());
1249 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
1250 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1251 // Safe because the only negative value (1 << Y) can take on is
1252 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1253 // the sign bit set.
1254 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1255 BO->setIsExact(I.isExact());
1263 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1265 /// 1) 1/C is exact, or
1266 /// 2) reciprocal is allowed.
1267 /// If the conversion was successful, the simplified expression "X * 1/C" is
1268 /// returned; otherwise, NULL is returned.
1270 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1271 bool AllowReciprocal) {
1272 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1275 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1276 APFloat Reciprocal(FpVal.getSemantics());
1277 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1279 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1280 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1281 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1282 Cvt = !Reciprocal.isDenormal();
1289 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1290 return BinaryOperator::CreateFMul(Dividend, R);
1293 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1294 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1296 if (Value *V = SimplifyVectorOp(I))
1297 return replaceInstUsesWith(I, V);
1299 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1300 DL, &TLI, &DT, &AC))
1301 return replaceInstUsesWith(I, V);
1303 if (isa<Constant>(Op0))
1304 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1305 if (Instruction *R = FoldOpIntoSelect(I, SI))
1308 bool AllowReassociate = I.hasUnsafeAlgebra();
1309 bool AllowReciprocal = I.hasAllowReciprocal();
1311 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1312 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1313 if (Instruction *R = FoldOpIntoSelect(I, SI))
1316 if (AllowReassociate) {
1317 Constant *C1 = nullptr;
1318 Constant *C2 = Op1C;
1320 Instruction *Res = nullptr;
1322 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1323 // (X*C1)/C2 => X * (C1/C2)
1325 Constant *C = ConstantExpr::getFDiv(C1, C2);
1327 Res = BinaryOperator::CreateFMul(X, C);
1328 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1329 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1331 Constant *C = ConstantExpr::getFMul(C1, C2);
1332 if (isNormalFp(C)) {
1333 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1335 Res = BinaryOperator::CreateFDiv(X, C);
1340 Res->setFastMathFlags(I.getFastMathFlags());
1346 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1347 T->copyFastMathFlags(&I);
1354 if (AllowReassociate && isa<Constant>(Op0)) {
1355 Constant *C1 = cast<Constant>(Op0), *C2;
1356 Constant *Fold = nullptr;
1358 bool CreateDiv = true;
1360 // C1 / (X*C2) => (C1/C2) / X
1361 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1362 Fold = ConstantExpr::getFDiv(C1, C2);
1363 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1364 // C1 / (X/C2) => (C1*C2) / X
1365 Fold = ConstantExpr::getFMul(C1, C2);
1366 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1367 // C1 / (C2/X) => (C1/C2) * X
1368 Fold = ConstantExpr::getFDiv(C1, C2);
1372 if (Fold && isNormalFp(Fold)) {
1373 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1374 : BinaryOperator::CreateFMul(X, Fold);
1375 R->setFastMathFlags(I.getFastMathFlags());
1381 if (AllowReassociate) {
1383 Value *NewInst = nullptr;
1384 Instruction *SimpR = nullptr;
1386 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1387 // (X/Y) / Z => X / (Y*Z)
1389 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1390 NewInst = Builder->CreateFMul(Y, Op1);
1391 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1392 FastMathFlags Flags = I.getFastMathFlags();
1393 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1394 RI->setFastMathFlags(Flags);
1396 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1398 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1399 // Z / (X/Y) => Z*Y / X
1401 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1402 NewInst = Builder->CreateFMul(Op0, Y);
1403 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1404 FastMathFlags Flags = I.getFastMathFlags();
1405 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1406 RI->setFastMathFlags(Flags);
1408 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1413 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1414 T->setDebugLoc(I.getDebugLoc());
1415 SimpR->setFastMathFlags(I.getFastMathFlags());
1424 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1425 I.setOperand(0, LHS);
1426 I.setOperand(1, RHS);
1433 /// This function implements the transforms common to both integer remainder
1434 /// instructions (urem and srem). It is called by the visitors to those integer
1435 /// remainder instructions.
1436 /// @brief Common integer remainder transforms
1437 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1438 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1440 // The RHS is known non-zero.
1441 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
1446 // Handle cases involving: rem X, (select Cond, Y, Z)
1447 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1450 if (isa<Constant>(Op1)) {
1451 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1452 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1453 if (Instruction *R = FoldOpIntoSelect(I, SI))
1455 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1456 using namespace llvm::PatternMatch;
1457 const APInt *Op1Int;
1458 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1459 (I.getOpcode() == Instruction::URem ||
1460 !Op1Int->isMinSignedValue())) {
1461 // foldOpIntoPhi will speculate instructions to the end of the PHI's
1462 // predecessor blocks, so do this only if we know the srem or urem
1464 if (Instruction *NV = foldOpIntoPhi(I, PN))
1469 // See if we can fold away this rem instruction.
1470 if (SimplifyDemandedInstructionBits(I))
1478 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1479 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1481 if (Value *V = SimplifyVectorOp(I))
1482 return replaceInstUsesWith(I, V);
1484 if (Value *V = SimplifyURemInst(Op0, Op1, DL, &TLI, &DT, &AC))
1485 return replaceInstUsesWith(I, V);
1487 if (Instruction *common = commonIRemTransforms(I))
1490 // (zext A) urem (zext B) --> zext (A urem B)
1491 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1492 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1493 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1496 // X urem Y -> X and Y-1, where Y is a power of 2,
1497 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
1498 Constant *N1 = Constant::getAllOnesValue(I.getType());
1499 Value *Add = Builder->CreateAdd(Op1, N1);
1500 return BinaryOperator::CreateAnd(Op0, Add);
1503 // 1 urem X -> zext(X != 1)
1504 if (match(Op0, m_One())) {
1505 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1506 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1507 return replaceInstUsesWith(I, Ext);
1510 // X urem C -> X < C ? X : X - C, where C >= signbit.
1511 const APInt *DivisorC;
1512 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
1513 Value *Cmp = Builder->CreateICmpULT(Op0, Op1);
1514 Value *Sub = Builder->CreateSub(Op0, Op1);
1515 return SelectInst::Create(Cmp, Op0, Sub);
1521 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1522 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1524 if (Value *V = SimplifyVectorOp(I))
1525 return replaceInstUsesWith(I, V);
1527 if (Value *V = SimplifySRemInst(Op0, Op1, DL, &TLI, &DT, &AC))
1528 return replaceInstUsesWith(I, V);
1530 // Handle the integer rem common cases
1531 if (Instruction *Common = commonIRemTransforms(I))
1537 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1538 Worklist.AddValue(I.getOperand(1));
1539 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1544 // If the sign bits of both operands are zero (i.e. we can prove they are
1545 // unsigned inputs), turn this into a urem.
1546 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1547 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1548 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1549 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1550 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1553 // If it's a constant vector, flip any negative values positive.
1554 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1555 Constant *C = cast<Constant>(Op1);
1556 unsigned VWidth = C->getType()->getVectorNumElements();
1558 bool hasNegative = false;
1559 bool hasMissing = false;
1560 for (unsigned i = 0; i != VWidth; ++i) {
1561 Constant *Elt = C->getAggregateElement(i);
1567 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1568 if (RHS->isNegative())
1572 if (hasNegative && !hasMissing) {
1573 SmallVector<Constant *, 16> Elts(VWidth);
1574 for (unsigned i = 0; i != VWidth; ++i) {
1575 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1576 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1577 if (RHS->isNegative())
1578 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1582 Constant *NewRHSV = ConstantVector::get(Elts);
1583 if (NewRHSV != C) { // Don't loop on -MININT
1584 Worklist.AddValue(I.getOperand(1));
1585 I.setOperand(1, NewRHSV);
1594 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1597 if (Value *V = SimplifyVectorOp(I))
1598 return replaceInstUsesWith(I, V);
1600 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1601 DL, &TLI, &DT, &AC))
1602 return replaceInstUsesWith(I, V);
1604 // Handle cases involving: rem X, (select Cond, Y, Z)
1605 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))