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