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