LLVM  mainline
InstCombineMulDivRem.cpp
Go to the documentation of this file.
00001 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
00011 // srem, urem, frem.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "InstCombineInternal.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 #define DEBUG_TYPE "instcombine"
00023 
00024 
00025 /// simplifyValueKnownNonZero - The specific integer value is used in a context
00026 /// where it is known to be non-zero.  If this allows us to simplify the
00027 /// computation, do so and return the new operand, otherwise return null.
00028 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
00029                                         Instruction &CxtI) {
00030   // If V has multiple uses, then we would have to do more analysis to determine
00031   // if this is safe.  For example, the use could be in dynamically unreached
00032   // code.
00033   if (!V->hasOneUse()) return nullptr;
00034 
00035   bool MadeChange = false;
00036 
00037   // ((1 << A) >>u B) --> (1 << (A-B))
00038   // Because V cannot be zero, we know that B is less than A.
00039   Value *A = nullptr, *B = nullptr, *One = nullptr;
00040   if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
00041       match(One, m_One())) {
00042     A = IC.Builder->CreateSub(A, B);
00043     return IC.Builder->CreateShl(One, A);
00044   }
00045 
00046   // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
00047   // inexact.  Similarly for <<.
00048   if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
00049     if (I->isLogicalShift() &&
00050         isKnownToBeAPowerOfTwo(I->getOperand(0), IC.getDataLayout(), false, 0,
00051                                IC.getAssumptionCache(), &CxtI,
00052                                IC.getDominatorTree())) {
00053       // We know that this is an exact/nuw shift and that the input is a
00054       // non-zero context as well.
00055       if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
00056         I->setOperand(0, V2);
00057         MadeChange = true;
00058       }
00059 
00060       if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
00061         I->setIsExact();
00062         MadeChange = true;
00063       }
00064 
00065       if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
00066         I->setHasNoUnsignedWrap();
00067         MadeChange = true;
00068       }
00069     }
00070 
00071   // TODO: Lots more we could do here:
00072   //    If V is a phi node, we can call this on each of its operands.
00073   //    "select cond, X, 0" can simplify to "X".
00074 
00075   return MadeChange ? V : nullptr;
00076 }
00077 
00078 
00079 /// MultiplyOverflows - True if the multiply can not be expressed in an int
00080 /// this size.
00081 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
00082                               bool IsSigned) {
00083   bool Overflow;
00084   if (IsSigned)
00085     Product = C1.smul_ov(C2, Overflow);
00086   else
00087     Product = C1.umul_ov(C2, Overflow);
00088 
00089   return Overflow;
00090 }
00091 
00092 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
00093 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
00094                        bool IsSigned) {
00095   assert(C1.getBitWidth() == C2.getBitWidth() &&
00096          "Inconsistent width of constants!");
00097 
00098   APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
00099   if (IsSigned)
00100     APInt::sdivrem(C1, C2, Quotient, Remainder);
00101   else
00102     APInt::udivrem(C1, C2, Quotient, Remainder);
00103 
00104   return Remainder.isMinValue();
00105 }
00106 
00107 /// \brief A helper routine of InstCombiner::visitMul().
00108 ///
00109 /// If C is a vector of known powers of 2, then this function returns
00110 /// a new vector obtained from C replacing each element with its logBase2.
00111 /// Return a null pointer otherwise.
00112 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
00113   const APInt *IVal;
00114   SmallVector<Constant *, 4> Elts;
00115 
00116   for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
00117     Constant *Elt = CV->getElementAsConstant(I);
00118     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
00119       return nullptr;
00120     Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
00121   }
00122 
00123   return ConstantVector::get(Elts);
00124 }
00125 
00126 /// \brief Return true if we can prove that:
00127 ///    (mul LHS, RHS)  === (mul nsw LHS, RHS)
00128 bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
00129                                             Instruction &CxtI) {
00130   // Multiplying n * m significant bits yields a result of n + m significant
00131   // bits. If the total number of significant bits does not exceed the
00132   // result bit width (minus 1), there is no overflow.
00133   // This means if we have enough leading sign bits in the operands
00134   // we can guarantee that the result does not overflow.
00135   // Ref: "Hacker's Delight" by Henry Warren
00136   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
00137 
00138   // Note that underestimating the number of sign bits gives a more
00139   // conservative answer.
00140   unsigned SignBits =
00141       ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
00142 
00143   // First handle the easy case: if we have enough sign bits there's
00144   // definitely no overflow.
00145   if (SignBits > BitWidth + 1)
00146     return true;
00147 
00148   // There are two ambiguous cases where there can be no overflow:
00149   //   SignBits == BitWidth + 1    and
00150   //   SignBits == BitWidth
00151   // The second case is difficult to check, therefore we only handle the
00152   // first case.
00153   if (SignBits == BitWidth + 1) {
00154     // It overflows only when both arguments are negative and the true
00155     // product is exactly the minimum negative number.
00156     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
00157     // For simplicity we just check if at least one side is not negative.
00158     bool LHSNonNegative, LHSNegative;
00159     bool RHSNonNegative, RHSNegative;
00160     ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
00161     ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
00162     if (LHSNonNegative || RHSNonNegative)
00163       return true;
00164   }
00165   return false;
00166 }
00167 
00168 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
00169   bool Changed = SimplifyAssociativeOrCommutative(I);
00170   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00171 
00172   if (Value *V = SimplifyVectorOp(I))
00173     return ReplaceInstUsesWith(I, V);
00174 
00175   if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AC))
00176     return ReplaceInstUsesWith(I, V);
00177 
00178   if (Value *V = SimplifyUsingDistributiveLaws(I))
00179     return ReplaceInstUsesWith(I, V);
00180 
00181   // X * -1 == 0 - X
00182   if (match(Op1, m_AllOnes())) {
00183     BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
00184     if (I.hasNoSignedWrap())
00185       BO->setHasNoSignedWrap();
00186     return BO;
00187   }
00188 
00189   // Also allow combining multiply instructions on vectors.
00190   {
00191     Value *NewOp;
00192     Constant *C1, *C2;
00193     const APInt *IVal;
00194     if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
00195                         m_Constant(C1))) &&
00196         match(C1, m_APInt(IVal))) {
00197       // ((X << C2)*C1) == (X * (C1 << C2))
00198       Constant *Shl = ConstantExpr::getShl(C1, C2);
00199       BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
00200       BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
00201       if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
00202         BO->setHasNoUnsignedWrap();
00203       if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
00204           Shl->isNotMinSignedValue())
00205         BO->setHasNoSignedWrap();
00206       return BO;
00207     }
00208 
00209     if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
00210       Constant *NewCst = nullptr;
00211       if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
00212         // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
00213         NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
00214       else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
00215         // Replace X*(2^C) with X << C, where C is a vector of known
00216         // constant powers of 2.
00217         NewCst = getLogBase2Vector(CV);
00218 
00219       if (NewCst) {
00220         BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
00221 
00222         if (I.hasNoUnsignedWrap())
00223           Shl->setHasNoUnsignedWrap();
00224         if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
00225           Shl->setHasNoSignedWrap();
00226 
00227         return Shl;
00228       }
00229     }
00230   }
00231 
00232   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
00233     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
00234     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
00235     // The "* (2**n)" thus becomes a potential shifting opportunity.
00236     {
00237       const APInt &   Val = CI->getValue();
00238       const APInt &PosVal = Val.abs();
00239       if (Val.isNegative() && PosVal.isPowerOf2()) {
00240         Value *X = nullptr, *Y = nullptr;
00241         if (Op0->hasOneUse()) {
00242           ConstantInt *C1;
00243           Value *Sub = nullptr;
00244           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
00245             Sub = Builder->CreateSub(X, Y, "suba");
00246           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
00247             Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
00248           if (Sub)
00249             return
00250               BinaryOperator::CreateMul(Sub,
00251                                         ConstantInt::get(Y->getType(), PosVal));
00252         }
00253       }
00254     }
00255   }
00256 
00257   // Simplify mul instructions with a constant RHS.
00258   if (isa<Constant>(Op1)) {
00259     // Try to fold constant mul into select arguments.
00260     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00261       if (Instruction *R = FoldOpIntoSelect(I, SI))
00262         return R;
00263 
00264     if (isa<PHINode>(Op0))
00265       if (Instruction *NV = FoldOpIntoPhi(I))
00266         return NV;
00267 
00268     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
00269     {
00270       Value *X;
00271       Constant *C1;
00272       if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
00273         Value *Mul = Builder->CreateMul(C1, Op1);
00274         // Only go forward with the transform if C1*CI simplifies to a tidier
00275         // constant.
00276         if (!match(Mul, m_Mul(m_Value(), m_Value())))
00277           return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
00278       }
00279     }
00280   }
00281 
00282   if (Value *Op0v = dyn_castNegVal(Op0)) {   // -X * -Y = X*Y
00283     if (Value *Op1v = dyn_castNegVal(Op1)) {
00284       BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
00285       if (I.hasNoSignedWrap() &&
00286           match(Op0, m_NSWSub(m_Value(), m_Value())) &&
00287           match(Op1, m_NSWSub(m_Value(), m_Value())))
00288         BO->setHasNoSignedWrap();
00289       return BO;
00290     }
00291   }
00292 
00293   // (X / Y) *  Y = X - (X % Y)
00294   // (X / Y) * -Y = (X % Y) - X
00295   {
00296     Value *Op1C = Op1;
00297     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
00298     if (!BO ||
00299         (BO->getOpcode() != Instruction::UDiv &&
00300          BO->getOpcode() != Instruction::SDiv)) {
00301       Op1C = Op0;
00302       BO = dyn_cast<BinaryOperator>(Op1);
00303     }
00304     Value *Neg = dyn_castNegVal(Op1C);
00305     if (BO && BO->hasOneUse() &&
00306         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
00307         (BO->getOpcode() == Instruction::UDiv ||
00308          BO->getOpcode() == Instruction::SDiv)) {
00309       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
00310 
00311       // If the division is exact, X % Y is zero, so we end up with X or -X.
00312       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
00313         if (SDiv->isExact()) {
00314           if (Op1BO == Op1C)
00315             return ReplaceInstUsesWith(I, Op0BO);
00316           return BinaryOperator::CreateNeg(Op0BO);
00317         }
00318 
00319       Value *Rem;
00320       if (BO->getOpcode() == Instruction::UDiv)
00321         Rem = Builder->CreateURem(Op0BO, Op1BO);
00322       else
00323         Rem = Builder->CreateSRem(Op0BO, Op1BO);
00324       Rem->takeName(BO);
00325 
00326       if (Op1BO == Op1C)
00327         return BinaryOperator::CreateSub(Op0BO, Rem);
00328       return BinaryOperator::CreateSub(Rem, Op0BO);
00329     }
00330   }
00331 
00332   /// i1 mul -> i1 and.
00333   if (I.getType()->getScalarType()->isIntegerTy(1))
00334     return BinaryOperator::CreateAnd(Op0, Op1);
00335 
00336   // X*(1 << Y) --> X << Y
00337   // (1 << Y)*X --> X << Y
00338   {
00339     Value *Y;
00340     BinaryOperator *BO = nullptr;
00341     bool ShlNSW = false;
00342     if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
00343       BO = BinaryOperator::CreateShl(Op1, Y);
00344       ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
00345     } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
00346       BO = BinaryOperator::CreateShl(Op0, Y);
00347       ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
00348     }
00349     if (BO) {
00350       if (I.hasNoUnsignedWrap())
00351         BO->setHasNoUnsignedWrap();
00352       if (I.hasNoSignedWrap() && ShlNSW)
00353         BO->setHasNoSignedWrap();
00354       return BO;
00355     }
00356   }
00357 
00358   // If one of the operands of the multiply is a cast from a boolean value, then
00359   // we know the bool is either zero or one, so this is a 'masking' multiply.
00360   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
00361   if (!I.getType()->isVectorTy()) {
00362     // -2 is "-1 << 1" so it is all bits set except the low one.
00363     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
00364 
00365     Value *BoolCast = nullptr, *OtherOp = nullptr;
00366     if (MaskedValueIsZero(Op0, Negative2, 0, &I))
00367       BoolCast = Op0, OtherOp = Op1;
00368     else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
00369       BoolCast = Op1, OtherOp = Op0;
00370 
00371     if (BoolCast) {
00372       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
00373                                     BoolCast);
00374       return BinaryOperator::CreateAnd(V, OtherOp);
00375     }
00376   }
00377 
00378   if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
00379     Changed = true;
00380     I.setHasNoSignedWrap(true);
00381   }
00382 
00383   if (!I.hasNoUnsignedWrap() &&
00384       computeOverflowForUnsignedMul(Op0, Op1, &I) ==
00385           OverflowResult::NeverOverflows) {
00386     Changed = true;
00387     I.setHasNoUnsignedWrap(true);
00388   }
00389 
00390   return Changed ? &I : nullptr;
00391 }
00392 
00393 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
00394 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
00395   if (!Op->hasOneUse())
00396     return;
00397 
00398   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
00399   if (!II)
00400     return;
00401   if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
00402     return;
00403   Log2 = II;
00404 
00405   Value *OpLog2Of = II->getArgOperand(0);
00406   if (!OpLog2Of->hasOneUse())
00407     return;
00408 
00409   Instruction *I = dyn_cast<Instruction>(OpLog2Of);
00410   if (!I)
00411     return;
00412   if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
00413     return;
00414 
00415   if (match(I->getOperand(0), m_SpecificFP(0.5)))
00416     Y = I->getOperand(1);
00417   else if (match(I->getOperand(1), m_SpecificFP(0.5)))
00418     Y = I->getOperand(0);
00419 }
00420 
00421 static bool isFiniteNonZeroFp(Constant *C) {
00422   if (C->getType()->isVectorTy()) {
00423     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
00424          ++I) {
00425       ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
00426       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
00427         return false;
00428     }
00429     return true;
00430   }
00431 
00432   return isa<ConstantFP>(C) &&
00433          cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
00434 }
00435 
00436 static bool isNormalFp(Constant *C) {
00437   if (C->getType()->isVectorTy()) {
00438     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
00439          ++I) {
00440       ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
00441       if (!CFP || !CFP->getValueAPF().isNormal())
00442         return false;
00443     }
00444     return true;
00445   }
00446 
00447   return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
00448 }
00449 
00450 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
00451 /// true iff the given value is FMul or FDiv with one and only one operand
00452 /// being a normal constant (i.e. not Zero/NaN/Infinity).
00453 static bool isFMulOrFDivWithConstant(Value *V) {
00454   Instruction *I = dyn_cast<Instruction>(V);
00455   if (!I || (I->getOpcode() != Instruction::FMul &&
00456              I->getOpcode() != Instruction::FDiv))
00457     return false;
00458 
00459   Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
00460   Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
00461 
00462   if (C0 && C1)
00463     return false;
00464 
00465   return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
00466 }
00467 
00468 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
00469 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
00470 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
00471 /// This function is to simplify "FMulOrDiv * C" and returns the
00472 /// resulting expression. Note that this function could return NULL in
00473 /// case the constants cannot be folded into a normal floating-point.
00474 ///
00475 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
00476                                    Instruction *InsertBefore) {
00477   assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
00478 
00479   Value *Opnd0 = FMulOrDiv->getOperand(0);
00480   Value *Opnd1 = FMulOrDiv->getOperand(1);
00481 
00482   Constant *C0 = dyn_cast<Constant>(Opnd0);
00483   Constant *C1 = dyn_cast<Constant>(Opnd1);
00484 
00485   BinaryOperator *R = nullptr;
00486 
00487   // (X * C0) * C => X * (C0*C)
00488   if (FMulOrDiv->getOpcode() == Instruction::FMul) {
00489     Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
00490     if (isNormalFp(F))
00491       R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
00492   } else {
00493     if (C0) {
00494       // (C0 / X) * C => (C0 * C) / X
00495       if (FMulOrDiv->hasOneUse()) {
00496         // It would otherwise introduce another div.
00497         Constant *F = ConstantExpr::getFMul(C0, C);
00498         if (isNormalFp(F))
00499           R = BinaryOperator::CreateFDiv(F, Opnd1);
00500       }
00501     } else {
00502       // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
00503       Constant *F = ConstantExpr::getFDiv(C, C1);
00504       if (isNormalFp(F)) {
00505         R = BinaryOperator::CreateFMul(Opnd0, F);
00506       } else {
00507         // (X / C1) * C => X / (C1/C)
00508         Constant *F = ConstantExpr::getFDiv(C1, C);
00509         if (isNormalFp(F))
00510           R = BinaryOperator::CreateFDiv(Opnd0, F);
00511       }
00512     }
00513   }
00514 
00515   if (R) {
00516     R->setHasUnsafeAlgebra(true);
00517     InsertNewInstWith(R, *InsertBefore);
00518   }
00519 
00520   return R;
00521 }
00522 
00523 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
00524   bool Changed = SimplifyAssociativeOrCommutative(I);
00525   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00526 
00527   if (Value *V = SimplifyVectorOp(I))
00528     return ReplaceInstUsesWith(I, V);
00529 
00530   if (isa<Constant>(Op0))
00531     std::swap(Op0, Op1);
00532 
00533   if (Value *V =
00534           SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
00535     return ReplaceInstUsesWith(I, V);
00536 
00537   bool AllowReassociate = I.hasUnsafeAlgebra();
00538 
00539   // Simplify mul instructions with a constant RHS.
00540   if (isa<Constant>(Op1)) {
00541     // Try to fold constant mul into select arguments.
00542     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00543       if (Instruction *R = FoldOpIntoSelect(I, SI))
00544         return R;
00545 
00546     if (isa<PHINode>(Op0))
00547       if (Instruction *NV = FoldOpIntoPhi(I))
00548         return NV;
00549 
00550     // (fmul X, -1.0) --> (fsub -0.0, X)
00551     if (match(Op1, m_SpecificFP(-1.0))) {
00552       Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
00553       Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
00554       RI->copyFastMathFlags(&I);
00555       return RI;
00556     }
00557 
00558     Constant *C = cast<Constant>(Op1);
00559     if (AllowReassociate && isFiniteNonZeroFp(C)) {
00560       // Let MDC denote an expression in one of these forms:
00561       // X * C, C/X, X/C, where C is a constant.
00562       //
00563       // Try to simplify "MDC * Constant"
00564       if (isFMulOrFDivWithConstant(Op0))
00565         if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
00566           return ReplaceInstUsesWith(I, V);
00567 
00568       // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
00569       Instruction *FAddSub = dyn_cast<Instruction>(Op0);
00570       if (FAddSub &&
00571           (FAddSub->getOpcode() == Instruction::FAdd ||
00572            FAddSub->getOpcode() == Instruction::FSub)) {
00573         Value *Opnd0 = FAddSub->getOperand(0);
00574         Value *Opnd1 = FAddSub->getOperand(1);
00575         Constant *C0 = dyn_cast<Constant>(Opnd0);
00576         Constant *C1 = dyn_cast<Constant>(Opnd1);
00577         bool Swap = false;
00578         if (C0) {
00579           std::swap(C0, C1);
00580           std::swap(Opnd0, Opnd1);
00581           Swap = true;
00582         }
00583 
00584         if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
00585           Value *M1 = ConstantExpr::getFMul(C1, C);
00586           Value *M0 = isNormalFp(cast<Constant>(M1)) ?
00587                       foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
00588                       nullptr;
00589           if (M0 && M1) {
00590             if (Swap && FAddSub->getOpcode() == Instruction::FSub)
00591               std::swap(M0, M1);
00592 
00593             Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
00594                                   ? BinaryOperator::CreateFAdd(M0, M1)
00595                                   : BinaryOperator::CreateFSub(M0, M1);
00596             RI->copyFastMathFlags(&I);
00597             return RI;
00598           }
00599         }
00600       }
00601     }
00602   }
00603 
00604   // sqrt(X) * sqrt(X) -> X
00605   if (AllowReassociate && (Op0 == Op1))
00606     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
00607       if (II->getIntrinsicID() == Intrinsic::sqrt)
00608         return ReplaceInstUsesWith(I, II->getOperand(0));
00609 
00610   // Under unsafe algebra do:
00611   // X * log2(0.5*Y) = X*log2(Y) - X
00612   if (AllowReassociate) {
00613     Value *OpX = nullptr;
00614     Value *OpY = nullptr;
00615     IntrinsicInst *Log2;
00616     detectLog2OfHalf(Op0, OpY, Log2);
00617     if (OpY) {
00618       OpX = Op1;
00619     } else {
00620       detectLog2OfHalf(Op1, OpY, Log2);
00621       if (OpY) {
00622         OpX = Op0;
00623       }
00624     }
00625     // if pattern detected emit alternate sequence
00626     if (OpX && OpY) {
00627       BuilderTy::FastMathFlagGuard Guard(*Builder);
00628       Builder->SetFastMathFlags(Log2->getFastMathFlags());
00629       Log2->setArgOperand(0, OpY);
00630       Value *FMulVal = Builder->CreateFMul(OpX, Log2);
00631       Value *FSub = Builder->CreateFSub(FMulVal, OpX);
00632       FSub->takeName(&I);
00633       return ReplaceInstUsesWith(I, FSub);
00634     }
00635   }
00636 
00637   // Handle symmetric situation in a 2-iteration loop
00638   Value *Opnd0 = Op0;
00639   Value *Opnd1 = Op1;
00640   for (int i = 0; i < 2; i++) {
00641     bool IgnoreZeroSign = I.hasNoSignedZeros();
00642     if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
00643       BuilderTy::FastMathFlagGuard Guard(*Builder);
00644       Builder->SetFastMathFlags(I.getFastMathFlags());
00645 
00646       Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
00647       Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
00648 
00649       // -X * -Y => X*Y
00650       if (N1) {
00651         Value *FMul = Builder->CreateFMul(N0, N1);
00652         FMul->takeName(&I);
00653         return ReplaceInstUsesWith(I, FMul);
00654       }
00655 
00656       if (Opnd0->hasOneUse()) {
00657         // -X * Y => -(X*Y) (Promote negation as high as possible)
00658         Value *T = Builder->CreateFMul(N0, Opnd1);
00659         Value *Neg = Builder->CreateFNeg(T);
00660         Neg->takeName(&I);
00661         return ReplaceInstUsesWith(I, Neg);
00662       }
00663     }
00664 
00665     // (X*Y) * X => (X*X) * Y where Y != X
00666     //  The purpose is two-fold:
00667     //   1) to form a power expression (of X).
00668     //   2) potentially shorten the critical path: After transformation, the
00669     //  latency of the instruction Y is amortized by the expression of X*X,
00670     //  and therefore Y is in a "less critical" position compared to what it
00671     //  was before the transformation.
00672     //
00673     if (AllowReassociate) {
00674       Value *Opnd0_0, *Opnd0_1;
00675       if (Opnd0->hasOneUse() &&
00676           match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
00677         Value *Y = nullptr;
00678         if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
00679           Y = Opnd0_1;
00680         else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
00681           Y = Opnd0_0;
00682 
00683         if (Y) {
00684           BuilderTy::FastMathFlagGuard Guard(*Builder);
00685           Builder->SetFastMathFlags(I.getFastMathFlags());
00686           Value *T = Builder->CreateFMul(Opnd1, Opnd1);
00687 
00688           Value *R = Builder->CreateFMul(T, Y);
00689           R->takeName(&I);
00690           return ReplaceInstUsesWith(I, R);
00691         }
00692       }
00693     }
00694 
00695     if (!isa<Constant>(Op1))
00696       std::swap(Opnd0, Opnd1);
00697     else
00698       break;
00699   }
00700 
00701   return Changed ? &I : nullptr;
00702 }
00703 
00704 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
00705 /// instruction.
00706 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
00707   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
00708 
00709   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
00710   int NonNullOperand = -1;
00711   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
00712     if (ST->isNullValue())
00713       NonNullOperand = 2;
00714   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
00715   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
00716     if (ST->isNullValue())
00717       NonNullOperand = 1;
00718 
00719   if (NonNullOperand == -1)
00720     return false;
00721 
00722   Value *SelectCond = SI->getOperand(0);
00723 
00724   // Change the div/rem to use 'Y' instead of the select.
00725   I.setOperand(1, SI->getOperand(NonNullOperand));
00726 
00727   // Okay, we know we replace the operand of the div/rem with 'Y' with no
00728   // problem.  However, the select, or the condition of the select may have
00729   // multiple uses.  Based on our knowledge that the operand must be non-zero,
00730   // propagate the known value for the select into other uses of it, and
00731   // propagate a known value of the condition into its other users.
00732 
00733   // If the select and condition only have a single use, don't bother with this,
00734   // early exit.
00735   if (SI->use_empty() && SelectCond->hasOneUse())
00736     return true;
00737 
00738   // Scan the current block backward, looking for other uses of SI.
00739   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
00740 
00741   while (BBI != BBFront) {
00742     --BBI;
00743     // If we found a call to a function, we can't assume it will return, so
00744     // information from below it cannot be propagated above it.
00745     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
00746       break;
00747 
00748     // Replace uses of the select or its condition with the known values.
00749     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
00750          I != E; ++I) {
00751       if (*I == SI) {
00752         *I = SI->getOperand(NonNullOperand);
00753         Worklist.Add(BBI);
00754       } else if (*I == SelectCond) {
00755         *I = Builder->getInt1(NonNullOperand == 1);
00756         Worklist.Add(BBI);
00757       }
00758     }
00759 
00760     // If we past the instruction, quit looking for it.
00761     if (&*BBI == SI)
00762       SI = nullptr;
00763     if (&*BBI == SelectCond)
00764       SelectCond = nullptr;
00765 
00766     // If we ran out of things to eliminate, break out of the loop.
00767     if (!SelectCond && !SI)
00768       break;
00769 
00770   }
00771   return true;
00772 }
00773 
00774 
00775 /// This function implements the transforms common to both integer division
00776 /// instructions (udiv and sdiv). It is called by the visitors to those integer
00777 /// division instructions.
00778 /// @brief Common integer divide transforms
00779 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
00780   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00781 
00782   // The RHS is known non-zero.
00783   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
00784     I.setOperand(1, V);
00785     return &I;
00786   }
00787 
00788   // Handle cases involving: [su]div X, (select Cond, Y, Z)
00789   // This does not apply for fdiv.
00790   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
00791     return &I;
00792 
00793   if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
00794     const APInt *C2;
00795     if (match(Op1, m_APInt(C2))) {
00796       Value *X;
00797       const APInt *C1;
00798       bool IsSigned = I.getOpcode() == Instruction::SDiv;
00799 
00800       // (X / C1) / C2  -> X / (C1*C2)
00801       if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
00802           (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
00803         APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
00804         if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
00805           return BinaryOperator::Create(I.getOpcode(), X,
00806                                         ConstantInt::get(I.getType(), Product));
00807       }
00808 
00809       if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
00810           (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
00811         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
00812 
00813         // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
00814         if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
00815           BinaryOperator *BO = BinaryOperator::Create(
00816               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
00817           BO->setIsExact(I.isExact());
00818           return BO;
00819         }
00820 
00821         // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
00822         if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
00823           BinaryOperator *BO = BinaryOperator::Create(
00824               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
00825           BO->setHasNoUnsignedWrap(
00826               !IsSigned &&
00827               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
00828           BO->setHasNoSignedWrap(
00829               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
00830           return BO;
00831         }
00832       }
00833 
00834       if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
00835            *C1 != C1->getBitWidth() - 1) ||
00836           (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
00837         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
00838         APInt C1Shifted = APInt::getOneBitSet(
00839             C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
00840 
00841         // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
00842         if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
00843           BinaryOperator *BO = BinaryOperator::Create(
00844               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
00845           BO->setIsExact(I.isExact());
00846           return BO;
00847         }
00848 
00849         // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
00850         if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
00851           BinaryOperator *BO = BinaryOperator::Create(
00852               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
00853           BO->setHasNoUnsignedWrap(
00854               !IsSigned &&
00855               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
00856           BO->setHasNoSignedWrap(
00857               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
00858           return BO;
00859         }
00860       }
00861 
00862       if (*C2 != 0) { // avoid X udiv 0
00863         if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00864           if (Instruction *R = FoldOpIntoSelect(I, SI))
00865             return R;
00866         if (isa<PHINode>(Op0))
00867           if (Instruction *NV = FoldOpIntoPhi(I))
00868             return NV;
00869       }
00870     }
00871   }
00872 
00873   if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
00874     if (One->isOne() && !I.getType()->isIntegerTy(1)) {
00875       bool isSigned = I.getOpcode() == Instruction::SDiv;
00876       if (isSigned) {
00877         // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
00878         // result is one, if Op1 is -1 then the result is minus one, otherwise
00879         // it's zero.
00880         Value *Inc = Builder->CreateAdd(Op1, One);
00881         Value *Cmp = Builder->CreateICmpULT(
00882                          Inc, ConstantInt::get(I.getType(), 3));
00883         return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
00884       } else {
00885         // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
00886         // result is one, otherwise it's zero.
00887         return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
00888       }
00889     }
00890   }
00891 
00892   // See if we can fold away this div instruction.
00893   if (SimplifyDemandedInstructionBits(I))
00894     return &I;
00895 
00896   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
00897   Value *X = nullptr, *Z = nullptr;
00898   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
00899     bool isSigned = I.getOpcode() == Instruction::SDiv;
00900     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
00901         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
00902       return BinaryOperator::Create(I.getOpcode(), X, Op1);
00903   }
00904 
00905   return nullptr;
00906 }
00907 
00908 /// dyn_castZExtVal - Checks if V is a zext or constant that can
00909 /// be truncated to Ty without losing bits.
00910 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
00911   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
00912     if (Z->getSrcTy() == Ty)
00913       return Z->getOperand(0);
00914   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
00915     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
00916       return ConstantExpr::getTrunc(C, Ty);
00917   }
00918   return nullptr;
00919 }
00920 
00921 namespace {
00922 const unsigned MaxDepth = 6;
00923 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
00924                                           const BinaryOperator &I,
00925                                           InstCombiner &IC);
00926 
00927 /// \brief Used to maintain state for visitUDivOperand().
00928 struct UDivFoldAction {
00929   FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
00930                                 ///< operand.  This can be zero if this action
00931                                 ///< joins two actions together.
00932 
00933   Value *OperandToFold;         ///< Which operand to fold.
00934   union {
00935     Instruction *FoldResult;    ///< The instruction returned when FoldAction is
00936                                 ///< invoked.
00937 
00938     size_t SelectLHSIdx;        ///< Stores the LHS action index if this action
00939                                 ///< joins two actions together.
00940   };
00941 
00942   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
00943       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
00944   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
00945       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
00946 };
00947 }
00948 
00949 // X udiv 2^C -> X >> C
00950 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
00951                                     const BinaryOperator &I, InstCombiner &IC) {
00952   const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
00953   BinaryOperator *LShr = BinaryOperator::CreateLShr(
00954       Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
00955   if (I.isExact())
00956     LShr->setIsExact();
00957   return LShr;
00958 }
00959 
00960 // X udiv C, where C >= signbit
00961 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
00962                                    const BinaryOperator &I, InstCombiner &IC) {
00963   Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
00964 
00965   return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
00966                             ConstantInt::get(I.getType(), 1));
00967 }
00968 
00969 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
00970 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
00971                                 InstCombiner &IC) {
00972   Instruction *ShiftLeft = cast<Instruction>(Op1);
00973   if (isa<ZExtInst>(ShiftLeft))
00974     ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
00975 
00976   const APInt &CI =
00977       cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
00978   Value *N = ShiftLeft->getOperand(1);
00979   if (CI != 1)
00980     N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
00981   if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
00982     N = IC.Builder->CreateZExt(N, Z->getDestTy());
00983   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
00984   if (I.isExact())
00985     LShr->setIsExact();
00986   return LShr;
00987 }
00988 
00989 // \brief Recursively visits the possible right hand operands of a udiv
00990 // instruction, seeing through select instructions, to determine if we can
00991 // replace the udiv with something simpler.  If we find that an operand is not
00992 // able to simplify the udiv, we abort the entire transformation.
00993 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
00994                                SmallVectorImpl<UDivFoldAction> &Actions,
00995                                unsigned Depth = 0) {
00996   // Check to see if this is an unsigned division with an exact power of 2,
00997   // if so, convert to a right shift.
00998   if (match(Op1, m_Power2())) {
00999     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
01000     return Actions.size();
01001   }
01002 
01003   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
01004     // X udiv C, where C >= signbit
01005     if (C->getValue().isNegative()) {
01006       Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
01007       return Actions.size();
01008     }
01009 
01010   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
01011   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
01012       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
01013     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
01014     return Actions.size();
01015   }
01016 
01017   // The remaining tests are all recursive, so bail out if we hit the limit.
01018   if (Depth++ == MaxDepth)
01019     return 0;
01020 
01021   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
01022     if (size_t LHSIdx =
01023             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
01024       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
01025         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
01026         return Actions.size();
01027       }
01028 
01029   return 0;
01030 }
01031 
01032 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
01033   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01034 
01035   if (Value *V = SimplifyVectorOp(I))
01036     return ReplaceInstUsesWith(I, V);
01037 
01038   if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AC))
01039     return ReplaceInstUsesWith(I, V);
01040 
01041   // Handle the integer div common cases
01042   if (Instruction *Common = commonIDivTransforms(I))
01043     return Common;
01044 
01045   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
01046   {
01047     Value *X;
01048     const APInt *C1, *C2;
01049     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
01050         match(Op1, m_APInt(C2))) {
01051       bool Overflow;
01052       APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
01053       if (!Overflow) {
01054         bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
01055         BinaryOperator *BO = BinaryOperator::CreateUDiv(
01056             X, ConstantInt::get(X->getType(), C2ShlC1));
01057         if (IsExact)
01058           BO->setIsExact();
01059         return BO;
01060       }
01061     }
01062   }
01063 
01064   // (zext A) udiv (zext B) --> zext (A udiv B)
01065   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
01066     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
01067       return new ZExtInst(
01068           Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
01069           I.getType());
01070 
01071   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
01072   SmallVector<UDivFoldAction, 6> UDivActions;
01073   if (visitUDivOperand(Op0, Op1, I, UDivActions))
01074     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
01075       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
01076       Value *ActionOp1 = UDivActions[i].OperandToFold;
01077       Instruction *Inst;
01078       if (Action)
01079         Inst = Action(Op0, ActionOp1, I, *this);
01080       else {
01081         // This action joins two actions together.  The RHS of this action is
01082         // simply the last action we processed, we saved the LHS action index in
01083         // the joining action.
01084         size_t SelectRHSIdx = i - 1;
01085         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
01086         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
01087         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
01088         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
01089                                   SelectLHS, SelectRHS);
01090       }
01091 
01092       // If this is the last action to process, return it to the InstCombiner.
01093       // Otherwise, we insert it before the UDiv and record it so that we may
01094       // use it as part of a joining action (i.e., a SelectInst).
01095       if (e - i != 1) {
01096         Inst->insertBefore(&I);
01097         UDivActions[i].FoldResult = Inst;
01098       } else
01099         return Inst;
01100     }
01101 
01102   return nullptr;
01103 }
01104 
01105 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
01106   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01107 
01108   if (Value *V = SimplifyVectorOp(I))
01109     return ReplaceInstUsesWith(I, V);
01110 
01111   if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AC))
01112     return ReplaceInstUsesWith(I, V);
01113 
01114   // Handle the integer div common cases
01115   if (Instruction *Common = commonIDivTransforms(I))
01116     return Common;
01117 
01118   // sdiv X, -1 == -X
01119   if (match(Op1, m_AllOnes()))
01120     return BinaryOperator::CreateNeg(Op0);
01121 
01122   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
01123     // sdiv X, C  -->  ashr exact X, log2(C)
01124     if (I.isExact() && RHS->getValue().isNonNegative() &&
01125         RHS->getValue().isPowerOf2()) {
01126       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
01127                                             RHS->getValue().exactLogBase2());
01128       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
01129     }
01130   }
01131 
01132   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
01133     // X/INT_MIN -> X == INT_MIN
01134     if (RHS->isMinSignedValue())
01135       return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
01136 
01137     // -X/C  -->  X/-C  provided the negation doesn't overflow.
01138     Value *X;
01139     if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
01140       auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
01141       BO->setIsExact(I.isExact());
01142       return BO;
01143     }
01144   }
01145 
01146   // If the sign bits of both operands are zero (i.e. we can prove they are
01147   // unsigned inputs), turn this into a udiv.
01148   if (I.getType()->isIntegerTy()) {
01149     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
01150     if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
01151       if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
01152         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
01153         auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
01154         BO->setIsExact(I.isExact());
01155         return BO;
01156       }
01157 
01158       if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
01159         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
01160         // Safe because the only negative value (1 << Y) can take on is
01161         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
01162         // the sign bit set.
01163         auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
01164         BO->setIsExact(I.isExact());
01165         return BO;
01166       }
01167     }
01168   }
01169 
01170   return nullptr;
01171 }
01172 
01173 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
01174 /// FP value and:
01175 ///    1) 1/C is exact, or
01176 ///    2) reciprocal is allowed.
01177 /// If the conversion was successful, the simplified expression "X * 1/C" is
01178 /// returned; otherwise, NULL is returned.
01179 ///
01180 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
01181                                              bool AllowReciprocal) {
01182   if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
01183     return nullptr;
01184 
01185   const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
01186   APFloat Reciprocal(FpVal.getSemantics());
01187   bool Cvt = FpVal.getExactInverse(&Reciprocal);
01188 
01189   if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
01190     Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
01191     (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
01192     Cvt = !Reciprocal.isDenormal();
01193   }
01194 
01195   if (!Cvt)
01196     return nullptr;
01197 
01198   ConstantFP *R;
01199   R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
01200   return BinaryOperator::CreateFMul(Dividend, R);
01201 }
01202 
01203 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
01204   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01205 
01206   if (Value *V = SimplifyVectorOp(I))
01207     return ReplaceInstUsesWith(I, V);
01208 
01209   if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
01210                                   DL, TLI, DT, AC))
01211     return ReplaceInstUsesWith(I, V);
01212 
01213   if (isa<Constant>(Op0))
01214     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
01215       if (Instruction *R = FoldOpIntoSelect(I, SI))
01216         return R;
01217 
01218   bool AllowReassociate = I.hasUnsafeAlgebra();
01219   bool AllowReciprocal = I.hasAllowReciprocal();
01220 
01221   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
01222     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
01223       if (Instruction *R = FoldOpIntoSelect(I, SI))
01224         return R;
01225 
01226     if (AllowReassociate) {
01227       Constant *C1 = nullptr;
01228       Constant *C2 = Op1C;
01229       Value *X;
01230       Instruction *Res = nullptr;
01231 
01232       if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
01233         // (X*C1)/C2 => X * (C1/C2)
01234         //
01235         Constant *C = ConstantExpr::getFDiv(C1, C2);
01236         if (isNormalFp(C))
01237           Res = BinaryOperator::CreateFMul(X, C);
01238       } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
01239         // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
01240         //
01241         Constant *C = ConstantExpr::getFMul(C1, C2);
01242         if (isNormalFp(C)) {
01243           Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
01244           if (!Res)
01245             Res = BinaryOperator::CreateFDiv(X, C);
01246         }
01247       }
01248 
01249       if (Res) {
01250         Res->setFastMathFlags(I.getFastMathFlags());
01251         return Res;
01252       }
01253     }
01254 
01255     // X / C => X * 1/C
01256     if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
01257       T->copyFastMathFlags(&I);
01258       return T;
01259     }
01260 
01261     return nullptr;
01262   }
01263 
01264   if (AllowReassociate && isa<Constant>(Op0)) {
01265     Constant *C1 = cast<Constant>(Op0), *C2;
01266     Constant *Fold = nullptr;
01267     Value *X;
01268     bool CreateDiv = true;
01269 
01270     // C1 / (X*C2) => (C1/C2) / X
01271     if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
01272       Fold = ConstantExpr::getFDiv(C1, C2);
01273     else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
01274       // C1 / (X/C2) => (C1*C2) / X
01275       Fold = ConstantExpr::getFMul(C1, C2);
01276     } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
01277       // C1 / (C2/X) => (C1/C2) * X
01278       Fold = ConstantExpr::getFDiv(C1, C2);
01279       CreateDiv = false;
01280     }
01281 
01282     if (Fold && isNormalFp(Fold)) {
01283       Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
01284                                  : BinaryOperator::CreateFMul(X, Fold);
01285       R->setFastMathFlags(I.getFastMathFlags());
01286       return R;
01287     }
01288     return nullptr;
01289   }
01290 
01291   if (AllowReassociate) {
01292     Value *X, *Y;
01293     Value *NewInst = nullptr;
01294     Instruction *SimpR = nullptr;
01295 
01296     if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
01297       // (X/Y) / Z => X / (Y*Z)
01298       //
01299       if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
01300         NewInst = Builder->CreateFMul(Y, Op1);
01301         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
01302           FastMathFlags Flags = I.getFastMathFlags();
01303           Flags &= cast<Instruction>(Op0)->getFastMathFlags();
01304           RI->setFastMathFlags(Flags);
01305         }
01306         SimpR = BinaryOperator::CreateFDiv(X, NewInst);
01307       }
01308     } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
01309       // Z / (X/Y) => Z*Y / X
01310       //
01311       if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
01312         NewInst = Builder->CreateFMul(Op0, Y);
01313         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
01314           FastMathFlags Flags = I.getFastMathFlags();
01315           Flags &= cast<Instruction>(Op1)->getFastMathFlags();
01316           RI->setFastMathFlags(Flags);
01317         }
01318         SimpR = BinaryOperator::CreateFDiv(NewInst, X);
01319       }
01320     }
01321 
01322     if (NewInst) {
01323       if (Instruction *T = dyn_cast<Instruction>(NewInst))
01324         T->setDebugLoc(I.getDebugLoc());
01325       SimpR->setFastMathFlags(I.getFastMathFlags());
01326       return SimpR;
01327     }
01328   }
01329 
01330   return nullptr;
01331 }
01332 
01333 /// This function implements the transforms common to both integer remainder
01334 /// instructions (urem and srem). It is called by the visitors to those integer
01335 /// remainder instructions.
01336 /// @brief Common integer remainder transforms
01337 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
01338   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01339 
01340   // The RHS is known non-zero.
01341   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
01342     I.setOperand(1, V);
01343     return &I;
01344   }
01345 
01346   // Handle cases involving: rem X, (select Cond, Y, Z)
01347   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
01348     return &I;
01349 
01350   if (isa<Constant>(Op1)) {
01351     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
01352       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
01353         if (Instruction *R = FoldOpIntoSelect(I, SI))
01354           return R;
01355       } else if (isa<PHINode>(Op0I)) {
01356         if (Instruction *NV = FoldOpIntoPhi(I))
01357           return NV;
01358       }
01359 
01360       // See if we can fold away this rem instruction.
01361       if (SimplifyDemandedInstructionBits(I))
01362         return &I;
01363     }
01364   }
01365 
01366   return nullptr;
01367 }
01368 
01369 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
01370   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01371 
01372   if (Value *V = SimplifyVectorOp(I))
01373     return ReplaceInstUsesWith(I, V);
01374 
01375   if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AC))
01376     return ReplaceInstUsesWith(I, V);
01377 
01378   if (Instruction *common = commonIRemTransforms(I))
01379     return common;
01380 
01381   // (zext A) urem (zext B) --> zext (A urem B)
01382   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
01383     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
01384       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
01385                           I.getType());
01386 
01387   // X urem Y -> X and Y-1, where Y is a power of 2,
01388   if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
01389     Constant *N1 = Constant::getAllOnesValue(I.getType());
01390     Value *Add = Builder->CreateAdd(Op1, N1);
01391     return BinaryOperator::CreateAnd(Op0, Add);
01392   }
01393 
01394   // 1 urem X -> zext(X != 1)
01395   if (match(Op0, m_One())) {
01396     Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
01397     Value *Ext = Builder->CreateZExt(Cmp, I.getType());
01398     return ReplaceInstUsesWith(I, Ext);
01399   }
01400 
01401   return nullptr;
01402 }
01403 
01404 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
01405   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01406 
01407   if (Value *V = SimplifyVectorOp(I))
01408     return ReplaceInstUsesWith(I, V);
01409 
01410   if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AC))
01411     return ReplaceInstUsesWith(I, V);
01412 
01413   // Handle the integer rem common cases
01414   if (Instruction *Common = commonIRemTransforms(I))
01415     return Common;
01416 
01417   {
01418     const APInt *Y;
01419     // X % -Y -> X % Y
01420     if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
01421       Worklist.AddValue(I.getOperand(1));
01422       I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
01423       return &I;
01424     }
01425   }
01426 
01427   // If the sign bits of both operands are zero (i.e. we can prove they are
01428   // unsigned inputs), turn this into a urem.
01429   if (I.getType()->isIntegerTy()) {
01430     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
01431     if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
01432         MaskedValueIsZero(Op0, Mask, 0, &I)) {
01433       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
01434       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
01435     }
01436   }
01437 
01438   // If it's a constant vector, flip any negative values positive.
01439   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
01440     Constant *C = cast<Constant>(Op1);
01441     unsigned VWidth = C->getType()->getVectorNumElements();
01442 
01443     bool hasNegative = false;
01444     bool hasMissing = false;
01445     for (unsigned i = 0; i != VWidth; ++i) {
01446       Constant *Elt = C->getAggregateElement(i);
01447       if (!Elt) {
01448         hasMissing = true;
01449         break;
01450       }
01451 
01452       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
01453         if (RHS->isNegative())
01454           hasNegative = true;
01455     }
01456 
01457     if (hasNegative && !hasMissing) {
01458       SmallVector<Constant *, 16> Elts(VWidth);
01459       for (unsigned i = 0; i != VWidth; ++i) {
01460         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
01461         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
01462           if (RHS->isNegative())
01463             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
01464         }
01465       }
01466 
01467       Constant *NewRHSV = ConstantVector::get(Elts);
01468       if (NewRHSV != C) {  // Don't loop on -MININT
01469         Worklist.AddValue(I.getOperand(1));
01470         I.setOperand(1, NewRHSV);
01471         return &I;
01472       }
01473     }
01474   }
01475 
01476   return nullptr;
01477 }
01478 
01479 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
01480   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01481 
01482   if (Value *V = SimplifyVectorOp(I))
01483     return ReplaceInstUsesWith(I, V);
01484 
01485   if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
01486                                   DL, TLI, DT, AC))
01487     return ReplaceInstUsesWith(I, V);
01488 
01489   // Handle cases involving: rem X, (select Cond, Y, Z)
01490   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
01491     return &I;
01492 
01493   return nullptr;
01494 }