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