1202375Srdivacky//===- InstCombineMulDivRem.cpp -------------------------------------------===// 2202375Srdivacky// 3202375Srdivacky// The LLVM Compiler Infrastructure 4202375Srdivacky// 5202375Srdivacky// This file is distributed under the University of Illinois Open Source 6202375Srdivacky// License. See LICENSE.TXT for details. 7202375Srdivacky// 8202375Srdivacky//===----------------------------------------------------------------------===// 9202375Srdivacky// 10202375Srdivacky// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv, 11202375Srdivacky// srem, urem, frem. 12202375Srdivacky// 13202375Srdivacky//===----------------------------------------------------------------------===// 14202375Srdivacky 15202375Srdivacky#include "InstCombine.h" 16218893Sdim#include "llvm/Analysis/InstructionSimplify.h" 17249423Sdim#include "llvm/IR/IntrinsicInst.h" 18202375Srdivacky#include "llvm/Support/PatternMatch.h" 19202375Srdivackyusing namespace llvm; 20202375Srdivackyusing namespace PatternMatch; 21202375Srdivacky 22223017Sdim 23223017Sdim/// simplifyValueKnownNonZero - The specific integer value is used in a context 24223017Sdim/// where it is known to be non-zero. If this allows us to simplify the 25223017Sdim/// computation, do so and return the new operand, otherwise return null. 26223017Sdimstatic Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) { 27223017Sdim // If V has multiple uses, then we would have to do more analysis to determine 28223017Sdim // if this is safe. For example, the use could be in dynamically unreached 29223017Sdim // code. 30223017Sdim if (!V->hasOneUse()) return 0; 31251662Sdim 32223017Sdim bool MadeChange = false; 33223017Sdim 34223017Sdim // ((1 << A) >>u B) --> (1 << (A-B)) 35223017Sdim // Because V cannot be zero, we know that B is less than A. 36223017Sdim Value *A = 0, *B = 0, *PowerOf2 = 0; 37223017Sdim if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))), 38223017Sdim m_Value(B))) && 39223017Sdim // The "1" can be any value known to be a power of 2. 40249423Sdim isKnownToBeAPowerOfTwo(PowerOf2)) { 41226633Sdim A = IC.Builder->CreateSub(A, B); 42223017Sdim return IC.Builder->CreateShl(PowerOf2, A); 43223017Sdim } 44251662Sdim 45223017Sdim // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it 46223017Sdim // inexact. Similarly for <<. 47223017Sdim if (BinaryOperator *I = dyn_cast<BinaryOperator>(V)) 48249423Sdim if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) { 49223017Sdim // We know that this is an exact/nuw shift and that the input is a 50223017Sdim // non-zero context as well. 51223017Sdim if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) { 52223017Sdim I->setOperand(0, V2); 53223017Sdim MadeChange = true; 54223017Sdim } 55251662Sdim 56223017Sdim if (I->getOpcode() == Instruction::LShr && !I->isExact()) { 57223017Sdim I->setIsExact(); 58223017Sdim MadeChange = true; 59223017Sdim } 60251662Sdim 61223017Sdim if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) { 62223017Sdim I->setHasNoUnsignedWrap(); 63223017Sdim MadeChange = true; 64223017Sdim } 65223017Sdim } 66223017Sdim 67223017Sdim // TODO: Lots more we could do here: 68223017Sdim // If V is a phi node, we can call this on each of its operands. 69223017Sdim // "select cond, X, 0" can simplify to "X". 70251662Sdim 71223017Sdim return MadeChange ? V : 0; 72223017Sdim} 73223017Sdim 74223017Sdim 75202375Srdivacky/// MultiplyOverflows - True if the multiply can not be expressed in an int 76202375Srdivacky/// this size. 77202375Srdivackystatic bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) { 78202375Srdivacky uint32_t W = C1->getBitWidth(); 79202375Srdivacky APInt LHSExt = C1->getValue(), RHSExt = C2->getValue(); 80202375Srdivacky if (sign) { 81218893Sdim LHSExt = LHSExt.sext(W * 2); 82218893Sdim RHSExt = RHSExt.sext(W * 2); 83202375Srdivacky } else { 84218893Sdim LHSExt = LHSExt.zext(W * 2); 85218893Sdim RHSExt = RHSExt.zext(W * 2); 86202375Srdivacky } 87251662Sdim 88202375Srdivacky APInt MulExt = LHSExt * RHSExt; 89251662Sdim 90202375Srdivacky if (!sign) 91202375Srdivacky return MulExt.ugt(APInt::getLowBitsSet(W * 2, W)); 92251662Sdim 93202375Srdivacky APInt Min = APInt::getSignedMinValue(W).sext(W * 2); 94202375Srdivacky APInt Max = APInt::getSignedMaxValue(W).sext(W * 2); 95202375Srdivacky return MulExt.slt(Min) || MulExt.sgt(Max); 96202375Srdivacky} 97202375Srdivacky 98263508Sdim/// \brief A helper routine of InstCombiner::visitMul(). 99263508Sdim/// 100263508Sdim/// If C is a vector of known powers of 2, then this function returns 101263508Sdim/// a new vector obtained from C replacing each element with its logBase2. 102263508Sdim/// Return a null pointer otherwise. 103263508Sdimstatic Constant *getLogBase2Vector(ConstantDataVector *CV) { 104263508Sdim const APInt *IVal; 105263508Sdim SmallVector<Constant *, 4> Elts; 106263508Sdim 107263508Sdim for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) { 108263508Sdim Constant *Elt = CV->getElementAsConstant(I); 109263508Sdim if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2()) 110263508Sdim return 0; 111263508Sdim Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2())); 112263508Sdim } 113263508Sdim 114263508Sdim return ConstantVector::get(Elts); 115263508Sdim} 116263508Sdim 117202375SrdivackyInstruction *InstCombiner::visitMul(BinaryOperator &I) { 118218893Sdim bool Changed = SimplifyAssociativeOrCommutative(I); 119202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 120202375Srdivacky 121218893Sdim if (Value *V = SimplifyMulInst(Op0, Op1, TD)) 122218893Sdim return ReplaceInstUsesWith(I, V); 123202375Srdivacky 124218893Sdim if (Value *V = SimplifyUsingDistributiveLaws(I)) 125218893Sdim return ReplaceInstUsesWith(I, V); 126202375Srdivacky 127218893Sdim if (match(Op1, m_AllOnes())) // X * -1 == 0 - X 128218893Sdim return BinaryOperator::CreateNeg(Op0, I.getName()); 129251662Sdim 130263508Sdim // Also allow combining multiply instructions on vectors. 131263508Sdim { 132263508Sdim Value *NewOp; 133263508Sdim Constant *C1, *C2; 134263508Sdim const APInt *IVal; 135263508Sdim if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)), 136263508Sdim m_Constant(C1))) && 137263508Sdim match(C1, m_APInt(IVal))) 138263508Sdim // ((X << C1)*C2) == (X * (C2 << C1)) 139263508Sdim return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2)); 140251662Sdim 141263508Sdim if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) { 142263508Sdim Constant *NewCst = 0; 143263508Sdim if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2()) 144263508Sdim // Replace X*(2^C) with X << C, where C is either a scalar or a splat. 145263508Sdim NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2()); 146263508Sdim else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1)) 147263508Sdim // Replace X*(2^C) with X << C, where C is a vector of known 148263508Sdim // constant powers of 2. 149263508Sdim NewCst = getLogBase2Vector(CV); 150251662Sdim 151263508Sdim if (NewCst) { 152263508Sdim BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst); 153263508Sdim if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap(); 154263508Sdim if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap(); 155263508Sdim return Shl; 156263508Sdim } 157202375Srdivacky } 158263508Sdim } 159251662Sdim 160263508Sdim if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 161218893Sdim // Canonicalize (X+C1)*CI -> X*CI+C1*CI. 162218893Sdim { Value *X; ConstantInt *C1; 163218893Sdim if (Op0->hasOneUse() && 164218893Sdim match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) { 165226633Sdim Value *Add = Builder->CreateMul(X, CI); 166218893Sdim return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI)); 167202375Srdivacky } 168218893Sdim } 169223017Sdim 170223017Sdim // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n 171223017Sdim // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n 172223017Sdim // The "* (2**n)" thus becomes a potential shifting opportunity. 173223017Sdim { 174223017Sdim const APInt & Val = CI->getValue(); 175223017Sdim const APInt &PosVal = Val.abs(); 176223017Sdim if (Val.isNegative() && PosVal.isPowerOf2()) { 177223017Sdim Value *X = 0, *Y = 0; 178223017Sdim if (Op0->hasOneUse()) { 179223017Sdim ConstantInt *C1; 180223017Sdim Value *Sub = 0; 181223017Sdim if (match(Op0, m_Sub(m_Value(Y), m_Value(X)))) 182223017Sdim Sub = Builder->CreateSub(X, Y, "suba"); 183223017Sdim else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1)))) 184223017Sdim Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc"); 185223017Sdim if (Sub) 186223017Sdim return 187223017Sdim BinaryOperator::CreateMul(Sub, 188223017Sdim ConstantInt::get(Y->getType(), PosVal)); 189223017Sdim } 190223017Sdim } 191223017Sdim } 192218893Sdim } 193251662Sdim 194218893Sdim // Simplify mul instructions with a constant RHS. 195251662Sdim if (isa<Constant>(Op1)) { 196202375Srdivacky // Try to fold constant mul into select arguments. 197202375Srdivacky if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 198202375Srdivacky if (Instruction *R = FoldOpIntoSelect(I, SI)) 199202375Srdivacky return R; 200202375Srdivacky 201202375Srdivacky if (isa<PHINode>(Op0)) 202202375Srdivacky if (Instruction *NV = FoldOpIntoPhi(I)) 203202375Srdivacky return NV; 204202375Srdivacky } 205202375Srdivacky 206202375Srdivacky if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y 207202375Srdivacky if (Value *Op1v = dyn_castNegVal(Op1)) 208202375Srdivacky return BinaryOperator::CreateMul(Op0v, Op1v); 209202375Srdivacky 210202375Srdivacky // (X / Y) * Y = X - (X % Y) 211202375Srdivacky // (X / Y) * -Y = (X % Y) - X 212202375Srdivacky { 213202375Srdivacky Value *Op1C = Op1; 214202375Srdivacky BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0); 215202375Srdivacky if (!BO || 216251662Sdim (BO->getOpcode() != Instruction::UDiv && 217202375Srdivacky BO->getOpcode() != Instruction::SDiv)) { 218202375Srdivacky Op1C = Op0; 219202375Srdivacky BO = dyn_cast<BinaryOperator>(Op1); 220202375Srdivacky } 221202375Srdivacky Value *Neg = dyn_castNegVal(Op1C); 222202375Srdivacky if (BO && BO->hasOneUse() && 223202375Srdivacky (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) && 224202375Srdivacky (BO->getOpcode() == Instruction::UDiv || 225202375Srdivacky BO->getOpcode() == Instruction::SDiv)) { 226202375Srdivacky Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1); 227202375Srdivacky 228218893Sdim // If the division is exact, X % Y is zero, so we end up with X or -X. 229218893Sdim if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO)) 230202375Srdivacky if (SDiv->isExact()) { 231202375Srdivacky if (Op1BO == Op1C) 232202375Srdivacky return ReplaceInstUsesWith(I, Op0BO); 233202375Srdivacky return BinaryOperator::CreateNeg(Op0BO); 234202375Srdivacky } 235202375Srdivacky 236202375Srdivacky Value *Rem; 237202375Srdivacky if (BO->getOpcode() == Instruction::UDiv) 238202375Srdivacky Rem = Builder->CreateURem(Op0BO, Op1BO); 239202375Srdivacky else 240202375Srdivacky Rem = Builder->CreateSRem(Op0BO, Op1BO); 241202375Srdivacky Rem->takeName(BO); 242202375Srdivacky 243202375Srdivacky if (Op1BO == Op1C) 244202375Srdivacky return BinaryOperator::CreateSub(Op0BO, Rem); 245202375Srdivacky return BinaryOperator::CreateSub(Rem, Op0BO); 246202375Srdivacky } 247202375Srdivacky } 248202375Srdivacky 249202375Srdivacky /// i1 mul -> i1 and. 250203954Srdivacky if (I.getType()->isIntegerTy(1)) 251202375Srdivacky return BinaryOperator::CreateAnd(Op0, Op1); 252202375Srdivacky 253202375Srdivacky // X*(1 << Y) --> X << Y 254202375Srdivacky // (1 << Y)*X --> X << Y 255202375Srdivacky { 256202375Srdivacky Value *Y; 257202375Srdivacky if (match(Op0, m_Shl(m_One(), m_Value(Y)))) 258202375Srdivacky return BinaryOperator::CreateShl(Op1, Y); 259202375Srdivacky if (match(Op1, m_Shl(m_One(), m_Value(Y)))) 260202375Srdivacky return BinaryOperator::CreateShl(Op0, Y); 261202375Srdivacky } 262251662Sdim 263202375Srdivacky // If one of the operands of the multiply is a cast from a boolean value, then 264202375Srdivacky // we know the bool is either zero or one, so this is a 'masking' multiply. 265202375Srdivacky // X * Y (where Y is 0 or 1) -> X & (0-Y) 266204642Srdivacky if (!I.getType()->isVectorTy()) { 267202375Srdivacky // -2 is "-1 << 1" so it is all bits set except the low one. 268202375Srdivacky APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true); 269251662Sdim 270202375Srdivacky Value *BoolCast = 0, *OtherOp = 0; 271202375Srdivacky if (MaskedValueIsZero(Op0, Negative2)) 272202375Srdivacky BoolCast = Op0, OtherOp = Op1; 273202375Srdivacky else if (MaskedValueIsZero(Op1, Negative2)) 274202375Srdivacky BoolCast = Op1, OtherOp = Op0; 275202375Srdivacky 276202375Srdivacky if (BoolCast) { 277202375Srdivacky Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()), 278226633Sdim BoolCast); 279202375Srdivacky return BinaryOperator::CreateAnd(V, OtherOp); 280202375Srdivacky } 281202375Srdivacky } 282202375Srdivacky 283202375Srdivacky return Changed ? &I : 0; 284202375Srdivacky} 285202375Srdivacky 286249423Sdim// 287249423Sdim// Detect pattern: 288249423Sdim// 289249423Sdim// log2(Y*0.5) 290249423Sdim// 291249423Sdim// And check for corresponding fast math flags 292249423Sdim// 293249423Sdim 294249423Sdimstatic void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) { 295249423Sdim 296249423Sdim if (!Op->hasOneUse()) 297249423Sdim return; 298249423Sdim 299249423Sdim IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op); 300249423Sdim if (!II) 301249423Sdim return; 302249423Sdim if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra()) 303249423Sdim return; 304249423Sdim Log2 = II; 305249423Sdim 306249423Sdim Value *OpLog2Of = II->getArgOperand(0); 307249423Sdim if (!OpLog2Of->hasOneUse()) 308249423Sdim return; 309249423Sdim 310249423Sdim Instruction *I = dyn_cast<Instruction>(OpLog2Of); 311249423Sdim if (!I) 312249423Sdim return; 313249423Sdim if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra()) 314249423Sdim return; 315251662Sdim 316249423Sdim ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0)); 317249423Sdim if (CFP && CFP->isExactlyValue(0.5)) { 318249423Sdim Y = I->getOperand(1); 319249423Sdim return; 320249423Sdim } 321249423Sdim CFP = dyn_cast<ConstantFP>(I->getOperand(1)); 322249423Sdim if (CFP && CFP->isExactlyValue(0.5)) 323249423Sdim Y = I->getOperand(0); 324251662Sdim} 325249423Sdim 326249423Sdim/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns 327249423Sdim/// true iff the given value is FMul or FDiv with one and only one operand 328249423Sdim/// being a normal constant (i.e. not Zero/NaN/Infinity). 329249423Sdimstatic bool isFMulOrFDivWithConstant(Value *V) { 330249423Sdim Instruction *I = dyn_cast<Instruction>(V); 331251662Sdim if (!I || (I->getOpcode() != Instruction::FMul && 332249423Sdim I->getOpcode() != Instruction::FDiv)) 333249423Sdim return false; 334249423Sdim 335249423Sdim ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0)); 336249423Sdim ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1)); 337249423Sdim 338249423Sdim if (C0 && C1) 339249423Sdim return false; 340249423Sdim 341263508Sdim return (C0 && C0->getValueAPF().isFiniteNonZero()) || 342263508Sdim (C1 && C1->getValueAPF().isFiniteNonZero()); 343249423Sdim} 344249423Sdim 345249423Sdimstatic bool isNormalFp(const ConstantFP *C) { 346249423Sdim const APFloat &Flt = C->getValueAPF(); 347263508Sdim return Flt.isNormal(); 348249423Sdim} 349249423Sdim 350249423Sdim/// foldFMulConst() is a helper routine of InstCombiner::visitFMul(). 351249423Sdim/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand 352249423Sdim/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true). 353251662Sdim/// This function is to simplify "FMulOrDiv * C" and returns the 354249423Sdim/// resulting expression. Note that this function could return NULL in 355249423Sdim/// case the constants cannot be folded into a normal floating-point. 356251662Sdim/// 357249423SdimValue *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, ConstantFP *C, 358249423Sdim Instruction *InsertBefore) { 359249423Sdim assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid"); 360249423Sdim 361249423Sdim Value *Opnd0 = FMulOrDiv->getOperand(0); 362249423Sdim Value *Opnd1 = FMulOrDiv->getOperand(1); 363249423Sdim 364249423Sdim ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0); 365249423Sdim ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1); 366249423Sdim 367249423Sdim BinaryOperator *R = 0; 368249423Sdim 369249423Sdim // (X * C0) * C => X * (C0*C) 370249423Sdim if (FMulOrDiv->getOpcode() == Instruction::FMul) { 371249423Sdim Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C); 372249423Sdim if (isNormalFp(cast<ConstantFP>(F))) 373249423Sdim R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F); 374249423Sdim } else { 375249423Sdim if (C0) { 376249423Sdim // (C0 / X) * C => (C0 * C) / X 377263508Sdim if (FMulOrDiv->hasOneUse()) { 378263508Sdim // It would otherwise introduce another div. 379263508Sdim ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C)); 380263508Sdim if (isNormalFp(F)) 381263508Sdim R = BinaryOperator::CreateFDiv(F, Opnd1); 382263508Sdim } 383249423Sdim } else { 384249423Sdim // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal 385249423Sdim ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1)); 386249423Sdim if (isNormalFp(F)) { 387249423Sdim R = BinaryOperator::CreateFMul(Opnd0, F); 388249423Sdim } else { 389251662Sdim // (X / C1) * C => X / (C1/C) 390249423Sdim Constant *F = ConstantExpr::getFDiv(C1, C); 391249423Sdim if (isNormalFp(cast<ConstantFP>(F))) 392249423Sdim R = BinaryOperator::CreateFDiv(Opnd0, F); 393249423Sdim } 394249423Sdim } 395249423Sdim } 396249423Sdim 397249423Sdim if (R) { 398249423Sdim R->setHasUnsafeAlgebra(true); 399249423Sdim InsertNewInstWith(R, *InsertBefore); 400249423Sdim } 401249423Sdim 402249423Sdim return R; 403249423Sdim} 404249423Sdim 405202375SrdivackyInstruction *InstCombiner::visitFMul(BinaryOperator &I) { 406218893Sdim bool Changed = SimplifyAssociativeOrCommutative(I); 407202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 408202375Srdivacky 409249423Sdim if (isa<Constant>(Op0)) 410249423Sdim std::swap(Op0, Op1); 411249423Sdim 412249423Sdim if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD)) 413249423Sdim return ReplaceInstUsesWith(I, V); 414249423Sdim 415249423Sdim bool AllowReassociate = I.hasUnsafeAlgebra(); 416249423Sdim 417234353Sdim // Simplify mul instructions with a constant RHS. 418249423Sdim if (isa<Constant>(Op1)) { 419202375Srdivacky // Try to fold constant mul into select arguments. 420202375Srdivacky if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 421202375Srdivacky if (Instruction *R = FoldOpIntoSelect(I, SI)) 422202375Srdivacky return R; 423202375Srdivacky 424202375Srdivacky if (isa<PHINode>(Op0)) 425202375Srdivacky if (Instruction *NV = FoldOpIntoPhi(I)) 426202375Srdivacky return NV; 427249423Sdim 428249423Sdim ConstantFP *C = dyn_cast<ConstantFP>(Op1); 429263508Sdim if (C && AllowReassociate && C->getValueAPF().isFiniteNonZero()) { 430249423Sdim // Let MDC denote an expression in one of these forms: 431249423Sdim // X * C, C/X, X/C, where C is a constant. 432249423Sdim // 433249423Sdim // Try to simplify "MDC * Constant" 434249423Sdim if (isFMulOrFDivWithConstant(Op0)) { 435249423Sdim Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I); 436249423Sdim if (V) 437249423Sdim return ReplaceInstUsesWith(I, V); 438249423Sdim } 439249423Sdim 440249423Sdim // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C) 441249423Sdim Instruction *FAddSub = dyn_cast<Instruction>(Op0); 442249423Sdim if (FAddSub && 443249423Sdim (FAddSub->getOpcode() == Instruction::FAdd || 444249423Sdim FAddSub->getOpcode() == Instruction::FSub)) { 445249423Sdim Value *Opnd0 = FAddSub->getOperand(0); 446249423Sdim Value *Opnd1 = FAddSub->getOperand(1); 447249423Sdim ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0); 448249423Sdim ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1); 449249423Sdim bool Swap = false; 450249423Sdim if (C0) { 451249423Sdim std::swap(C0, C1); 452249423Sdim std::swap(Opnd0, Opnd1); 453251662Sdim Swap = true; 454249423Sdim } 455249423Sdim 456263508Sdim if (C1 && C1->getValueAPF().isFiniteNonZero() && 457249423Sdim isFMulOrFDivWithConstant(Opnd0)) { 458249423Sdim Value *M1 = ConstantExpr::getFMul(C1, C); 459251662Sdim Value *M0 = isNormalFp(cast<ConstantFP>(M1)) ? 460249423Sdim foldFMulConst(cast<Instruction>(Opnd0), C, &I) : 461249423Sdim 0; 462249423Sdim if (M0 && M1) { 463249423Sdim if (Swap && FAddSub->getOpcode() == Instruction::FSub) 464249423Sdim std::swap(M0, M1); 465249423Sdim 466263508Sdim Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd) 467263508Sdim ? BinaryOperator::CreateFAdd(M0, M1) 468263508Sdim : BinaryOperator::CreateFSub(M0, M1); 469249423Sdim RI->copyFastMathFlags(&I); 470249423Sdim return RI; 471249423Sdim } 472249423Sdim } 473249423Sdim } 474249423Sdim } 475202375Srdivacky } 476202375Srdivacky 477202375Srdivacky 478249423Sdim // Under unsafe algebra do: 479249423Sdim // X * log2(0.5*Y) = X*log2(Y) - X 480249423Sdim if (I.hasUnsafeAlgebra()) { 481249423Sdim Value *OpX = NULL; 482249423Sdim Value *OpY = NULL; 483249423Sdim IntrinsicInst *Log2; 484249423Sdim detectLog2OfHalf(Op0, OpY, Log2); 485249423Sdim if (OpY) { 486249423Sdim OpX = Op1; 487249423Sdim } else { 488249423Sdim detectLog2OfHalf(Op1, OpY, Log2); 489249423Sdim if (OpY) { 490249423Sdim OpX = Op0; 491249423Sdim } 492249423Sdim } 493249423Sdim // if pattern detected emit alternate sequence 494249423Sdim if (OpX && OpY) { 495263508Sdim BuilderTy::FastMathFlagGuard Guard(*Builder); 496263508Sdim Builder->SetFastMathFlags(Log2->getFastMathFlags()); 497249423Sdim Log2->setArgOperand(0, OpY); 498249423Sdim Value *FMulVal = Builder->CreateFMul(OpX, Log2); 499263508Sdim Value *FSub = Builder->CreateFSub(FMulVal, OpX); 500263508Sdim FSub->takeName(&I); 501263508Sdim return ReplaceInstUsesWith(I, FSub); 502249423Sdim } 503249423Sdim } 504249423Sdim 505249423Sdim // Handle symmetric situation in a 2-iteration loop 506249423Sdim Value *Opnd0 = Op0; 507249423Sdim Value *Opnd1 = Op1; 508249423Sdim for (int i = 0; i < 2; i++) { 509249423Sdim bool IgnoreZeroSign = I.hasNoSignedZeros(); 510249423Sdim if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) { 511263508Sdim BuilderTy::FastMathFlagGuard Guard(*Builder); 512263508Sdim Builder->SetFastMathFlags(I.getFastMathFlags()); 513263508Sdim 514249423Sdim Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign); 515249423Sdim Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign); 516249423Sdim 517249423Sdim // -X * -Y => X*Y 518249423Sdim if (N1) 519249423Sdim return BinaryOperator::CreateFMul(N0, N1); 520249423Sdim 521249423Sdim if (Opnd0->hasOneUse()) { 522249423Sdim // -X * Y => -(X*Y) (Promote negation as high as possible) 523249423Sdim Value *T = Builder->CreateFMul(N0, Opnd1); 524263508Sdim Value *Neg = Builder->CreateFNeg(T); 525263508Sdim Neg->takeName(&I); 526263508Sdim return ReplaceInstUsesWith(I, Neg); 527249423Sdim } 528249423Sdim } 529249423Sdim 530249423Sdim // (X*Y) * X => (X*X) * Y where Y != X 531251662Sdim // The purpose is two-fold: 532249423Sdim // 1) to form a power expression (of X). 533249423Sdim // 2) potentially shorten the critical path: After transformation, the 534249423Sdim // latency of the instruction Y is amortized by the expression of X*X, 535249423Sdim // and therefore Y is in a "less critical" position compared to what it 536249423Sdim // was before the transformation. 537249423Sdim // 538249423Sdim if (AllowReassociate) { 539249423Sdim Value *Opnd0_0, *Opnd0_1; 540249423Sdim if (Opnd0->hasOneUse() && 541249423Sdim match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) { 542249423Sdim Value *Y = 0; 543249423Sdim if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1) 544249423Sdim Y = Opnd0_1; 545249423Sdim else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1) 546249423Sdim Y = Opnd0_0; 547249423Sdim 548249423Sdim if (Y) { 549263508Sdim BuilderTy::FastMathFlagGuard Guard(*Builder); 550263508Sdim Builder->SetFastMathFlags(I.getFastMathFlags()); 551263508Sdim Value *T = Builder->CreateFMul(Opnd1, Opnd1); 552249423Sdim 553263508Sdim Value *R = Builder->CreateFMul(T, Y); 554263508Sdim R->takeName(&I); 555263508Sdim return ReplaceInstUsesWith(I, R); 556249423Sdim } 557249423Sdim } 558249423Sdim } 559249423Sdim 560251662Sdim // B * (uitofp i1 C) -> select C, B, 0 561251662Sdim if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) { 562251662Sdim Value *LHS = Op0, *RHS = Op1; 563251662Sdim Value *B, *C; 564263508Sdim if (!match(RHS, m_UIToFP(m_Value(C)))) 565251662Sdim std::swap(LHS, RHS); 566251662Sdim 567263508Sdim if (match(RHS, m_UIToFP(m_Value(C))) && C->getType()->isIntegerTy(1)) { 568251662Sdim B = LHS; 569251662Sdim Value *Zero = ConstantFP::getNegativeZero(B->getType()); 570251662Sdim return SelectInst::Create(C, B, Zero); 571251662Sdim } 572251662Sdim } 573251662Sdim 574251662Sdim // A * (1 - uitofp i1 C) -> select C, 0, A 575251662Sdim if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) { 576251662Sdim Value *LHS = Op0, *RHS = Op1; 577251662Sdim Value *A, *C; 578263508Sdim if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C))))) 579251662Sdim std::swap(LHS, RHS); 580251662Sdim 581263508Sdim if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) && 582251662Sdim C->getType()->isIntegerTy(1)) { 583251662Sdim A = LHS; 584251662Sdim Value *Zero = ConstantFP::getNegativeZero(A->getType()); 585251662Sdim return SelectInst::Create(C, Zero, A); 586251662Sdim } 587251662Sdim } 588251662Sdim 589249423Sdim if (!isa<Constant>(Op1)) 590249423Sdim std::swap(Opnd0, Opnd1); 591249423Sdim else 592249423Sdim break; 593249423Sdim } 594249423Sdim 595202375Srdivacky return Changed ? &I : 0; 596202375Srdivacky} 597202375Srdivacky 598202375Srdivacky/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select 599202375Srdivacky/// instruction. 600202375Srdivackybool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) { 601202375Srdivacky SelectInst *SI = cast<SelectInst>(I.getOperand(1)); 602251662Sdim 603202375Srdivacky // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 604202375Srdivacky int NonNullOperand = -1; 605202375Srdivacky if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1))) 606202375Srdivacky if (ST->isNullValue()) 607202375Srdivacky NonNullOperand = 2; 608202375Srdivacky // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 609202375Srdivacky if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2))) 610202375Srdivacky if (ST->isNullValue()) 611202375Srdivacky NonNullOperand = 1; 612251662Sdim 613202375Srdivacky if (NonNullOperand == -1) 614202375Srdivacky return false; 615251662Sdim 616202375Srdivacky Value *SelectCond = SI->getOperand(0); 617251662Sdim 618202375Srdivacky // Change the div/rem to use 'Y' instead of the select. 619202375Srdivacky I.setOperand(1, SI->getOperand(NonNullOperand)); 620251662Sdim 621202375Srdivacky // Okay, we know we replace the operand of the div/rem with 'Y' with no 622202375Srdivacky // problem. However, the select, or the condition of the select may have 623202375Srdivacky // multiple uses. Based on our knowledge that the operand must be non-zero, 624202375Srdivacky // propagate the known value for the select into other uses of it, and 625202375Srdivacky // propagate a known value of the condition into its other users. 626251662Sdim 627202375Srdivacky // If the select and condition only have a single use, don't bother with this, 628202375Srdivacky // early exit. 629202375Srdivacky if (SI->use_empty() && SelectCond->hasOneUse()) 630202375Srdivacky return true; 631251662Sdim 632202375Srdivacky // Scan the current block backward, looking for other uses of SI. 633202375Srdivacky BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin(); 634251662Sdim 635202375Srdivacky while (BBI != BBFront) { 636202375Srdivacky --BBI; 637202375Srdivacky // If we found a call to a function, we can't assume it will return, so 638202375Srdivacky // information from below it cannot be propagated above it. 639202375Srdivacky if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI)) 640202375Srdivacky break; 641251662Sdim 642202375Srdivacky // Replace uses of the select or its condition with the known values. 643202375Srdivacky for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); 644202375Srdivacky I != E; ++I) { 645202375Srdivacky if (*I == SI) { 646202375Srdivacky *I = SI->getOperand(NonNullOperand); 647202375Srdivacky Worklist.Add(BBI); 648202375Srdivacky } else if (*I == SelectCond) { 649263508Sdim *I = Builder->getInt1(NonNullOperand == 1); 650202375Srdivacky Worklist.Add(BBI); 651202375Srdivacky } 652202375Srdivacky } 653251662Sdim 654202375Srdivacky // If we past the instruction, quit looking for it. 655202375Srdivacky if (&*BBI == SI) 656202375Srdivacky SI = 0; 657202375Srdivacky if (&*BBI == SelectCond) 658202375Srdivacky SelectCond = 0; 659251662Sdim 660202375Srdivacky // If we ran out of things to eliminate, break out of the loop. 661202375Srdivacky if (SelectCond == 0 && SI == 0) 662202375Srdivacky break; 663251662Sdim 664202375Srdivacky } 665202375Srdivacky return true; 666202375Srdivacky} 667202375Srdivacky 668202375Srdivacky 669202375Srdivacky/// This function implements the transforms common to both integer division 670202375Srdivacky/// instructions (udiv and sdiv). It is called by the visitors to those integer 671202375Srdivacky/// division instructions. 672202375Srdivacky/// @brief Common integer divide transforms 673202375SrdivackyInstruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) { 674202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 675202375Srdivacky 676223017Sdim // The RHS is known non-zero. 677223017Sdim if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 678223017Sdim I.setOperand(1, V); 679223017Sdim return &I; 680223017Sdim } 681251662Sdim 682202375Srdivacky // Handle cases involving: [su]div X, (select Cond, Y, Z) 683202375Srdivacky // This does not apply for fdiv. 684202375Srdivacky if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 685202375Srdivacky return &I; 686202375Srdivacky 687202375Srdivacky if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 688202375Srdivacky // (X / C1) / C2 -> X / (C1*C2) 689202375Srdivacky if (Instruction *LHS = dyn_cast<Instruction>(Op0)) 690202375Srdivacky if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode()) 691202375Srdivacky if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) { 692202375Srdivacky if (MultiplyOverflows(RHS, LHSRHS, 693202375Srdivacky I.getOpcode()==Instruction::SDiv)) 694202375Srdivacky return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); 695218893Sdim return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0), 696218893Sdim ConstantExpr::getMul(RHS, LHSRHS)); 697202375Srdivacky } 698202375Srdivacky 699202375Srdivacky if (!RHS->isZero()) { // avoid X udiv 0 700202375Srdivacky if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 701202375Srdivacky if (Instruction *R = FoldOpIntoSelect(I, SI)) 702202375Srdivacky return R; 703202375Srdivacky if (isa<PHINode>(Op0)) 704202375Srdivacky if (Instruction *NV = FoldOpIntoPhi(I)) 705202375Srdivacky return NV; 706202375Srdivacky } 707202375Srdivacky } 708202375Srdivacky 709221345Sdim // See if we can fold away this div instruction. 710221345Sdim if (SimplifyDemandedInstructionBits(I)) 711221345Sdim return &I; 712221345Sdim 713218893Sdim // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 714218893Sdim Value *X = 0, *Z = 0; 715218893Sdim if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1 716218893Sdim bool isSigned = I.getOpcode() == Instruction::SDiv; 717218893Sdim if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 718218893Sdim (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 719218893Sdim return BinaryOperator::Create(I.getOpcode(), X, Op1); 720202375Srdivacky } 721202375Srdivacky 722202375Srdivacky return 0; 723202375Srdivacky} 724202375Srdivacky 725221345Sdim/// dyn_castZExtVal - Checks if V is a zext or constant that can 726221345Sdim/// be truncated to Ty without losing bits. 727226633Sdimstatic Value *dyn_castZExtVal(Value *V, Type *Ty) { 728221345Sdim if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) { 729221345Sdim if (Z->getSrcTy() == Ty) 730221345Sdim return Z->getOperand(0); 731221345Sdim } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) { 732221345Sdim if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth()) 733221345Sdim return ConstantExpr::getTrunc(C, Ty); 734221345Sdim } 735221345Sdim return 0; 736221345Sdim} 737221345Sdim 738263508Sdimnamespace { 739263508Sdimconst unsigned MaxDepth = 6; 740263508Sdimtypedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1, 741263508Sdim const BinaryOperator &I, 742263508Sdim InstCombiner &IC); 743263508Sdim 744263508Sdim/// \brief Used to maintain state for visitUDivOperand(). 745263508Sdimstruct UDivFoldAction { 746263508Sdim FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this 747263508Sdim ///< operand. This can be zero if this action 748263508Sdim ///< joins two actions together. 749263508Sdim 750263508Sdim Value *OperandToFold; ///< Which operand to fold. 751263508Sdim union { 752263508Sdim Instruction *FoldResult; ///< The instruction returned when FoldAction is 753263508Sdim ///< invoked. 754263508Sdim 755263508Sdim size_t SelectLHSIdx; ///< Stores the LHS action index if this action 756263508Sdim ///< joins two actions together. 757263508Sdim }; 758263508Sdim 759263508Sdim UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand) 760263508Sdim : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {} 761263508Sdim UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS) 762263508Sdim : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {} 763263508Sdim}; 764263508Sdim} 765263508Sdim 766263508Sdim// X udiv 2^C -> X >> C 767263508Sdimstatic Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1, 768263508Sdim const BinaryOperator &I, InstCombiner &IC) { 769263508Sdim const APInt &C = cast<Constant>(Op1)->getUniqueInteger(); 770263508Sdim BinaryOperator *LShr = BinaryOperator::CreateLShr( 771263508Sdim Op0, ConstantInt::get(Op0->getType(), C.logBase2())); 772263508Sdim if (I.isExact()) LShr->setIsExact(); 773263508Sdim return LShr; 774263508Sdim} 775263508Sdim 776263508Sdim// X udiv C, where C >= signbit 777263508Sdimstatic Instruction *foldUDivNegCst(Value *Op0, Value *Op1, 778263508Sdim const BinaryOperator &I, InstCombiner &IC) { 779263508Sdim Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1)); 780263508Sdim 781263508Sdim return SelectInst::Create(ICI, Constant::getNullValue(I.getType()), 782263508Sdim ConstantInt::get(I.getType(), 1)); 783263508Sdim} 784263508Sdim 785263508Sdim// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 786263508Sdimstatic Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I, 787263508Sdim InstCombiner &IC) { 788263508Sdim Instruction *ShiftLeft = cast<Instruction>(Op1); 789263508Sdim if (isa<ZExtInst>(ShiftLeft)) 790263508Sdim ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0)); 791263508Sdim 792263508Sdim const APInt &CI = 793263508Sdim cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger(); 794263508Sdim Value *N = ShiftLeft->getOperand(1); 795263508Sdim if (CI != 1) 796263508Sdim N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2())); 797263508Sdim if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1)) 798263508Sdim N = IC.Builder->CreateZExt(N, Z->getDestTy()); 799263508Sdim BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N); 800263508Sdim if (I.isExact()) LShr->setIsExact(); 801263508Sdim return LShr; 802263508Sdim} 803263508Sdim 804263508Sdim// \brief Recursively visits the possible right hand operands of a udiv 805263508Sdim// instruction, seeing through select instructions, to determine if we can 806263508Sdim// replace the udiv with something simpler. If we find that an operand is not 807263508Sdim// able to simplify the udiv, we abort the entire transformation. 808263508Sdimstatic size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I, 809263508Sdim SmallVectorImpl<UDivFoldAction> &Actions, 810263508Sdim unsigned Depth = 0) { 811263508Sdim // Check to see if this is an unsigned division with an exact power of 2, 812263508Sdim // if so, convert to a right shift. 813263508Sdim if (match(Op1, m_Power2())) { 814263508Sdim Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1)); 815263508Sdim return Actions.size(); 816263508Sdim } 817263508Sdim 818263508Sdim if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) 819263508Sdim // X udiv C, where C >= signbit 820263508Sdim if (C->getValue().isNegative()) { 821263508Sdim Actions.push_back(UDivFoldAction(foldUDivNegCst, C)); 822263508Sdim return Actions.size(); 823263508Sdim } 824263508Sdim 825263508Sdim // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 826263508Sdim if (match(Op1, m_Shl(m_Power2(), m_Value())) || 827263508Sdim match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) { 828263508Sdim Actions.push_back(UDivFoldAction(foldUDivShl, Op1)); 829263508Sdim return Actions.size(); 830263508Sdim } 831263508Sdim 832263508Sdim // The remaining tests are all recursive, so bail out if we hit the limit. 833263508Sdim if (Depth++ == MaxDepth) 834263508Sdim return 0; 835263508Sdim 836263508Sdim if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 837263508Sdim if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions)) 838263508Sdim if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) { 839263508Sdim Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1)); 840263508Sdim return Actions.size(); 841263508Sdim } 842263508Sdim 843263508Sdim return 0; 844263508Sdim} 845263508Sdim 846202375SrdivackyInstruction *InstCombiner::visitUDiv(BinaryOperator &I) { 847202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 848202375Srdivacky 849218893Sdim if (Value *V = SimplifyUDivInst(Op0, Op1, TD)) 850218893Sdim return ReplaceInstUsesWith(I, V); 851218893Sdim 852202375Srdivacky // Handle the integer div common cases 853202375Srdivacky if (Instruction *Common = commonIDivTransforms(I)) 854202375Srdivacky return Common; 855251662Sdim 856243830Sdim // (x lshr C1) udiv C2 --> x udiv (C2 << C1) 857243830Sdim if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) { 858243830Sdim Value *X; 859243830Sdim ConstantInt *C1; 860243830Sdim if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) { 861243830Sdim APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1)); 862243830Sdim return BinaryOperator::CreateUDiv(X, Builder->getInt(NC)); 863243830Sdim } 864243830Sdim } 865243830Sdim 866221345Sdim // (zext A) udiv (zext B) --> zext (A udiv B) 867221345Sdim if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 868221345Sdim if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 869221345Sdim return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", 870221345Sdim I.isExact()), 871221345Sdim I.getType()); 872221345Sdim 873263508Sdim // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...)))) 874263508Sdim SmallVector<UDivFoldAction, 6> UDivActions; 875263508Sdim if (visitUDivOperand(Op0, Op1, I, UDivActions)) 876263508Sdim for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) { 877263508Sdim FoldUDivOperandCb Action = UDivActions[i].FoldAction; 878263508Sdim Value *ActionOp1 = UDivActions[i].OperandToFold; 879263508Sdim Instruction *Inst; 880263508Sdim if (Action) 881263508Sdim Inst = Action(Op0, ActionOp1, I, *this); 882263508Sdim else { 883263508Sdim // This action joins two actions together. The RHS of this action is 884263508Sdim // simply the last action we processed, we saved the LHS action index in 885263508Sdim // the joining action. 886263508Sdim size_t SelectRHSIdx = i - 1; 887263508Sdim Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult; 888263508Sdim size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx; 889263508Sdim Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult; 890263508Sdim Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(), 891263508Sdim SelectLHS, SelectRHS); 892263508Sdim } 893263508Sdim 894263508Sdim // If this is the last action to process, return it to the InstCombiner. 895263508Sdim // Otherwise, we insert it before the UDiv and record it so that we may 896263508Sdim // use it as part of a joining action (i.e., a SelectInst). 897263508Sdim if (e - i != 1) { 898263508Sdim Inst->insertBefore(&I); 899263508Sdim UDivActions[i].FoldResult = Inst; 900263508Sdim } else 901263508Sdim return Inst; 902263508Sdim } 903263508Sdim 904202375Srdivacky return 0; 905202375Srdivacky} 906202375Srdivacky 907202375SrdivackyInstruction *InstCombiner::visitSDiv(BinaryOperator &I) { 908202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 909202375Srdivacky 910218893Sdim if (Value *V = SimplifySDivInst(Op0, Op1, TD)) 911218893Sdim return ReplaceInstUsesWith(I, V); 912218893Sdim 913202375Srdivacky // Handle the integer div common cases 914202375Srdivacky if (Instruction *Common = commonIDivTransforms(I)) 915202375Srdivacky return Common; 916202375Srdivacky 917202375Srdivacky if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 918202375Srdivacky // sdiv X, -1 == -X 919202375Srdivacky if (RHS->isAllOnesValue()) 920202375Srdivacky return BinaryOperator::CreateNeg(Op0); 921202375Srdivacky 922218893Sdim // sdiv X, C --> ashr exact X, log2(C) 923218893Sdim if (I.isExact() && RHS->getValue().isNonNegative() && 924202375Srdivacky RHS->getValue().isPowerOf2()) { 925202375Srdivacky Value *ShAmt = llvm::ConstantInt::get(RHS->getType(), 926202375Srdivacky RHS->getValue().exactLogBase2()); 927218893Sdim return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName()); 928202375Srdivacky } 929202375Srdivacky 930202375Srdivacky // -X/C --> X/-C provided the negation doesn't overflow. 931202375Srdivacky if (SubOperator *Sub = dyn_cast<SubOperator>(Op0)) 932218893Sdim if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap()) 933202375Srdivacky return BinaryOperator::CreateSDiv(Sub->getOperand(1), 934202375Srdivacky ConstantExpr::getNeg(RHS)); 935202375Srdivacky } 936202375Srdivacky 937202375Srdivacky // If the sign bits of both operands are zero (i.e. we can prove they are 938202375Srdivacky // unsigned inputs), turn this into a udiv. 939203954Srdivacky if (I.getType()->isIntegerTy()) { 940202375Srdivacky APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 941202375Srdivacky if (MaskedValueIsZero(Op0, Mask)) { 942202375Srdivacky if (MaskedValueIsZero(Op1, Mask)) { 943202375Srdivacky // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 944202375Srdivacky return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 945202375Srdivacky } 946251662Sdim 947218893Sdim if (match(Op1, m_Shl(m_Power2(), m_Value()))) { 948202375Srdivacky // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 949202375Srdivacky // Safe because the only negative value (1 << Y) can take on is 950202375Srdivacky // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 951202375Srdivacky // the sign bit set. 952202375Srdivacky return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 953202375Srdivacky } 954202375Srdivacky } 955202375Srdivacky } 956251662Sdim 957202375Srdivacky return 0; 958202375Srdivacky} 959202375Srdivacky 960249423Sdim/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special 961249423Sdim/// FP value and: 962251662Sdim/// 1) 1/C is exact, or 963249423Sdim/// 2) reciprocal is allowed. 964263508Sdim/// If the conversion was successful, the simplified expression "X * 1/C" is 965249423Sdim/// returned; otherwise, NULL is returned. 966249423Sdim/// 967249423Sdimstatic Instruction *CvtFDivConstToReciprocal(Value *Dividend, 968249423Sdim ConstantFP *Divisor, 969249423Sdim bool AllowReciprocal) { 970249423Sdim const APFloat &FpVal = Divisor->getValueAPF(); 971249423Sdim APFloat Reciprocal(FpVal.getSemantics()); 972249423Sdim bool Cvt = FpVal.getExactInverse(&Reciprocal); 973251662Sdim 974263508Sdim if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) { 975249423Sdim Reciprocal = APFloat(FpVal.getSemantics(), 1.0f); 976249423Sdim (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven); 977249423Sdim Cvt = !Reciprocal.isDenormal(); 978249423Sdim } 979249423Sdim 980249423Sdim if (!Cvt) 981249423Sdim return 0; 982249423Sdim 983249423Sdim ConstantFP *R; 984249423Sdim R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal); 985249423Sdim return BinaryOperator::CreateFMul(Dividend, R); 986249423Sdim} 987249423Sdim 988202375SrdivackyInstruction *InstCombiner::visitFDiv(BinaryOperator &I) { 989218893Sdim Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 990218893Sdim 991218893Sdim if (Value *V = SimplifyFDivInst(Op0, Op1, TD)) 992218893Sdim return ReplaceInstUsesWith(I, V); 993218893Sdim 994263508Sdim if (isa<Constant>(Op0)) 995263508Sdim if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 996263508Sdim if (Instruction *R = FoldOpIntoSelect(I, SI)) 997263508Sdim return R; 998263508Sdim 999249423Sdim bool AllowReassociate = I.hasUnsafeAlgebra(); 1000249423Sdim bool AllowReciprocal = I.hasAllowReciprocal(); 1001249423Sdim 1002221345Sdim if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 1003263508Sdim if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 1004263508Sdim if (Instruction *R = FoldOpIntoSelect(I, SI)) 1005263508Sdim return R; 1006263508Sdim 1007249423Sdim if (AllowReassociate) { 1008249423Sdim ConstantFP *C1 = 0; 1009249423Sdim ConstantFP *C2 = Op1C; 1010249423Sdim Value *X; 1011249423Sdim Instruction *Res = 0; 1012202375Srdivacky 1013249423Sdim if (match(Op0, m_FMul(m_Value(X), m_ConstantFP(C1)))) { 1014249423Sdim // (X*C1)/C2 => X * (C1/C2) 1015249423Sdim // 1016249423Sdim Constant *C = ConstantExpr::getFDiv(C1, C2); 1017249423Sdim const APFloat &F = cast<ConstantFP>(C)->getValueAPF(); 1018263508Sdim if (F.isNormal()) 1019249423Sdim Res = BinaryOperator::CreateFMul(X, C); 1020249423Sdim } else if (match(Op0, m_FDiv(m_Value(X), m_ConstantFP(C1)))) { 1021249423Sdim // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed] 1022249423Sdim // 1023249423Sdim Constant *C = ConstantExpr::getFMul(C1, C2); 1024249423Sdim const APFloat &F = cast<ConstantFP>(C)->getValueAPF(); 1025263508Sdim if (F.isNormal()) { 1026251662Sdim Res = CvtFDivConstToReciprocal(X, cast<ConstantFP>(C), 1027249423Sdim AllowReciprocal); 1028249423Sdim if (!Res) 1029251662Sdim Res = BinaryOperator::CreateFDiv(X, C); 1030249423Sdim } 1031249423Sdim } 1032249423Sdim 1033249423Sdim if (Res) { 1034249423Sdim Res->setFastMathFlags(I.getFastMathFlags()); 1035249423Sdim return Res; 1036249423Sdim } 1037221345Sdim } 1038249423Sdim 1039249423Sdim // X / C => X * 1/C 1040249423Sdim if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) 1041249423Sdim return T; 1042249423Sdim 1043249423Sdim return 0; 1044202375Srdivacky } 1045202375Srdivacky 1046249423Sdim if (AllowReassociate && isa<ConstantFP>(Op0)) { 1047249423Sdim ConstantFP *C1 = cast<ConstantFP>(Op0), *C2; 1048249423Sdim Constant *Fold = 0; 1049249423Sdim Value *X; 1050249423Sdim bool CreateDiv = true; 1051249423Sdim 1052249423Sdim // C1 / (X*C2) => (C1/C2) / X 1053249423Sdim if (match(Op1, m_FMul(m_Value(X), m_ConstantFP(C2)))) 1054249423Sdim Fold = ConstantExpr::getFDiv(C1, C2); 1055249423Sdim else if (match(Op1, m_FDiv(m_Value(X), m_ConstantFP(C2)))) { 1056249423Sdim // C1 / (X/C2) => (C1*C2) / X 1057249423Sdim Fold = ConstantExpr::getFMul(C1, C2); 1058249423Sdim } else if (match(Op1, m_FDiv(m_ConstantFP(C2), m_Value(X)))) { 1059249423Sdim // C1 / (C2/X) => (C1/C2) * X 1060249423Sdim Fold = ConstantExpr::getFDiv(C1, C2); 1061249423Sdim CreateDiv = false; 1062249423Sdim } 1063249423Sdim 1064249423Sdim if (Fold) { 1065249423Sdim const APFloat &FoldC = cast<ConstantFP>(Fold)->getValueAPF(); 1066263508Sdim if (FoldC.isNormal()) { 1067251662Sdim Instruction *R = CreateDiv ? 1068249423Sdim BinaryOperator::CreateFDiv(Fold, X) : 1069249423Sdim BinaryOperator::CreateFMul(X, Fold); 1070249423Sdim R->setFastMathFlags(I.getFastMathFlags()); 1071249423Sdim return R; 1072249423Sdim } 1073249423Sdim } 1074249423Sdim return 0; 1075249423Sdim } 1076249423Sdim 1077249423Sdim if (AllowReassociate) { 1078249423Sdim Value *X, *Y; 1079249423Sdim Value *NewInst = 0; 1080249423Sdim Instruction *SimpR = 0; 1081249423Sdim 1082249423Sdim if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) { 1083249423Sdim // (X/Y) / Z => X / (Y*Z) 1084249423Sdim // 1085249423Sdim if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op1)) { 1086249423Sdim NewInst = Builder->CreateFMul(Y, Op1); 1087249423Sdim SimpR = BinaryOperator::CreateFDiv(X, NewInst); 1088249423Sdim } 1089249423Sdim } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) { 1090249423Sdim // Z / (X/Y) => Z*Y / X 1091249423Sdim // 1092249423Sdim if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op0)) { 1093249423Sdim NewInst = Builder->CreateFMul(Op0, Y); 1094249423Sdim SimpR = BinaryOperator::CreateFDiv(NewInst, X); 1095249423Sdim } 1096249423Sdim } 1097249423Sdim 1098249423Sdim if (NewInst) { 1099249423Sdim if (Instruction *T = dyn_cast<Instruction>(NewInst)) 1100249423Sdim T->setDebugLoc(I.getDebugLoc()); 1101249423Sdim SimpR->setFastMathFlags(I.getFastMathFlags()); 1102249423Sdim return SimpR; 1103249423Sdim } 1104249423Sdim } 1105249423Sdim 1106202375Srdivacky return 0; 1107202375Srdivacky} 1108202375Srdivacky 1109202375Srdivacky/// This function implements the transforms common to both integer remainder 1110202375Srdivacky/// instructions (urem and srem). It is called by the visitors to those integer 1111202375Srdivacky/// remainder instructions. 1112202375Srdivacky/// @brief Common integer remainder transforms 1113202375SrdivackyInstruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) { 1114202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1115202375Srdivacky 1116223017Sdim // The RHS is known non-zero. 1117223017Sdim if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 1118223017Sdim I.setOperand(1, V); 1119223017Sdim return &I; 1120223017Sdim } 1121223017Sdim 1122221345Sdim // Handle cases involving: rem X, (select Cond, Y, Z) 1123221345Sdim if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 1124221345Sdim return &I; 1125202375Srdivacky 1126223017Sdim if (isa<ConstantInt>(Op1)) { 1127202375Srdivacky if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 1128202375Srdivacky if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 1129202375Srdivacky if (Instruction *R = FoldOpIntoSelect(I, SI)) 1130202375Srdivacky return R; 1131202375Srdivacky } else if (isa<PHINode>(Op0I)) { 1132202375Srdivacky if (Instruction *NV = FoldOpIntoPhi(I)) 1133202375Srdivacky return NV; 1134202375Srdivacky } 1135202375Srdivacky 1136202375Srdivacky // See if we can fold away this rem instruction. 1137202375Srdivacky if (SimplifyDemandedInstructionBits(I)) 1138202375Srdivacky return &I; 1139202375Srdivacky } 1140202375Srdivacky } 1141202375Srdivacky 1142202375Srdivacky return 0; 1143202375Srdivacky} 1144202375Srdivacky 1145202375SrdivackyInstruction *InstCombiner::visitURem(BinaryOperator &I) { 1146202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1147202375Srdivacky 1148221345Sdim if (Value *V = SimplifyURemInst(Op0, Op1, TD)) 1149221345Sdim return ReplaceInstUsesWith(I, V); 1150221345Sdim 1151202375Srdivacky if (Instruction *common = commonIRemTransforms(I)) 1152202375Srdivacky return common; 1153251662Sdim 1154263508Sdim // (zext A) urem (zext B) --> zext (A urem B) 1155263508Sdim if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 1156263508Sdim if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 1157263508Sdim return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1), 1158263508Sdim I.getType()); 1159202375Srdivacky 1160263508Sdim // X urem Y -> X and Y-1, where Y is a power of 2, 1161263508Sdim if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) { 1162218893Sdim Constant *N1 = Constant::getAllOnesValue(I.getType()); 1163226633Sdim Value *Add = Builder->CreateAdd(Op1, N1); 1164218893Sdim return BinaryOperator::CreateAnd(Op0, Add); 1165202375Srdivacky } 1166202375Srdivacky 1167263508Sdim // 1 urem X -> zext(X != 1) 1168263508Sdim if (match(Op0, m_One())) { 1169263508Sdim Value *Cmp = Builder->CreateICmpNE(Op1, Op0); 1170263508Sdim Value *Ext = Builder->CreateZExt(Cmp, I.getType()); 1171263508Sdim return ReplaceInstUsesWith(I, Ext); 1172202375Srdivacky } 1173221345Sdim 1174202375Srdivacky return 0; 1175202375Srdivacky} 1176202375Srdivacky 1177202375SrdivackyInstruction *InstCombiner::visitSRem(BinaryOperator &I) { 1178202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1179202375Srdivacky 1180221345Sdim if (Value *V = SimplifySRemInst(Op0, Op1, TD)) 1181221345Sdim return ReplaceInstUsesWith(I, V); 1182221345Sdim 1183202375Srdivacky // Handle the integer rem common cases 1184202375Srdivacky if (Instruction *Common = commonIRemTransforms(I)) 1185202375Srdivacky return Common; 1186251662Sdim 1187202375Srdivacky if (Value *RHSNeg = dyn_castNegVal(Op1)) 1188202375Srdivacky if (!isa<Constant>(RHSNeg) || 1189202375Srdivacky (isa<ConstantInt>(RHSNeg) && 1190202375Srdivacky cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) { 1191202375Srdivacky // X % -Y -> X % Y 1192202375Srdivacky Worklist.AddValue(I.getOperand(1)); 1193202375Srdivacky I.setOperand(1, RHSNeg); 1194202375Srdivacky return &I; 1195202375Srdivacky } 1196202375Srdivacky 1197202375Srdivacky // If the sign bits of both operands are zero (i.e. we can prove they are 1198202375Srdivacky // unsigned inputs), turn this into a urem. 1199203954Srdivacky if (I.getType()->isIntegerTy()) { 1200202375Srdivacky APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 1201202375Srdivacky if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) { 1202202375Srdivacky // X srem Y -> X urem Y, iff X and Y don't have sign bit set 1203202375Srdivacky return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 1204202375Srdivacky } 1205202375Srdivacky } 1206202375Srdivacky 1207202375Srdivacky // If it's a constant vector, flip any negative values positive. 1208234353Sdim if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) { 1209234353Sdim Constant *C = cast<Constant>(Op1); 1210234353Sdim unsigned VWidth = C->getType()->getVectorNumElements(); 1211202375Srdivacky 1212202375Srdivacky bool hasNegative = false; 1213234353Sdim bool hasMissing = false; 1214234353Sdim for (unsigned i = 0; i != VWidth; ++i) { 1215234353Sdim Constant *Elt = C->getAggregateElement(i); 1216234353Sdim if (Elt == 0) { 1217234353Sdim hasMissing = true; 1218234353Sdim break; 1219234353Sdim } 1220234353Sdim 1221234353Sdim if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt)) 1222224145Sdim if (RHS->isNegative()) 1223202375Srdivacky hasNegative = true; 1224234353Sdim } 1225202375Srdivacky 1226234353Sdim if (hasNegative && !hasMissing) { 1227234353Sdim SmallVector<Constant *, 16> Elts(VWidth); 1228202375Srdivacky for (unsigned i = 0; i != VWidth; ++i) { 1229234353Sdim Elts[i] = C->getAggregateElement(i); // Handle undef, etc. 1230234353Sdim if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) { 1231224145Sdim if (RHS->isNegative()) 1232202375Srdivacky Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 1233202375Srdivacky } 1234202375Srdivacky } 1235202375Srdivacky 1236202375Srdivacky Constant *NewRHSV = ConstantVector::get(Elts); 1237234353Sdim if (NewRHSV != C) { // Don't loop on -MININT 1238202375Srdivacky Worklist.AddValue(I.getOperand(1)); 1239202375Srdivacky I.setOperand(1, NewRHSV); 1240202375Srdivacky return &I; 1241202375Srdivacky } 1242202375Srdivacky } 1243202375Srdivacky } 1244202375Srdivacky 1245202375Srdivacky return 0; 1246202375Srdivacky} 1247202375Srdivacky 1248202375SrdivackyInstruction *InstCombiner::visitFRem(BinaryOperator &I) { 1249221345Sdim Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1250221345Sdim 1251221345Sdim if (Value *V = SimplifyFRemInst(Op0, Op1, TD)) 1252221345Sdim return ReplaceInstUsesWith(I, V); 1253221345Sdim 1254221345Sdim // Handle cases involving: rem X, (select Cond, Y, Z) 1255221345Sdim if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 1256221345Sdim return &I; 1257221345Sdim 1258221345Sdim return 0; 1259202375Srdivacky} 1260