Carve out a place in instcombine to put transformations which work knowing that their
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineMulDivRem.cpp
1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11 // srem, urem, frem.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstCombine.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/PatternMatch.h"
19 using namespace llvm;
20 using namespace PatternMatch;
21
22
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
29   // code.
30   if (!V->hasOneUse()) return 0;
31   
32   // ((1 << A) >>u B) --> (1 << (A-B))
33   // Because V cannot be zero, we know that B is less than A.
34   Value *A = 0, *B = 0; ConstantInt *One = 0;
35   if (match(V, m_LShr(m_OneUse(m_Shl(m_ConstantInt(One), m_Value(A))),
36                       m_Value(B))) &&
37       // The "1" can be any value known to be a power of 2.
38       One->getValue().isPowerOf2()) {
39     A = IC.Builder->CreateSub(A, B, "tmp");
40     return IC.Builder->CreateShl(One, A);
41   }
42   
43   return 0;
44 }
45
46
47 /// MultiplyOverflows - True if the multiply can not be expressed in an int
48 /// this size.
49 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
50   uint32_t W = C1->getBitWidth();
51   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
52   if (sign) {
53     LHSExt = LHSExt.sext(W * 2);
54     RHSExt = RHSExt.sext(W * 2);
55   } else {
56     LHSExt = LHSExt.zext(W * 2);
57     RHSExt = RHSExt.zext(W * 2);
58   }
59   
60   APInt MulExt = LHSExt * RHSExt;
61   
62   if (!sign)
63     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
64   
65   APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
66   APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
67   return MulExt.slt(Min) || MulExt.sgt(Max);
68 }
69
70 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
71   bool Changed = SimplifyAssociativeOrCommutative(I);
72   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
73
74   if (Value *V = SimplifyMulInst(Op0, Op1, TD))
75     return ReplaceInstUsesWith(I, V);
76
77   if (Value *V = SimplifyUsingDistributiveLaws(I))
78     return ReplaceInstUsesWith(I, V);
79
80   if (match(Op1, m_AllOnes()))  // X * -1 == 0 - X
81     return BinaryOperator::CreateNeg(Op0, I.getName());
82   
83   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
84     
85     // ((X << C1)*C2) == (X * (C2 << C1))
86     if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
87       if (SI->getOpcode() == Instruction::Shl)
88         if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
89           return BinaryOperator::CreateMul(SI->getOperand(0),
90                                            ConstantExpr::getShl(CI, ShOp));
91     
92     const APInt &Val = CI->getValue();
93     if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
94       Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
95       BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
96       if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
97       if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
98       return Shl;
99     }
100     
101     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
102     { Value *X; ConstantInt *C1;
103       if (Op0->hasOneUse() &&
104           match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
105         Value *Add = Builder->CreateMul(X, CI, "tmp");
106         return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
107       }
108     }
109   }
110   
111   // Simplify mul instructions with a constant RHS.
112   if (isa<Constant>(Op1)) {    
113     // Try to fold constant mul into select arguments.
114     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
115       if (Instruction *R = FoldOpIntoSelect(I, SI))
116         return R;
117
118     if (isa<PHINode>(Op0))
119       if (Instruction *NV = FoldOpIntoPhi(I))
120         return NV;
121   }
122
123   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
124     if (Value *Op1v = dyn_castNegVal(Op1))
125       return BinaryOperator::CreateMul(Op0v, Op1v);
126
127   // (X / Y) *  Y = X - (X % Y)
128   // (X / Y) * -Y = (X % Y) - X
129   {
130     Value *Op1C = Op1;
131     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
132     if (!BO ||
133         (BO->getOpcode() != Instruction::UDiv && 
134          BO->getOpcode() != Instruction::SDiv)) {
135       Op1C = Op0;
136       BO = dyn_cast<BinaryOperator>(Op1);
137     }
138     Value *Neg = dyn_castNegVal(Op1C);
139     if (BO && BO->hasOneUse() &&
140         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
141         (BO->getOpcode() == Instruction::UDiv ||
142          BO->getOpcode() == Instruction::SDiv)) {
143       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
144
145       // If the division is exact, X % Y is zero, so we end up with X or -X.
146       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
147         if (SDiv->isExact()) {
148           if (Op1BO == Op1C)
149             return ReplaceInstUsesWith(I, Op0BO);
150           return BinaryOperator::CreateNeg(Op0BO);
151         }
152
153       Value *Rem;
154       if (BO->getOpcode() == Instruction::UDiv)
155         Rem = Builder->CreateURem(Op0BO, Op1BO);
156       else
157         Rem = Builder->CreateSRem(Op0BO, Op1BO);
158       Rem->takeName(BO);
159
160       if (Op1BO == Op1C)
161         return BinaryOperator::CreateSub(Op0BO, Rem);
162       return BinaryOperator::CreateSub(Rem, Op0BO);
163     }
164   }
165
166   /// i1 mul -> i1 and.
167   if (I.getType()->isIntegerTy(1))
168     return BinaryOperator::CreateAnd(Op0, Op1);
169
170   // X*(1 << Y) --> X << Y
171   // (1 << Y)*X --> X << Y
172   {
173     Value *Y;
174     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
175       return BinaryOperator::CreateShl(Op1, Y);
176     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
177       return BinaryOperator::CreateShl(Op0, Y);
178   }
179   
180   // If one of the operands of the multiply is a cast from a boolean value, then
181   // we know the bool is either zero or one, so this is a 'masking' multiply.
182   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
183   if (!I.getType()->isVectorTy()) {
184     // -2 is "-1 << 1" so it is all bits set except the low one.
185     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
186     
187     Value *BoolCast = 0, *OtherOp = 0;
188     if (MaskedValueIsZero(Op0, Negative2))
189       BoolCast = Op0, OtherOp = Op1;
190     else if (MaskedValueIsZero(Op1, Negative2))
191       BoolCast = Op1, OtherOp = Op0;
192
193     if (BoolCast) {
194       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
195                                     BoolCast, "tmp");
196       return BinaryOperator::CreateAnd(V, OtherOp);
197     }
198   }
199
200   return Changed ? &I : 0;
201 }
202
203 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
204   bool Changed = SimplifyAssociativeOrCommutative(I);
205   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
206
207   // Simplify mul instructions with a constant RHS...
208   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
209     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
210       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
211       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
212       if (Op1F->isExactlyValue(1.0))
213         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'fmul double %X, 1.0'
214     } else if (Op1C->getType()->isVectorTy()) {
215       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
216         // As above, vector X*splat(1.0) -> X in all defined cases.
217         if (Constant *Splat = Op1V->getSplatValue()) {
218           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
219             if (F->isExactlyValue(1.0))
220               return ReplaceInstUsesWith(I, Op0);
221         }
222       }
223     }
224
225     // Try to fold constant mul into select arguments.
226     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
227       if (Instruction *R = FoldOpIntoSelect(I, SI))
228         return R;
229
230     if (isa<PHINode>(Op0))
231       if (Instruction *NV = FoldOpIntoPhi(I))
232         return NV;
233   }
234
235   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
236     if (Value *Op1v = dyn_castFNegVal(Op1))
237       return BinaryOperator::CreateFMul(Op0v, Op1v);
238
239   return Changed ? &I : 0;
240 }
241
242 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
243 /// instruction.
244 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
245   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
246   
247   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
248   int NonNullOperand = -1;
249   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
250     if (ST->isNullValue())
251       NonNullOperand = 2;
252   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
253   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
254     if (ST->isNullValue())
255       NonNullOperand = 1;
256   
257   if (NonNullOperand == -1)
258     return false;
259   
260   Value *SelectCond = SI->getOperand(0);
261   
262   // Change the div/rem to use 'Y' instead of the select.
263   I.setOperand(1, SI->getOperand(NonNullOperand));
264   
265   // Okay, we know we replace the operand of the div/rem with 'Y' with no
266   // problem.  However, the select, or the condition of the select may have
267   // multiple uses.  Based on our knowledge that the operand must be non-zero,
268   // propagate the known value for the select into other uses of it, and
269   // propagate a known value of the condition into its other users.
270   
271   // If the select and condition only have a single use, don't bother with this,
272   // early exit.
273   if (SI->use_empty() && SelectCond->hasOneUse())
274     return true;
275   
276   // Scan the current block backward, looking for other uses of SI.
277   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
278   
279   while (BBI != BBFront) {
280     --BBI;
281     // If we found a call to a function, we can't assume it will return, so
282     // information from below it cannot be propagated above it.
283     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
284       break;
285     
286     // Replace uses of the select or its condition with the known values.
287     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
288          I != E; ++I) {
289       if (*I == SI) {
290         *I = SI->getOperand(NonNullOperand);
291         Worklist.Add(BBI);
292       } else if (*I == SelectCond) {
293         *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
294                                    ConstantInt::getFalse(BBI->getContext());
295         Worklist.Add(BBI);
296       }
297     }
298     
299     // If we past the instruction, quit looking for it.
300     if (&*BBI == SI)
301       SI = 0;
302     if (&*BBI == SelectCond)
303       SelectCond = 0;
304     
305     // If we ran out of things to eliminate, break out of the loop.
306     if (SelectCond == 0 && SI == 0)
307       break;
308     
309   }
310   return true;
311 }
312
313
314 /// This function implements the transforms common to both integer division
315 /// instructions (udiv and sdiv). It is called by the visitors to those integer
316 /// division instructions.
317 /// @brief Common integer divide transforms
318 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
319   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
320
321   // The RHS is known non-zero.
322   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
323     I.setOperand(1, V);
324     return &I;
325   }
326   
327   // Handle cases involving: [su]div X, (select Cond, Y, Z)
328   // This does not apply for fdiv.
329   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
330     return &I;
331
332   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
333     // (X / C1) / C2  -> X / (C1*C2)
334     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
335       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
336         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
337           if (MultiplyOverflows(RHS, LHSRHS,
338                                 I.getOpcode()==Instruction::SDiv))
339             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
340           return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
341                                         ConstantExpr::getMul(RHS, LHSRHS));
342         }
343
344     if (!RHS->isZero()) { // avoid X udiv 0
345       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
346         if (Instruction *R = FoldOpIntoSelect(I, SI))
347           return R;
348       if (isa<PHINode>(Op0))
349         if (Instruction *NV = FoldOpIntoPhi(I))
350           return NV;
351     }
352   }
353
354   // See if we can fold away this div instruction.
355   if (SimplifyDemandedInstructionBits(I))
356     return &I;
357
358   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
359   Value *X = 0, *Z = 0;
360   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
361     bool isSigned = I.getOpcode() == Instruction::SDiv;
362     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
363         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
364       return BinaryOperator::Create(I.getOpcode(), X, Op1);
365   }
366
367   return 0;
368 }
369
370 /// dyn_castZExtVal - Checks if V is a zext or constant that can
371 /// be truncated to Ty without losing bits.
372 static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
373   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
374     if (Z->getSrcTy() == Ty)
375       return Z->getOperand(0);
376   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
377     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
378       return ConstantExpr::getTrunc(C, Ty);
379   }
380   return 0;
381 }
382
383 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
384   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
385
386   if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
387     return ReplaceInstUsesWith(I, V);
388
389   // Handle the integer div common cases
390   if (Instruction *Common = commonIDivTransforms(I))
391     return Common;
392
393   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
394     // X udiv 2^C -> X >> C
395     // Check to see if this is an unsigned division with an exact power of 2,
396     // if so, convert to a right shift.
397     if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
398       BinaryOperator *LShr =
399         BinaryOperator::CreateLShr(Op0, 
400             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
401       if (I.isExact()) LShr->setIsExact();
402       return LShr;
403     }
404
405     // X udiv C, where C >= signbit
406     if (C->getValue().isNegative()) {
407       Value *IC = Builder->CreateICmpULT(Op0, C);
408       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
409                                 ConstantInt::get(I.getType(), 1));
410     }
411   }
412
413   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
414   { const APInt *CI; Value *N;
415     if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
416       if (*CI != 1)
417         N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
418                                "tmp");
419       if (I.isExact())
420         return BinaryOperator::CreateExactLShr(Op0, N);
421       return BinaryOperator::CreateLShr(Op0, N);
422     }
423   }
424   
425   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
426   // where C1&C2 are powers of two.
427   { Value *Cond; const APInt *C1, *C2;
428     if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
429       // Construct the "on true" case of the select
430       Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
431                                        I.isExact());
432   
433       // Construct the "on false" case of the select
434       Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
435                                        I.isExact());
436       
437       // construct the select instruction and return it.
438       return SelectInst::Create(Cond, TSI, FSI);
439     }
440   }
441
442   // (zext A) udiv (zext B) --> zext (A udiv B)
443   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
444     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
445       return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
446                                               I.isExact()),
447                           I.getType());
448
449   return 0;
450 }
451
452 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
453   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
454
455   if (Value *V = SimplifySDivInst(Op0, Op1, TD))
456     return ReplaceInstUsesWith(I, V);
457
458   // Handle the integer div common cases
459   if (Instruction *Common = commonIDivTransforms(I))
460     return Common;
461
462   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
463     // sdiv X, -1 == -X
464     if (RHS->isAllOnesValue())
465       return BinaryOperator::CreateNeg(Op0);
466
467     // sdiv X, C  -->  ashr exact X, log2(C)
468     if (I.isExact() && RHS->getValue().isNonNegative() &&
469         RHS->getValue().isPowerOf2()) {
470       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
471                                             RHS->getValue().exactLogBase2());
472       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
473     }
474
475     // -X/C  -->  X/-C  provided the negation doesn't overflow.
476     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
477       if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
478         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
479                                           ConstantExpr::getNeg(RHS));
480   }
481
482   // If the sign bits of both operands are zero (i.e. we can prove they are
483   // unsigned inputs), turn this into a udiv.
484   if (I.getType()->isIntegerTy()) {
485     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
486     if (MaskedValueIsZero(Op0, Mask)) {
487       if (MaskedValueIsZero(Op1, Mask)) {
488         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
489         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
490       }
491       
492       if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
493         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
494         // Safe because the only negative value (1 << Y) can take on is
495         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
496         // the sign bit set.
497         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
498       }
499     }
500   }
501   
502   return 0;
503 }
504
505 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
506   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
507
508   if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
509     return ReplaceInstUsesWith(I, V);
510
511   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
512     const APFloat &Op1F = Op1C->getValueAPF();
513
514     // If the divisor has an exact multiplicative inverse we can turn the fdiv
515     // into a cheaper fmul.
516     APFloat Reciprocal(Op1F.getSemantics());
517     if (Op1F.getExactInverse(&Reciprocal)) {
518       ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
519       return BinaryOperator::CreateFMul(Op0, RFP);
520     }
521   }
522
523   return 0;
524 }
525
526 /// This function implements the transforms common to both integer remainder
527 /// instructions (urem and srem). It is called by the visitors to those integer
528 /// remainder instructions.
529 /// @brief Common integer remainder transforms
530 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
531   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
532
533   // The RHS is known non-zero.
534   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
535     I.setOperand(1, V);
536     return &I;
537   }
538
539   // Handle cases involving: rem X, (select Cond, Y, Z)
540   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
541     return &I;
542
543   if (isa<ConstantInt>(Op1)) {
544     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
545       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
546         if (Instruction *R = FoldOpIntoSelect(I, SI))
547           return R;
548       } else if (isa<PHINode>(Op0I)) {
549         if (Instruction *NV = FoldOpIntoPhi(I))
550           return NV;
551       }
552
553       // See if we can fold away this rem instruction.
554       if (SimplifyDemandedInstructionBits(I))
555         return &I;
556     }
557   }
558
559   return 0;
560 }
561
562 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
563   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
564
565   if (Value *V = SimplifyURemInst(Op0, Op1, TD))
566     return ReplaceInstUsesWith(I, V);
567
568   if (Instruction *common = commonIRemTransforms(I))
569     return common;
570   
571   // X urem C^2 -> X and C-1
572   { const APInt *C;
573     if (match(Op1, m_Power2(C)))
574       return BinaryOperator::CreateAnd(Op0,
575                                        ConstantInt::get(I.getType(), *C-1));
576   }
577
578   // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
579   if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
580     Constant *N1 = Constant::getAllOnesValue(I.getType());
581     Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
582     return BinaryOperator::CreateAnd(Op0, Add);
583   }
584
585   // urem X, (select Cond, 2^C1, 2^C2) -->
586   //    select Cond, (and X, C1-1), (and X, C2-1)
587   // when C1&C2 are powers of two.
588   { Value *Cond; const APInt *C1, *C2;
589     if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
590       Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
591       Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
592       return SelectInst::Create(Cond, TrueAnd, FalseAnd);
593     }
594   }
595
596   // (zext A) urem (zext B) --> zext (A urem B)
597   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
598     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
599       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
600                           I.getType());
601
602   return 0;
603 }
604
605 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
606   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
607
608   if (Value *V = SimplifySRemInst(Op0, Op1, TD))
609     return ReplaceInstUsesWith(I, V);
610
611   // Handle the integer rem common cases
612   if (Instruction *Common = commonIRemTransforms(I))
613     return Common;
614   
615   if (Value *RHSNeg = dyn_castNegVal(Op1))
616     if (!isa<Constant>(RHSNeg) ||
617         (isa<ConstantInt>(RHSNeg) &&
618          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
619       // X % -Y -> X % Y
620       Worklist.AddValue(I.getOperand(1));
621       I.setOperand(1, RHSNeg);
622       return &I;
623     }
624
625   // If the sign bits of both operands are zero (i.e. we can prove they are
626   // unsigned inputs), turn this into a urem.
627   if (I.getType()->isIntegerTy()) {
628     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
629     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
630       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
631       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
632     }
633   }
634
635   // If it's a constant vector, flip any negative values positive.
636   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
637     unsigned VWidth = RHSV->getNumOperands();
638
639     bool hasNegative = false;
640     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
641       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
642         if (RHS->getValue().isNegative())
643           hasNegative = true;
644
645     if (hasNegative) {
646       std::vector<Constant *> Elts(VWidth);
647       for (unsigned i = 0; i != VWidth; ++i) {
648         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
649           if (RHS->getValue().isNegative())
650             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
651           else
652             Elts[i] = RHS;
653         }
654       }
655
656       Constant *NewRHSV = ConstantVector::get(Elts);
657       if (NewRHSV != RHSV) {
658         Worklist.AddValue(I.getOperand(1));
659         I.setOperand(1, NewRHSV);
660         return &I;
661       }
662     }
663   }
664
665   return 0;
666 }
667
668 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
669   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
670
671   if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
672     return ReplaceInstUsesWith(I, V);
673
674   // Handle cases involving: rem X, (select Cond, Y, Z)
675   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
676     return &I;
677
678   return 0;
679 }