Use the new script to sort the includes of every file under lib.
[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/Analysis/InstructionSimplify.h"
17 #include "llvm/IntrinsicInst.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.getDataLayout())) {
41     A = IC.Builder->CreateSub(A, B);
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.getDataLayout())) {
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);
135         return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
136       }
137     }
138
139     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
140     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
141     // The "* (2**n)" thus becomes a potential shifting opportunity.
142     {
143       const APInt &   Val = CI->getValue();
144       const APInt &PosVal = Val.abs();
145       if (Val.isNegative() && PosVal.isPowerOf2()) {
146         Value *X = 0, *Y = 0;
147         if (Op0->hasOneUse()) {
148           ConstantInt *C1;
149           Value *Sub = 0;
150           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
151             Sub = Builder->CreateSub(X, Y, "suba");
152           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
153             Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
154           if (Sub)
155             return
156               BinaryOperator::CreateMul(Sub,
157                                         ConstantInt::get(Y->getType(), PosVal));
158         }
159       }
160     }
161   }
162   
163   // Simplify mul instructions with a constant RHS.
164   if (isa<Constant>(Op1)) {    
165     // Try to fold constant mul into select arguments.
166     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
167       if (Instruction *R = FoldOpIntoSelect(I, SI))
168         return R;
169
170     if (isa<PHINode>(Op0))
171       if (Instruction *NV = FoldOpIntoPhi(I))
172         return NV;
173   }
174
175   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
176     if (Value *Op1v = dyn_castNegVal(Op1))
177       return BinaryOperator::CreateMul(Op0v, Op1v);
178
179   // (X / Y) *  Y = X - (X % Y)
180   // (X / Y) * -Y = (X % Y) - X
181   {
182     Value *Op1C = Op1;
183     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
184     if (!BO ||
185         (BO->getOpcode() != Instruction::UDiv && 
186          BO->getOpcode() != Instruction::SDiv)) {
187       Op1C = Op0;
188       BO = dyn_cast<BinaryOperator>(Op1);
189     }
190     Value *Neg = dyn_castNegVal(Op1C);
191     if (BO && BO->hasOneUse() &&
192         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
193         (BO->getOpcode() == Instruction::UDiv ||
194          BO->getOpcode() == Instruction::SDiv)) {
195       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
196
197       // If the division is exact, X % Y is zero, so we end up with X or -X.
198       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
199         if (SDiv->isExact()) {
200           if (Op1BO == Op1C)
201             return ReplaceInstUsesWith(I, Op0BO);
202           return BinaryOperator::CreateNeg(Op0BO);
203         }
204
205       Value *Rem;
206       if (BO->getOpcode() == Instruction::UDiv)
207         Rem = Builder->CreateURem(Op0BO, Op1BO);
208       else
209         Rem = Builder->CreateSRem(Op0BO, Op1BO);
210       Rem->takeName(BO);
211
212       if (Op1BO == Op1C)
213         return BinaryOperator::CreateSub(Op0BO, Rem);
214       return BinaryOperator::CreateSub(Rem, Op0BO);
215     }
216   }
217
218   /// i1 mul -> i1 and.
219   if (I.getType()->isIntegerTy(1))
220     return BinaryOperator::CreateAnd(Op0, Op1);
221
222   // X*(1 << Y) --> X << Y
223   // (1 << Y)*X --> X << Y
224   {
225     Value *Y;
226     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
227       return BinaryOperator::CreateShl(Op1, Y);
228     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
229       return BinaryOperator::CreateShl(Op0, Y);
230   }
231   
232   // If one of the operands of the multiply is a cast from a boolean value, then
233   // we know the bool is either zero or one, so this is a 'masking' multiply.
234   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
235   if (!I.getType()->isVectorTy()) {
236     // -2 is "-1 << 1" so it is all bits set except the low one.
237     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
238     
239     Value *BoolCast = 0, *OtherOp = 0;
240     if (MaskedValueIsZero(Op0, Negative2))
241       BoolCast = Op0, OtherOp = Op1;
242     else if (MaskedValueIsZero(Op1, Negative2))
243       BoolCast = Op1, OtherOp = Op0;
244
245     if (BoolCast) {
246       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
247                                     BoolCast);
248       return BinaryOperator::CreateAnd(V, OtherOp);
249     }
250   }
251
252   return Changed ? &I : 0;
253 }
254
255 //
256 // Detect pattern:
257 //
258 // log2(Y*0.5)
259 //
260 // And check for corresponding fast math flags
261 //
262
263 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
264
265    if (!Op->hasOneUse())
266      return;
267
268    IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
269    if (!II)
270      return;
271    if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
272      return;
273    Log2 = II;
274
275    Value *OpLog2Of = II->getArgOperand(0);
276    if (!OpLog2Of->hasOneUse())
277      return;
278
279    Instruction *I = dyn_cast<Instruction>(OpLog2Of);
280    if (!I)
281      return;
282    if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
283      return;
284               
285    ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
286    if (CFP && CFP->isExactlyValue(0.5)) {
287      Y = I->getOperand(1);
288      return;
289    }
290    CFP = dyn_cast<ConstantFP>(I->getOperand(1));
291    if (CFP && CFP->isExactlyValue(0.5))
292      Y = I->getOperand(0);
293
294
295 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
296   bool Changed = SimplifyAssociativeOrCommutative(I);
297   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
298
299   // Simplify mul instructions with a constant RHS.
300   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
301     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
302       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
303       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
304       if (Op1F->isExactlyValue(1.0))
305         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'fmul double %X, 1.0'
306     } else if (ConstantDataVector *Op1V = dyn_cast<ConstantDataVector>(Op1C)) {
307       // As above, vector X*splat(1.0) -> X in all defined cases.
308       if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
309         if (F->isExactlyValue(1.0))
310           return ReplaceInstUsesWith(I, Op0);
311     }
312
313     // Try to fold constant mul into select arguments.
314     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
315       if (Instruction *R = FoldOpIntoSelect(I, SI))
316         return R;
317
318     if (isa<PHINode>(Op0))
319       if (Instruction *NV = FoldOpIntoPhi(I))
320         return NV;
321   }
322
323   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
324     if (Value *Op1v = dyn_castFNegVal(Op1))
325       return BinaryOperator::CreateFMul(Op0v, Op1v);
326
327   // Under unsafe algebra do:
328   // X * log2(0.5*Y) = X*log2(Y) - X
329   if (I.hasUnsafeAlgebra()) {
330     Value *OpX = NULL;
331     Value *OpY = NULL;
332     IntrinsicInst *Log2;
333     detectLog2OfHalf(Op0, OpY, Log2);
334     if (OpY) {
335       OpX = Op1;
336     } else {
337       detectLog2OfHalf(Op1, OpY, Log2);
338       if (OpY) {
339         OpX = Op0;
340       }
341     }
342     // if pattern detected emit alternate sequence
343     if (OpX && OpY) {
344       Log2->setArgOperand(0, OpY);
345       Value *FMulVal = Builder->CreateFMul(OpX, Log2);
346       Instruction *FMul = cast<Instruction>(FMulVal);
347       FMul->copyFastMathFlags(Log2);
348       Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
349       FSub->copyFastMathFlags(Log2);
350       return FSub;
351     }
352   }
353
354   return Changed ? &I : 0;
355 }
356
357 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
358 /// instruction.
359 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
360   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
361   
362   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
363   int NonNullOperand = -1;
364   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
365     if (ST->isNullValue())
366       NonNullOperand = 2;
367   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
368   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
369     if (ST->isNullValue())
370       NonNullOperand = 1;
371   
372   if (NonNullOperand == -1)
373     return false;
374   
375   Value *SelectCond = SI->getOperand(0);
376   
377   // Change the div/rem to use 'Y' instead of the select.
378   I.setOperand(1, SI->getOperand(NonNullOperand));
379   
380   // Okay, we know we replace the operand of the div/rem with 'Y' with no
381   // problem.  However, the select, or the condition of the select may have
382   // multiple uses.  Based on our knowledge that the operand must be non-zero,
383   // propagate the known value for the select into other uses of it, and
384   // propagate a known value of the condition into its other users.
385   
386   // If the select and condition only have a single use, don't bother with this,
387   // early exit.
388   if (SI->use_empty() && SelectCond->hasOneUse())
389     return true;
390   
391   // Scan the current block backward, looking for other uses of SI.
392   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
393   
394   while (BBI != BBFront) {
395     --BBI;
396     // If we found a call to a function, we can't assume it will return, so
397     // information from below it cannot be propagated above it.
398     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
399       break;
400     
401     // Replace uses of the select or its condition with the known values.
402     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
403          I != E; ++I) {
404       if (*I == SI) {
405         *I = SI->getOperand(NonNullOperand);
406         Worklist.Add(BBI);
407       } else if (*I == SelectCond) {
408         *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
409                                    ConstantInt::getFalse(BBI->getContext());
410         Worklist.Add(BBI);
411       }
412     }
413     
414     // If we past the instruction, quit looking for it.
415     if (&*BBI == SI)
416       SI = 0;
417     if (&*BBI == SelectCond)
418       SelectCond = 0;
419     
420     // If we ran out of things to eliminate, break out of the loop.
421     if (SelectCond == 0 && SI == 0)
422       break;
423     
424   }
425   return true;
426 }
427
428
429 /// This function implements the transforms common to both integer division
430 /// instructions (udiv and sdiv). It is called by the visitors to those integer
431 /// division instructions.
432 /// @brief Common integer divide transforms
433 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
434   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
435
436   // The RHS is known non-zero.
437   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
438     I.setOperand(1, V);
439     return &I;
440   }
441   
442   // Handle cases involving: [su]div X, (select Cond, Y, Z)
443   // This does not apply for fdiv.
444   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
445     return &I;
446
447   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
448     // (X / C1) / C2  -> X / (C1*C2)
449     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
450       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
451         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
452           if (MultiplyOverflows(RHS, LHSRHS,
453                                 I.getOpcode()==Instruction::SDiv))
454             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
455           return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
456                                         ConstantExpr::getMul(RHS, LHSRHS));
457         }
458
459     if (!RHS->isZero()) { // avoid X udiv 0
460       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
461         if (Instruction *R = FoldOpIntoSelect(I, SI))
462           return R;
463       if (isa<PHINode>(Op0))
464         if (Instruction *NV = FoldOpIntoPhi(I))
465           return NV;
466     }
467   }
468
469   // See if we can fold away this div instruction.
470   if (SimplifyDemandedInstructionBits(I))
471     return &I;
472
473   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
474   Value *X = 0, *Z = 0;
475   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
476     bool isSigned = I.getOpcode() == Instruction::SDiv;
477     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
478         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
479       return BinaryOperator::Create(I.getOpcode(), X, Op1);
480   }
481
482   return 0;
483 }
484
485 /// dyn_castZExtVal - Checks if V is a zext or constant that can
486 /// be truncated to Ty without losing bits.
487 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
488   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
489     if (Z->getSrcTy() == Ty)
490       return Z->getOperand(0);
491   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
492     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
493       return ConstantExpr::getTrunc(C, Ty);
494   }
495   return 0;
496 }
497
498 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
499   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
500
501   if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
502     return ReplaceInstUsesWith(I, V);
503
504   // Handle the integer div common cases
505   if (Instruction *Common = commonIDivTransforms(I))
506     return Common;
507   
508   { 
509     // X udiv 2^C -> X >> C
510     // Check to see if this is an unsigned division with an exact power of 2,
511     // if so, convert to a right shift.
512     const APInt *C;
513     if (match(Op1, m_Power2(C))) {
514       BinaryOperator *LShr =
515       BinaryOperator::CreateLShr(Op0, 
516                                  ConstantInt::get(Op0->getType(), 
517                                                   C->logBase2()));
518       if (I.isExact()) LShr->setIsExact();
519       return LShr;
520     }
521   }
522
523   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
524     // X udiv C, where C >= signbit
525     if (C->getValue().isNegative()) {
526       Value *IC = Builder->CreateICmpULT(Op0, C);
527       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
528                                 ConstantInt::get(I.getType(), 1));
529     }
530   }
531
532   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
533   if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
534     Value *X;
535     ConstantInt *C1;
536     if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
537       APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
538       return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
539     }
540   }
541
542   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
543   { const APInt *CI; Value *N;
544     if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
545         match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
546       if (*CI != 1)
547         N = Builder->CreateAdd(N,
548                                ConstantInt::get(N->getType(), CI->logBase2()));
549       if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
550         N = Builder->CreateZExt(N, Z->getDestTy());
551       if (I.isExact())
552         return BinaryOperator::CreateExactLShr(Op0, N);
553       return BinaryOperator::CreateLShr(Op0, N);
554     }
555   }
556   
557   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
558   // where C1&C2 are powers of two.
559   { Value *Cond; const APInt *C1, *C2;
560     if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
561       // Construct the "on true" case of the select
562       Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
563                                        I.isExact());
564   
565       // Construct the "on false" case of the select
566       Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
567                                        I.isExact());
568       
569       // construct the select instruction and return it.
570       return SelectInst::Create(Cond, TSI, FSI);
571     }
572   }
573
574   // (zext A) udiv (zext B) --> zext (A udiv B)
575   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
576     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
577       return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
578                                               I.isExact()),
579                           I.getType());
580
581   return 0;
582 }
583
584 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
585   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
586
587   if (Value *V = SimplifySDivInst(Op0, Op1, TD))
588     return ReplaceInstUsesWith(I, V);
589
590   // Handle the integer div common cases
591   if (Instruction *Common = commonIDivTransforms(I))
592     return Common;
593
594   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
595     // sdiv X, -1 == -X
596     if (RHS->isAllOnesValue())
597       return BinaryOperator::CreateNeg(Op0);
598
599     // sdiv X, C  -->  ashr exact X, log2(C)
600     if (I.isExact() && RHS->getValue().isNonNegative() &&
601         RHS->getValue().isPowerOf2()) {
602       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
603                                             RHS->getValue().exactLogBase2());
604       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
605     }
606
607     // -X/C  -->  X/-C  provided the negation doesn't overflow.
608     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
609       if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
610         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
611                                           ConstantExpr::getNeg(RHS));
612   }
613
614   // If the sign bits of both operands are zero (i.e. we can prove they are
615   // unsigned inputs), turn this into a udiv.
616   if (I.getType()->isIntegerTy()) {
617     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
618     if (MaskedValueIsZero(Op0, Mask)) {
619       if (MaskedValueIsZero(Op1, Mask)) {
620         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
621         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
622       }
623       
624       if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
625         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
626         // Safe because the only negative value (1 << Y) can take on is
627         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
628         // the sign bit set.
629         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
630       }
631     }
632   }
633   
634   return 0;
635 }
636
637 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
638   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
639
640   if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
641     return ReplaceInstUsesWith(I, V);
642
643   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
644     const APFloat &Op1F = Op1C->getValueAPF();
645
646     // If the divisor has an exact multiplicative inverse we can turn the fdiv
647     // into a cheaper fmul.
648     APFloat Reciprocal(Op1F.getSemantics());
649     if (Op1F.getExactInverse(&Reciprocal)) {
650       ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
651       return BinaryOperator::CreateFMul(Op0, RFP);
652     }
653   }
654
655   return 0;
656 }
657
658 /// This function implements the transforms common to both integer remainder
659 /// instructions (urem and srem). It is called by the visitors to those integer
660 /// remainder instructions.
661 /// @brief Common integer remainder transforms
662 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
663   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
664
665   // The RHS is known non-zero.
666   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
667     I.setOperand(1, V);
668     return &I;
669   }
670
671   // Handle cases involving: rem X, (select Cond, Y, Z)
672   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
673     return &I;
674
675   if (isa<ConstantInt>(Op1)) {
676     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
677       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
678         if (Instruction *R = FoldOpIntoSelect(I, SI))
679           return R;
680       } else if (isa<PHINode>(Op0I)) {
681         if (Instruction *NV = FoldOpIntoPhi(I))
682           return NV;
683       }
684
685       // See if we can fold away this rem instruction.
686       if (SimplifyDemandedInstructionBits(I))
687         return &I;
688     }
689   }
690
691   return 0;
692 }
693
694 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
695   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
696
697   if (Value *V = SimplifyURemInst(Op0, Op1, TD))
698     return ReplaceInstUsesWith(I, V);
699
700   if (Instruction *common = commonIRemTransforms(I))
701     return common;
702   
703   // X urem C^2 -> X and C-1
704   { const APInt *C;
705     if (match(Op1, m_Power2(C)))
706       return BinaryOperator::CreateAnd(Op0,
707                                        ConstantInt::get(I.getType(), *C-1));
708   }
709
710   // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
711   if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
712     Constant *N1 = Constant::getAllOnesValue(I.getType());
713     Value *Add = Builder->CreateAdd(Op1, N1);
714     return BinaryOperator::CreateAnd(Op0, Add);
715   }
716
717   // urem X, (select Cond, 2^C1, 2^C2) -->
718   //    select Cond, (and X, C1-1), (and X, C2-1)
719   // when C1&C2 are powers of two.
720   { Value *Cond; const APInt *C1, *C2;
721     if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
722       Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
723       Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
724       return SelectInst::Create(Cond, TrueAnd, FalseAnd);
725     }
726   }
727
728   // (zext A) urem (zext B) --> zext (A urem B)
729   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
730     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
731       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
732                           I.getType());
733
734   return 0;
735 }
736
737 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
738   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
739
740   if (Value *V = SimplifySRemInst(Op0, Op1, TD))
741     return ReplaceInstUsesWith(I, V);
742
743   // Handle the integer rem common cases
744   if (Instruction *Common = commonIRemTransforms(I))
745     return Common;
746   
747   if (Value *RHSNeg = dyn_castNegVal(Op1))
748     if (!isa<Constant>(RHSNeg) ||
749         (isa<ConstantInt>(RHSNeg) &&
750          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
751       // X % -Y -> X % Y
752       Worklist.AddValue(I.getOperand(1));
753       I.setOperand(1, RHSNeg);
754       return &I;
755     }
756
757   // If the sign bits of both operands are zero (i.e. we can prove they are
758   // unsigned inputs), turn this into a urem.
759   if (I.getType()->isIntegerTy()) {
760     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
761     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
762       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
763       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
764     }
765   }
766
767   // If it's a constant vector, flip any negative values positive.
768   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
769     Constant *C = cast<Constant>(Op1);
770     unsigned VWidth = C->getType()->getVectorNumElements();
771
772     bool hasNegative = false;
773     bool hasMissing = false;
774     for (unsigned i = 0; i != VWidth; ++i) {
775       Constant *Elt = C->getAggregateElement(i);
776       if (Elt == 0) {
777         hasMissing = true;
778         break;
779       }
780
781       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
782         if (RHS->isNegative())
783           hasNegative = true;
784     }
785
786     if (hasNegative && !hasMissing) {
787       SmallVector<Constant *, 16> Elts(VWidth);
788       for (unsigned i = 0; i != VWidth; ++i) {
789         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
790         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
791           if (RHS->isNegative())
792             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
793         }
794       }
795
796       Constant *NewRHSV = ConstantVector::get(Elts);
797       if (NewRHSV != C) {  // Don't loop on -MININT
798         Worklist.AddValue(I.getOperand(1));
799         I.setOperand(1, NewRHSV);
800         return &I;
801       }
802     }
803   }
804
805   return 0;
806 }
807
808 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
809   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
810
811   if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
812     return ReplaceInstUsesWith(I, V);
813
814   // Handle cases involving: rem X, (select Cond, Y, Z)
815   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
816     return &I;
817
818   return 0;
819 }