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