LLVM API Documentation

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