rearrange two transforms, since one subsumes the other. Make the shift-exactness
[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   bool MadeChange = false;
33
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))),
38                       m_Value(B))) &&
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);
43   }
44   
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)) {
53         I->setOperand(0, V2);
54         MadeChange = true;
55       }
56       
57       if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
58         I->setIsExact();
59         MadeChange = true;
60       }
61       
62       if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
63         I->setHasNoUnsignedWrap();
64         MadeChange = true;
65       }
66     }
67
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".
71   
72   return MadeChange ? V : 0;
73 }
74
75
76 /// MultiplyOverflows - True if the multiply can not be expressed in an int
77 /// this size.
78 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
79   uint32_t W = C1->getBitWidth();
80   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
81   if (sign) {
82     LHSExt = LHSExt.sext(W * 2);
83     RHSExt = RHSExt.sext(W * 2);
84   } else {
85     LHSExt = LHSExt.zext(W * 2);
86     RHSExt = RHSExt.zext(W * 2);
87   }
88   
89   APInt MulExt = LHSExt * RHSExt;
90   
91   if (!sign)
92     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
93   
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);
97 }
98
99 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
100   bool Changed = SimplifyAssociativeOrCommutative(I);
101   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
102
103   if (Value *V = SimplifyMulInst(Op0, Op1, TD))
104     return ReplaceInstUsesWith(I, V);
105
106   if (Value *V = SimplifyUsingDistributiveLaws(I))
107     return ReplaceInstUsesWith(I, V);
108
109   if (match(Op1, m_AllOnes()))  // X * -1 == 0 - X
110     return BinaryOperator::CreateNeg(Op0, I.getName());
111   
112   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
113     
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));
120     
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();
127       return Shl;
128     }
129     
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));
136       }
137     }
138   }
139   
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))
145         return R;
146
147     if (isa<PHINode>(Op0))
148       if (Instruction *NV = FoldOpIntoPhi(I))
149         return NV;
150   }
151
152   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
153     if (Value *Op1v = dyn_castNegVal(Op1))
154       return BinaryOperator::CreateMul(Op0v, Op1v);
155
156   // (X / Y) *  Y = X - (X % Y)
157   // (X / Y) * -Y = (X % Y) - X
158   {
159     Value *Op1C = Op1;
160     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
161     if (!BO ||
162         (BO->getOpcode() != Instruction::UDiv && 
163          BO->getOpcode() != Instruction::SDiv)) {
164       Op1C = Op0;
165       BO = dyn_cast<BinaryOperator>(Op1);
166     }
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);
173
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()) {
177           if (Op1BO == Op1C)
178             return ReplaceInstUsesWith(I, Op0BO);
179           return BinaryOperator::CreateNeg(Op0BO);
180         }
181
182       Value *Rem;
183       if (BO->getOpcode() == Instruction::UDiv)
184         Rem = Builder->CreateURem(Op0BO, Op1BO);
185       else
186         Rem = Builder->CreateSRem(Op0BO, Op1BO);
187       Rem->takeName(BO);
188
189       if (Op1BO == Op1C)
190         return BinaryOperator::CreateSub(Op0BO, Rem);
191       return BinaryOperator::CreateSub(Rem, Op0BO);
192     }
193   }
194
195   /// i1 mul -> i1 and.
196   if (I.getType()->isIntegerTy(1))
197     return BinaryOperator::CreateAnd(Op0, Op1);
198
199   // X*(1 << Y) --> X << Y
200   // (1 << Y)*X --> X << Y
201   {
202     Value *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);
207   }
208   
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);
215     
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;
221
222     if (BoolCast) {
223       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
224                                     BoolCast, "tmp");
225       return BinaryOperator::CreateAnd(V, OtherOp);
226     }
227   }
228
229   return Changed ? &I : 0;
230 }
231
232 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
233   bool Changed = SimplifyAssociativeOrCommutative(I);
234   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
235
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);
250         }
251       }
252     }
253
254     // Try to fold constant mul into select arguments.
255     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
256       if (Instruction *R = FoldOpIntoSelect(I, SI))
257         return R;
258
259     if (isa<PHINode>(Op0))
260       if (Instruction *NV = FoldOpIntoPhi(I))
261         return NV;
262   }
263
264   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
265     if (Value *Op1v = dyn_castFNegVal(Op1))
266       return BinaryOperator::CreateFMul(Op0v, Op1v);
267
268   return Changed ? &I : 0;
269 }
270
271 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
272 /// instruction.
273 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
274   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
275   
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())
280       NonNullOperand = 2;
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())
284       NonNullOperand = 1;
285   
286   if (NonNullOperand == -1)
287     return false;
288   
289   Value *SelectCond = SI->getOperand(0);
290   
291   // Change the div/rem to use 'Y' instead of the select.
292   I.setOperand(1, SI->getOperand(NonNullOperand));
293   
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.
299   
300   // If the select and condition only have a single use, don't bother with this,
301   // early exit.
302   if (SI->use_empty() && SelectCond->hasOneUse())
303     return true;
304   
305   // Scan the current block backward, looking for other uses of SI.
306   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
307   
308   while (BBI != BBFront) {
309     --BBI;
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))
313       break;
314     
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();
317          I != E; ++I) {
318       if (*I == SI) {
319         *I = SI->getOperand(NonNullOperand);
320         Worklist.Add(BBI);
321       } else if (*I == SelectCond) {
322         *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
323                                    ConstantInt::getFalse(BBI->getContext());
324         Worklist.Add(BBI);
325       }
326     }
327     
328     // If we past the instruction, quit looking for it.
329     if (&*BBI == SI)
330       SI = 0;
331     if (&*BBI == SelectCond)
332       SelectCond = 0;
333     
334     // If we ran out of things to eliminate, break out of the loop.
335     if (SelectCond == 0 && SI == 0)
336       break;
337     
338   }
339   return true;
340 }
341
342
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);
349
350   // The RHS is known non-zero.
351   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
352     I.setOperand(1, V);
353     return &I;
354   }
355   
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))
359     return &I;
360
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));
371         }
372
373     if (!RHS->isZero()) { // avoid X udiv 0
374       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
375         if (Instruction *R = FoldOpIntoSelect(I, SI))
376           return R;
377       if (isa<PHINode>(Op0))
378         if (Instruction *NV = FoldOpIntoPhi(I))
379           return NV;
380     }
381   }
382
383   // See if we can fold away this div instruction.
384   if (SimplifyDemandedInstructionBits(I))
385     return &I;
386
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);
394   }
395
396   return 0;
397 }
398
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);
408   }
409   return 0;
410 }
411
412 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
413   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
414
415   if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
416     return ReplaceInstUsesWith(I, V);
417
418   // Handle the integer div common cases
419   if (Instruction *Common = commonIDivTransforms(I))
420     return Common;
421
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();
431       return LShr;
432     }
433
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));
439     }
440   }
441
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)))) {
445       if (*CI != 1)
446         N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
447                                "tmp");
448       if (I.isExact())
449         return BinaryOperator::CreateExactLShr(Op0, N);
450       return BinaryOperator::CreateLShr(Op0, N);
451     }
452   }
453   
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",
460                                        I.isExact());
461   
462       // Construct the "on false" case of the select
463       Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
464                                        I.isExact());
465       
466       // construct the select instruction and return it.
467       return SelectInst::Create(Cond, TSI, FSI);
468     }
469   }
470
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",
475                                               I.isExact()),
476                           I.getType());
477
478   return 0;
479 }
480
481 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
482   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
483
484   if (Value *V = SimplifySDivInst(Op0, Op1, TD))
485     return ReplaceInstUsesWith(I, V);
486
487   // Handle the integer div common cases
488   if (Instruction *Common = commonIDivTransforms(I))
489     return Common;
490
491   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
492     // sdiv X, -1 == -X
493     if (RHS->isAllOnesValue())
494       return BinaryOperator::CreateNeg(Op0);
495
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());
502     }
503
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));
509   }
510
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());
519       }
520       
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
525         // the sign bit set.
526         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
527       }
528     }
529   }
530   
531   return 0;
532 }
533
534 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
535   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
536
537   if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
538     return ReplaceInstUsesWith(I, V);
539
540   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
541     const APFloat &Op1F = Op1C->getValueAPF();
542
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);
549     }
550   }
551
552   return 0;
553 }
554
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);
561
562   // The RHS is known non-zero.
563   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
564     I.setOperand(1, V);
565     return &I;
566   }
567
568   // Handle cases involving: rem X, (select Cond, Y, Z)
569   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
570     return &I;
571
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))
576           return R;
577       } else if (isa<PHINode>(Op0I)) {
578         if (Instruction *NV = FoldOpIntoPhi(I))
579           return NV;
580       }
581
582       // See if we can fold away this rem instruction.
583       if (SimplifyDemandedInstructionBits(I))
584         return &I;
585     }
586   }
587
588   return 0;
589 }
590
591 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
592   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
593
594   if (Value *V = SimplifyURemInst(Op0, Op1, TD))
595     return ReplaceInstUsesWith(I, V);
596
597   if (Instruction *common = commonIRemTransforms(I))
598     return common;
599   
600   // X urem C^2 -> X and C-1
601   { const APInt *C;
602     if (match(Op1, m_Power2(C)))
603       return BinaryOperator::CreateAnd(Op0,
604                                        ConstantInt::get(I.getType(), *C-1));
605   }
606
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);
612   }
613
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);
622     }
623   }
624
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),
629                           I.getType());
630
631   return 0;
632 }
633
634 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
635   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
636
637   if (Value *V = SimplifySRemInst(Op0, Op1, TD))
638     return ReplaceInstUsesWith(I, V);
639
640   // Handle the integer rem common cases
641   if (Instruction *Common = commonIRemTransforms(I))
642     return Common;
643   
644   if (Value *RHSNeg = dyn_castNegVal(Op1))
645     if (!isa<Constant>(RHSNeg) ||
646         (isa<ConstantInt>(RHSNeg) &&
647          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
648       // X % -Y -> X % Y
649       Worklist.AddValue(I.getOperand(1));
650       I.setOperand(1, RHSNeg);
651       return &I;
652     }
653
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());
661     }
662   }
663
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();
667
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())
672           hasNegative = true;
673
674     if (hasNegative) {
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));
680           else
681             Elts[i] = RHS;
682         }
683       }
684
685       Constant *NewRHSV = ConstantVector::get(Elts);
686       if (NewRHSV != RHSV) {
687         Worklist.AddValue(I.getOperand(1));
688         I.setOperand(1, NewRHSV);
689         return &I;
690       }
691     }
692   }
693
694   return 0;
695 }
696
697 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
698   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
699
700   if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
701     return ReplaceInstUsesWith(I, V);
702
703   // Handle cases involving: rem X, (select Cond, Y, Z)
704   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
705     return &I;
706
707   return 0;
708 }