1 //===- InstCombineMulDivRem.cpp -------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv, 10 // srem, urem, frem. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/InstructionSimplify.h" 19 #include "llvm/IR/BasicBlock.h" 20 #include "llvm/IR/Constant.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/InstrTypes.h" 23 #include "llvm/IR/Instruction.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/Intrinsics.h" 27 #include "llvm/IR/Operator.h" 28 #include "llvm/IR/PatternMatch.h" 29 #include "llvm/IR/Type.h" 30 #include "llvm/IR/Value.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/KnownBits.h" 34 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 35 #include "llvm/Transforms/InstCombine/InstCombiner.h" 36 #include "llvm/Transforms/Utils/BuildLibCalls.h" 37 #include <cassert> 38 #include <cstddef> 39 #include <cstdint> 40 #include <utility> 41 42 using namespace llvm; 43 using namespace PatternMatch; 44 45 #define DEBUG_TYPE "instcombine" 46 47 /// The specific integer value is used in a context where it is known to be 48 /// non-zero. If this allows us to simplify the computation, do so and return 49 /// the new operand, otherwise return null. 50 static Value *simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, 51 Instruction &CxtI) { 52 // If V has multiple uses, then we would have to do more analysis to determine 53 // if this is safe. For example, the use could be in dynamically unreached 54 // code. 55 if (!V->hasOneUse()) return nullptr; 56 57 bool MadeChange = false; 58 59 // ((1 << A) >>u B) --> (1 << (A-B)) 60 // Because V cannot be zero, we know that B is less than A. 61 Value *A = nullptr, *B = nullptr, *One = nullptr; 62 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) && 63 match(One, m_One())) { 64 A = IC.Builder.CreateSub(A, B); 65 return IC.Builder.CreateShl(One, A); 66 } 67 68 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it 69 // inexact. Similarly for <<. 70 BinaryOperator *I = dyn_cast<BinaryOperator>(V); 71 if (I && I->isLogicalShift() && 72 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) { 73 // We know that this is an exact/nuw shift and that the input is a 74 // non-zero context as well. 75 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) { 76 IC.replaceOperand(*I, 0, V2); 77 MadeChange = true; 78 } 79 80 if (I->getOpcode() == Instruction::LShr && !I->isExact()) { 81 I->setIsExact(); 82 MadeChange = true; 83 } 84 85 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) { 86 I->setHasNoUnsignedWrap(); 87 MadeChange = true; 88 } 89 } 90 91 // TODO: Lots more we could do here: 92 // If V is a phi node, we can call this on each of its operands. 93 // "select cond, X, 0" can simplify to "X". 94 95 return MadeChange ? V : nullptr; 96 } 97 98 /// A helper routine of InstCombiner::visitMul(). 99 /// 100 /// If C is a scalar/fixed width vector of known powers of 2, then this 101 /// function returns a new scalar/fixed width vector obtained from logBase2 102 /// of C. 103 /// Return a null pointer otherwise. 104 static Constant *getLogBase2(Type *Ty, Constant *C) { 105 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N. 106 // FIXME: just assert that C there is no undef in \p C. 107 108 const APInt *IVal; 109 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2()) 110 return ConstantInt::get(Ty, IVal->logBase2()); 111 112 // FIXME: We can extract pow of 2 of splat constant for scalable vectors. 113 if (!isa<FixedVectorType>(Ty)) 114 return nullptr; 115 116 SmallVector<Constant *, 4> Elts; 117 for (unsigned I = 0, E = cast<FixedVectorType>(Ty)->getNumElements(); I != E; 118 ++I) { 119 Constant *Elt = C->getAggregateElement(I); 120 if (!Elt) 121 return nullptr; 122 if (isa<UndefValue>(Elt)) { 123 Elts.push_back(UndefValue::get(Ty->getScalarType())); 124 continue; 125 } 126 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2()) 127 return nullptr; 128 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2())); 129 } 130 131 return ConstantVector::get(Elts); 132 } 133 134 // TODO: This is a specific form of a much more general pattern. 135 // We could detect a select with any binop identity constant, or we 136 // could use SimplifyBinOp to see if either arm of the select reduces. 137 // But that needs to be done carefully and/or while removing potential 138 // reverse canonicalizations as in InstCombiner::foldSelectIntoOp(). 139 static Value *foldMulSelectToNegate(BinaryOperator &I, 140 InstCombiner::BuilderTy &Builder) { 141 Value *Cond, *OtherOp; 142 143 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp 144 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp 145 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())), 146 m_Value(OtherOp)))) 147 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp)); 148 149 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp 150 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp 151 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())), 152 m_Value(OtherOp)))) 153 return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp); 154 155 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp 156 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp 157 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0), 158 m_SpecificFP(-1.0))), 159 m_Value(OtherOp)))) { 160 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 161 Builder.setFastMathFlags(I.getFastMathFlags()); 162 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp)); 163 } 164 165 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp 166 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp 167 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0), 168 m_SpecificFP(1.0))), 169 m_Value(OtherOp)))) { 170 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 171 Builder.setFastMathFlags(I.getFastMathFlags()); 172 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp); 173 } 174 175 return nullptr; 176 } 177 178 Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) { 179 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1), 180 SQ.getWithInstruction(&I))) 181 return replaceInstUsesWith(I, V); 182 183 if (SimplifyAssociativeOrCommutative(I)) 184 return &I; 185 186 if (Instruction *X = foldVectorBinop(I)) 187 return X; 188 189 if (Value *V = SimplifyUsingDistributiveLaws(I)) 190 return replaceInstUsesWith(I, V); 191 192 // X * -1 == 0 - X 193 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 194 if (match(Op1, m_AllOnes())) { 195 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName()); 196 if (I.hasNoSignedWrap()) 197 BO->setHasNoSignedWrap(); 198 return BO; 199 } 200 201 // Also allow combining multiply instructions on vectors. 202 { 203 Value *NewOp; 204 Constant *C1, *C2; 205 const APInt *IVal; 206 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)), 207 m_Constant(C1))) && 208 match(C1, m_APInt(IVal))) { 209 // ((X << C2)*C1) == (X * (C1 << C2)) 210 Constant *Shl = ConstantExpr::getShl(C1, C2); 211 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0)); 212 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl); 213 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap()) 214 BO->setHasNoUnsignedWrap(); 215 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() && 216 Shl->isNotMinSignedValue()) 217 BO->setHasNoSignedWrap(); 218 return BO; 219 } 220 221 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) { 222 // Replace X*(2^C) with X << C, where C is either a scalar or a vector. 223 // Note that we need to sanitize undef multipliers to 1, 224 // to avoid introducing poison. 225 Constant *SafeC1 = Constant::replaceUndefsWith( 226 C1, ConstantInt::get(C1->getType()->getScalarType(), 1)); 227 if (Constant *NewCst = getLogBase2(NewOp->getType(), SafeC1)) { 228 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst); 229 230 if (I.hasNoUnsignedWrap()) 231 Shl->setHasNoUnsignedWrap(); 232 if (I.hasNoSignedWrap()) { 233 const APInt *V; 234 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1) 235 Shl->setHasNoSignedWrap(); 236 } 237 238 return Shl; 239 } 240 } 241 } 242 243 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) { 244 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation. 245 // The "* (1<<C)" thus becomes a potential shifting opportunity. 246 if (Value *NegOp0 = Negator::Negate(/*IsNegation*/ true, Op0, *this)) 247 return BinaryOperator::CreateMul( 248 NegOp0, ConstantExpr::getNeg(cast<Constant>(Op1)), I.getName()); 249 } 250 251 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I)) 252 return FoldedMul; 253 254 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder)) 255 return replaceInstUsesWith(I, FoldedMul); 256 257 // Simplify mul instructions with a constant RHS. 258 if (isa<Constant>(Op1)) { 259 // Canonicalize (X+C1)*CI -> X*CI+C1*CI. 260 Value *X; 261 Constant *C1; 262 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) { 263 Value *Mul = Builder.CreateMul(C1, Op1); 264 // Only go forward with the transform if C1*CI simplifies to a tidier 265 // constant. 266 if (!match(Mul, m_Mul(m_Value(), m_Value()))) 267 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul); 268 } 269 } 270 271 // abs(X) * abs(X) -> X * X 272 // nabs(X) * nabs(X) -> X * X 273 if (Op0 == Op1) { 274 Value *X, *Y; 275 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor; 276 if (SPF == SPF_ABS || SPF == SPF_NABS) 277 return BinaryOperator::CreateMul(X, X); 278 279 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) 280 return BinaryOperator::CreateMul(X, X); 281 } 282 283 // -X * C --> X * -C 284 Value *X, *Y; 285 Constant *Op1C; 286 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C))) 287 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C)); 288 289 // -X * -Y --> X * Y 290 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) { 291 auto *NewMul = BinaryOperator::CreateMul(X, Y); 292 if (I.hasNoSignedWrap() && 293 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() && 294 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap()) 295 NewMul->setHasNoSignedWrap(); 296 return NewMul; 297 } 298 299 // -X * Y --> -(X * Y) 300 // X * -Y --> -(X * Y) 301 if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y)))) 302 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y)); 303 304 // (X / Y) * Y = X - (X % Y) 305 // (X / Y) * -Y = (X % Y) - X 306 { 307 Value *Y = Op1; 308 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0); 309 if (!Div || (Div->getOpcode() != Instruction::UDiv && 310 Div->getOpcode() != Instruction::SDiv)) { 311 Y = Op0; 312 Div = dyn_cast<BinaryOperator>(Op1); 313 } 314 Value *Neg = dyn_castNegVal(Y); 315 if (Div && Div->hasOneUse() && 316 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) && 317 (Div->getOpcode() == Instruction::UDiv || 318 Div->getOpcode() == Instruction::SDiv)) { 319 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1); 320 321 // If the division is exact, X % Y is zero, so we end up with X or -X. 322 if (Div->isExact()) { 323 if (DivOp1 == Y) 324 return replaceInstUsesWith(I, X); 325 return BinaryOperator::CreateNeg(X); 326 } 327 328 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem 329 : Instruction::SRem; 330 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1); 331 if (DivOp1 == Y) 332 return BinaryOperator::CreateSub(X, Rem); 333 return BinaryOperator::CreateSub(Rem, X); 334 } 335 } 336 337 /// i1 mul -> i1 and. 338 if (I.getType()->isIntOrIntVectorTy(1)) 339 return BinaryOperator::CreateAnd(Op0, Op1); 340 341 // X*(1 << Y) --> X << Y 342 // (1 << Y)*X --> X << Y 343 { 344 Value *Y; 345 BinaryOperator *BO = nullptr; 346 bool ShlNSW = false; 347 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) { 348 BO = BinaryOperator::CreateShl(Op1, Y); 349 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap(); 350 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) { 351 BO = BinaryOperator::CreateShl(Op0, Y); 352 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap(); 353 } 354 if (BO) { 355 if (I.hasNoUnsignedWrap()) 356 BO->setHasNoUnsignedWrap(); 357 if (I.hasNoSignedWrap() && ShlNSW) 358 BO->setHasNoSignedWrap(); 359 return BO; 360 } 361 } 362 363 // (zext bool X) * (zext bool Y) --> zext (and X, Y) 364 // (sext bool X) * (sext bool Y) --> zext (and X, Y) 365 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same) 366 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) || 367 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) && 368 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() && 369 (Op0->hasOneUse() || Op1->hasOneUse())) { 370 Value *And = Builder.CreateAnd(X, Y, "mulbool"); 371 return CastInst::Create(Instruction::ZExt, And, I.getType()); 372 } 373 // (sext bool X) * (zext bool Y) --> sext (and X, Y) 374 // (zext bool X) * (sext bool Y) --> sext (and X, Y) 375 // Note: -1 * 1 == 1 * -1 == -1 376 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) || 377 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) && 378 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() && 379 (Op0->hasOneUse() || Op1->hasOneUse())) { 380 Value *And = Builder.CreateAnd(X, Y, "mulbool"); 381 return CastInst::Create(Instruction::SExt, And, I.getType()); 382 } 383 384 // (bool X) * Y --> X ? Y : 0 385 // Y * (bool X) --> X ? Y : 0 386 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 387 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0)); 388 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 389 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0)); 390 391 // (lshr X, 31) * Y --> (ashr X, 31) & Y 392 // Y * (lshr X, 31) --> (ashr X, 31) & Y 393 // TODO: We are not checking one-use because the elimination of the multiply 394 // is better for analysis? 395 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be 396 // more similar to what we're doing above. 397 const APInt *C; 398 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1) 399 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1); 400 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1) 401 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0); 402 403 if (Instruction *Ext = narrowMathIfNoOverflow(I)) 404 return Ext; 405 406 bool Changed = false; 407 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) { 408 Changed = true; 409 I.setHasNoSignedWrap(true); 410 } 411 412 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) { 413 Changed = true; 414 I.setHasNoUnsignedWrap(true); 415 } 416 417 return Changed ? &I : nullptr; 418 } 419 420 Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) { 421 BinaryOperator::BinaryOps Opcode = I.getOpcode(); 422 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) && 423 "Expected fmul or fdiv"); 424 425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 426 Value *X, *Y; 427 428 // -X * -Y --> X * Y 429 // -X / -Y --> X / Y 430 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 431 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I); 432 433 // fabs(X) * fabs(X) -> X * X 434 // fabs(X) / fabs(X) -> X / X 435 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X)))) 436 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I); 437 438 // fabs(X) * fabs(Y) --> fabs(X * Y) 439 // fabs(X) / fabs(Y) --> fabs(X / Y) 440 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) && 441 (Op0->hasOneUse() || Op1->hasOneUse())) { 442 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 443 Builder.setFastMathFlags(I.getFastMathFlags()); 444 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 445 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY); 446 Fabs->takeName(&I); 447 return replaceInstUsesWith(I, Fabs); 448 } 449 450 return nullptr; 451 } 452 453 Instruction *InstCombinerImpl::visitFMul(BinaryOperator &I) { 454 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1), 455 I.getFastMathFlags(), 456 SQ.getWithInstruction(&I))) 457 return replaceInstUsesWith(I, V); 458 459 if (SimplifyAssociativeOrCommutative(I)) 460 return &I; 461 462 if (Instruction *X = foldVectorBinop(I)) 463 return X; 464 465 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I)) 466 return FoldedMul; 467 468 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder)) 469 return replaceInstUsesWith(I, FoldedMul); 470 471 if (Instruction *R = foldFPSignBitOps(I)) 472 return R; 473 474 // X * -1.0 --> -X 475 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 476 if (match(Op1, m_SpecificFP(-1.0))) 477 return UnaryOperator::CreateFNegFMF(Op0, &I); 478 479 // -X * C --> X * -C 480 Value *X, *Y; 481 Constant *C; 482 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C))) 483 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I); 484 485 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E) 486 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1)) 487 return replaceInstUsesWith(I, V); 488 489 if (I.hasAllowReassoc()) { 490 // Reassociate constant RHS with another constant to form constant 491 // expression. 492 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) { 493 Constant *C1; 494 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) { 495 // (C1 / X) * C --> (C * C1) / X 496 Constant *CC1 = ConstantExpr::getFMul(C, C1); 497 if (CC1->isNormalFP()) 498 return BinaryOperator::CreateFDivFMF(CC1, X, &I); 499 } 500 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) { 501 // (X / C1) * C --> X * (C / C1) 502 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1); 503 if (CDivC1->isNormalFP()) 504 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I); 505 506 // If the constant was a denormal, try reassociating differently. 507 // (X / C1) * C --> X / (C1 / C) 508 Constant *C1DivC = ConstantExpr::getFDiv(C1, C); 509 if (Op0->hasOneUse() && C1DivC->isNormalFP()) 510 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I); 511 } 512 513 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are 514 // canonicalized to 'fadd X, C'. Distributing the multiply may allow 515 // further folds and (X * C) + C2 is 'fma'. 516 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) { 517 // (X + C1) * C --> (X * C) + (C * C1) 518 Constant *CC1 = ConstantExpr::getFMul(C, C1); 519 Value *XC = Builder.CreateFMulFMF(X, C, &I); 520 return BinaryOperator::CreateFAddFMF(XC, CC1, &I); 521 } 522 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) { 523 // (C1 - X) * C --> (C * C1) - (X * C) 524 Constant *CC1 = ConstantExpr::getFMul(C, C1); 525 Value *XC = Builder.CreateFMulFMF(X, C, &I); 526 return BinaryOperator::CreateFSubFMF(CC1, XC, &I); 527 } 528 } 529 530 Value *Z; 531 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))), 532 m_Value(Z)))) { 533 // Sink division: (X / Y) * Z --> (X * Z) / Y 534 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I); 535 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I); 536 } 537 538 // sqrt(X) * sqrt(Y) -> sqrt(X * Y) 539 // nnan disallows the possibility of returning a number if both operands are 540 // negative (in that case, we should return NaN). 541 if (I.hasNoNaNs() && 542 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) && 543 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) { 544 Value *XY = Builder.CreateFMulFMF(X, Y, &I); 545 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I); 546 return replaceInstUsesWith(I, Sqrt); 547 } 548 549 // The following transforms are done irrespective of the number of uses 550 // for the expression "1.0/sqrt(X)". 551 // 1) 1.0/sqrt(X) * X -> X/sqrt(X) 552 // 2) X * 1.0/sqrt(X) -> X/sqrt(X) 553 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it 554 // has the necessary (reassoc) fast-math-flags. 555 if (I.hasNoSignedZeros() && 556 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) && 557 match(Y, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && Op1 == X) 558 return BinaryOperator::CreateFDivFMF(X, Y, &I); 559 if (I.hasNoSignedZeros() && 560 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) && 561 match(Y, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && Op0 == X) 562 return BinaryOperator::CreateFDivFMF(X, Y, &I); 563 564 // Like the similar transform in instsimplify, this requires 'nsz' because 565 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0. 566 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && 567 Op0->hasNUses(2)) { 568 // Peek through fdiv to find squaring of square root: 569 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y 570 if (match(Op0, m_FDiv(m_Value(X), 571 m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) { 572 Value *XX = Builder.CreateFMulFMF(X, X, &I); 573 return BinaryOperator::CreateFDivFMF(XX, Y, &I); 574 } 575 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X) 576 if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)), 577 m_Value(X)))) { 578 Value *XX = Builder.CreateFMulFMF(X, X, &I); 579 return BinaryOperator::CreateFDivFMF(Y, XX, &I); 580 } 581 } 582 583 // exp(X) * exp(Y) -> exp(X + Y) 584 // Match as long as at least one of exp has only one use. 585 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) && 586 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) && 587 (Op0->hasOneUse() || Op1->hasOneUse())) { 588 Value *XY = Builder.CreateFAddFMF(X, Y, &I); 589 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I); 590 return replaceInstUsesWith(I, Exp); 591 } 592 593 // exp2(X) * exp2(Y) -> exp2(X + Y) 594 // Match as long as at least one of exp2 has only one use. 595 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) && 596 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) && 597 (Op0->hasOneUse() || Op1->hasOneUse())) { 598 Value *XY = Builder.CreateFAddFMF(X, Y, &I); 599 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I); 600 return replaceInstUsesWith(I, Exp2); 601 } 602 603 // (X*Y) * X => (X*X) * Y where Y != X 604 // The purpose is two-fold: 605 // 1) to form a power expression (of X). 606 // 2) potentially shorten the critical path: After transformation, the 607 // latency of the instruction Y is amortized by the expression of X*X, 608 // and therefore Y is in a "less critical" position compared to what it 609 // was before the transformation. 610 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && 611 Op1 != Y) { 612 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I); 613 return BinaryOperator::CreateFMulFMF(XX, Y, &I); 614 } 615 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && 616 Op0 != Y) { 617 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I); 618 return BinaryOperator::CreateFMulFMF(XX, Y, &I); 619 } 620 } 621 622 // log2(X * 0.5) * Y = log2(X) * Y - Y 623 if (I.isFast()) { 624 IntrinsicInst *Log2 = nullptr; 625 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>( 626 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) { 627 Log2 = cast<IntrinsicInst>(Op0); 628 Y = Op1; 629 } 630 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>( 631 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) { 632 Log2 = cast<IntrinsicInst>(Op1); 633 Y = Op0; 634 } 635 if (Log2) { 636 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I); 637 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I); 638 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I); 639 } 640 } 641 642 return nullptr; 643 } 644 645 /// Fold a divide or remainder with a select instruction divisor when one of the 646 /// select operands is zero. In that case, we can use the other select operand 647 /// because div/rem by zero is undefined. 648 bool InstCombinerImpl::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) { 649 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1)); 650 if (!SI) 651 return false; 652 653 int NonNullOperand; 654 if (match(SI->getTrueValue(), m_Zero())) 655 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 656 NonNullOperand = 2; 657 else if (match(SI->getFalseValue(), m_Zero())) 658 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 659 NonNullOperand = 1; 660 else 661 return false; 662 663 // Change the div/rem to use 'Y' instead of the select. 664 replaceOperand(I, 1, SI->getOperand(NonNullOperand)); 665 666 // Okay, we know we replace the operand of the div/rem with 'Y' with no 667 // problem. However, the select, or the condition of the select may have 668 // multiple uses. Based on our knowledge that the operand must be non-zero, 669 // propagate the known value for the select into other uses of it, and 670 // propagate a known value of the condition into its other users. 671 672 // If the select and condition only have a single use, don't bother with this, 673 // early exit. 674 Value *SelectCond = SI->getCondition(); 675 if (SI->use_empty() && SelectCond->hasOneUse()) 676 return true; 677 678 // Scan the current block backward, looking for other uses of SI. 679 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin(); 680 Type *CondTy = SelectCond->getType(); 681 while (BBI != BBFront) { 682 --BBI; 683 // If we found an instruction that we can't assume will return, so 684 // information from below it cannot be propagated above it. 685 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI)) 686 break; 687 688 // Replace uses of the select or its condition with the known values. 689 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); 690 I != E; ++I) { 691 if (*I == SI) { 692 replaceUse(*I, SI->getOperand(NonNullOperand)); 693 Worklist.push(&*BBI); 694 } else if (*I == SelectCond) { 695 replaceUse(*I, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy) 696 : ConstantInt::getFalse(CondTy)); 697 Worklist.push(&*BBI); 698 } 699 } 700 701 // If we past the instruction, quit looking for it. 702 if (&*BBI == SI) 703 SI = nullptr; 704 if (&*BBI == SelectCond) 705 SelectCond = nullptr; 706 707 // If we ran out of things to eliminate, break out of the loop. 708 if (!SelectCond && !SI) 709 break; 710 711 } 712 return true; 713 } 714 715 /// True if the multiply can not be expressed in an int this size. 716 static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product, 717 bool IsSigned) { 718 bool Overflow; 719 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow); 720 return Overflow; 721 } 722 723 /// True if C1 is a multiple of C2. Quotient contains C1/C2. 724 static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, 725 bool IsSigned) { 726 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal"); 727 728 // Bail if we will divide by zero. 729 if (C2.isNullValue()) 730 return false; 731 732 // Bail if we would divide INT_MIN by -1. 733 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue()) 734 return false; 735 736 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned); 737 if (IsSigned) 738 APInt::sdivrem(C1, C2, Quotient, Remainder); 739 else 740 APInt::udivrem(C1, C2, Quotient, Remainder); 741 742 return Remainder.isMinValue(); 743 } 744 745 /// This function implements the transforms common to both integer division 746 /// instructions (udiv and sdiv). It is called by the visitors to those integer 747 /// division instructions. 748 /// Common integer divide transforms 749 Instruction *InstCombinerImpl::commonIDivTransforms(BinaryOperator &I) { 750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 751 bool IsSigned = I.getOpcode() == Instruction::SDiv; 752 Type *Ty = I.getType(); 753 754 // The RHS is known non-zero. 755 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) 756 return replaceOperand(I, 1, V); 757 758 // Handle cases involving: [su]div X, (select Cond, Y, Z) 759 // This does not apply for fdiv. 760 if (simplifyDivRemOfSelectWithZeroOp(I)) 761 return &I; 762 763 const APInt *C2; 764 if (match(Op1, m_APInt(C2))) { 765 Value *X; 766 const APInt *C1; 767 768 // (X / C1) / C2 -> X / (C1*C2) 769 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) || 770 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) { 771 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 772 if (!multiplyOverflows(*C1, *C2, Product, IsSigned)) 773 return BinaryOperator::Create(I.getOpcode(), X, 774 ConstantInt::get(Ty, Product)); 775 } 776 777 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) || 778 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) { 779 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 780 781 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1. 782 if (isMultiple(*C2, *C1, Quotient, IsSigned)) { 783 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X, 784 ConstantInt::get(Ty, Quotient)); 785 NewDiv->setIsExact(I.isExact()); 786 return NewDiv; 787 } 788 789 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2. 790 if (isMultiple(*C1, *C2, Quotient, IsSigned)) { 791 auto *Mul = BinaryOperator::Create(Instruction::Mul, X, 792 ConstantInt::get(Ty, Quotient)); 793 auto *OBO = cast<OverflowingBinaryOperator>(Op0); 794 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap()); 795 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap()); 796 return Mul; 797 } 798 } 799 800 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) && 801 *C1 != C1->getBitWidth() - 1) || 802 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) { 803 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 804 APInt C1Shifted = APInt::getOneBitSet( 805 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue())); 806 807 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1. 808 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) { 809 auto *BO = BinaryOperator::Create(I.getOpcode(), X, 810 ConstantInt::get(Ty, Quotient)); 811 BO->setIsExact(I.isExact()); 812 return BO; 813 } 814 815 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2. 816 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) { 817 auto *Mul = BinaryOperator::Create(Instruction::Mul, X, 818 ConstantInt::get(Ty, Quotient)); 819 auto *OBO = cast<OverflowingBinaryOperator>(Op0); 820 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap()); 821 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap()); 822 return Mul; 823 } 824 } 825 826 if (!C2->isNullValue()) // avoid X udiv 0 827 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I)) 828 return FoldedDiv; 829 } 830 831 if (match(Op0, m_One())) { 832 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?"); 833 if (IsSigned) { 834 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the 835 // result is one, if Op1 is -1 then the result is minus one, otherwise 836 // it's zero. 837 Value *Inc = Builder.CreateAdd(Op1, Op0); 838 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3)); 839 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0)); 840 } else { 841 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the 842 // result is one, otherwise it's zero. 843 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty); 844 } 845 } 846 847 // See if we can fold away this div instruction. 848 if (SimplifyDemandedInstructionBits(I)) 849 return &I; 850 851 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 852 Value *X, *Z; 853 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1 854 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 855 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 856 return BinaryOperator::Create(I.getOpcode(), X, Op1); 857 858 // (X << Y) / X -> 1 << Y 859 Value *Y; 860 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y)))) 861 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y); 862 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y)))) 863 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y); 864 865 // X / (X * Y) -> 1 / Y if the multiplication does not overflow. 866 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) { 867 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap(); 868 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap(); 869 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) { 870 replaceOperand(I, 0, ConstantInt::get(Ty, 1)); 871 replaceOperand(I, 1, Y); 872 return &I; 873 } 874 } 875 876 return nullptr; 877 } 878 879 static const unsigned MaxDepth = 6; 880 881 namespace { 882 883 using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1, 884 const BinaryOperator &I, 885 InstCombinerImpl &IC); 886 887 /// Used to maintain state for visitUDivOperand(). 888 struct UDivFoldAction { 889 /// Informs visitUDiv() how to fold this operand. This can be zero if this 890 /// action joins two actions together. 891 FoldUDivOperandCb FoldAction; 892 893 /// Which operand to fold. 894 Value *OperandToFold; 895 896 union { 897 /// The instruction returned when FoldAction is invoked. 898 Instruction *FoldResult; 899 900 /// Stores the LHS action index if this action joins two actions together. 901 size_t SelectLHSIdx; 902 }; 903 904 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand) 905 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {} 906 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS) 907 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {} 908 }; 909 910 } // end anonymous namespace 911 912 // X udiv 2^C -> X >> C 913 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1, 914 const BinaryOperator &I, 915 InstCombinerImpl &IC) { 916 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1)); 917 if (!C1) 918 llvm_unreachable("Failed to constant fold udiv -> logbase2"); 919 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1); 920 if (I.isExact()) 921 LShr->setIsExact(); 922 return LShr; 923 } 924 925 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 926 // X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2) 927 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I, 928 InstCombinerImpl &IC) { 929 Value *ShiftLeft; 930 if (!match(Op1, m_ZExt(m_Value(ShiftLeft)))) 931 ShiftLeft = Op1; 932 933 Constant *CI; 934 Value *N; 935 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N)))) 936 llvm_unreachable("match should never fail here!"); 937 Constant *Log2Base = getLogBase2(N->getType(), CI); 938 if (!Log2Base) 939 llvm_unreachable("getLogBase2 should never fail here!"); 940 N = IC.Builder.CreateAdd(N, Log2Base); 941 if (Op1 != ShiftLeft) 942 N = IC.Builder.CreateZExt(N, Op1->getType()); 943 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N); 944 if (I.isExact()) 945 LShr->setIsExact(); 946 return LShr; 947 } 948 949 // Recursively visits the possible right hand operands of a udiv 950 // instruction, seeing through select instructions, to determine if we can 951 // replace the udiv with something simpler. If we find that an operand is not 952 // able to simplify the udiv, we abort the entire transformation. 953 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I, 954 SmallVectorImpl<UDivFoldAction> &Actions, 955 unsigned Depth = 0) { 956 // FIXME: assert that Op1 isn't/doesn't contain undef. 957 958 // Check to see if this is an unsigned division with an exact power of 2, 959 // if so, convert to a right shift. 960 if (match(Op1, m_Power2())) { 961 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1)); 962 return Actions.size(); 963 } 964 965 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 966 if (match(Op1, m_Shl(m_Power2(), m_Value())) || 967 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) { 968 Actions.push_back(UDivFoldAction(foldUDivShl, Op1)); 969 return Actions.size(); 970 } 971 972 // The remaining tests are all recursive, so bail out if we hit the limit. 973 if (Depth++ == MaxDepth) 974 return 0; 975 976 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 977 // FIXME: missed optimization: if one of the hands of select is/contains 978 // undef, just directly pick the other one. 979 // FIXME: can both hands contain undef? 980 if (size_t LHSIdx = 981 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth)) 982 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) { 983 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1)); 984 return Actions.size(); 985 } 986 987 return 0; 988 } 989 990 /// If we have zero-extended operands of an unsigned div or rem, we may be able 991 /// to narrow the operation (sink the zext below the math). 992 static Instruction *narrowUDivURem(BinaryOperator &I, 993 InstCombiner::BuilderTy &Builder) { 994 Instruction::BinaryOps Opcode = I.getOpcode(); 995 Value *N = I.getOperand(0); 996 Value *D = I.getOperand(1); 997 Type *Ty = I.getType(); 998 Value *X, *Y; 999 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) && 1000 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) { 1001 // udiv (zext X), (zext Y) --> zext (udiv X, Y) 1002 // urem (zext X), (zext Y) --> zext (urem X, Y) 1003 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y); 1004 return new ZExtInst(NarrowOp, Ty); 1005 } 1006 1007 Constant *C; 1008 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) || 1009 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) { 1010 // If the constant is the same in the smaller type, use the narrow version. 1011 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType()); 1012 if (ConstantExpr::getZExt(TruncC, Ty) != C) 1013 return nullptr; 1014 1015 // udiv (zext X), C --> zext (udiv X, C') 1016 // urem (zext X), C --> zext (urem X, C') 1017 // udiv C, (zext X) --> zext (udiv C', X) 1018 // urem C, (zext X) --> zext (urem C', X) 1019 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC) 1020 : Builder.CreateBinOp(Opcode, TruncC, X); 1021 return new ZExtInst(NarrowOp, Ty); 1022 } 1023 1024 return nullptr; 1025 } 1026 1027 Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) { 1028 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1), 1029 SQ.getWithInstruction(&I))) 1030 return replaceInstUsesWith(I, V); 1031 1032 if (Instruction *X = foldVectorBinop(I)) 1033 return X; 1034 1035 // Handle the integer div common cases 1036 if (Instruction *Common = commonIDivTransforms(I)) 1037 return Common; 1038 1039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1040 Value *X; 1041 const APInt *C1, *C2; 1042 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) { 1043 // (X lshr C1) udiv C2 --> X udiv (C2 << C1) 1044 bool Overflow; 1045 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow); 1046 if (!Overflow) { 1047 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value())); 1048 BinaryOperator *BO = BinaryOperator::CreateUDiv( 1049 X, ConstantInt::get(X->getType(), C2ShlC1)); 1050 if (IsExact) 1051 BO->setIsExact(); 1052 return BO; 1053 } 1054 } 1055 1056 // Op0 / C where C is large (negative) --> zext (Op0 >= C) 1057 // TODO: Could use isKnownNegative() to handle non-constant values. 1058 Type *Ty = I.getType(); 1059 if (match(Op1, m_Negative())) { 1060 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1); 1061 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1062 } 1063 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined) 1064 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 1065 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty)); 1066 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1067 } 1068 1069 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder)) 1070 return NarrowDiv; 1071 1072 // If the udiv operands are non-overflowing multiplies with a common operand, 1073 // then eliminate the common factor: 1074 // (A * B) / (A * X) --> B / X (and commuted variants) 1075 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching. 1076 // TODO: If -reassociation handled this generally, we could remove this. 1077 Value *A, *B; 1078 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) { 1079 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) || 1080 match(Op1, m_NUWMul(m_Value(X), m_Specific(A)))) 1081 return BinaryOperator::CreateUDiv(B, X); 1082 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) || 1083 match(Op1, m_NUWMul(m_Value(X), m_Specific(B)))) 1084 return BinaryOperator::CreateUDiv(A, X); 1085 } 1086 1087 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...)))) 1088 SmallVector<UDivFoldAction, 6> UDivActions; 1089 if (visitUDivOperand(Op0, Op1, I, UDivActions)) 1090 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) { 1091 FoldUDivOperandCb Action = UDivActions[i].FoldAction; 1092 Value *ActionOp1 = UDivActions[i].OperandToFold; 1093 Instruction *Inst; 1094 if (Action) 1095 Inst = Action(Op0, ActionOp1, I, *this); 1096 else { 1097 // This action joins two actions together. The RHS of this action is 1098 // simply the last action we processed, we saved the LHS action index in 1099 // the joining action. 1100 size_t SelectRHSIdx = i - 1; 1101 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult; 1102 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx; 1103 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult; 1104 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(), 1105 SelectLHS, SelectRHS); 1106 } 1107 1108 // If this is the last action to process, return it to the InstCombiner. 1109 // Otherwise, we insert it before the UDiv and record it so that we may 1110 // use it as part of a joining action (i.e., a SelectInst). 1111 if (e - i != 1) { 1112 Inst->insertBefore(&I); 1113 UDivActions[i].FoldResult = Inst; 1114 } else 1115 return Inst; 1116 } 1117 1118 return nullptr; 1119 } 1120 1121 Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) { 1122 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1), 1123 SQ.getWithInstruction(&I))) 1124 return replaceInstUsesWith(I, V); 1125 1126 if (Instruction *X = foldVectorBinop(I)) 1127 return X; 1128 1129 // Handle the integer div common cases 1130 if (Instruction *Common = commonIDivTransforms(I)) 1131 return Common; 1132 1133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1134 Type *Ty = I.getType(); 1135 Value *X; 1136 // sdiv Op0, -1 --> -Op0 1137 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined) 1138 if (match(Op1, m_AllOnes()) || 1139 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1140 return BinaryOperator::CreateNeg(Op0); 1141 1142 // X / INT_MIN --> X == INT_MIN 1143 if (match(Op1, m_SignMask())) 1144 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty); 1145 1146 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative 1147 // sdiv exact X, -1<<C --> -(ashr exact X, C) 1148 if (I.isExact() && ((match(Op1, m_Power2()) && match(Op1, m_NonNegative())) || 1149 match(Op1, m_NegatedPower2()))) { 1150 bool DivisorWasNegative = match(Op1, m_NegatedPower2()); 1151 if (DivisorWasNegative) 1152 Op1 = ConstantExpr::getNeg(cast<Constant>(Op1)); 1153 auto *AShr = BinaryOperator::CreateExactAShr( 1154 Op0, getLogBase2(Ty, cast<Constant>(Op1)), I.getName()); 1155 if (!DivisorWasNegative) 1156 return AShr; 1157 Builder.Insert(AShr); 1158 AShr->setName(I.getName() + ".neg"); 1159 return BinaryOperator::CreateNeg(AShr, I.getName()); 1160 } 1161 1162 const APInt *Op1C; 1163 if (match(Op1, m_APInt(Op1C))) { 1164 // If the dividend is sign-extended and the constant divisor is small enough 1165 // to fit in the source type, shrink the division to the narrower type: 1166 // (sext X) sdiv C --> sext (X sdiv C) 1167 Value *Op0Src; 1168 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) && 1169 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) { 1170 1171 // In the general case, we need to make sure that the dividend is not the 1172 // minimum signed value because dividing that by -1 is UB. But here, we 1173 // know that the -1 divisor case is already handled above. 1174 1175 Constant *NarrowDivisor = 1176 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType()); 1177 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor); 1178 return new SExtInst(NarrowOp, Ty); 1179 } 1180 1181 // -X / C --> X / -C (if the negation doesn't overflow). 1182 // TODO: This could be enhanced to handle arbitrary vector constants by 1183 // checking if all elements are not the min-signed-val. 1184 if (!Op1C->isMinSignedValue() && 1185 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) { 1186 Constant *NegC = ConstantInt::get(Ty, -(*Op1C)); 1187 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC); 1188 BO->setIsExact(I.isExact()); 1189 return BO; 1190 } 1191 } 1192 1193 // -X / Y --> -(X / Y) 1194 Value *Y; 1195 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) 1196 return BinaryOperator::CreateNSWNeg( 1197 Builder.CreateSDiv(X, Y, I.getName(), I.isExact())); 1198 1199 // abs(X) / X --> X > -1 ? 1 : -1 1200 // X / abs(X) --> X > -1 ? 1 : -1 1201 if (match(&I, m_c_BinOp( 1202 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())), 1203 m_Deferred(X)))) { 1204 Constant *NegOne = ConstantInt::getAllOnesValue(Ty); 1205 Value *Cond = Builder.CreateICmpSGT(X, NegOne); 1206 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1), NegOne); 1207 } 1208 1209 // If the sign bits of both operands are zero (i.e. we can prove they are 1210 // unsigned inputs), turn this into a udiv. 1211 APInt Mask(APInt::getSignMask(Ty->getScalarSizeInBits())); 1212 if (MaskedValueIsZero(Op0, Mask, 0, &I)) { 1213 if (MaskedValueIsZero(Op1, Mask, 0, &I)) { 1214 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 1215 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 1216 BO->setIsExact(I.isExact()); 1217 return BO; 1218 } 1219 1220 if (match(Op1, m_NegatedPower2())) { 1221 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) -> 1222 // -> -(X udiv (1 << C)) -> -(X u>> C) 1223 return BinaryOperator::CreateNeg(Builder.Insert(foldUDivPow2Cst( 1224 Op0, ConstantExpr::getNeg(cast<Constant>(Op1)), I, *this))); 1225 } 1226 1227 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) { 1228 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 1229 // Safe because the only negative value (1 << Y) can take on is 1230 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 1231 // the sign bit set. 1232 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 1233 BO->setIsExact(I.isExact()); 1234 return BO; 1235 } 1236 } 1237 1238 return nullptr; 1239 } 1240 1241 /// Remove negation and try to convert division into multiplication. 1242 static Instruction *foldFDivConstantDivisor(BinaryOperator &I) { 1243 Constant *C; 1244 if (!match(I.getOperand(1), m_Constant(C))) 1245 return nullptr; 1246 1247 // -X / C --> X / -C 1248 Value *X; 1249 if (match(I.getOperand(0), m_FNeg(m_Value(X)))) 1250 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I); 1251 1252 // If the constant divisor has an exact inverse, this is always safe. If not, 1253 // then we can still create a reciprocal if fast-math-flags allow it and the 1254 // constant is a regular number (not zero, infinite, or denormal). 1255 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP()))) 1256 return nullptr; 1257 1258 // Disallow denormal constants because we don't know what would happen 1259 // on all targets. 1260 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that 1261 // denorms are flushed? 1262 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C); 1263 if (!RecipC->isNormalFP()) 1264 return nullptr; 1265 1266 // X / C --> X * (1 / C) 1267 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I); 1268 } 1269 1270 /// Remove negation and try to reassociate constant math. 1271 static Instruction *foldFDivConstantDividend(BinaryOperator &I) { 1272 Constant *C; 1273 if (!match(I.getOperand(0), m_Constant(C))) 1274 return nullptr; 1275 1276 // C / -X --> -C / X 1277 Value *X; 1278 if (match(I.getOperand(1), m_FNeg(m_Value(X)))) 1279 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I); 1280 1281 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal()) 1282 return nullptr; 1283 1284 // Try to reassociate C / X expressions where X includes another constant. 1285 Constant *C2, *NewC = nullptr; 1286 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) { 1287 // C / (X * C2) --> (C / C2) / X 1288 NewC = ConstantExpr::getFDiv(C, C2); 1289 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) { 1290 // C / (X / C2) --> (C * C2) / X 1291 NewC = ConstantExpr::getFMul(C, C2); 1292 } 1293 // Disallow denormal constants because we don't know what would happen 1294 // on all targets. 1295 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that 1296 // denorms are flushed? 1297 if (!NewC || !NewC->isNormalFP()) 1298 return nullptr; 1299 1300 return BinaryOperator::CreateFDivFMF(NewC, X, &I); 1301 } 1302 1303 Instruction *InstCombinerImpl::visitFDiv(BinaryOperator &I) { 1304 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1), 1305 I.getFastMathFlags(), 1306 SQ.getWithInstruction(&I))) 1307 return replaceInstUsesWith(I, V); 1308 1309 if (Instruction *X = foldVectorBinop(I)) 1310 return X; 1311 1312 if (Instruction *R = foldFDivConstantDivisor(I)) 1313 return R; 1314 1315 if (Instruction *R = foldFDivConstantDividend(I)) 1316 return R; 1317 1318 if (Instruction *R = foldFPSignBitOps(I)) 1319 return R; 1320 1321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1322 if (isa<Constant>(Op0)) 1323 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 1324 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1325 return R; 1326 1327 if (isa<Constant>(Op1)) 1328 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 1329 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1330 return R; 1331 1332 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) { 1333 Value *X, *Y; 1334 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) && 1335 (!isa<Constant>(Y) || !isa<Constant>(Op1))) { 1336 // (X / Y) / Z => X / (Y * Z) 1337 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I); 1338 return BinaryOperator::CreateFDivFMF(X, YZ, &I); 1339 } 1340 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) && 1341 (!isa<Constant>(Y) || !isa<Constant>(Op0))) { 1342 // Z / (X / Y) => (Y * Z) / X 1343 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I); 1344 return BinaryOperator::CreateFDivFMF(YZ, X, &I); 1345 } 1346 // Z / (1.0 / Y) => (Y * Z) 1347 // 1348 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The 1349 // m_OneUse check is avoided because even in the case of the multiple uses 1350 // for 1.0/Y, the number of instructions remain the same and a division is 1351 // replaced by a multiplication. 1352 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) 1353 return BinaryOperator::CreateFMulFMF(Y, Op0, &I); 1354 } 1355 1356 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) { 1357 // sin(X) / cos(X) -> tan(X) 1358 // cos(X) / sin(X) -> 1/tan(X) (cotangent) 1359 Value *X; 1360 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) && 1361 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X))); 1362 bool IsCot = 1363 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) && 1364 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X))); 1365 1366 if ((IsTan || IsCot) && 1367 hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) { 1368 IRBuilder<> B(&I); 1369 IRBuilder<>::FastMathFlagGuard FMFGuard(B); 1370 B.setFastMathFlags(I.getFastMathFlags()); 1371 AttributeList Attrs = 1372 cast<CallBase>(Op0)->getCalledFunction()->getAttributes(); 1373 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf, 1374 LibFunc_tanl, B, Attrs); 1375 if (IsCot) 1376 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res); 1377 return replaceInstUsesWith(I, Res); 1378 } 1379 } 1380 1381 // X / (X * Y) --> 1.0 / Y 1382 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed. 1383 // We can ignore the possibility that X is infinity because INF/INF is NaN. 1384 Value *X, *Y; 1385 if (I.hasNoNaNs() && I.hasAllowReassoc() && 1386 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) { 1387 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0)); 1388 replaceOperand(I, 1, Y); 1389 return &I; 1390 } 1391 1392 // X / fabs(X) -> copysign(1.0, X) 1393 // fabs(X) / X -> copysign(1.0, X) 1394 if (I.hasNoNaNs() && I.hasNoInfs() && 1395 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) || 1396 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) { 1397 Value *V = Builder.CreateBinaryIntrinsic( 1398 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I); 1399 return replaceInstUsesWith(I, V); 1400 } 1401 return nullptr; 1402 } 1403 1404 /// This function implements the transforms common to both integer remainder 1405 /// instructions (urem and srem). It is called by the visitors to those integer 1406 /// remainder instructions. 1407 /// Common integer remainder transforms 1408 Instruction *InstCombinerImpl::commonIRemTransforms(BinaryOperator &I) { 1409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1410 1411 // The RHS is known non-zero. 1412 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) 1413 return replaceOperand(I, 1, V); 1414 1415 // Handle cases involving: rem X, (select Cond, Y, Z) 1416 if (simplifyDivRemOfSelectWithZeroOp(I)) 1417 return &I; 1418 1419 if (isa<Constant>(Op1)) { 1420 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 1421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 1422 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1423 return R; 1424 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) { 1425 const APInt *Op1Int; 1426 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() && 1427 (I.getOpcode() == Instruction::URem || 1428 !Op1Int->isMinSignedValue())) { 1429 // foldOpIntoPhi will speculate instructions to the end of the PHI's 1430 // predecessor blocks, so do this only if we know the srem or urem 1431 // will not fault. 1432 if (Instruction *NV = foldOpIntoPhi(I, PN)) 1433 return NV; 1434 } 1435 } 1436 1437 // See if we can fold away this rem instruction. 1438 if (SimplifyDemandedInstructionBits(I)) 1439 return &I; 1440 } 1441 } 1442 1443 return nullptr; 1444 } 1445 1446 Instruction *InstCombinerImpl::visitURem(BinaryOperator &I) { 1447 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1), 1448 SQ.getWithInstruction(&I))) 1449 return replaceInstUsesWith(I, V); 1450 1451 if (Instruction *X = foldVectorBinop(I)) 1452 return X; 1453 1454 if (Instruction *common = commonIRemTransforms(I)) 1455 return common; 1456 1457 if (Instruction *NarrowRem = narrowUDivURem(I, Builder)) 1458 return NarrowRem; 1459 1460 // X urem Y -> X and Y-1, where Y is a power of 2, 1461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1462 Type *Ty = I.getType(); 1463 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) { 1464 // This may increase instruction count, we don't enforce that Y is a 1465 // constant. 1466 Constant *N1 = Constant::getAllOnesValue(Ty); 1467 Value *Add = Builder.CreateAdd(Op1, N1); 1468 return BinaryOperator::CreateAnd(Op0, Add); 1469 } 1470 1471 // 1 urem X -> zext(X != 1) 1472 if (match(Op0, m_One())) { 1473 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1)); 1474 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1475 } 1476 1477 // X urem C -> X < C ? X : X - C, where C >= signbit. 1478 if (match(Op1, m_Negative())) { 1479 Value *Cmp = Builder.CreateICmpULT(Op0, Op1); 1480 Value *Sub = Builder.CreateSub(Op0, Op1); 1481 return SelectInst::Create(Cmp, Op0, Sub); 1482 } 1483 1484 // If the divisor is a sext of a boolean, then the divisor must be max 1485 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also 1486 // max unsigned value. In that case, the remainder is 0: 1487 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0 1488 Value *X; 1489 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 1490 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty)); 1491 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0); 1492 } 1493 1494 return nullptr; 1495 } 1496 1497 Instruction *InstCombinerImpl::visitSRem(BinaryOperator &I) { 1498 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1), 1499 SQ.getWithInstruction(&I))) 1500 return replaceInstUsesWith(I, V); 1501 1502 if (Instruction *X = foldVectorBinop(I)) 1503 return X; 1504 1505 // Handle the integer rem common cases 1506 if (Instruction *Common = commonIRemTransforms(I)) 1507 return Common; 1508 1509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1510 { 1511 const APInt *Y; 1512 // X % -Y -> X % Y 1513 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) 1514 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y)); 1515 } 1516 1517 // -X srem Y --> -(X srem Y) 1518 Value *X, *Y; 1519 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) 1520 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y)); 1521 1522 // If the sign bits of both operands are zero (i.e. we can prove they are 1523 // unsigned inputs), turn this into a urem. 1524 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits())); 1525 if (MaskedValueIsZero(Op1, Mask, 0, &I) && 1526 MaskedValueIsZero(Op0, Mask, 0, &I)) { 1527 // X srem Y -> X urem Y, iff X and Y don't have sign bit set 1528 return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 1529 } 1530 1531 // If it's a constant vector, flip any negative values positive. 1532 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) { 1533 Constant *C = cast<Constant>(Op1); 1534 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements(); 1535 1536 bool hasNegative = false; 1537 bool hasMissing = false; 1538 for (unsigned i = 0; i != VWidth; ++i) { 1539 Constant *Elt = C->getAggregateElement(i); 1540 if (!Elt) { 1541 hasMissing = true; 1542 break; 1543 } 1544 1545 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt)) 1546 if (RHS->isNegative()) 1547 hasNegative = true; 1548 } 1549 1550 if (hasNegative && !hasMissing) { 1551 SmallVector<Constant *, 16> Elts(VWidth); 1552 for (unsigned i = 0; i != VWidth; ++i) { 1553 Elts[i] = C->getAggregateElement(i); // Handle undef, etc. 1554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) { 1555 if (RHS->isNegative()) 1556 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 1557 } 1558 } 1559 1560 Constant *NewRHSV = ConstantVector::get(Elts); 1561 if (NewRHSV != C) // Don't loop on -MININT 1562 return replaceOperand(I, 1, NewRHSV); 1563 } 1564 } 1565 1566 return nullptr; 1567 } 1568 1569 Instruction *InstCombinerImpl::visitFRem(BinaryOperator &I) { 1570 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1), 1571 I.getFastMathFlags(), 1572 SQ.getWithInstruction(&I))) 1573 return replaceInstUsesWith(I, V); 1574 1575 if (Instruction *X = foldVectorBinop(I)) 1576 return X; 1577 1578 return nullptr; 1579 } 1580