1 //===- InstCombineMulDivRem.cpp -------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv, 11 // srem, urem, frem. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "InstCombine.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/IR/IntrinsicInst.h" 18 #include "llvm/IR/PatternMatch.h" 19 using namespace llvm; 20 using namespace PatternMatch; 21 22 #define DEBUG_TYPE "instcombine" 23 24 25 /// simplifyValueKnownNonZero - The specific integer value is used in a context 26 /// where it is known to be non-zero. If this allows us to simplify the 27 /// computation, do so and return the new operand, otherwise return null. 28 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) { 29 // If V has multiple uses, then we would have to do more analysis to determine 30 // if this is safe. For example, the use could be in dynamically unreached 31 // code. 32 if (!V->hasOneUse()) return 0; 33 34 bool MadeChange = false; 35 36 // ((1 << A) >>u B) --> (1 << (A-B)) 37 // Because V cannot be zero, we know that B is less than A. 38 Value *A = 0, *B = 0, *PowerOf2 = 0; 39 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))), 40 m_Value(B))) && 41 // The "1" can be any value known to be a power of 2. 42 isKnownToBeAPowerOfTwo(PowerOf2)) { 43 A = IC.Builder->CreateSub(A, B); 44 return IC.Builder->CreateShl(PowerOf2, A); 45 } 46 47 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it 48 // inexact. Similarly for <<. 49 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V)) 50 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) { 51 // We know that this is an exact/nuw shift and that the input is a 52 // non-zero context as well. 53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) { 54 I->setOperand(0, V2); 55 MadeChange = true; 56 } 57 58 if (I->getOpcode() == Instruction::LShr && !I->isExact()) { 59 I->setIsExact(); 60 MadeChange = true; 61 } 62 63 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) { 64 I->setHasNoUnsignedWrap(); 65 MadeChange = true; 66 } 67 } 68 69 // TODO: Lots more we could do here: 70 // If V is a phi node, we can call this on each of its operands. 71 // "select cond, X, 0" can simplify to "X". 72 73 return MadeChange ? V : 0; 74 } 75 76 77 /// MultiplyOverflows - True if the multiply can not be expressed in an int 78 /// this size. 79 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) { 80 uint32_t W = C1->getBitWidth(); 81 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue(); 82 if (sign) { 83 LHSExt = LHSExt.sext(W * 2); 84 RHSExt = RHSExt.sext(W * 2); 85 } else { 86 LHSExt = LHSExt.zext(W * 2); 87 RHSExt = RHSExt.zext(W * 2); 88 } 89 90 APInt MulExt = LHSExt * RHSExt; 91 92 if (!sign) 93 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W)); 94 95 APInt Min = APInt::getSignedMinValue(W).sext(W * 2); 96 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2); 97 return MulExt.slt(Min) || MulExt.sgt(Max); 98 } 99 100 /// \brief A helper routine of InstCombiner::visitMul(). 101 /// 102 /// If C is a vector of known powers of 2, then this function returns 103 /// a new vector obtained from C replacing each element with its logBase2. 104 /// Return a null pointer otherwise. 105 static Constant *getLogBase2Vector(ConstantDataVector *CV) { 106 const APInt *IVal; 107 SmallVector<Constant *, 4> Elts; 108 109 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) { 110 Constant *Elt = CV->getElementAsConstant(I); 111 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2()) 112 return 0; 113 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2())); 114 } 115 116 return ConstantVector::get(Elts); 117 } 118 119 Instruction *InstCombiner::visitMul(BinaryOperator &I) { 120 bool Changed = SimplifyAssociativeOrCommutative(I); 121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 122 123 if (Value *V = SimplifyMulInst(Op0, Op1, DL)) 124 return ReplaceInstUsesWith(I, V); 125 126 if (Value *V = SimplifyUsingDistributiveLaws(I)) 127 return ReplaceInstUsesWith(I, V); 128 129 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X 130 return BinaryOperator::CreateNeg(Op0, I.getName()); 131 132 // Also allow combining multiply instructions on vectors. 133 { 134 Value *NewOp; 135 Constant *C1, *C2; 136 const APInt *IVal; 137 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)), 138 m_Constant(C1))) && 139 match(C1, m_APInt(IVal))) 140 // ((X << C1)*C2) == (X * (C2 << C1)) 141 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2)); 142 143 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) { 144 Constant *NewCst = 0; 145 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2()) 146 // Replace X*(2^C) with X << C, where C is either a scalar or a splat. 147 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2()); 148 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1)) 149 // Replace X*(2^C) with X << C, where C is a vector of known 150 // constant powers of 2. 151 NewCst = getLogBase2Vector(CV); 152 153 if (NewCst) { 154 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst); 155 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap(); 156 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap(); 157 return Shl; 158 } 159 } 160 } 161 162 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 163 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n 164 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n 165 // The "* (2**n)" thus becomes a potential shifting opportunity. 166 { 167 const APInt & Val = CI->getValue(); 168 const APInt &PosVal = Val.abs(); 169 if (Val.isNegative() && PosVal.isPowerOf2()) { 170 Value *X = 0, *Y = 0; 171 if (Op0->hasOneUse()) { 172 ConstantInt *C1; 173 Value *Sub = 0; 174 if (match(Op0, m_Sub(m_Value(Y), m_Value(X)))) 175 Sub = Builder->CreateSub(X, Y, "suba"); 176 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1)))) 177 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc"); 178 if (Sub) 179 return 180 BinaryOperator::CreateMul(Sub, 181 ConstantInt::get(Y->getType(), PosVal)); 182 } 183 } 184 } 185 } 186 187 // Simplify mul instructions with a constant RHS. 188 if (isa<Constant>(Op1)) { 189 // Try to fold constant mul into select arguments. 190 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 191 if (Instruction *R = FoldOpIntoSelect(I, SI)) 192 return R; 193 194 if (isa<PHINode>(Op0)) 195 if (Instruction *NV = FoldOpIntoPhi(I)) 196 return NV; 197 198 // Canonicalize (X+C1)*CI -> X*CI+C1*CI. 199 { 200 Value *X; 201 Constant *C1; 202 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) { 203 Value *Add = Builder->CreateMul(X, Op1); 204 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, Op1)); 205 } 206 } 207 } 208 209 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y 210 if (Value *Op1v = dyn_castNegVal(Op1)) 211 return BinaryOperator::CreateMul(Op0v, Op1v); 212 213 // (X / Y) * Y = X - (X % Y) 214 // (X / Y) * -Y = (X % Y) - X 215 { 216 Value *Op1C = Op1; 217 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0); 218 if (!BO || 219 (BO->getOpcode() != Instruction::UDiv && 220 BO->getOpcode() != Instruction::SDiv)) { 221 Op1C = Op0; 222 BO = dyn_cast<BinaryOperator>(Op1); 223 } 224 Value *Neg = dyn_castNegVal(Op1C); 225 if (BO && BO->hasOneUse() && 226 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) && 227 (BO->getOpcode() == Instruction::UDiv || 228 BO->getOpcode() == Instruction::SDiv)) { 229 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1); 230 231 // If the division is exact, X % Y is zero, so we end up with X or -X. 232 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO)) 233 if (SDiv->isExact()) { 234 if (Op1BO == Op1C) 235 return ReplaceInstUsesWith(I, Op0BO); 236 return BinaryOperator::CreateNeg(Op0BO); 237 } 238 239 Value *Rem; 240 if (BO->getOpcode() == Instruction::UDiv) 241 Rem = Builder->CreateURem(Op0BO, Op1BO); 242 else 243 Rem = Builder->CreateSRem(Op0BO, Op1BO); 244 Rem->takeName(BO); 245 246 if (Op1BO == Op1C) 247 return BinaryOperator::CreateSub(Op0BO, Rem); 248 return BinaryOperator::CreateSub(Rem, Op0BO); 249 } 250 } 251 252 /// i1 mul -> i1 and. 253 if (I.getType()->getScalarType()->isIntegerTy(1)) 254 return BinaryOperator::CreateAnd(Op0, Op1); 255 256 // X*(1 << Y) --> X << Y 257 // (1 << Y)*X --> X << Y 258 { 259 Value *Y; 260 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) 261 return BinaryOperator::CreateShl(Op1, Y); 262 if (match(Op1, m_Shl(m_One(), m_Value(Y)))) 263 return BinaryOperator::CreateShl(Op0, Y); 264 } 265 266 // If one of the operands of the multiply is a cast from a boolean value, then 267 // we know the bool is either zero or one, so this is a 'masking' multiply. 268 // X * Y (where Y is 0 or 1) -> X & (0-Y) 269 if (!I.getType()->isVectorTy()) { 270 // -2 is "-1 << 1" so it is all bits set except the low one. 271 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true); 272 273 Value *BoolCast = 0, *OtherOp = 0; 274 if (MaskedValueIsZero(Op0, Negative2)) 275 BoolCast = Op0, OtherOp = Op1; 276 else if (MaskedValueIsZero(Op1, Negative2)) 277 BoolCast = Op1, OtherOp = Op0; 278 279 if (BoolCast) { 280 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()), 281 BoolCast); 282 return BinaryOperator::CreateAnd(V, OtherOp); 283 } 284 } 285 286 return Changed ? &I : 0; 287 } 288 289 // 290 // Detect pattern: 291 // 292 // log2(Y*0.5) 293 // 294 // And check for corresponding fast math flags 295 // 296 297 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) { 298 299 if (!Op->hasOneUse()) 300 return; 301 302 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op); 303 if (!II) 304 return; 305 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra()) 306 return; 307 Log2 = II; 308 309 Value *OpLog2Of = II->getArgOperand(0); 310 if (!OpLog2Of->hasOneUse()) 311 return; 312 313 Instruction *I = dyn_cast<Instruction>(OpLog2Of); 314 if (!I) 315 return; 316 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra()) 317 return; 318 319 if (match(I->getOperand(0), m_SpecificFP(0.5))) 320 Y = I->getOperand(1); 321 else if (match(I->getOperand(1), m_SpecificFP(0.5))) 322 Y = I->getOperand(0); 323 } 324 325 static bool isFiniteNonZeroFp(Constant *C) { 326 if (C->getType()->isVectorTy()) { 327 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; 328 ++I) { 329 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I)); 330 if (!CFP || !CFP->getValueAPF().isFiniteNonZero()) 331 return false; 332 } 333 return true; 334 } 335 336 return isa<ConstantFP>(C) && 337 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero(); 338 } 339 340 static bool isNormalFp(Constant *C) { 341 if (C->getType()->isVectorTy()) { 342 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; 343 ++I) { 344 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I)); 345 if (!CFP || !CFP->getValueAPF().isNormal()) 346 return false; 347 } 348 return true; 349 } 350 351 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal(); 352 } 353 354 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns 355 /// true iff the given value is FMul or FDiv with one and only one operand 356 /// being a normal constant (i.e. not Zero/NaN/Infinity). 357 static bool isFMulOrFDivWithConstant(Value *V) { 358 Instruction *I = dyn_cast<Instruction>(V); 359 if (!I || (I->getOpcode() != Instruction::FMul && 360 I->getOpcode() != Instruction::FDiv)) 361 return false; 362 363 Constant *C0 = dyn_cast<Constant>(I->getOperand(0)); 364 Constant *C1 = dyn_cast<Constant>(I->getOperand(1)); 365 366 if (C0 && C1) 367 return false; 368 369 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1)); 370 } 371 372 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul(). 373 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand 374 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true). 375 /// This function is to simplify "FMulOrDiv * C" and returns the 376 /// resulting expression. Note that this function could return NULL in 377 /// case the constants cannot be folded into a normal floating-point. 378 /// 379 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C, 380 Instruction *InsertBefore) { 381 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid"); 382 383 Value *Opnd0 = FMulOrDiv->getOperand(0); 384 Value *Opnd1 = FMulOrDiv->getOperand(1); 385 386 Constant *C0 = dyn_cast<Constant>(Opnd0); 387 Constant *C1 = dyn_cast<Constant>(Opnd1); 388 389 BinaryOperator *R = 0; 390 391 // (X * C0) * C => X * (C0*C) 392 if (FMulOrDiv->getOpcode() == Instruction::FMul) { 393 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C); 394 if (isNormalFp(F)) 395 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F); 396 } else { 397 if (C0) { 398 // (C0 / X) * C => (C0 * C) / X 399 if (FMulOrDiv->hasOneUse()) { 400 // It would otherwise introduce another div. 401 Constant *F = ConstantExpr::getFMul(C0, C); 402 if (isNormalFp(F)) 403 R = BinaryOperator::CreateFDiv(F, Opnd1); 404 } 405 } else { 406 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal 407 Constant *F = ConstantExpr::getFDiv(C, C1); 408 if (isNormalFp(F)) { 409 R = BinaryOperator::CreateFMul(Opnd0, F); 410 } else { 411 // (X / C1) * C => X / (C1/C) 412 Constant *F = ConstantExpr::getFDiv(C1, C); 413 if (isNormalFp(F)) 414 R = BinaryOperator::CreateFDiv(Opnd0, F); 415 } 416 } 417 } 418 419 if (R) { 420 R->setHasUnsafeAlgebra(true); 421 InsertNewInstWith(R, *InsertBefore); 422 } 423 424 return R; 425 } 426 427 Instruction *InstCombiner::visitFMul(BinaryOperator &I) { 428 bool Changed = SimplifyAssociativeOrCommutative(I); 429 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 430 431 if (isa<Constant>(Op0)) 432 std::swap(Op0, Op1); 433 434 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL)) 435 return ReplaceInstUsesWith(I, V); 436 437 bool AllowReassociate = I.hasUnsafeAlgebra(); 438 439 // Simplify mul instructions with a constant RHS. 440 if (isa<Constant>(Op1)) { 441 // Try to fold constant mul into select arguments. 442 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 443 if (Instruction *R = FoldOpIntoSelect(I, SI)) 444 return R; 445 446 if (isa<PHINode>(Op0)) 447 if (Instruction *NV = FoldOpIntoPhi(I)) 448 return NV; 449 450 // (fmul X, -1.0) --> (fsub -0.0, X) 451 if (match(Op1, m_SpecificFP(-1.0))) { 452 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType()); 453 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0); 454 RI->copyFastMathFlags(&I); 455 return RI; 456 } 457 458 Constant *C = cast<Constant>(Op1); 459 if (AllowReassociate && isFiniteNonZeroFp(C)) { 460 // Let MDC denote an expression in one of these forms: 461 // X * C, C/X, X/C, where C is a constant. 462 // 463 // Try to simplify "MDC * Constant" 464 if (isFMulOrFDivWithConstant(Op0)) 465 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I)) 466 return ReplaceInstUsesWith(I, V); 467 468 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C) 469 Instruction *FAddSub = dyn_cast<Instruction>(Op0); 470 if (FAddSub && 471 (FAddSub->getOpcode() == Instruction::FAdd || 472 FAddSub->getOpcode() == Instruction::FSub)) { 473 Value *Opnd0 = FAddSub->getOperand(0); 474 Value *Opnd1 = FAddSub->getOperand(1); 475 Constant *C0 = dyn_cast<Constant>(Opnd0); 476 Constant *C1 = dyn_cast<Constant>(Opnd1); 477 bool Swap = false; 478 if (C0) { 479 std::swap(C0, C1); 480 std::swap(Opnd0, Opnd1); 481 Swap = true; 482 } 483 484 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) { 485 Value *M1 = ConstantExpr::getFMul(C1, C); 486 Value *M0 = isNormalFp(cast<Constant>(M1)) ? 487 foldFMulConst(cast<Instruction>(Opnd0), C, &I) : 488 0; 489 if (M0 && M1) { 490 if (Swap && FAddSub->getOpcode() == Instruction::FSub) 491 std::swap(M0, M1); 492 493 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd) 494 ? BinaryOperator::CreateFAdd(M0, M1) 495 : BinaryOperator::CreateFSub(M0, M1); 496 RI->copyFastMathFlags(&I); 497 return RI; 498 } 499 } 500 } 501 } 502 } 503 504 505 // Under unsafe algebra do: 506 // X * log2(0.5*Y) = X*log2(Y) - X 507 if (I.hasUnsafeAlgebra()) { 508 Value *OpX = NULL; 509 Value *OpY = NULL; 510 IntrinsicInst *Log2; 511 detectLog2OfHalf(Op0, OpY, Log2); 512 if (OpY) { 513 OpX = Op1; 514 } else { 515 detectLog2OfHalf(Op1, OpY, Log2); 516 if (OpY) { 517 OpX = Op0; 518 } 519 } 520 // if pattern detected emit alternate sequence 521 if (OpX && OpY) { 522 BuilderTy::FastMathFlagGuard Guard(*Builder); 523 Builder->SetFastMathFlags(Log2->getFastMathFlags()); 524 Log2->setArgOperand(0, OpY); 525 Value *FMulVal = Builder->CreateFMul(OpX, Log2); 526 Value *FSub = Builder->CreateFSub(FMulVal, OpX); 527 FSub->takeName(&I); 528 return ReplaceInstUsesWith(I, FSub); 529 } 530 } 531 532 // Handle symmetric situation in a 2-iteration loop 533 Value *Opnd0 = Op0; 534 Value *Opnd1 = Op1; 535 for (int i = 0; i < 2; i++) { 536 bool IgnoreZeroSign = I.hasNoSignedZeros(); 537 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) { 538 BuilderTy::FastMathFlagGuard Guard(*Builder); 539 Builder->SetFastMathFlags(I.getFastMathFlags()); 540 541 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign); 542 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign); 543 544 // -X * -Y => X*Y 545 if (N1) { 546 Value *FMul = Builder->CreateFMul(N0, N1); 547 FMul->takeName(&I); 548 return ReplaceInstUsesWith(I, FMul); 549 } 550 551 if (Opnd0->hasOneUse()) { 552 // -X * Y => -(X*Y) (Promote negation as high as possible) 553 Value *T = Builder->CreateFMul(N0, Opnd1); 554 Value *Neg = Builder->CreateFNeg(T); 555 Neg->takeName(&I); 556 return ReplaceInstUsesWith(I, Neg); 557 } 558 } 559 560 // (X*Y) * X => (X*X) * Y where Y != X 561 // The purpose is two-fold: 562 // 1) to form a power expression (of X). 563 // 2) potentially shorten the critical path: After transformation, the 564 // latency of the instruction Y is amortized by the expression of X*X, 565 // and therefore Y is in a "less critical" position compared to what it 566 // was before the transformation. 567 // 568 if (AllowReassociate) { 569 Value *Opnd0_0, *Opnd0_1; 570 if (Opnd0->hasOneUse() && 571 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) { 572 Value *Y = 0; 573 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1) 574 Y = Opnd0_1; 575 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1) 576 Y = Opnd0_0; 577 578 if (Y) { 579 BuilderTy::FastMathFlagGuard Guard(*Builder); 580 Builder->SetFastMathFlags(I.getFastMathFlags()); 581 Value *T = Builder->CreateFMul(Opnd1, Opnd1); 582 583 Value *R = Builder->CreateFMul(T, Y); 584 R->takeName(&I); 585 return ReplaceInstUsesWith(I, R); 586 } 587 } 588 } 589 590 // B * (uitofp i1 C) -> select C, B, 0 591 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) { 592 Value *LHS = Op0, *RHS = Op1; 593 Value *B, *C; 594 if (!match(RHS, m_UIToFP(m_Value(C)))) 595 std::swap(LHS, RHS); 596 597 if (match(RHS, m_UIToFP(m_Value(C))) && 598 C->getType()->getScalarType()->isIntegerTy(1)) { 599 B = LHS; 600 Value *Zero = ConstantFP::getNegativeZero(B->getType()); 601 return SelectInst::Create(C, B, Zero); 602 } 603 } 604 605 // A * (1 - uitofp i1 C) -> select C, 0, A 606 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) { 607 Value *LHS = Op0, *RHS = Op1; 608 Value *A, *C; 609 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C))))) 610 std::swap(LHS, RHS); 611 612 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) && 613 C->getType()->getScalarType()->isIntegerTy(1)) { 614 A = LHS; 615 Value *Zero = ConstantFP::getNegativeZero(A->getType()); 616 return SelectInst::Create(C, Zero, A); 617 } 618 } 619 620 if (!isa<Constant>(Op1)) 621 std::swap(Opnd0, Opnd1); 622 else 623 break; 624 } 625 626 return Changed ? &I : 0; 627 } 628 629 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select 630 /// instruction. 631 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) { 632 SelectInst *SI = cast<SelectInst>(I.getOperand(1)); 633 634 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 635 int NonNullOperand = -1; 636 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1))) 637 if (ST->isNullValue()) 638 NonNullOperand = 2; 639 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 640 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2))) 641 if (ST->isNullValue()) 642 NonNullOperand = 1; 643 644 if (NonNullOperand == -1) 645 return false; 646 647 Value *SelectCond = SI->getOperand(0); 648 649 // Change the div/rem to use 'Y' instead of the select. 650 I.setOperand(1, SI->getOperand(NonNullOperand)); 651 652 // Okay, we know we replace the operand of the div/rem with 'Y' with no 653 // problem. However, the select, or the condition of the select may have 654 // multiple uses. Based on our knowledge that the operand must be non-zero, 655 // propagate the known value for the select into other uses of it, and 656 // propagate a known value of the condition into its other users. 657 658 // If the select and condition only have a single use, don't bother with this, 659 // early exit. 660 if (SI->use_empty() && SelectCond->hasOneUse()) 661 return true; 662 663 // Scan the current block backward, looking for other uses of SI. 664 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin(); 665 666 while (BBI != BBFront) { 667 --BBI; 668 // If we found a call to a function, we can't assume it will return, so 669 // information from below it cannot be propagated above it. 670 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI)) 671 break; 672 673 // Replace uses of the select or its condition with the known values. 674 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); 675 I != E; ++I) { 676 if (*I == SI) { 677 *I = SI->getOperand(NonNullOperand); 678 Worklist.Add(BBI); 679 } else if (*I == SelectCond) { 680 *I = Builder->getInt1(NonNullOperand == 1); 681 Worklist.Add(BBI); 682 } 683 } 684 685 // If we past the instruction, quit looking for it. 686 if (&*BBI == SI) 687 SI = 0; 688 if (&*BBI == SelectCond) 689 SelectCond = 0; 690 691 // If we ran out of things to eliminate, break out of the loop. 692 if (SelectCond == 0 && SI == 0) 693 break; 694 695 } 696 return true; 697 } 698 699 700 /// This function implements the transforms common to both integer division 701 /// instructions (udiv and sdiv). It is called by the visitors to those integer 702 /// division instructions. 703 /// @brief Common integer divide transforms 704 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) { 705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 706 707 // The RHS is known non-zero. 708 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 709 I.setOperand(1, V); 710 return &I; 711 } 712 713 // Handle cases involving: [su]div X, (select Cond, Y, Z) 714 // This does not apply for fdiv. 715 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 716 return &I; 717 718 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 719 // (X / C1) / C2 -> X / (C1*C2) 720 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) 721 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode()) 722 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) { 723 if (MultiplyOverflows(RHS, LHSRHS, 724 I.getOpcode()==Instruction::SDiv)) 725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); 726 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0), 727 ConstantExpr::getMul(RHS, LHSRHS)); 728 } 729 730 if (!RHS->isZero()) { // avoid X udiv 0 731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 732 if (Instruction *R = FoldOpIntoSelect(I, SI)) 733 return R; 734 if (isa<PHINode>(Op0)) 735 if (Instruction *NV = FoldOpIntoPhi(I)) 736 return NV; 737 } 738 } 739 740 // See if we can fold away this div instruction. 741 if (SimplifyDemandedInstructionBits(I)) 742 return &I; 743 744 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 745 Value *X = 0, *Z = 0; 746 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1 747 bool isSigned = I.getOpcode() == Instruction::SDiv; 748 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 749 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 750 return BinaryOperator::Create(I.getOpcode(), X, Op1); 751 } 752 753 return 0; 754 } 755 756 /// dyn_castZExtVal - Checks if V is a zext or constant that can 757 /// be truncated to Ty without losing bits. 758 static Value *dyn_castZExtVal(Value *V, Type *Ty) { 759 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) { 760 if (Z->getSrcTy() == Ty) 761 return Z->getOperand(0); 762 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) { 763 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth()) 764 return ConstantExpr::getTrunc(C, Ty); 765 } 766 return 0; 767 } 768 769 namespace { 770 const unsigned MaxDepth = 6; 771 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1, 772 const BinaryOperator &I, 773 InstCombiner &IC); 774 775 /// \brief Used to maintain state for visitUDivOperand(). 776 struct UDivFoldAction { 777 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this 778 ///< operand. This can be zero if this action 779 ///< joins two actions together. 780 781 Value *OperandToFold; ///< Which operand to fold. 782 union { 783 Instruction *FoldResult; ///< The instruction returned when FoldAction is 784 ///< invoked. 785 786 size_t SelectLHSIdx; ///< Stores the LHS action index if this action 787 ///< joins two actions together. 788 }; 789 790 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand) 791 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {} 792 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS) 793 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {} 794 }; 795 } 796 797 // X udiv 2^C -> X >> C 798 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1, 799 const BinaryOperator &I, InstCombiner &IC) { 800 const APInt &C = cast<Constant>(Op1)->getUniqueInteger(); 801 BinaryOperator *LShr = BinaryOperator::CreateLShr( 802 Op0, ConstantInt::get(Op0->getType(), C.logBase2())); 803 if (I.isExact()) LShr->setIsExact(); 804 return LShr; 805 } 806 807 // X udiv C, where C >= signbit 808 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1, 809 const BinaryOperator &I, InstCombiner &IC) { 810 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1)); 811 812 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()), 813 ConstantInt::get(I.getType(), 1)); 814 } 815 816 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 817 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I, 818 InstCombiner &IC) { 819 Instruction *ShiftLeft = cast<Instruction>(Op1); 820 if (isa<ZExtInst>(ShiftLeft)) 821 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0)); 822 823 const APInt &CI = 824 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger(); 825 Value *N = ShiftLeft->getOperand(1); 826 if (CI != 1) 827 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2())); 828 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1)) 829 N = IC.Builder->CreateZExt(N, Z->getDestTy()); 830 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N); 831 if (I.isExact()) LShr->setIsExact(); 832 return LShr; 833 } 834 835 // \brief Recursively visits the possible right hand operands of a udiv 836 // instruction, seeing through select instructions, to determine if we can 837 // replace the udiv with something simpler. If we find that an operand is not 838 // able to simplify the udiv, we abort the entire transformation. 839 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I, 840 SmallVectorImpl<UDivFoldAction> &Actions, 841 unsigned Depth = 0) { 842 // Check to see if this is an unsigned division with an exact power of 2, 843 // if so, convert to a right shift. 844 if (match(Op1, m_Power2())) { 845 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1)); 846 return Actions.size(); 847 } 848 849 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) 850 // X udiv C, where C >= signbit 851 if (C->getValue().isNegative()) { 852 Actions.push_back(UDivFoldAction(foldUDivNegCst, C)); 853 return Actions.size(); 854 } 855 856 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 857 if (match(Op1, m_Shl(m_Power2(), m_Value())) || 858 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) { 859 Actions.push_back(UDivFoldAction(foldUDivShl, Op1)); 860 return Actions.size(); 861 } 862 863 // The remaining tests are all recursive, so bail out if we hit the limit. 864 if (Depth++ == MaxDepth) 865 return 0; 866 867 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 868 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions)) 869 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) { 870 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1)); 871 return Actions.size(); 872 } 873 874 return 0; 875 } 876 877 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) { 878 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 879 880 if (Value *V = SimplifyUDivInst(Op0, Op1, DL)) 881 return ReplaceInstUsesWith(I, V); 882 883 // Handle the integer div common cases 884 if (Instruction *Common = commonIDivTransforms(I)) 885 return Common; 886 887 // (x lshr C1) udiv C2 --> x udiv (C2 << C1) 888 if (Constant *C2 = dyn_cast<Constant>(Op1)) { 889 Value *X; 890 Constant *C1; 891 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1)))) 892 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1)); 893 } 894 895 // (zext A) udiv (zext B) --> zext (A udiv B) 896 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 897 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 898 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", 899 I.isExact()), 900 I.getType()); 901 902 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...)))) 903 SmallVector<UDivFoldAction, 6> UDivActions; 904 if (visitUDivOperand(Op0, Op1, I, UDivActions)) 905 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) { 906 FoldUDivOperandCb Action = UDivActions[i].FoldAction; 907 Value *ActionOp1 = UDivActions[i].OperandToFold; 908 Instruction *Inst; 909 if (Action) 910 Inst = Action(Op0, ActionOp1, I, *this); 911 else { 912 // This action joins two actions together. The RHS of this action is 913 // simply the last action we processed, we saved the LHS action index in 914 // the joining action. 915 size_t SelectRHSIdx = i - 1; 916 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult; 917 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx; 918 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult; 919 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(), 920 SelectLHS, SelectRHS); 921 } 922 923 // If this is the last action to process, return it to the InstCombiner. 924 // Otherwise, we insert it before the UDiv and record it so that we may 925 // use it as part of a joining action (i.e., a SelectInst). 926 if (e - i != 1) { 927 Inst->insertBefore(&I); 928 UDivActions[i].FoldResult = Inst; 929 } else 930 return Inst; 931 } 932 933 return 0; 934 } 935 936 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) { 937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 938 939 if (Value *V = SimplifySDivInst(Op0, Op1, DL)) 940 return ReplaceInstUsesWith(I, V); 941 942 // Handle the integer div common cases 943 if (Instruction *Common = commonIDivTransforms(I)) 944 return Common; 945 946 // sdiv X, -1 == -X 947 if (match(Op1, m_AllOnes())) 948 return BinaryOperator::CreateNeg(Op0); 949 950 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 951 // sdiv X, C --> ashr exact X, log2(C) 952 if (I.isExact() && RHS->getValue().isNonNegative() && 953 RHS->getValue().isPowerOf2()) { 954 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(), 955 RHS->getValue().exactLogBase2()); 956 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName()); 957 } 958 } 959 960 if (Constant *RHS = dyn_cast<Constant>(Op1)) { 961 // -X/C --> X/-C provided the negation doesn't overflow. 962 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0)) 963 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap()) 964 return BinaryOperator::CreateSDiv(Sub->getOperand(1), 965 ConstantExpr::getNeg(RHS)); 966 } 967 968 // If the sign bits of both operands are zero (i.e. we can prove they are 969 // unsigned inputs), turn this into a udiv. 970 if (I.getType()->isIntegerTy()) { 971 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 972 if (MaskedValueIsZero(Op0, Mask)) { 973 if (MaskedValueIsZero(Op1, Mask)) { 974 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 975 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 976 } 977 978 if (match(Op1, m_Shl(m_Power2(), m_Value()))) { 979 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 980 // Safe because the only negative value (1 << Y) can take on is 981 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 982 // the sign bit set. 983 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 984 } 985 } 986 } 987 988 return 0; 989 } 990 991 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special 992 /// FP value and: 993 /// 1) 1/C is exact, or 994 /// 2) reciprocal is allowed. 995 /// If the conversion was successful, the simplified expression "X * 1/C" is 996 /// returned; otherwise, NULL is returned. 997 /// 998 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, 999 Constant *Divisor, 1000 bool AllowReciprocal) { 1001 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors. 1002 return 0; 1003 1004 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF(); 1005 APFloat Reciprocal(FpVal.getSemantics()); 1006 bool Cvt = FpVal.getExactInverse(&Reciprocal); 1007 1008 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) { 1009 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f); 1010 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven); 1011 Cvt = !Reciprocal.isDenormal(); 1012 } 1013 1014 if (!Cvt) 1015 return 0; 1016 1017 ConstantFP *R; 1018 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal); 1019 return BinaryOperator::CreateFMul(Dividend, R); 1020 } 1021 1022 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) { 1023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1024 1025 if (Value *V = SimplifyFDivInst(Op0, Op1, DL)) 1026 return ReplaceInstUsesWith(I, V); 1027 1028 if (isa<Constant>(Op0)) 1029 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 1030 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1031 return R; 1032 1033 bool AllowReassociate = I.hasUnsafeAlgebra(); 1034 bool AllowReciprocal = I.hasAllowReciprocal(); 1035 1036 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 1037 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 1038 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1039 return R; 1040 1041 if (AllowReassociate) { 1042 Constant *C1 = 0; 1043 Constant *C2 = Op1C; 1044 Value *X; 1045 Instruction *Res = 0; 1046 1047 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) { 1048 // (X*C1)/C2 => X * (C1/C2) 1049 // 1050 Constant *C = ConstantExpr::getFDiv(C1, C2); 1051 if (isNormalFp(C)) 1052 Res = BinaryOperator::CreateFMul(X, C); 1053 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) { 1054 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed] 1055 // 1056 Constant *C = ConstantExpr::getFMul(C1, C2); 1057 if (isNormalFp(C)) { 1058 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal); 1059 if (!Res) 1060 Res = BinaryOperator::CreateFDiv(X, C); 1061 } 1062 } 1063 1064 if (Res) { 1065 Res->setFastMathFlags(I.getFastMathFlags()); 1066 return Res; 1067 } 1068 } 1069 1070 // X / C => X * 1/C 1071 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) { 1072 T->copyFastMathFlags(&I); 1073 return T; 1074 } 1075 1076 return 0; 1077 } 1078 1079 if (AllowReassociate && isa<Constant>(Op0)) { 1080 Constant *C1 = cast<Constant>(Op0), *C2; 1081 Constant *Fold = 0; 1082 Value *X; 1083 bool CreateDiv = true; 1084 1085 // C1 / (X*C2) => (C1/C2) / X 1086 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2)))) 1087 Fold = ConstantExpr::getFDiv(C1, C2); 1088 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) { 1089 // C1 / (X/C2) => (C1*C2) / X 1090 Fold = ConstantExpr::getFMul(C1, C2); 1091 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) { 1092 // C1 / (C2/X) => (C1/C2) * X 1093 Fold = ConstantExpr::getFDiv(C1, C2); 1094 CreateDiv = false; 1095 } 1096 1097 if (Fold && isNormalFp(Fold)) { 1098 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X) 1099 : BinaryOperator::CreateFMul(X, Fold); 1100 R->setFastMathFlags(I.getFastMathFlags()); 1101 return R; 1102 } 1103 return 0; 1104 } 1105 1106 if (AllowReassociate) { 1107 Value *X, *Y; 1108 Value *NewInst = 0; 1109 Instruction *SimpR = 0; 1110 1111 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) { 1112 // (X/Y) / Z => X / (Y*Z) 1113 // 1114 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) { 1115 NewInst = Builder->CreateFMul(Y, Op1); 1116 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) { 1117 FastMathFlags Flags = I.getFastMathFlags(); 1118 Flags &= cast<Instruction>(Op0)->getFastMathFlags(); 1119 RI->setFastMathFlags(Flags); 1120 } 1121 SimpR = BinaryOperator::CreateFDiv(X, NewInst); 1122 } 1123 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) { 1124 // Z / (X/Y) => Z*Y / X 1125 // 1126 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) { 1127 NewInst = Builder->CreateFMul(Op0, Y); 1128 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) { 1129 FastMathFlags Flags = I.getFastMathFlags(); 1130 Flags &= cast<Instruction>(Op1)->getFastMathFlags(); 1131 RI->setFastMathFlags(Flags); 1132 } 1133 SimpR = BinaryOperator::CreateFDiv(NewInst, X); 1134 } 1135 } 1136 1137 if (NewInst) { 1138 if (Instruction *T = dyn_cast<Instruction>(NewInst)) 1139 T->setDebugLoc(I.getDebugLoc()); 1140 SimpR->setFastMathFlags(I.getFastMathFlags()); 1141 return SimpR; 1142 } 1143 } 1144 1145 return 0; 1146 } 1147 1148 /// This function implements the transforms common to both integer remainder 1149 /// instructions (urem and srem). It is called by the visitors to those integer 1150 /// remainder instructions. 1151 /// @brief Common integer remainder transforms 1152 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) { 1153 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1154 1155 // The RHS is known non-zero. 1156 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 1157 I.setOperand(1, V); 1158 return &I; 1159 } 1160 1161 // Handle cases involving: rem X, (select Cond, Y, Z) 1162 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 1163 return &I; 1164 1165 if (isa<Constant>(Op1)) { 1166 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 1167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 1168 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1169 return R; 1170 } else if (isa<PHINode>(Op0I)) { 1171 if (Instruction *NV = FoldOpIntoPhi(I)) 1172 return NV; 1173 } 1174 1175 // See if we can fold away this rem instruction. 1176 if (SimplifyDemandedInstructionBits(I)) 1177 return &I; 1178 } 1179 } 1180 1181 return 0; 1182 } 1183 1184 Instruction *InstCombiner::visitURem(BinaryOperator &I) { 1185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1186 1187 if (Value *V = SimplifyURemInst(Op0, Op1, DL)) 1188 return ReplaceInstUsesWith(I, V); 1189 1190 if (Instruction *common = commonIRemTransforms(I)) 1191 return common; 1192 1193 // (zext A) urem (zext B) --> zext (A urem B) 1194 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 1195 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 1196 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1), 1197 I.getType()); 1198 1199 // X urem Y -> X and Y-1, where Y is a power of 2, 1200 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) { 1201 Constant *N1 = Constant::getAllOnesValue(I.getType()); 1202 Value *Add = Builder->CreateAdd(Op1, N1); 1203 return BinaryOperator::CreateAnd(Op0, Add); 1204 } 1205 1206 // 1 urem X -> zext(X != 1) 1207 if (match(Op0, m_One())) { 1208 Value *Cmp = Builder->CreateICmpNE(Op1, Op0); 1209 Value *Ext = Builder->CreateZExt(Cmp, I.getType()); 1210 return ReplaceInstUsesWith(I, Ext); 1211 } 1212 1213 return 0; 1214 } 1215 1216 Instruction *InstCombiner::visitSRem(BinaryOperator &I) { 1217 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1218 1219 if (Value *V = SimplifySRemInst(Op0, Op1, DL)) 1220 return ReplaceInstUsesWith(I, V); 1221 1222 // Handle the integer rem common cases 1223 if (Instruction *Common = commonIRemTransforms(I)) 1224 return Common; 1225 1226 if (Value *RHSNeg = dyn_castNegVal(Op1)) 1227 if (!isa<Constant>(RHSNeg) || 1228 (isa<ConstantInt>(RHSNeg) && 1229 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) { 1230 // X % -Y -> X % Y 1231 Worklist.AddValue(I.getOperand(1)); 1232 I.setOperand(1, RHSNeg); 1233 return &I; 1234 } 1235 1236 // If the sign bits of both operands are zero (i.e. we can prove they are 1237 // unsigned inputs), turn this into a urem. 1238 if (I.getType()->isIntegerTy()) { 1239 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 1240 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) { 1241 // X srem Y -> X urem Y, iff X and Y don't have sign bit set 1242 return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 1243 } 1244 } 1245 1246 // If it's a constant vector, flip any negative values positive. 1247 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) { 1248 Constant *C = cast<Constant>(Op1); 1249 unsigned VWidth = C->getType()->getVectorNumElements(); 1250 1251 bool hasNegative = false; 1252 bool hasMissing = false; 1253 for (unsigned i = 0; i != VWidth; ++i) { 1254 Constant *Elt = C->getAggregateElement(i); 1255 if (Elt == 0) { 1256 hasMissing = true; 1257 break; 1258 } 1259 1260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt)) 1261 if (RHS->isNegative()) 1262 hasNegative = true; 1263 } 1264 1265 if (hasNegative && !hasMissing) { 1266 SmallVector<Constant *, 16> Elts(VWidth); 1267 for (unsigned i = 0; i != VWidth; ++i) { 1268 Elts[i] = C->getAggregateElement(i); // Handle undef, etc. 1269 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) { 1270 if (RHS->isNegative()) 1271 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 1272 } 1273 } 1274 1275 Constant *NewRHSV = ConstantVector::get(Elts); 1276 if (NewRHSV != C) { // Don't loop on -MININT 1277 Worklist.AddValue(I.getOperand(1)); 1278 I.setOperand(1, NewRHSV); 1279 return &I; 1280 } 1281 } 1282 } 1283 1284 return 0; 1285 } 1286 1287 Instruction *InstCombiner::visitFRem(BinaryOperator &I) { 1288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1289 1290 if (Value *V = SimplifyFRemInst(Op0, Op1, DL)) 1291 return ReplaceInstUsesWith(I, V); 1292 1293 // Handle cases involving: rem X, (select Cond, Y, Z) 1294 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 1295 return &I; 1296 1297 return 0; 1298 } 1299