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