InstCombineMulDivRem.cpp revision 05cd88656135255b545d24adb51c2ba1b5c8b99e
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/IntrinsicInst.h" 17#include "llvm/Analysis/InstructionSimplify.h" 18#include "llvm/Support/PatternMatch.h" 19using namespace llvm; 20using namespace PatternMatch; 21 22 23/// simplifyValueKnownNonZero - The specific integer value is used in a context 24/// where it is known to be non-zero. If this allows us to simplify the 25/// computation, do so and return the new operand, otherwise return null. 26static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) { 27 // If V has multiple uses, then we would have to do more analysis to determine 28 // if this is safe. For example, the use could be in dynamically unreached 29 // code. 30 if (!V->hasOneUse()) return 0; 31 32 33 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it 34 // inexact. Similarly for <<. 35 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V)) 36 if (I->isLogicalShift() && 37 isPowerOfTwo(I->getOperand(0), IC.getTargetData())) { 38 if (I->getOpcode() == Instruction::LShr && !I->isExact()) { 39 I->setIsExact(); 40 return I; 41 } 42 43 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) { 44 I->setHasNoUnsignedWrap(); 45 return I; 46 } 47 } 48 49 // ((1 << A) >>u B) --> (1 << (A-B)) 50 // Because V cannot be zero, we know that B is less than A. 51 Value *A = 0, *B = 0, *PowerOf2 = 0; 52 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))), 53 m_Value(B))) && 54 // The "1" can be any value known to be a power of 2. 55 isPowerOfTwo(PowerOf2, IC.getTargetData())) { 56 A = IC.Builder->CreateSub(A, B, "tmp"); 57 return IC.Builder->CreateShl(PowerOf2, A); 58 } 59 60 // TODO: Lots more we could do here: 61 // "1 >> X" could get an "isexact" bit. 62 // If V is a phi node, we can call this on each of its operands. 63 // "select cond, X, 0" can simplify to "X". 64 65 return 0; 66} 67 68 69/// MultiplyOverflows - True if the multiply can not be expressed in an int 70/// this size. 71static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) { 72 uint32_t W = C1->getBitWidth(); 73 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue(); 74 if (sign) { 75 LHSExt = LHSExt.sext(W * 2); 76 RHSExt = RHSExt.sext(W * 2); 77 } else { 78 LHSExt = LHSExt.zext(W * 2); 79 RHSExt = RHSExt.zext(W * 2); 80 } 81 82 APInt MulExt = LHSExt * RHSExt; 83 84 if (!sign) 85 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W)); 86 87 APInt Min = APInt::getSignedMinValue(W).sext(W * 2); 88 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2); 89 return MulExt.slt(Min) || MulExt.sgt(Max); 90} 91 92Instruction *InstCombiner::visitMul(BinaryOperator &I) { 93 bool Changed = SimplifyAssociativeOrCommutative(I); 94 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 95 96 if (Value *V = SimplifyMulInst(Op0, Op1, TD)) 97 return ReplaceInstUsesWith(I, V); 98 99 if (Value *V = SimplifyUsingDistributiveLaws(I)) 100 return ReplaceInstUsesWith(I, V); 101 102 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X 103 return BinaryOperator::CreateNeg(Op0, I.getName()); 104 105 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 106 107 // ((X << C1)*C2) == (X * (C2 << C1)) 108 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0)) 109 if (SI->getOpcode() == Instruction::Shl) 110 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1))) 111 return BinaryOperator::CreateMul(SI->getOperand(0), 112 ConstantExpr::getShl(CI, ShOp)); 113 114 const APInt &Val = CI->getValue(); 115 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C 116 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2()); 117 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst); 118 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap(); 119 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap(); 120 return Shl; 121 } 122 123 // Canonicalize (X+C1)*CI -> X*CI+C1*CI. 124 { Value *X; ConstantInt *C1; 125 if (Op0->hasOneUse() && 126 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) { 127 Value *Add = Builder->CreateMul(X, CI, "tmp"); 128 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI)); 129 } 130 } 131 } 132 133 // Simplify mul instructions with a constant RHS. 134 if (isa<Constant>(Op1)) { 135 // Try to fold constant mul into select arguments. 136 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 137 if (Instruction *R = FoldOpIntoSelect(I, SI)) 138 return R; 139 140 if (isa<PHINode>(Op0)) 141 if (Instruction *NV = FoldOpIntoPhi(I)) 142 return NV; 143 } 144 145 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y 146 if (Value *Op1v = dyn_castNegVal(Op1)) 147 return BinaryOperator::CreateMul(Op0v, Op1v); 148 149 // (X / Y) * Y = X - (X % Y) 150 // (X / Y) * -Y = (X % Y) - X 151 { 152 Value *Op1C = Op1; 153 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0); 154 if (!BO || 155 (BO->getOpcode() != Instruction::UDiv && 156 BO->getOpcode() != Instruction::SDiv)) { 157 Op1C = Op0; 158 BO = dyn_cast<BinaryOperator>(Op1); 159 } 160 Value *Neg = dyn_castNegVal(Op1C); 161 if (BO && BO->hasOneUse() && 162 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) && 163 (BO->getOpcode() == Instruction::UDiv || 164 BO->getOpcode() == Instruction::SDiv)) { 165 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1); 166 167 // If the division is exact, X % Y is zero, so we end up with X or -X. 168 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO)) 169 if (SDiv->isExact()) { 170 if (Op1BO == Op1C) 171 return ReplaceInstUsesWith(I, Op0BO); 172 return BinaryOperator::CreateNeg(Op0BO); 173 } 174 175 Value *Rem; 176 if (BO->getOpcode() == Instruction::UDiv) 177 Rem = Builder->CreateURem(Op0BO, Op1BO); 178 else 179 Rem = Builder->CreateSRem(Op0BO, Op1BO); 180 Rem->takeName(BO); 181 182 if (Op1BO == Op1C) 183 return BinaryOperator::CreateSub(Op0BO, Rem); 184 return BinaryOperator::CreateSub(Rem, Op0BO); 185 } 186 } 187 188 /// i1 mul -> i1 and. 189 if (I.getType()->isIntegerTy(1)) 190 return BinaryOperator::CreateAnd(Op0, Op1); 191 192 // X*(1 << Y) --> X << Y 193 // (1 << Y)*X --> X << Y 194 { 195 Value *Y; 196 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) 197 return BinaryOperator::CreateShl(Op1, Y); 198 if (match(Op1, m_Shl(m_One(), m_Value(Y)))) 199 return BinaryOperator::CreateShl(Op0, Y); 200 } 201 202 // If one of the operands of the multiply is a cast from a boolean value, then 203 // we know the bool is either zero or one, so this is a 'masking' multiply. 204 // X * Y (where Y is 0 or 1) -> X & (0-Y) 205 if (!I.getType()->isVectorTy()) { 206 // -2 is "-1 << 1" so it is all bits set except the low one. 207 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true); 208 209 Value *BoolCast = 0, *OtherOp = 0; 210 if (MaskedValueIsZero(Op0, Negative2)) 211 BoolCast = Op0, OtherOp = Op1; 212 else if (MaskedValueIsZero(Op1, Negative2)) 213 BoolCast = Op1, OtherOp = Op0; 214 215 if (BoolCast) { 216 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()), 217 BoolCast, "tmp"); 218 return BinaryOperator::CreateAnd(V, OtherOp); 219 } 220 } 221 222 return Changed ? &I : 0; 223} 224 225Instruction *InstCombiner::visitFMul(BinaryOperator &I) { 226 bool Changed = SimplifyAssociativeOrCommutative(I); 227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 228 229 // Simplify mul instructions with a constant RHS... 230 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 231 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) { 232 // "In IEEE floating point, x*1 is not equivalent to x for nans. However, 233 // ANSI says we can drop signals, so we can do this anyway." (from GCC) 234 if (Op1F->isExactlyValue(1.0)) 235 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0' 236 } else if (Op1C->getType()->isVectorTy()) { 237 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) { 238 // As above, vector X*splat(1.0) -> X in all defined cases. 239 if (Constant *Splat = Op1V->getSplatValue()) { 240 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat)) 241 if (F->isExactlyValue(1.0)) 242 return ReplaceInstUsesWith(I, Op0); 243 } 244 } 245 } 246 247 // Try to fold constant mul into select arguments. 248 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 249 if (Instruction *R = FoldOpIntoSelect(I, SI)) 250 return R; 251 252 if (isa<PHINode>(Op0)) 253 if (Instruction *NV = FoldOpIntoPhi(I)) 254 return NV; 255 } 256 257 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y 258 if (Value *Op1v = dyn_castFNegVal(Op1)) 259 return BinaryOperator::CreateFMul(Op0v, Op1v); 260 261 return Changed ? &I : 0; 262} 263 264/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select 265/// instruction. 266bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) { 267 SelectInst *SI = cast<SelectInst>(I.getOperand(1)); 268 269 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 270 int NonNullOperand = -1; 271 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1))) 272 if (ST->isNullValue()) 273 NonNullOperand = 2; 274 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 275 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2))) 276 if (ST->isNullValue()) 277 NonNullOperand = 1; 278 279 if (NonNullOperand == -1) 280 return false; 281 282 Value *SelectCond = SI->getOperand(0); 283 284 // Change the div/rem to use 'Y' instead of the select. 285 I.setOperand(1, SI->getOperand(NonNullOperand)); 286 287 // Okay, we know we replace the operand of the div/rem with 'Y' with no 288 // problem. However, the select, or the condition of the select may have 289 // multiple uses. Based on our knowledge that the operand must be non-zero, 290 // propagate the known value for the select into other uses of it, and 291 // propagate a known value of the condition into its other users. 292 293 // If the select and condition only have a single use, don't bother with this, 294 // early exit. 295 if (SI->use_empty() && SelectCond->hasOneUse()) 296 return true; 297 298 // Scan the current block backward, looking for other uses of SI. 299 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin(); 300 301 while (BBI != BBFront) { 302 --BBI; 303 // If we found a call to a function, we can't assume it will return, so 304 // information from below it cannot be propagated above it. 305 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI)) 306 break; 307 308 // Replace uses of the select or its condition with the known values. 309 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); 310 I != E; ++I) { 311 if (*I == SI) { 312 *I = SI->getOperand(NonNullOperand); 313 Worklist.Add(BBI); 314 } else if (*I == SelectCond) { 315 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) : 316 ConstantInt::getFalse(BBI->getContext()); 317 Worklist.Add(BBI); 318 } 319 } 320 321 // If we past the instruction, quit looking for it. 322 if (&*BBI == SI) 323 SI = 0; 324 if (&*BBI == SelectCond) 325 SelectCond = 0; 326 327 // If we ran out of things to eliminate, break out of the loop. 328 if (SelectCond == 0 && SI == 0) 329 break; 330 331 } 332 return true; 333} 334 335 336/// This function implements the transforms common to both integer division 337/// instructions (udiv and sdiv). It is called by the visitors to those integer 338/// division instructions. 339/// @brief Common integer divide transforms 340Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) { 341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 342 343 // The RHS is known non-zero. 344 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 345 I.setOperand(1, V); 346 return &I; 347 } 348 349 // Handle cases involving: [su]div X, (select Cond, Y, Z) 350 // This does not apply for fdiv. 351 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 352 return &I; 353 354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 355 // (X / C1) / C2 -> X / (C1*C2) 356 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) 357 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode()) 358 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) { 359 if (MultiplyOverflows(RHS, LHSRHS, 360 I.getOpcode()==Instruction::SDiv)) 361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); 362 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0), 363 ConstantExpr::getMul(RHS, LHSRHS)); 364 } 365 366 if (!RHS->isZero()) { // avoid X udiv 0 367 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 368 if (Instruction *R = FoldOpIntoSelect(I, SI)) 369 return R; 370 if (isa<PHINode>(Op0)) 371 if (Instruction *NV = FoldOpIntoPhi(I)) 372 return NV; 373 } 374 } 375 376 // See if we can fold away this div instruction. 377 if (SimplifyDemandedInstructionBits(I)) 378 return &I; 379 380 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 381 Value *X = 0, *Z = 0; 382 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1 383 bool isSigned = I.getOpcode() == Instruction::SDiv; 384 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 385 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 386 return BinaryOperator::Create(I.getOpcode(), X, Op1); 387 } 388 389 return 0; 390} 391 392/// dyn_castZExtVal - Checks if V is a zext or constant that can 393/// be truncated to Ty without losing bits. 394static Value *dyn_castZExtVal(Value *V, const Type *Ty) { 395 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) { 396 if (Z->getSrcTy() == Ty) 397 return Z->getOperand(0); 398 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) { 399 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth()) 400 return ConstantExpr::getTrunc(C, Ty); 401 } 402 return 0; 403} 404 405Instruction *InstCombiner::visitUDiv(BinaryOperator &I) { 406 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 407 408 if (Value *V = SimplifyUDivInst(Op0, Op1, TD)) 409 return ReplaceInstUsesWith(I, V); 410 411 // Handle the integer div common cases 412 if (Instruction *Common = commonIDivTransforms(I)) 413 return Common; 414 415 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) { 416 // X udiv 2^C -> X >> C 417 // Check to see if this is an unsigned division with an exact power of 2, 418 // if so, convert to a right shift. 419 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2 420 BinaryOperator *LShr = 421 BinaryOperator::CreateLShr(Op0, 422 ConstantInt::get(Op0->getType(), C->getValue().logBase2())); 423 if (I.isExact()) LShr->setIsExact(); 424 return LShr; 425 } 426 427 // X udiv C, where C >= signbit 428 if (C->getValue().isNegative()) { 429 Value *IC = Builder->CreateICmpULT(Op0, C); 430 return SelectInst::Create(IC, Constant::getNullValue(I.getType()), 431 ConstantInt::get(I.getType(), 1)); 432 } 433 } 434 435 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 436 { const APInt *CI; Value *N; 437 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) { 438 if (*CI != 1) 439 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()), 440 "tmp"); 441 if (I.isExact()) 442 return BinaryOperator::CreateExactLShr(Op0, N); 443 return BinaryOperator::CreateLShr(Op0, N); 444 } 445 } 446 447 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2) 448 // where C1&C2 are powers of two. 449 { Value *Cond; const APInt *C1, *C2; 450 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) { 451 // Construct the "on true" case of the select 452 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t", 453 I.isExact()); 454 455 // Construct the "on false" case of the select 456 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f", 457 I.isExact()); 458 459 // construct the select instruction and return it. 460 return SelectInst::Create(Cond, TSI, FSI); 461 } 462 } 463 464 // (zext A) udiv (zext B) --> zext (A udiv B) 465 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 466 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 467 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", 468 I.isExact()), 469 I.getType()); 470 471 return 0; 472} 473 474Instruction *InstCombiner::visitSDiv(BinaryOperator &I) { 475 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 476 477 if (Value *V = SimplifySDivInst(Op0, Op1, TD)) 478 return ReplaceInstUsesWith(I, V); 479 480 // Handle the integer div common cases 481 if (Instruction *Common = commonIDivTransforms(I)) 482 return Common; 483 484 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 485 // sdiv X, -1 == -X 486 if (RHS->isAllOnesValue()) 487 return BinaryOperator::CreateNeg(Op0); 488 489 // sdiv X, C --> ashr exact X, log2(C) 490 if (I.isExact() && RHS->getValue().isNonNegative() && 491 RHS->getValue().isPowerOf2()) { 492 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(), 493 RHS->getValue().exactLogBase2()); 494 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName()); 495 } 496 497 // -X/C --> X/-C provided the negation doesn't overflow. 498 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0)) 499 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap()) 500 return BinaryOperator::CreateSDiv(Sub->getOperand(1), 501 ConstantExpr::getNeg(RHS)); 502 } 503 504 // If the sign bits of both operands are zero (i.e. we can prove they are 505 // unsigned inputs), turn this into a udiv. 506 if (I.getType()->isIntegerTy()) { 507 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 508 if (MaskedValueIsZero(Op0, Mask)) { 509 if (MaskedValueIsZero(Op1, Mask)) { 510 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 511 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 512 } 513 514 if (match(Op1, m_Shl(m_Power2(), m_Value()))) { 515 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 516 // Safe because the only negative value (1 << Y) can take on is 517 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 518 // the sign bit set. 519 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 520 } 521 } 522 } 523 524 return 0; 525} 526 527Instruction *InstCombiner::visitFDiv(BinaryOperator &I) { 528 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 529 530 if (Value *V = SimplifyFDivInst(Op0, Op1, TD)) 531 return ReplaceInstUsesWith(I, V); 532 533 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 534 const APFloat &Op1F = Op1C->getValueAPF(); 535 536 // If the divisor has an exact multiplicative inverse we can turn the fdiv 537 // into a cheaper fmul. 538 APFloat Reciprocal(Op1F.getSemantics()); 539 if (Op1F.getExactInverse(&Reciprocal)) { 540 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal); 541 return BinaryOperator::CreateFMul(Op0, RFP); 542 } 543 } 544 545 return 0; 546} 547 548/// This function implements the transforms common to both integer remainder 549/// instructions (urem and srem). It is called by the visitors to those integer 550/// remainder instructions. 551/// @brief Common integer remainder transforms 552Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) { 553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 554 555 // The RHS is known non-zero. 556 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 557 I.setOperand(1, V); 558 return &I; 559 } 560 561 // Handle cases involving: rem X, (select Cond, Y, Z) 562 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 563 return &I; 564 565 if (isa<ConstantInt>(Op1)) { 566 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 568 if (Instruction *R = FoldOpIntoSelect(I, SI)) 569 return R; 570 } else if (isa<PHINode>(Op0I)) { 571 if (Instruction *NV = FoldOpIntoPhi(I)) 572 return NV; 573 } 574 575 // See if we can fold away this rem instruction. 576 if (SimplifyDemandedInstructionBits(I)) 577 return &I; 578 } 579 } 580 581 return 0; 582} 583 584Instruction *InstCombiner::visitURem(BinaryOperator &I) { 585 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 586 587 if (Value *V = SimplifyURemInst(Op0, Op1, TD)) 588 return ReplaceInstUsesWith(I, V); 589 590 if (Instruction *common = commonIRemTransforms(I)) 591 return common; 592 593 // X urem C^2 -> X and C-1 594 { const APInt *C; 595 if (match(Op1, m_Power2(C))) 596 return BinaryOperator::CreateAnd(Op0, 597 ConstantInt::get(I.getType(), *C-1)); 598 } 599 600 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) 601 if (match(Op1, m_Shl(m_Power2(), m_Value()))) { 602 Constant *N1 = Constant::getAllOnesValue(I.getType()); 603 Value *Add = Builder->CreateAdd(Op1, N1, "tmp"); 604 return BinaryOperator::CreateAnd(Op0, Add); 605 } 606 607 // urem X, (select Cond, 2^C1, 2^C2) --> 608 // select Cond, (and X, C1-1), (and X, C2-1) 609 // when C1&C2 are powers of two. 610 { Value *Cond; const APInt *C1, *C2; 611 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) { 612 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t"); 613 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f"); 614 return SelectInst::Create(Cond, TrueAnd, FalseAnd); 615 } 616 } 617 618 // (zext A) urem (zext B) --> zext (A urem B) 619 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 620 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 621 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1), 622 I.getType()); 623 624 return 0; 625} 626 627Instruction *InstCombiner::visitSRem(BinaryOperator &I) { 628 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 629 630 if (Value *V = SimplifySRemInst(Op0, Op1, TD)) 631 return ReplaceInstUsesWith(I, V); 632 633 // Handle the integer rem common cases 634 if (Instruction *Common = commonIRemTransforms(I)) 635 return Common; 636 637 if (Value *RHSNeg = dyn_castNegVal(Op1)) 638 if (!isa<Constant>(RHSNeg) || 639 (isa<ConstantInt>(RHSNeg) && 640 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) { 641 // X % -Y -> X % Y 642 Worklist.AddValue(I.getOperand(1)); 643 I.setOperand(1, RHSNeg); 644 return &I; 645 } 646 647 // If the sign bits of both operands are zero (i.e. we can prove they are 648 // unsigned inputs), turn this into a urem. 649 if (I.getType()->isIntegerTy()) { 650 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 651 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) { 652 // X srem Y -> X urem Y, iff X and Y don't have sign bit set 653 return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 654 } 655 } 656 657 // If it's a constant vector, flip any negative values positive. 658 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) { 659 unsigned VWidth = RHSV->getNumOperands(); 660 661 bool hasNegative = false; 662 for (unsigned i = 0; !hasNegative && i != VWidth; ++i) 663 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) 664 if (RHS->getValue().isNegative()) 665 hasNegative = true; 666 667 if (hasNegative) { 668 std::vector<Constant *> Elts(VWidth); 669 for (unsigned i = 0; i != VWidth; ++i) { 670 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) { 671 if (RHS->getValue().isNegative()) 672 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 673 else 674 Elts[i] = RHS; 675 } 676 } 677 678 Constant *NewRHSV = ConstantVector::get(Elts); 679 if (NewRHSV != RHSV) { 680 Worklist.AddValue(I.getOperand(1)); 681 I.setOperand(1, NewRHSV); 682 return &I; 683 } 684 } 685 } 686 687 return 0; 688} 689 690Instruction *InstCombiner::visitFRem(BinaryOperator &I) { 691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 692 693 if (Value *V = SimplifyFRemInst(Op0, Op1, TD)) 694 return ReplaceInstUsesWith(I, V); 695 696 // Handle cases involving: rem X, (select Cond, Y, Z) 697 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 698 return &I; 699 700 return 0; 701} 702