1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
13 //===----------------------------------------------------------------------===//
15 #include "InstCombine.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/PatternMatch.h"
20 using namespace PatternMatch;
23 /// simplifyValueKnownNonZero - The specific integer value is used in a context
24 /// where it is known to be non-zero. If this allows us to simplify the
25 /// computation, do so and return the new operand, otherwise return null.
26 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
27 // If V has multiple uses, then we would have to do more analysis to determine
28 // if this is safe. For example, the use could be in dynamically unreached
30 if (!V->hasOneUse()) return 0;
33 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
34 // inexact. Similarly for <<.
35 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
36 if (I->isLogicalShift() &&
37 isPowerOfTwo(I->getOperand(0), IC.getTargetData())) {
38 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
43 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
44 I->setHasNoUnsignedWrap();
49 // ((1 << A) >>u B) --> (1 << (A-B))
50 // Because V cannot be zero, we know that B is less than A.
51 Value *A = 0, *B = 0, *PowerOf2 = 0;
52 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
54 // The "1" can be any value known to be a power of 2.
55 isPowerOfTwo(PowerOf2, IC.getTargetData())) {
56 A = IC.Builder->CreateSub(A, B, "tmp");
57 return IC.Builder->CreateShl(PowerOf2, A);
60 // TODO: Lots more we could do here:
61 // "1 >> X" could get an "isexact" bit.
62 // If V is a phi node, we can call this on each of its operands.
63 // "select cond, X, 0" can simplify to "X".
69 /// MultiplyOverflows - True if the multiply can not be expressed in an int
71 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
72 uint32_t W = C1->getBitWidth();
73 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
75 LHSExt = LHSExt.sext(W * 2);
76 RHSExt = RHSExt.sext(W * 2);
78 LHSExt = LHSExt.zext(W * 2);
79 RHSExt = RHSExt.zext(W * 2);
82 APInt MulExt = LHSExt * RHSExt;
85 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
87 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
88 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
89 return MulExt.slt(Min) || MulExt.sgt(Max);
92 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
93 bool Changed = SimplifyAssociativeOrCommutative(I);
94 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
96 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
97 return ReplaceInstUsesWith(I, V);
99 if (Value *V = SimplifyUsingDistributiveLaws(I))
100 return ReplaceInstUsesWith(I, V);
102 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
103 return BinaryOperator::CreateNeg(Op0, I.getName());
105 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
107 // ((X << C1)*C2) == (X * (C2 << C1))
108 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
109 if (SI->getOpcode() == Instruction::Shl)
110 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
111 return BinaryOperator::CreateMul(SI->getOperand(0),
112 ConstantExpr::getShl(CI, ShOp));
114 const APInt &Val = CI->getValue();
115 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
116 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
117 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
118 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
119 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
123 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
124 { Value *X; ConstantInt *C1;
125 if (Op0->hasOneUse() &&
126 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
127 Value *Add = Builder->CreateMul(X, CI, "tmp");
128 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
133 // Simplify mul instructions with a constant RHS.
134 if (isa<Constant>(Op1)) {
135 // Try to fold constant mul into select arguments.
136 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
137 if (Instruction *R = FoldOpIntoSelect(I, SI))
140 if (isa<PHINode>(Op0))
141 if (Instruction *NV = FoldOpIntoPhi(I))
145 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
146 if (Value *Op1v = dyn_castNegVal(Op1))
147 return BinaryOperator::CreateMul(Op0v, Op1v);
149 // (X / Y) * Y = X - (X % Y)
150 // (X / Y) * -Y = (X % Y) - X
153 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
155 (BO->getOpcode() != Instruction::UDiv &&
156 BO->getOpcode() != Instruction::SDiv)) {
158 BO = dyn_cast<BinaryOperator>(Op1);
160 Value *Neg = dyn_castNegVal(Op1C);
161 if (BO && BO->hasOneUse() &&
162 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
163 (BO->getOpcode() == Instruction::UDiv ||
164 BO->getOpcode() == Instruction::SDiv)) {
165 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
167 // If the division is exact, X % Y is zero, so we end up with X or -X.
168 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
169 if (SDiv->isExact()) {
171 return ReplaceInstUsesWith(I, Op0BO);
172 return BinaryOperator::CreateNeg(Op0BO);
176 if (BO->getOpcode() == Instruction::UDiv)
177 Rem = Builder->CreateURem(Op0BO, Op1BO);
179 Rem = Builder->CreateSRem(Op0BO, Op1BO);
183 return BinaryOperator::CreateSub(Op0BO, Rem);
184 return BinaryOperator::CreateSub(Rem, Op0BO);
188 /// i1 mul -> i1 and.
189 if (I.getType()->isIntegerTy(1))
190 return BinaryOperator::CreateAnd(Op0, Op1);
192 // X*(1 << Y) --> X << Y
193 // (1 << Y)*X --> X << Y
196 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
197 return BinaryOperator::CreateShl(Op1, Y);
198 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
199 return BinaryOperator::CreateShl(Op0, Y);
202 // If one of the operands of the multiply is a cast from a boolean value, then
203 // we know the bool is either zero or one, so this is a 'masking' multiply.
204 // X * Y (where Y is 0 or 1) -> X & (0-Y)
205 if (!I.getType()->isVectorTy()) {
206 // -2 is "-1 << 1" so it is all bits set except the low one.
207 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
209 Value *BoolCast = 0, *OtherOp = 0;
210 if (MaskedValueIsZero(Op0, Negative2))
211 BoolCast = Op0, OtherOp = Op1;
212 else if (MaskedValueIsZero(Op1, Negative2))
213 BoolCast = Op1, OtherOp = Op0;
216 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
218 return BinaryOperator::CreateAnd(V, OtherOp);
222 return Changed ? &I : 0;
225 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
226 bool Changed = SimplifyAssociativeOrCommutative(I);
227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
229 // Simplify mul instructions with a constant RHS...
230 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
231 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
232 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
233 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
234 if (Op1F->isExactlyValue(1.0))
235 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
236 } else if (Op1C->getType()->isVectorTy()) {
237 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
238 // As above, vector X*splat(1.0) -> X in all defined cases.
239 if (Constant *Splat = Op1V->getSplatValue()) {
240 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
241 if (F->isExactlyValue(1.0))
242 return ReplaceInstUsesWith(I, Op0);
247 // Try to fold constant mul into select arguments.
248 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
249 if (Instruction *R = FoldOpIntoSelect(I, SI))
252 if (isa<PHINode>(Op0))
253 if (Instruction *NV = FoldOpIntoPhi(I))
257 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
258 if (Value *Op1v = dyn_castFNegVal(Op1))
259 return BinaryOperator::CreateFMul(Op0v, Op1v);
261 return Changed ? &I : 0;
264 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
266 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
267 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
269 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
270 int NonNullOperand = -1;
271 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
272 if (ST->isNullValue())
274 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
275 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
276 if (ST->isNullValue())
279 if (NonNullOperand == -1)
282 Value *SelectCond = SI->getOperand(0);
284 // Change the div/rem to use 'Y' instead of the select.
285 I.setOperand(1, SI->getOperand(NonNullOperand));
287 // Okay, we know we replace the operand of the div/rem with 'Y' with no
288 // problem. However, the select, or the condition of the select may have
289 // multiple uses. Based on our knowledge that the operand must be non-zero,
290 // propagate the known value for the select into other uses of it, and
291 // propagate a known value of the condition into its other users.
293 // If the select and condition only have a single use, don't bother with this,
295 if (SI->use_empty() && SelectCond->hasOneUse())
298 // Scan the current block backward, looking for other uses of SI.
299 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
301 while (BBI != BBFront) {
303 // If we found a call to a function, we can't assume it will return, so
304 // information from below it cannot be propagated above it.
305 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
308 // Replace uses of the select or its condition with the known values.
309 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
312 *I = SI->getOperand(NonNullOperand);
314 } else if (*I == SelectCond) {
315 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
316 ConstantInt::getFalse(BBI->getContext());
321 // If we past the instruction, quit looking for it.
324 if (&*BBI == SelectCond)
327 // If we ran out of things to eliminate, break out of the loop.
328 if (SelectCond == 0 && SI == 0)
336 /// This function implements the transforms common to both integer division
337 /// instructions (udiv and sdiv). It is called by the visitors to those integer
338 /// division instructions.
339 /// @brief Common integer divide transforms
340 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
343 // The RHS is known non-zero.
344 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
349 // Handle cases involving: [su]div X, (select Cond, Y, Z)
350 // This does not apply for fdiv.
351 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
355 // (X / C1) / C2 -> X / (C1*C2)
356 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
357 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
358 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
359 if (MultiplyOverflows(RHS, LHSRHS,
360 I.getOpcode()==Instruction::SDiv))
361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
362 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
363 ConstantExpr::getMul(RHS, LHSRHS));
366 if (!RHS->isZero()) { // avoid X udiv 0
367 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
368 if (Instruction *R = FoldOpIntoSelect(I, SI))
370 if (isa<PHINode>(Op0))
371 if (Instruction *NV = FoldOpIntoPhi(I))
376 // See if we can fold away this div instruction.
377 if (SimplifyDemandedInstructionBits(I))
380 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
381 Value *X = 0, *Z = 0;
382 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
383 bool isSigned = I.getOpcode() == Instruction::SDiv;
384 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
385 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
386 return BinaryOperator::Create(I.getOpcode(), X, Op1);
392 /// dyn_castZExtVal - Checks if V is a zext or constant that can
393 /// be truncated to Ty without losing bits.
394 static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
395 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
396 if (Z->getSrcTy() == Ty)
397 return Z->getOperand(0);
398 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
399 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
400 return ConstantExpr::getTrunc(C, Ty);
405 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
406 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
408 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
409 return ReplaceInstUsesWith(I, V);
411 // Handle the integer div common cases
412 if (Instruction *Common = commonIDivTransforms(I))
415 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
416 // X udiv 2^C -> X >> C
417 // Check to see if this is an unsigned division with an exact power of 2,
418 // if so, convert to a right shift.
419 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
420 BinaryOperator *LShr =
421 BinaryOperator::CreateLShr(Op0,
422 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
423 if (I.isExact()) LShr->setIsExact();
427 // X udiv C, where C >= signbit
428 if (C->getValue().isNegative()) {
429 Value *IC = Builder->CreateICmpULT(Op0, C);
430 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
431 ConstantInt::get(I.getType(), 1));
435 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
436 { const APInt *CI; Value *N;
437 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
439 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
442 return BinaryOperator::CreateExactLShr(Op0, N);
443 return BinaryOperator::CreateLShr(Op0, N);
447 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
448 // where C1&C2 are powers of two.
449 { Value *Cond; const APInt *C1, *C2;
450 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
451 // Construct the "on true" case of the select
452 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
455 // Construct the "on false" case of the select
456 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
459 // construct the select instruction and return it.
460 return SelectInst::Create(Cond, TSI, FSI);
464 // (zext A) udiv (zext B) --> zext (A udiv B)
465 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
466 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
467 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
474 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
475 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
477 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
478 return ReplaceInstUsesWith(I, V);
480 // Handle the integer div common cases
481 if (Instruction *Common = commonIDivTransforms(I))
484 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
486 if (RHS->isAllOnesValue())
487 return BinaryOperator::CreateNeg(Op0);
489 // sdiv X, C --> ashr exact X, log2(C)
490 if (I.isExact() && RHS->getValue().isNonNegative() &&
491 RHS->getValue().isPowerOf2()) {
492 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
493 RHS->getValue().exactLogBase2());
494 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
497 // -X/C --> X/-C provided the negation doesn't overflow.
498 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
499 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
500 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
501 ConstantExpr::getNeg(RHS));
504 // If the sign bits of both operands are zero (i.e. we can prove they are
505 // unsigned inputs), turn this into a udiv.
506 if (I.getType()->isIntegerTy()) {
507 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
508 if (MaskedValueIsZero(Op0, Mask)) {
509 if (MaskedValueIsZero(Op1, Mask)) {
510 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
511 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
514 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
515 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
516 // Safe because the only negative value (1 << Y) can take on is
517 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
519 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
527 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
528 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
530 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
531 return ReplaceInstUsesWith(I, V);
533 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
534 const APFloat &Op1F = Op1C->getValueAPF();
536 // If the divisor has an exact multiplicative inverse we can turn the fdiv
537 // into a cheaper fmul.
538 APFloat Reciprocal(Op1F.getSemantics());
539 if (Op1F.getExactInverse(&Reciprocal)) {
540 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
541 return BinaryOperator::CreateFMul(Op0, RFP);
548 /// This function implements the transforms common to both integer remainder
549 /// instructions (urem and srem). It is called by the visitors to those integer
550 /// remainder instructions.
551 /// @brief Common integer remainder transforms
552 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
555 // The RHS is known non-zero.
556 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
561 // Handle cases involving: rem X, (select Cond, Y, Z)
562 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
565 if (isa<ConstantInt>(Op1)) {
566 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
568 if (Instruction *R = FoldOpIntoSelect(I, SI))
570 } else if (isa<PHINode>(Op0I)) {
571 if (Instruction *NV = FoldOpIntoPhi(I))
575 // See if we can fold away this rem instruction.
576 if (SimplifyDemandedInstructionBits(I))
584 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
585 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
587 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
588 return ReplaceInstUsesWith(I, V);
590 if (Instruction *common = commonIRemTransforms(I))
593 // X urem C^2 -> X and C-1
595 if (match(Op1, m_Power2(C)))
596 return BinaryOperator::CreateAnd(Op0,
597 ConstantInt::get(I.getType(), *C-1));
600 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
601 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
602 Constant *N1 = Constant::getAllOnesValue(I.getType());
603 Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
604 return BinaryOperator::CreateAnd(Op0, Add);
607 // urem X, (select Cond, 2^C1, 2^C2) -->
608 // select Cond, (and X, C1-1), (and X, C2-1)
609 // when C1&C2 are powers of two.
610 { Value *Cond; const APInt *C1, *C2;
611 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
612 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
613 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
614 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
618 // (zext A) urem (zext B) --> zext (A urem B)
619 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
620 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
621 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
627 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
628 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
630 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
631 return ReplaceInstUsesWith(I, V);
633 // Handle the integer rem common cases
634 if (Instruction *Common = commonIRemTransforms(I))
637 if (Value *RHSNeg = dyn_castNegVal(Op1))
638 if (!isa<Constant>(RHSNeg) ||
639 (isa<ConstantInt>(RHSNeg) &&
640 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
642 Worklist.AddValue(I.getOperand(1));
643 I.setOperand(1, RHSNeg);
647 // If the sign bits of both operands are zero (i.e. we can prove they are
648 // unsigned inputs), turn this into a urem.
649 if (I.getType()->isIntegerTy()) {
650 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
651 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
652 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
653 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
657 // If it's a constant vector, flip any negative values positive.
658 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
659 unsigned VWidth = RHSV->getNumOperands();
661 bool hasNegative = false;
662 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
663 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
664 if (RHS->getValue().isNegative())
668 std::vector<Constant *> Elts(VWidth);
669 for (unsigned i = 0; i != VWidth; ++i) {
670 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
671 if (RHS->getValue().isNegative())
672 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
678 Constant *NewRHSV = ConstantVector::get(Elts);
679 if (NewRHSV != RHSV) {
680 Worklist.AddValue(I.getOperand(1));
681 I.setOperand(1, NewRHSV);
690 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
693 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
694 return ReplaceInstUsesWith(I, V);
696 // Handle cases involving: rem X, (select Cond, Y, Z)
697 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))