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