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;
32 bool MadeChange = false;
34 // ((1 << A) >>u B) --> (1 << (A-B))
35 // Because V cannot be zero, we know that B is less than A.
36 Value *A = 0, *B = 0, *PowerOf2 = 0;
37 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
39 // The "1" can be any value known to be a power of 2.
40 isPowerOfTwo(PowerOf2, IC.getTargetData())) {
41 A = IC.Builder->CreateSub(A, B, "tmp");
42 return IC.Builder->CreateShl(PowerOf2, A);
45 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
46 // inexact. Similarly for <<.
47 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
48 if (I->isLogicalShift() &&
49 isPowerOfTwo(I->getOperand(0), IC.getTargetData())) {
50 // We know that this is an exact/nuw shift and that the input is a
51 // non-zero context as well.
52 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
57 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
62 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
63 I->setHasNoUnsignedWrap();
68 // TODO: Lots more we could do here:
69 // If V is a phi node, we can call this on each of its operands.
70 // "select cond, X, 0" can simplify to "X".
72 return MadeChange ? V : 0;
76 /// MultiplyOverflows - True if the multiply can not be expressed in an int
78 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
79 uint32_t W = C1->getBitWidth();
80 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 LHSExt = LHSExt.sext(W * 2);
83 RHSExt = RHSExt.sext(W * 2);
85 LHSExt = LHSExt.zext(W * 2);
86 RHSExt = RHSExt.zext(W * 2);
89 APInt MulExt = LHSExt * RHSExt;
92 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
94 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
95 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
96 return MulExt.slt(Min) || MulExt.sgt(Max);
99 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
100 bool Changed = SimplifyAssociativeOrCommutative(I);
101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
103 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
104 return ReplaceInstUsesWith(I, V);
106 if (Value *V = SimplifyUsingDistributiveLaws(I))
107 return ReplaceInstUsesWith(I, V);
109 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
110 return BinaryOperator::CreateNeg(Op0, I.getName());
112 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
114 // ((X << C1)*C2) == (X * (C2 << C1))
115 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
116 if (SI->getOpcode() == Instruction::Shl)
117 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
118 return BinaryOperator::CreateMul(SI->getOperand(0),
119 ConstantExpr::getShl(CI, ShOp));
121 const APInt &Val = CI->getValue();
122 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
123 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
124 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
125 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
126 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
130 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
131 { Value *X; ConstantInt *C1;
132 if (Op0->hasOneUse() &&
133 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
134 Value *Add = Builder->CreateMul(X, CI, "tmp");
135 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
140 // Simplify mul instructions with a constant RHS.
141 if (isa<Constant>(Op1)) {
142 // Try to fold constant mul into select arguments.
143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
144 if (Instruction *R = FoldOpIntoSelect(I, SI))
147 if (isa<PHINode>(Op0))
148 if (Instruction *NV = FoldOpIntoPhi(I))
152 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
153 if (Value *Op1v = dyn_castNegVal(Op1))
154 return BinaryOperator::CreateMul(Op0v, Op1v);
156 // (X / Y) * Y = X - (X % Y)
157 // (X / Y) * -Y = (X % Y) - X
160 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
162 (BO->getOpcode() != Instruction::UDiv &&
163 BO->getOpcode() != Instruction::SDiv)) {
165 BO = dyn_cast<BinaryOperator>(Op1);
167 Value *Neg = dyn_castNegVal(Op1C);
168 if (BO && BO->hasOneUse() &&
169 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
170 (BO->getOpcode() == Instruction::UDiv ||
171 BO->getOpcode() == Instruction::SDiv)) {
172 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
174 // If the division is exact, X % Y is zero, so we end up with X or -X.
175 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
176 if (SDiv->isExact()) {
178 return ReplaceInstUsesWith(I, Op0BO);
179 return BinaryOperator::CreateNeg(Op0BO);
183 if (BO->getOpcode() == Instruction::UDiv)
184 Rem = Builder->CreateURem(Op0BO, Op1BO);
186 Rem = Builder->CreateSRem(Op0BO, Op1BO);
190 return BinaryOperator::CreateSub(Op0BO, Rem);
191 return BinaryOperator::CreateSub(Rem, Op0BO);
195 /// i1 mul -> i1 and.
196 if (I.getType()->isIntegerTy(1))
197 return BinaryOperator::CreateAnd(Op0, Op1);
199 // X*(1 << Y) --> X << Y
200 // (1 << Y)*X --> X << Y
203 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
204 return BinaryOperator::CreateShl(Op1, Y);
205 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
206 return BinaryOperator::CreateShl(Op0, Y);
209 // If one of the operands of the multiply is a cast from a boolean value, then
210 // we know the bool is either zero or one, so this is a 'masking' multiply.
211 // X * Y (where Y is 0 or 1) -> X & (0-Y)
212 if (!I.getType()->isVectorTy()) {
213 // -2 is "-1 << 1" so it is all bits set except the low one.
214 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
216 Value *BoolCast = 0, *OtherOp = 0;
217 if (MaskedValueIsZero(Op0, Negative2))
218 BoolCast = Op0, OtherOp = Op1;
219 else if (MaskedValueIsZero(Op1, Negative2))
220 BoolCast = Op1, OtherOp = Op0;
223 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
225 return BinaryOperator::CreateAnd(V, OtherOp);
229 return Changed ? &I : 0;
232 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
233 bool Changed = SimplifyAssociativeOrCommutative(I);
234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
236 // Simplify mul instructions with a constant RHS...
237 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
238 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
239 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
240 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
241 if (Op1F->isExactlyValue(1.0))
242 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
243 } else if (Op1C->getType()->isVectorTy()) {
244 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
245 // As above, vector X*splat(1.0) -> X in all defined cases.
246 if (Constant *Splat = Op1V->getSplatValue()) {
247 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
248 if (F->isExactlyValue(1.0))
249 return ReplaceInstUsesWith(I, Op0);
254 // Try to fold constant mul into select arguments.
255 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
256 if (Instruction *R = FoldOpIntoSelect(I, SI))
259 if (isa<PHINode>(Op0))
260 if (Instruction *NV = FoldOpIntoPhi(I))
264 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
265 if (Value *Op1v = dyn_castFNegVal(Op1))
266 return BinaryOperator::CreateFMul(Op0v, Op1v);
268 return Changed ? &I : 0;
271 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
273 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
274 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
276 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
277 int NonNullOperand = -1;
278 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
279 if (ST->isNullValue())
281 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
282 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
283 if (ST->isNullValue())
286 if (NonNullOperand == -1)
289 Value *SelectCond = SI->getOperand(0);
291 // Change the div/rem to use 'Y' instead of the select.
292 I.setOperand(1, SI->getOperand(NonNullOperand));
294 // Okay, we know we replace the operand of the div/rem with 'Y' with no
295 // problem. However, the select, or the condition of the select may have
296 // multiple uses. Based on our knowledge that the operand must be non-zero,
297 // propagate the known value for the select into other uses of it, and
298 // propagate a known value of the condition into its other users.
300 // If the select and condition only have a single use, don't bother with this,
302 if (SI->use_empty() && SelectCond->hasOneUse())
305 // Scan the current block backward, looking for other uses of SI.
306 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
308 while (BBI != BBFront) {
310 // If we found a call to a function, we can't assume it will return, so
311 // information from below it cannot be propagated above it.
312 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
315 // Replace uses of the select or its condition with the known values.
316 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
319 *I = SI->getOperand(NonNullOperand);
321 } else if (*I == SelectCond) {
322 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
323 ConstantInt::getFalse(BBI->getContext());
328 // If we past the instruction, quit looking for it.
331 if (&*BBI == SelectCond)
334 // If we ran out of things to eliminate, break out of the loop.
335 if (SelectCond == 0 && SI == 0)
343 /// This function implements the transforms common to both integer division
344 /// instructions (udiv and sdiv). It is called by the visitors to those integer
345 /// division instructions.
346 /// @brief Common integer divide transforms
347 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
350 // The RHS is known non-zero.
351 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
356 // Handle cases involving: [su]div X, (select Cond, Y, Z)
357 // This does not apply for fdiv.
358 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
361 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
362 // (X / C1) / C2 -> X / (C1*C2)
363 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
364 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
365 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
366 if (MultiplyOverflows(RHS, LHSRHS,
367 I.getOpcode()==Instruction::SDiv))
368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
369 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
370 ConstantExpr::getMul(RHS, LHSRHS));
373 if (!RHS->isZero()) { // avoid X udiv 0
374 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
375 if (Instruction *R = FoldOpIntoSelect(I, SI))
377 if (isa<PHINode>(Op0))
378 if (Instruction *NV = FoldOpIntoPhi(I))
383 // See if we can fold away this div instruction.
384 if (SimplifyDemandedInstructionBits(I))
387 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
388 Value *X = 0, *Z = 0;
389 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
390 bool isSigned = I.getOpcode() == Instruction::SDiv;
391 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
392 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
393 return BinaryOperator::Create(I.getOpcode(), X, Op1);
399 /// dyn_castZExtVal - Checks if V is a zext or constant that can
400 /// be truncated to Ty without losing bits.
401 static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
402 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
403 if (Z->getSrcTy() == Ty)
404 return Z->getOperand(0);
405 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
406 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
407 return ConstantExpr::getTrunc(C, Ty);
412 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
415 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
416 return ReplaceInstUsesWith(I, V);
418 // Handle the integer div common cases
419 if (Instruction *Common = commonIDivTransforms(I))
422 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
423 // X udiv 2^C -> X >> C
424 // Check to see if this is an unsigned division with an exact power of 2,
425 // if so, convert to a right shift.
426 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
427 BinaryOperator *LShr =
428 BinaryOperator::CreateLShr(Op0,
429 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
430 if (I.isExact()) LShr->setIsExact();
434 // X udiv C, where C >= signbit
435 if (C->getValue().isNegative()) {
436 Value *IC = Builder->CreateICmpULT(Op0, C);
437 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
438 ConstantInt::get(I.getType(), 1));
442 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
443 { const APInt *CI; Value *N;
444 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
446 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
449 return BinaryOperator::CreateExactLShr(Op0, N);
450 return BinaryOperator::CreateLShr(Op0, N);
454 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
455 // where C1&C2 are powers of two.
456 { Value *Cond; const APInt *C1, *C2;
457 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
458 // Construct the "on true" case of the select
459 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
462 // Construct the "on false" case of the select
463 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
466 // construct the select instruction and return it.
467 return SelectInst::Create(Cond, TSI, FSI);
471 // (zext A) udiv (zext B) --> zext (A udiv B)
472 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
473 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
474 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
481 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
484 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
485 return ReplaceInstUsesWith(I, V);
487 // Handle the integer div common cases
488 if (Instruction *Common = commonIDivTransforms(I))
491 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
493 if (RHS->isAllOnesValue())
494 return BinaryOperator::CreateNeg(Op0);
496 // sdiv X, C --> ashr exact X, log2(C)
497 if (I.isExact() && RHS->getValue().isNonNegative() &&
498 RHS->getValue().isPowerOf2()) {
499 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
500 RHS->getValue().exactLogBase2());
501 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
504 // -X/C --> X/-C provided the negation doesn't overflow.
505 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
506 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
507 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
508 ConstantExpr::getNeg(RHS));
511 // If the sign bits of both operands are zero (i.e. we can prove they are
512 // unsigned inputs), turn this into a udiv.
513 if (I.getType()->isIntegerTy()) {
514 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
515 if (MaskedValueIsZero(Op0, Mask)) {
516 if (MaskedValueIsZero(Op1, Mask)) {
517 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
518 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
521 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
522 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
523 // Safe because the only negative value (1 << Y) can take on is
524 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
526 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
534 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
535 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
537 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
538 return ReplaceInstUsesWith(I, V);
540 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
541 const APFloat &Op1F = Op1C->getValueAPF();
543 // If the divisor has an exact multiplicative inverse we can turn the fdiv
544 // into a cheaper fmul.
545 APFloat Reciprocal(Op1F.getSemantics());
546 if (Op1F.getExactInverse(&Reciprocal)) {
547 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
548 return BinaryOperator::CreateFMul(Op0, RFP);
555 /// This function implements the transforms common to both integer remainder
556 /// instructions (urem and srem). It is called by the visitors to those integer
557 /// remainder instructions.
558 /// @brief Common integer remainder transforms
559 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
562 // The RHS is known non-zero.
563 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
568 // Handle cases involving: rem X, (select Cond, Y, Z)
569 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
572 if (isa<ConstantInt>(Op1)) {
573 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
574 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
575 if (Instruction *R = FoldOpIntoSelect(I, SI))
577 } else if (isa<PHINode>(Op0I)) {
578 if (Instruction *NV = FoldOpIntoPhi(I))
582 // See if we can fold away this rem instruction.
583 if (SimplifyDemandedInstructionBits(I))
591 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
594 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
595 return ReplaceInstUsesWith(I, V);
597 if (Instruction *common = commonIRemTransforms(I))
600 // X urem C^2 -> X and C-1
602 if (match(Op1, m_Power2(C)))
603 return BinaryOperator::CreateAnd(Op0,
604 ConstantInt::get(I.getType(), *C-1));
607 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
608 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
609 Constant *N1 = Constant::getAllOnesValue(I.getType());
610 Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
611 return BinaryOperator::CreateAnd(Op0, Add);
614 // urem X, (select Cond, 2^C1, 2^C2) -->
615 // select Cond, (and X, C1-1), (and X, C2-1)
616 // when C1&C2 are powers of two.
617 { Value *Cond; const APInt *C1, *C2;
618 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
619 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
620 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
621 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
625 // (zext A) urem (zext B) --> zext (A urem B)
626 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
627 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
628 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
634 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
637 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
638 return ReplaceInstUsesWith(I, V);
640 // Handle the integer rem common cases
641 if (Instruction *Common = commonIRemTransforms(I))
644 if (Value *RHSNeg = dyn_castNegVal(Op1))
645 if (!isa<Constant>(RHSNeg) ||
646 (isa<ConstantInt>(RHSNeg) &&
647 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
649 Worklist.AddValue(I.getOperand(1));
650 I.setOperand(1, RHSNeg);
654 // If the sign bits of both operands are zero (i.e. we can prove they are
655 // unsigned inputs), turn this into a urem.
656 if (I.getType()->isIntegerTy()) {
657 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
658 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
659 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
660 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
664 // If it's a constant vector, flip any negative values positive.
665 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
666 unsigned VWidth = RHSV->getNumOperands();
668 bool hasNegative = false;
669 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
670 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
671 if (RHS->getValue().isNegative())
675 std::vector<Constant *> Elts(VWidth);
676 for (unsigned i = 0; i != VWidth; ++i) {
677 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
678 if (RHS->getValue().isNegative())
679 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
685 Constant *NewRHSV = ConstantVector::get(Elts);
686 if (NewRHSV != RHSV) {
687 Worklist.AddValue(I.getOperand(1));
688 I.setOperand(1, NewRHSV);
697 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
698 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
700 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
701 return ReplaceInstUsesWith(I, V);
703 // Handle cases involving: rem X, (select Cond, Y, Z)
704 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))