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