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