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