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 // ((ashr X, 31) | 1) * X --> abs(X) 394 // X * ((ashr X, 31) | 1) --> abs(X) 395 if (match(&I, m_c_BinOp(m_Or(m_AShr(m_Value(X), 396 m_SpecificIntAllowUndef(BitWidth - 1)), 397 m_One()), 398 m_Deferred(X)))) { 399 Value *Abs = Builder.CreateBinaryIntrinsic( 400 Intrinsic::abs, X, 401 ConstantInt::getBool(I.getContext(), I.hasNoSignedWrap())); 402 Abs->takeName(&I); 403 return replaceInstUsesWith(I, Abs); 404 } 405 406 if (Instruction *Ext = narrowMathIfNoOverflow(I)) 407 return Ext; 408 409 bool Changed = false; 410 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) { 411 Changed = true; 412 I.setHasNoSignedWrap(true); 413 } 414 415 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) { 416 Changed = true; 417 I.setHasNoUnsignedWrap(true); 418 } 419 420 return Changed ? &I : nullptr; 421 } 422 423 Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) { 424 BinaryOperator::BinaryOps Opcode = I.getOpcode(); 425 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) && 426 "Expected fmul or fdiv"); 427 428 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 429 Value *X, *Y; 430 431 // -X * -Y --> X * Y 432 // -X / -Y --> X / Y 433 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 434 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I); 435 436 // fabs(X) * fabs(X) -> X * X 437 // fabs(X) / fabs(X) -> X / X 438 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X)))) 439 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I); 440 441 // fabs(X) * fabs(Y) --> fabs(X * Y) 442 // fabs(X) / fabs(Y) --> fabs(X / Y) 443 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) && 444 (Op0->hasOneUse() || Op1->hasOneUse())) { 445 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 446 Builder.setFastMathFlags(I.getFastMathFlags()); 447 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 448 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY); 449 Fabs->takeName(&I); 450 return replaceInstUsesWith(I, Fabs); 451 } 452 453 return nullptr; 454 } 455 456 Instruction *InstCombinerImpl::visitFMul(BinaryOperator &I) { 457 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1), 458 I.getFastMathFlags(), 459 SQ.getWithInstruction(&I))) 460 return replaceInstUsesWith(I, V); 461 462 if (SimplifyAssociativeOrCommutative(I)) 463 return &I; 464 465 if (Instruction *X = foldVectorBinop(I)) 466 return X; 467 468 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 469 return Phi; 470 471 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I)) 472 return FoldedMul; 473 474 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder)) 475 return replaceInstUsesWith(I, FoldedMul); 476 477 if (Instruction *R = foldFPSignBitOps(I)) 478 return R; 479 480 // X * -1.0 --> -X 481 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 482 if (match(Op1, m_SpecificFP(-1.0))) 483 return UnaryOperator::CreateFNegFMF(Op0, &I); 484 485 // -X * C --> X * -C 486 Value *X, *Y; 487 Constant *C; 488 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C))) 489 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I); 490 491 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E) 492 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1)) 493 return replaceInstUsesWith(I, V); 494 495 if (I.hasAllowReassoc()) { 496 // Reassociate constant RHS with another constant to form constant 497 // expression. 498 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) { 499 Constant *C1; 500 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) { 501 // (C1 / X) * C --> (C * C1) / X 502 Constant *CC1 = ConstantExpr::getFMul(C, C1); 503 if (CC1->isNormalFP()) 504 return BinaryOperator::CreateFDivFMF(CC1, X, &I); 505 } 506 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) { 507 // (X / C1) * C --> X * (C / C1) 508 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1); 509 if (CDivC1->isNormalFP()) 510 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I); 511 512 // If the constant was a denormal, try reassociating differently. 513 // (X / C1) * C --> X / (C1 / C) 514 Constant *C1DivC = ConstantExpr::getFDiv(C1, C); 515 if (Op0->hasOneUse() && C1DivC->isNormalFP()) 516 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I); 517 } 518 519 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are 520 // canonicalized to 'fadd X, C'. Distributing the multiply may allow 521 // further folds and (X * C) + C2 is 'fma'. 522 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) { 523 // (X + C1) * C --> (X * C) + (C * C1) 524 Constant *CC1 = ConstantExpr::getFMul(C, C1); 525 Value *XC = Builder.CreateFMulFMF(X, C, &I); 526 return BinaryOperator::CreateFAddFMF(XC, CC1, &I); 527 } 528 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) { 529 // (C1 - X) * C --> (C * C1) - (X * C) 530 Constant *CC1 = ConstantExpr::getFMul(C, C1); 531 Value *XC = Builder.CreateFMulFMF(X, C, &I); 532 return BinaryOperator::CreateFSubFMF(CC1, XC, &I); 533 } 534 } 535 536 Value *Z; 537 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))), 538 m_Value(Z)))) { 539 // Sink division: (X / Y) * Z --> (X * Z) / Y 540 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I); 541 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I); 542 } 543 544 // sqrt(X) * sqrt(Y) -> sqrt(X * Y) 545 // nnan disallows the possibility of returning a number if both operands are 546 // negative (in that case, we should return NaN). 547 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) && 548 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) { 549 Value *XY = Builder.CreateFMulFMF(X, Y, &I); 550 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I); 551 return replaceInstUsesWith(I, Sqrt); 552 } 553 554 // The following transforms are done irrespective of the number of uses 555 // for the expression "1.0/sqrt(X)". 556 // 1) 1.0/sqrt(X) * X -> X/sqrt(X) 557 // 2) X * 1.0/sqrt(X) -> X/sqrt(X) 558 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it 559 // has the necessary (reassoc) fast-math-flags. 560 if (I.hasNoSignedZeros() && 561 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) && 562 match(Y, m_Sqrt(m_Value(X))) && Op1 == X) 563 return BinaryOperator::CreateFDivFMF(X, Y, &I); 564 if (I.hasNoSignedZeros() && 565 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) && 566 match(Y, m_Sqrt(m_Value(X))) && Op0 == X) 567 return BinaryOperator::CreateFDivFMF(X, Y, &I); 568 569 // Like the similar transform in instsimplify, this requires 'nsz' because 570 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0. 571 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && 572 Op0->hasNUses(2)) { 573 // Peek through fdiv to find squaring of square root: 574 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y 575 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) { 576 Value *XX = Builder.CreateFMulFMF(X, X, &I); 577 return BinaryOperator::CreateFDivFMF(XX, Y, &I); 578 } 579 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X) 580 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) { 581 Value *XX = Builder.CreateFMulFMF(X, X, &I); 582 return BinaryOperator::CreateFDivFMF(Y, XX, &I); 583 } 584 } 585 586 if (I.isOnlyUserOfAnyOperand()) { 587 // pow(x, y) * pow(x, z) -> pow(x, y + z) 588 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) && 589 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Specific(X), m_Value(Z)))) { 590 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I); 591 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I); 592 return replaceInstUsesWith(I, NewPow); 593 } 594 595 // powi(x, y) * powi(x, z) -> powi(x, y + z) 596 if (match(Op0, m_Intrinsic<Intrinsic::powi>(m_Value(X), m_Value(Y))) && 597 match(Op1, m_Intrinsic<Intrinsic::powi>(m_Specific(X), m_Value(Z))) && 598 Y->getType() == Z->getType()) { 599 auto *YZ = Builder.CreateAdd(Y, Z); 600 auto *NewPow = Builder.CreateIntrinsic( 601 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I); 602 return replaceInstUsesWith(I, NewPow); 603 } 604 605 // exp(X) * exp(Y) -> exp(X + Y) 606 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) && 607 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y)))) { 608 Value *XY = Builder.CreateFAddFMF(X, Y, &I); 609 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I); 610 return replaceInstUsesWith(I, Exp); 611 } 612 613 // exp2(X) * exp2(Y) -> exp2(X + Y) 614 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) && 615 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y)))) { 616 Value *XY = Builder.CreateFAddFMF(X, Y, &I); 617 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I); 618 return replaceInstUsesWith(I, Exp2); 619 } 620 } 621 622 // (X*Y) * X => (X*X) * Y where Y != X 623 // The purpose is two-fold: 624 // 1) to form a power expression (of X). 625 // 2) potentially shorten the critical path: After transformation, the 626 // latency of the instruction Y is amortized by the expression of X*X, 627 // and therefore Y is in a "less critical" position compared to what it 628 // was before the transformation. 629 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && 630 Op1 != Y) { 631 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I); 632 return BinaryOperator::CreateFMulFMF(XX, Y, &I); 633 } 634 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && 635 Op0 != Y) { 636 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I); 637 return BinaryOperator::CreateFMulFMF(XX, Y, &I); 638 } 639 } 640 641 // log2(X * 0.5) * Y = log2(X) * Y - Y 642 if (I.isFast()) { 643 IntrinsicInst *Log2 = nullptr; 644 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>( 645 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) { 646 Log2 = cast<IntrinsicInst>(Op0); 647 Y = Op1; 648 } 649 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>( 650 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) { 651 Log2 = cast<IntrinsicInst>(Op1); 652 Y = Op0; 653 } 654 if (Log2) { 655 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I); 656 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I); 657 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I); 658 } 659 } 660 661 return nullptr; 662 } 663 664 /// Fold a divide or remainder with a select instruction divisor when one of the 665 /// select operands is zero. In that case, we can use the other select operand 666 /// because div/rem by zero is undefined. 667 bool InstCombinerImpl::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) { 668 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1)); 669 if (!SI) 670 return false; 671 672 int NonNullOperand; 673 if (match(SI->getTrueValue(), m_Zero())) 674 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 675 NonNullOperand = 2; 676 else if (match(SI->getFalseValue(), m_Zero())) 677 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 678 NonNullOperand = 1; 679 else 680 return false; 681 682 // Change the div/rem to use 'Y' instead of the select. 683 replaceOperand(I, 1, SI->getOperand(NonNullOperand)); 684 685 // Okay, we know we replace the operand of the div/rem with 'Y' with no 686 // problem. However, the select, or the condition of the select may have 687 // multiple uses. Based on our knowledge that the operand must be non-zero, 688 // propagate the known value for the select into other uses of it, and 689 // propagate a known value of the condition into its other users. 690 691 // If the select and condition only have a single use, don't bother with this, 692 // early exit. 693 Value *SelectCond = SI->getCondition(); 694 if (SI->use_empty() && SelectCond->hasOneUse()) 695 return true; 696 697 // Scan the current block backward, looking for other uses of SI. 698 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin(); 699 Type *CondTy = SelectCond->getType(); 700 while (BBI != BBFront) { 701 --BBI; 702 // If we found an instruction that we can't assume will return, so 703 // information from below it cannot be propagated above it. 704 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI)) 705 break; 706 707 // Replace uses of the select or its condition with the known values. 708 for (Use &Op : BBI->operands()) { 709 if (Op == SI) { 710 replaceUse(Op, SI->getOperand(NonNullOperand)); 711 Worklist.push(&*BBI); 712 } else if (Op == SelectCond) { 713 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy) 714 : ConstantInt::getFalse(CondTy)); 715 Worklist.push(&*BBI); 716 } 717 } 718 719 // If we past the instruction, quit looking for it. 720 if (&*BBI == SI) 721 SI = nullptr; 722 if (&*BBI == SelectCond) 723 SelectCond = nullptr; 724 725 // If we ran out of things to eliminate, break out of the loop. 726 if (!SelectCond && !SI) 727 break; 728 729 } 730 return true; 731 } 732 733 /// True if the multiply can not be expressed in an int this size. 734 static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product, 735 bool IsSigned) { 736 bool Overflow; 737 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow); 738 return Overflow; 739 } 740 741 /// True if C1 is a multiple of C2. Quotient contains C1/C2. 742 static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, 743 bool IsSigned) { 744 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal"); 745 746 // Bail if we will divide by zero. 747 if (C2.isZero()) 748 return false; 749 750 // Bail if we would divide INT_MIN by -1. 751 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes()) 752 return false; 753 754 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned); 755 if (IsSigned) 756 APInt::sdivrem(C1, C2, Quotient, Remainder); 757 else 758 APInt::udivrem(C1, C2, Quotient, Remainder); 759 760 return Remainder.isMinValue(); 761 } 762 763 /// This function implements the transforms common to both integer division 764 /// instructions (udiv and sdiv). It is called by the visitors to those integer 765 /// division instructions. 766 /// Common integer divide transforms 767 Instruction *InstCombinerImpl::commonIDivTransforms(BinaryOperator &I) { 768 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 769 return Phi; 770 771 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 772 bool IsSigned = I.getOpcode() == Instruction::SDiv; 773 Type *Ty = I.getType(); 774 775 // The RHS is known non-zero. 776 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) 777 return replaceOperand(I, 1, V); 778 779 // Handle cases involving: [su]div X, (select Cond, Y, Z) 780 // This does not apply for fdiv. 781 if (simplifyDivRemOfSelectWithZeroOp(I)) 782 return &I; 783 784 // If the divisor is a select-of-constants, try to constant fold all div ops: 785 // C / (select Cond, TrueC, FalseC) --> select Cond, (C / TrueC), (C / FalseC) 786 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds. 787 if (match(Op0, m_ImmConstant()) && 788 match(Op1, m_Select(m_Value(), m_ImmConstant(), m_ImmConstant()))) { 789 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1), 790 /*FoldWithMultiUse*/ true)) 791 return R; 792 } 793 794 const APInt *C2; 795 if (match(Op1, m_APInt(C2))) { 796 Value *X; 797 const APInt *C1; 798 799 // (X / C1) / C2 -> X / (C1*C2) 800 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) || 801 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) { 802 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 803 if (!multiplyOverflows(*C1, *C2, Product, IsSigned)) 804 return BinaryOperator::Create(I.getOpcode(), X, 805 ConstantInt::get(Ty, Product)); 806 } 807 808 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) || 809 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) { 810 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 811 812 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1. 813 if (isMultiple(*C2, *C1, Quotient, IsSigned)) { 814 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X, 815 ConstantInt::get(Ty, Quotient)); 816 NewDiv->setIsExact(I.isExact()); 817 return NewDiv; 818 } 819 820 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2. 821 if (isMultiple(*C1, *C2, Quotient, IsSigned)) { 822 auto *Mul = BinaryOperator::Create(Instruction::Mul, X, 823 ConstantInt::get(Ty, Quotient)); 824 auto *OBO = cast<OverflowingBinaryOperator>(Op0); 825 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap()); 826 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap()); 827 return Mul; 828 } 829 } 830 831 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) && 832 C1->ult(C1->getBitWidth() - 1)) || 833 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) && 834 C1->ult(C1->getBitWidth()))) { 835 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 836 APInt C1Shifted = APInt::getOneBitSet( 837 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue())); 838 839 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1. 840 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) { 841 auto *BO = BinaryOperator::Create(I.getOpcode(), X, 842 ConstantInt::get(Ty, Quotient)); 843 BO->setIsExact(I.isExact()); 844 return BO; 845 } 846 847 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2. 848 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) { 849 auto *Mul = BinaryOperator::Create(Instruction::Mul, X, 850 ConstantInt::get(Ty, Quotient)); 851 auto *OBO = cast<OverflowingBinaryOperator>(Op0); 852 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap()); 853 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap()); 854 return Mul; 855 } 856 } 857 858 if (!C2->isZero()) // avoid X udiv 0 859 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I)) 860 return FoldedDiv; 861 } 862 863 if (match(Op0, m_One())) { 864 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?"); 865 if (IsSigned) { 866 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0 867 // (Op1 + 1) u< 3 ? Op1 : 0 868 // Op1 must be frozen because we are increasing its number of uses. 869 Value *F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr"); 870 Value *Inc = Builder.CreateAdd(F1, Op0); 871 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3)); 872 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0)); 873 } else { 874 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the 875 // result is one, otherwise it's zero. 876 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty); 877 } 878 } 879 880 // See if we can fold away this div instruction. 881 if (SimplifyDemandedInstructionBits(I)) 882 return &I; 883 884 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 885 Value *X, *Z; 886 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1 887 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 888 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 889 return BinaryOperator::Create(I.getOpcode(), X, Op1); 890 891 // (X << Y) / X -> 1 << Y 892 Value *Y; 893 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y)))) 894 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y); 895 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y)))) 896 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y); 897 898 // X / (X * Y) -> 1 / Y if the multiplication does not overflow. 899 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) { 900 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap(); 901 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap(); 902 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) { 903 replaceOperand(I, 0, ConstantInt::get(Ty, 1)); 904 replaceOperand(I, 1, Y); 905 return &I; 906 } 907 } 908 909 return nullptr; 910 } 911 912 static const unsigned MaxDepth = 6; 913 914 // Take the exact integer log2 of the value. If DoFold is true, create the 915 // actual instructions, otherwise return a non-null dummy value. Return nullptr 916 // on failure. 917 static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth, 918 bool DoFold) { 919 auto IfFold = [DoFold](function_ref<Value *()> Fn) { 920 if (!DoFold) 921 return reinterpret_cast<Value *>(-1); 922 return Fn(); 923 }; 924 925 // FIXME: assert that Op1 isn't/doesn't contain undef. 926 927 // log2(2^C) -> C 928 if (match(Op, m_Power2())) 929 return IfFold([&]() { 930 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op)); 931 if (!C) 932 llvm_unreachable("Failed to constant fold udiv -> logbase2"); 933 return C; 934 }); 935 936 // The remaining tests are all recursive, so bail out if we hit the limit. 937 if (Depth++ == MaxDepth) 938 return nullptr; 939 940 // log2(zext X) -> zext log2(X) 941 // FIXME: Require one use? 942 Value *X, *Y; 943 if (match(Op, m_ZExt(m_Value(X)))) 944 if (Value *LogX = takeLog2(Builder, X, Depth, DoFold)) 945 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); }); 946 947 // log2(X << Y) -> log2(X) + Y 948 // FIXME: Require one use unless X is 1? 949 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) 950 if (Value *LogX = takeLog2(Builder, X, Depth, DoFold)) 951 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); }); 952 953 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y) 954 // FIXME: missed optimization: if one of the hands of select is/contains 955 // undef, just directly pick the other one. 956 // FIXME: can both hands contain undef? 957 // FIXME: Require one use? 958 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) 959 if (Value *LogX = takeLog2(Builder, SI->getOperand(1), Depth, DoFold)) 960 if (Value *LogY = takeLog2(Builder, SI->getOperand(2), Depth, DoFold)) 961 return IfFold([&]() { 962 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY); 963 }); 964 965 // log2(umin(X, Y)) -> umin(log2(X), log2(Y)) 966 // log2(umax(X, Y)) -> umax(log2(X), log2(Y)) 967 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op); 968 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) 969 if (Value *LogX = takeLog2(Builder, MinMax->getLHS(), Depth, DoFold)) 970 if (Value *LogY = takeLog2(Builder, MinMax->getRHS(), Depth, DoFold)) 971 return IfFold([&]() { 972 return Builder.CreateBinaryIntrinsic( 973 MinMax->getIntrinsicID(), LogX, LogY); 974 }); 975 976 return nullptr; 977 } 978 979 /// If we have zero-extended operands of an unsigned div or rem, we may be able 980 /// to narrow the operation (sink the zext below the math). 981 static Instruction *narrowUDivURem(BinaryOperator &I, 982 InstCombiner::BuilderTy &Builder) { 983 Instruction::BinaryOps Opcode = I.getOpcode(); 984 Value *N = I.getOperand(0); 985 Value *D = I.getOperand(1); 986 Type *Ty = I.getType(); 987 Value *X, *Y; 988 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) && 989 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) { 990 // udiv (zext X), (zext Y) --> zext (udiv X, Y) 991 // urem (zext X), (zext Y) --> zext (urem X, Y) 992 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y); 993 return new ZExtInst(NarrowOp, Ty); 994 } 995 996 Constant *C; 997 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) || 998 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) { 999 // If the constant is the same in the smaller type, use the narrow version. 1000 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType()); 1001 if (ConstantExpr::getZExt(TruncC, Ty) != C) 1002 return nullptr; 1003 1004 // udiv (zext X), C --> zext (udiv X, C') 1005 // urem (zext X), C --> zext (urem X, C') 1006 // udiv C, (zext X) --> zext (udiv C', X) 1007 // urem C, (zext X) --> zext (urem C', X) 1008 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC) 1009 : Builder.CreateBinOp(Opcode, TruncC, X); 1010 return new ZExtInst(NarrowOp, Ty); 1011 } 1012 1013 return nullptr; 1014 } 1015 1016 Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) { 1017 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1), 1018 SQ.getWithInstruction(&I))) 1019 return replaceInstUsesWith(I, V); 1020 1021 if (Instruction *X = foldVectorBinop(I)) 1022 return X; 1023 1024 // Handle the integer div common cases 1025 if (Instruction *Common = commonIDivTransforms(I)) 1026 return Common; 1027 1028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1029 Value *X; 1030 const APInt *C1, *C2; 1031 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) { 1032 // (X lshr C1) udiv C2 --> X udiv (C2 << C1) 1033 bool Overflow; 1034 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow); 1035 if (!Overflow) { 1036 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value())); 1037 BinaryOperator *BO = BinaryOperator::CreateUDiv( 1038 X, ConstantInt::get(X->getType(), C2ShlC1)); 1039 if (IsExact) 1040 BO->setIsExact(); 1041 return BO; 1042 } 1043 } 1044 1045 // Op0 / C where C is large (negative) --> zext (Op0 >= C) 1046 // TODO: Could use isKnownNegative() to handle non-constant values. 1047 Type *Ty = I.getType(); 1048 if (match(Op1, m_Negative())) { 1049 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1); 1050 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1051 } 1052 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined) 1053 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 1054 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty)); 1055 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1056 } 1057 1058 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder)) 1059 return NarrowDiv; 1060 1061 // If the udiv operands are non-overflowing multiplies with a common operand, 1062 // then eliminate the common factor: 1063 // (A * B) / (A * X) --> B / X (and commuted variants) 1064 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching. 1065 // TODO: If -reassociation handled this generally, we could remove this. 1066 Value *A, *B; 1067 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) { 1068 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) || 1069 match(Op1, m_NUWMul(m_Value(X), m_Specific(A)))) 1070 return BinaryOperator::CreateUDiv(B, X); 1071 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) || 1072 match(Op1, m_NUWMul(m_Value(X), m_Specific(B)))) 1073 return BinaryOperator::CreateUDiv(A, X); 1074 } 1075 1076 // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away. 1077 if (takeLog2(Builder, Op1, /*Depth*/0, /*DoFold*/false)) { 1078 Value *Res = takeLog2(Builder, Op1, /*Depth*/0, /*DoFold*/true); 1079 return replaceInstUsesWith( 1080 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact())); 1081 } 1082 1083 return nullptr; 1084 } 1085 1086 Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) { 1087 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1), 1088 SQ.getWithInstruction(&I))) 1089 return replaceInstUsesWith(I, V); 1090 1091 if (Instruction *X = foldVectorBinop(I)) 1092 return X; 1093 1094 // Handle the integer div common cases 1095 if (Instruction *Common = commonIDivTransforms(I)) 1096 return Common; 1097 1098 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1099 Type *Ty = I.getType(); 1100 Value *X; 1101 // sdiv Op0, -1 --> -Op0 1102 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined) 1103 if (match(Op1, m_AllOnes()) || 1104 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1105 return BinaryOperator::CreateNeg(Op0); 1106 1107 // X / INT_MIN --> X == INT_MIN 1108 if (match(Op1, m_SignMask())) 1109 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty); 1110 1111 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative 1112 // sdiv exact X, -1<<C --> -(ashr exact X, C) 1113 if (I.isExact() && ((match(Op1, m_Power2()) && match(Op1, m_NonNegative())) || 1114 match(Op1, m_NegatedPower2()))) { 1115 bool DivisorWasNegative = match(Op1, m_NegatedPower2()); 1116 if (DivisorWasNegative) 1117 Op1 = ConstantExpr::getNeg(cast<Constant>(Op1)); 1118 auto *AShr = BinaryOperator::CreateExactAShr( 1119 Op0, ConstantExpr::getExactLogBase2(cast<Constant>(Op1)), I.getName()); 1120 if (!DivisorWasNegative) 1121 return AShr; 1122 Builder.Insert(AShr); 1123 AShr->setName(I.getName() + ".neg"); 1124 return BinaryOperator::CreateNeg(AShr, I.getName()); 1125 } 1126 1127 const APInt *Op1C; 1128 if (match(Op1, m_APInt(Op1C))) { 1129 // If the dividend is sign-extended and the constant divisor is small enough 1130 // to fit in the source type, shrink the division to the narrower type: 1131 // (sext X) sdiv C --> sext (X sdiv C) 1132 Value *Op0Src; 1133 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) && 1134 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) { 1135 1136 // In the general case, we need to make sure that the dividend is not the 1137 // minimum signed value because dividing that by -1 is UB. But here, we 1138 // know that the -1 divisor case is already handled above. 1139 1140 Constant *NarrowDivisor = 1141 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType()); 1142 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor); 1143 return new SExtInst(NarrowOp, Ty); 1144 } 1145 1146 // -X / C --> X / -C (if the negation doesn't overflow). 1147 // TODO: This could be enhanced to handle arbitrary vector constants by 1148 // checking if all elements are not the min-signed-val. 1149 if (!Op1C->isMinSignedValue() && 1150 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) { 1151 Constant *NegC = ConstantInt::get(Ty, -(*Op1C)); 1152 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC); 1153 BO->setIsExact(I.isExact()); 1154 return BO; 1155 } 1156 } 1157 1158 // -X / Y --> -(X / Y) 1159 Value *Y; 1160 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) 1161 return BinaryOperator::CreateNSWNeg( 1162 Builder.CreateSDiv(X, Y, I.getName(), I.isExact())); 1163 1164 // abs(X) / X --> X > -1 ? 1 : -1 1165 // X / abs(X) --> X > -1 ? 1 : -1 1166 if (match(&I, m_c_BinOp( 1167 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())), 1168 m_Deferred(X)))) { 1169 Value *Cond = Builder.CreateIsNotNeg(X); 1170 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1), 1171 ConstantInt::getAllOnesValue(Ty)); 1172 } 1173 1174 // If the sign bits of both operands are zero (i.e. we can prove they are 1175 // unsigned inputs), turn this into a udiv. 1176 APInt Mask(APInt::getSignMask(Ty->getScalarSizeInBits())); 1177 if (MaskedValueIsZero(Op0, Mask, 0, &I)) { 1178 if (MaskedValueIsZero(Op1, Mask, 0, &I)) { 1179 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 1180 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 1181 BO->setIsExact(I.isExact()); 1182 return BO; 1183 } 1184 1185 if (match(Op1, m_NegatedPower2())) { 1186 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) -> 1187 // -> -(X udiv (1 << C)) -> -(X u>> C) 1188 Constant *CNegLog2 = ConstantExpr::getExactLogBase2( 1189 ConstantExpr::getNeg(cast<Constant>(Op1))); 1190 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact()); 1191 return BinaryOperator::CreateNeg(Shr); 1192 } 1193 1194 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) { 1195 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 1196 // Safe because the only negative value (1 << Y) can take on is 1197 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 1198 // the sign bit set. 1199 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 1200 BO->setIsExact(I.isExact()); 1201 return BO; 1202 } 1203 } 1204 1205 return nullptr; 1206 } 1207 1208 /// Remove negation and try to convert division into multiplication. 1209 static Instruction *foldFDivConstantDivisor(BinaryOperator &I) { 1210 Constant *C; 1211 if (!match(I.getOperand(1), m_Constant(C))) 1212 return nullptr; 1213 1214 // -X / C --> X / -C 1215 Value *X; 1216 if (match(I.getOperand(0), m_FNeg(m_Value(X)))) 1217 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I); 1218 1219 // If the constant divisor has an exact inverse, this is always safe. If not, 1220 // then we can still create a reciprocal if fast-math-flags allow it and the 1221 // constant is a regular number (not zero, infinite, or denormal). 1222 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP()))) 1223 return nullptr; 1224 1225 // Disallow denormal constants because we don't know what would happen 1226 // on all targets. 1227 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that 1228 // denorms are flushed? 1229 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C); 1230 if (!RecipC->isNormalFP()) 1231 return nullptr; 1232 1233 // X / C --> X * (1 / C) 1234 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I); 1235 } 1236 1237 /// Remove negation and try to reassociate constant math. 1238 static Instruction *foldFDivConstantDividend(BinaryOperator &I) { 1239 Constant *C; 1240 if (!match(I.getOperand(0), m_Constant(C))) 1241 return nullptr; 1242 1243 // C / -X --> -C / X 1244 Value *X; 1245 if (match(I.getOperand(1), m_FNeg(m_Value(X)))) 1246 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I); 1247 1248 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal()) 1249 return nullptr; 1250 1251 // Try to reassociate C / X expressions where X includes another constant. 1252 Constant *C2, *NewC = nullptr; 1253 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) { 1254 // C / (X * C2) --> (C / C2) / X 1255 NewC = ConstantExpr::getFDiv(C, C2); 1256 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) { 1257 // C / (X / C2) --> (C * C2) / X 1258 NewC = ConstantExpr::getFMul(C, C2); 1259 } 1260 // Disallow denormal constants because we don't know what would happen 1261 // on all targets. 1262 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that 1263 // denorms are flushed? 1264 if (!NewC || !NewC->isNormalFP()) 1265 return nullptr; 1266 1267 return BinaryOperator::CreateFDivFMF(NewC, X, &I); 1268 } 1269 1270 /// Negate the exponent of pow/exp to fold division-by-pow() into multiply. 1271 static Instruction *foldFDivPowDivisor(BinaryOperator &I, 1272 InstCombiner::BuilderTy &Builder) { 1273 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1274 auto *II = dyn_cast<IntrinsicInst>(Op1); 1275 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() || 1276 !I.hasAllowReciprocal()) 1277 return nullptr; 1278 1279 // Z / pow(X, Y) --> Z * pow(X, -Y) 1280 // Z / exp{2}(Y) --> Z * exp{2}(-Y) 1281 // In the general case, this creates an extra instruction, but fmul allows 1282 // for better canonicalization and optimization than fdiv. 1283 Intrinsic::ID IID = II->getIntrinsicID(); 1284 SmallVector<Value *> Args; 1285 switch (IID) { 1286 case Intrinsic::pow: 1287 Args.push_back(II->getArgOperand(0)); 1288 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I)); 1289 break; 1290 case Intrinsic::powi: { 1291 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable. 1292 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so 1293 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows 1294 // non-standard results, so this corner case should be acceptable if the 1295 // code rules out INF values. 1296 if (!I.hasNoInfs()) 1297 return nullptr; 1298 Args.push_back(II->getArgOperand(0)); 1299 Args.push_back(Builder.CreateNeg(II->getArgOperand(1))); 1300 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()}; 1301 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I); 1302 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I); 1303 } 1304 case Intrinsic::exp: 1305 case Intrinsic::exp2: 1306 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I)); 1307 break; 1308 default: 1309 return nullptr; 1310 } 1311 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I); 1312 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I); 1313 } 1314 1315 Instruction *InstCombinerImpl::visitFDiv(BinaryOperator &I) { 1316 Module *M = I.getModule(); 1317 1318 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1), 1319 I.getFastMathFlags(), 1320 SQ.getWithInstruction(&I))) 1321 return replaceInstUsesWith(I, V); 1322 1323 if (Instruction *X = foldVectorBinop(I)) 1324 return X; 1325 1326 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 1327 return Phi; 1328 1329 if (Instruction *R = foldFDivConstantDivisor(I)) 1330 return R; 1331 1332 if (Instruction *R = foldFDivConstantDividend(I)) 1333 return R; 1334 1335 if (Instruction *R = foldFPSignBitOps(I)) 1336 return R; 1337 1338 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1339 if (isa<Constant>(Op0)) 1340 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 1341 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1342 return R; 1343 1344 if (isa<Constant>(Op1)) 1345 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 1346 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1347 return R; 1348 1349 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) { 1350 Value *X, *Y; 1351 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) && 1352 (!isa<Constant>(Y) || !isa<Constant>(Op1))) { 1353 // (X / Y) / Z => X / (Y * Z) 1354 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I); 1355 return BinaryOperator::CreateFDivFMF(X, YZ, &I); 1356 } 1357 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) && 1358 (!isa<Constant>(Y) || !isa<Constant>(Op0))) { 1359 // Z / (X / Y) => (Y * Z) / X 1360 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I); 1361 return BinaryOperator::CreateFDivFMF(YZ, X, &I); 1362 } 1363 // Z / (1.0 / Y) => (Y * Z) 1364 // 1365 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The 1366 // m_OneUse check is avoided because even in the case of the multiple uses 1367 // for 1.0/Y, the number of instructions remain the same and a division is 1368 // replaced by a multiplication. 1369 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) 1370 return BinaryOperator::CreateFMulFMF(Y, Op0, &I); 1371 } 1372 1373 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) { 1374 // sin(X) / cos(X) -> tan(X) 1375 // cos(X) / sin(X) -> 1/tan(X) (cotangent) 1376 Value *X; 1377 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) && 1378 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X))); 1379 bool IsCot = 1380 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) && 1381 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X))); 1382 1383 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan, 1384 LibFunc_tanf, LibFunc_tanl)) { 1385 IRBuilder<> B(&I); 1386 IRBuilder<>::FastMathFlagGuard FMFGuard(B); 1387 B.setFastMathFlags(I.getFastMathFlags()); 1388 AttributeList Attrs = 1389 cast<CallBase>(Op0)->getCalledFunction()->getAttributes(); 1390 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf, 1391 LibFunc_tanl, B, Attrs); 1392 if (IsCot) 1393 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res); 1394 return replaceInstUsesWith(I, Res); 1395 } 1396 } 1397 1398 // X / (X * Y) --> 1.0 / Y 1399 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed. 1400 // We can ignore the possibility that X is infinity because INF/INF is NaN. 1401 Value *X, *Y; 1402 if (I.hasNoNaNs() && I.hasAllowReassoc() && 1403 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) { 1404 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0)); 1405 replaceOperand(I, 1, Y); 1406 return &I; 1407 } 1408 1409 // X / fabs(X) -> copysign(1.0, X) 1410 // fabs(X) / X -> copysign(1.0, X) 1411 if (I.hasNoNaNs() && I.hasNoInfs() && 1412 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) || 1413 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) { 1414 Value *V = Builder.CreateBinaryIntrinsic( 1415 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I); 1416 return replaceInstUsesWith(I, V); 1417 } 1418 1419 if (Instruction *Mul = foldFDivPowDivisor(I, Builder)) 1420 return Mul; 1421 1422 return nullptr; 1423 } 1424 1425 /// This function implements the transforms common to both integer remainder 1426 /// instructions (urem and srem). It is called by the visitors to those integer 1427 /// remainder instructions. 1428 /// Common integer remainder transforms 1429 Instruction *InstCombinerImpl::commonIRemTransforms(BinaryOperator &I) { 1430 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 1431 return Phi; 1432 1433 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1434 1435 // The RHS is known non-zero. 1436 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) 1437 return replaceOperand(I, 1, V); 1438 1439 // Handle cases involving: rem X, (select Cond, Y, Z) 1440 if (simplifyDivRemOfSelectWithZeroOp(I)) 1441 return &I; 1442 1443 // If the divisor is a select-of-constants, try to constant fold all rem ops: 1444 // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC) 1445 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds. 1446 if (match(Op0, m_ImmConstant()) && 1447 match(Op1, m_Select(m_Value(), m_ImmConstant(), m_ImmConstant()))) { 1448 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1), 1449 /*FoldWithMultiUse*/ true)) 1450 return R; 1451 } 1452 1453 if (isa<Constant>(Op1)) { 1454 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 1455 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 1456 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1457 return R; 1458 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) { 1459 const APInt *Op1Int; 1460 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() && 1461 (I.getOpcode() == Instruction::URem || 1462 !Op1Int->isMinSignedValue())) { 1463 // foldOpIntoPhi will speculate instructions to the end of the PHI's 1464 // predecessor blocks, so do this only if we know the srem or urem 1465 // will not fault. 1466 if (Instruction *NV = foldOpIntoPhi(I, PN)) 1467 return NV; 1468 } 1469 } 1470 1471 // See if we can fold away this rem instruction. 1472 if (SimplifyDemandedInstructionBits(I)) 1473 return &I; 1474 } 1475 } 1476 1477 return nullptr; 1478 } 1479 1480 Instruction *InstCombinerImpl::visitURem(BinaryOperator &I) { 1481 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1), 1482 SQ.getWithInstruction(&I))) 1483 return replaceInstUsesWith(I, V); 1484 1485 if (Instruction *X = foldVectorBinop(I)) 1486 return X; 1487 1488 if (Instruction *common = commonIRemTransforms(I)) 1489 return common; 1490 1491 if (Instruction *NarrowRem = narrowUDivURem(I, Builder)) 1492 return NarrowRem; 1493 1494 // X urem Y -> X and Y-1, where Y is a power of 2, 1495 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1496 Type *Ty = I.getType(); 1497 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) { 1498 // This may increase instruction count, we don't enforce that Y is a 1499 // constant. 1500 Constant *N1 = Constant::getAllOnesValue(Ty); 1501 Value *Add = Builder.CreateAdd(Op1, N1); 1502 return BinaryOperator::CreateAnd(Op0, Add); 1503 } 1504 1505 // 1 urem X -> zext(X != 1) 1506 if (match(Op0, m_One())) { 1507 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1)); 1508 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1509 } 1510 1511 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit. 1512 // Op0 must be frozen because we are increasing its number of uses. 1513 if (match(Op1, m_Negative())) { 1514 Value *F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr"); 1515 Value *Cmp = Builder.CreateICmpULT(F0, Op1); 1516 Value *Sub = Builder.CreateSub(F0, Op1); 1517 return SelectInst::Create(Cmp, F0, Sub); 1518 } 1519 1520 // If the divisor is a sext of a boolean, then the divisor must be max 1521 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also 1522 // max unsigned value. In that case, the remainder is 0: 1523 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0 1524 Value *X; 1525 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 1526 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty)); 1527 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0); 1528 } 1529 1530 return nullptr; 1531 } 1532 1533 Instruction *InstCombinerImpl::visitSRem(BinaryOperator &I) { 1534 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1), 1535 SQ.getWithInstruction(&I))) 1536 return replaceInstUsesWith(I, V); 1537 1538 if (Instruction *X = foldVectorBinop(I)) 1539 return X; 1540 1541 // Handle the integer rem common cases 1542 if (Instruction *Common = commonIRemTransforms(I)) 1543 return Common; 1544 1545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1546 { 1547 const APInt *Y; 1548 // X % -Y -> X % Y 1549 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) 1550 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y)); 1551 } 1552 1553 // -X srem Y --> -(X srem Y) 1554 Value *X, *Y; 1555 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) 1556 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y)); 1557 1558 // If the sign bits of both operands are zero (i.e. we can prove they are 1559 // unsigned inputs), turn this into a urem. 1560 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits())); 1561 if (MaskedValueIsZero(Op1, Mask, 0, &I) && 1562 MaskedValueIsZero(Op0, Mask, 0, &I)) { 1563 // X srem Y -> X urem Y, iff X and Y don't have sign bit set 1564 return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 1565 } 1566 1567 // If it's a constant vector, flip any negative values positive. 1568 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) { 1569 Constant *C = cast<Constant>(Op1); 1570 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements(); 1571 1572 bool hasNegative = false; 1573 bool hasMissing = false; 1574 for (unsigned i = 0; i != VWidth; ++i) { 1575 Constant *Elt = C->getAggregateElement(i); 1576 if (!Elt) { 1577 hasMissing = true; 1578 break; 1579 } 1580 1581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt)) 1582 if (RHS->isNegative()) 1583 hasNegative = true; 1584 } 1585 1586 if (hasNegative && !hasMissing) { 1587 SmallVector<Constant *, 16> Elts(VWidth); 1588 for (unsigned i = 0; i != VWidth; ++i) { 1589 Elts[i] = C->getAggregateElement(i); // Handle undef, etc. 1590 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) { 1591 if (RHS->isNegative()) 1592 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 1593 } 1594 } 1595 1596 Constant *NewRHSV = ConstantVector::get(Elts); 1597 if (NewRHSV != C) // Don't loop on -MININT 1598 return replaceOperand(I, 1, NewRHSV); 1599 } 1600 } 1601 1602 return nullptr; 1603 } 1604 1605 Instruction *InstCombinerImpl::visitFRem(BinaryOperator &I) { 1606 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1), 1607 I.getFastMathFlags(), 1608 SQ.getWithInstruction(&I))) 1609 return replaceInstUsesWith(I, V); 1610 1611 if (Instruction *X = foldVectorBinop(I)) 1612 return X; 1613 1614 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 1615 return Phi; 1616 1617 return nullptr; 1618 } 1619