Fix a bug in InstCombine where it attempted to cast a Value* to an Instruction*
[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/IR/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       isKnownToBeAPowerOfTwo(PowerOf2)) {
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() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
49       // We know that this is an exact/nuw shift and that the input is a
50       // non-zero context as well.
51       if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
52         I->setOperand(0, V2);
53         MadeChange = true;
54       }
55
56       if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
57         I->setIsExact();
58         MadeChange = true;
59       }
60
61       if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
62         I->setHasNoUnsignedWrap();
63         MadeChange = true;
64       }
65     }
66
67   // TODO: Lots more we could do here:
68   //    If V is a phi node, we can call this on each of its operands.
69   //    "select cond, X, 0" can simplify to "X".
70
71   return MadeChange ? V : 0;
72 }
73
74
75 /// MultiplyOverflows - True if the multiply can not be expressed in an int
76 /// this size.
77 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
78   uint32_t W = C1->getBitWidth();
79   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
80   if (sign) {
81     LHSExt = LHSExt.sext(W * 2);
82     RHSExt = RHSExt.sext(W * 2);
83   } else {
84     LHSExt = LHSExt.zext(W * 2);
85     RHSExt = RHSExt.zext(W * 2);
86   }
87
88   APInt MulExt = LHSExt * RHSExt;
89
90   if (!sign)
91     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
92
93   APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
94   APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
95   return MulExt.slt(Min) || MulExt.sgt(Max);
96 }
97
98 /// \brief A helper routine of InstCombiner::visitMul().
99 ///
100 /// If C is a vector of known powers of 2, then this function returns
101 /// a new vector obtained from C replacing each element with its logBase2.
102 /// Return a null pointer otherwise.
103 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
104   const APInt *IVal;
105   SmallVector<Constant *, 4> Elts;
106
107   for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
108     Constant *Elt = CV->getElementAsConstant(I);
109     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
110       return 0;
111     Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
112   }
113
114   return ConstantVector::get(Elts);
115 }
116
117 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
118   bool Changed = SimplifyAssociativeOrCommutative(I);
119   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
120
121   if (Value *V = SimplifyMulInst(Op0, Op1, TD))
122     return ReplaceInstUsesWith(I, V);
123
124   if (Value *V = SimplifyUsingDistributiveLaws(I))
125     return ReplaceInstUsesWith(I, V);
126
127   if (match(Op1, m_AllOnes()))  // X * -1 == 0 - X
128     return BinaryOperator::CreateNeg(Op0, I.getName());
129
130   // Also allow combining multiply instructions on vectors.
131   {
132     Value *NewOp;
133     Constant *C1, *C2;
134     const APInt *IVal;
135     if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
136                         m_Constant(C1))) &&
137         match(C1, m_APInt(IVal)))
138       // ((X << C1)*C2) == (X * (C2 << C1))
139       return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
140
141     if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
142       Constant *NewCst = 0;
143       if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
144         // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
145         NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
146       else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
147         // Replace X*(2^C) with X << C, where C is a vector of known
148         // constant powers of 2.
149         NewCst = getLogBase2Vector(CV);
150
151       if (NewCst) {
152         BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
153         if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
154         if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
155         return Shl;
156       }
157     }
158   }
159
160   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
161     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
162     { Value *X; ConstantInt *C1;
163       if (Op0->hasOneUse() &&
164           match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
165         Value *Add = Builder->CreateMul(X, CI);
166         return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
167       }
168     }
169
170     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
171     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
172     // The "* (2**n)" thus becomes a potential shifting opportunity.
173     {
174       const APInt &   Val = CI->getValue();
175       const APInt &PosVal = Val.abs();
176       if (Val.isNegative() && PosVal.isPowerOf2()) {
177         Value *X = 0, *Y = 0;
178         if (Op0->hasOneUse()) {
179           ConstantInt *C1;
180           Value *Sub = 0;
181           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
182             Sub = Builder->CreateSub(X, Y, "suba");
183           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
184             Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
185           if (Sub)
186             return
187               BinaryOperator::CreateMul(Sub,
188                                         ConstantInt::get(Y->getType(), PosVal));
189         }
190       }
191     }
192   }
193
194   // Simplify mul instructions with a constant RHS.
195   if (isa<Constant>(Op1)) {
196     // Try to fold constant mul into select arguments.
197     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
198       if (Instruction *R = FoldOpIntoSelect(I, SI))
199         return R;
200
201     if (isa<PHINode>(Op0))
202       if (Instruction *NV = FoldOpIntoPhi(I))
203         return NV;
204   }
205
206   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
207     if (Value *Op1v = dyn_castNegVal(Op1))
208       return BinaryOperator::CreateMul(Op0v, Op1v);
209
210   // (X / Y) *  Y = X - (X % Y)
211   // (X / Y) * -Y = (X % Y) - X
212   {
213     Value *Op1C = Op1;
214     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
215     if (!BO ||
216         (BO->getOpcode() != Instruction::UDiv &&
217          BO->getOpcode() != Instruction::SDiv)) {
218       Op1C = Op0;
219       BO = dyn_cast<BinaryOperator>(Op1);
220     }
221     Value *Neg = dyn_castNegVal(Op1C);
222     if (BO && BO->hasOneUse() &&
223         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
224         (BO->getOpcode() == Instruction::UDiv ||
225          BO->getOpcode() == Instruction::SDiv)) {
226       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
227
228       // If the division is exact, X % Y is zero, so we end up with X or -X.
229       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
230         if (SDiv->isExact()) {
231           if (Op1BO == Op1C)
232             return ReplaceInstUsesWith(I, Op0BO);
233           return BinaryOperator::CreateNeg(Op0BO);
234         }
235
236       Value *Rem;
237       if (BO->getOpcode() == Instruction::UDiv)
238         Rem = Builder->CreateURem(Op0BO, Op1BO);
239       else
240         Rem = Builder->CreateSRem(Op0BO, Op1BO);
241       Rem->takeName(BO);
242
243       if (Op1BO == Op1C)
244         return BinaryOperator::CreateSub(Op0BO, Rem);
245       return BinaryOperator::CreateSub(Rem, Op0BO);
246     }
247   }
248
249   /// i1 mul -> i1 and.
250   if (I.getType()->isIntegerTy(1))
251     return BinaryOperator::CreateAnd(Op0, Op1);
252
253   // X*(1 << Y) --> X << Y
254   // (1 << Y)*X --> X << Y
255   {
256     Value *Y;
257     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
258       return BinaryOperator::CreateShl(Op1, Y);
259     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
260       return BinaryOperator::CreateShl(Op0, Y);
261   }
262
263   // If one of the operands of the multiply is a cast from a boolean value, then
264   // we know the bool is either zero or one, so this is a 'masking' multiply.
265   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
266   if (!I.getType()->isVectorTy()) {
267     // -2 is "-1 << 1" so it is all bits set except the low one.
268     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
269
270     Value *BoolCast = 0, *OtherOp = 0;
271     if (MaskedValueIsZero(Op0, Negative2))
272       BoolCast = Op0, OtherOp = Op1;
273     else if (MaskedValueIsZero(Op1, Negative2))
274       BoolCast = Op1, OtherOp = Op0;
275
276     if (BoolCast) {
277       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
278                                     BoolCast);
279       return BinaryOperator::CreateAnd(V, OtherOp);
280     }
281   }
282
283   return Changed ? &I : 0;
284 }
285
286 //
287 // Detect pattern:
288 //
289 // log2(Y*0.5)
290 //
291 // And check for corresponding fast math flags
292 //
293
294 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
295
296    if (!Op->hasOneUse())
297      return;
298
299    IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
300    if (!II)
301      return;
302    if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
303      return;
304    Log2 = II;
305
306    Value *OpLog2Of = II->getArgOperand(0);
307    if (!OpLog2Of->hasOneUse())
308      return;
309
310    Instruction *I = dyn_cast<Instruction>(OpLog2Of);
311    if (!I)
312      return;
313    if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
314      return;
315
316    ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
317    if (CFP && CFP->isExactlyValue(0.5)) {
318      Y = I->getOperand(1);
319      return;
320    }
321    CFP = dyn_cast<ConstantFP>(I->getOperand(1));
322    if (CFP && CFP->isExactlyValue(0.5))
323      Y = I->getOperand(0);
324 }
325
326 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
327 /// true iff the given value is FMul or FDiv with one and only one operand
328 /// being a normal constant (i.e. not Zero/NaN/Infinity).
329 static bool isFMulOrFDivWithConstant(Value *V) {
330   Instruction *I = dyn_cast<Instruction>(V);
331   if (!I || (I->getOpcode() != Instruction::FMul &&
332              I->getOpcode() != Instruction::FDiv))
333     return false;
334
335   ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
336   ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
337
338   if (C0 && C1)
339     return false;
340
341   return (C0 && C0->getValueAPF().isFiniteNonZero()) ||
342          (C1 && C1->getValueAPF().isFiniteNonZero());
343 }
344
345 static bool isNormalFp(const ConstantFP *C) {
346   const APFloat &Flt = C->getValueAPF();
347   return Flt.isNormal();
348 }
349
350 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
351 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
352 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
353 /// This function is to simplify "FMulOrDiv * C" and returns the
354 /// resulting expression. Note that this function could return NULL in
355 /// case the constants cannot be folded into a normal floating-point.
356 ///
357 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, ConstantFP *C,
358                                    Instruction *InsertBefore) {
359   assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
360
361   Value *Opnd0 = FMulOrDiv->getOperand(0);
362   Value *Opnd1 = FMulOrDiv->getOperand(1);
363
364   ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
365   ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
366
367   BinaryOperator *R = 0;
368
369   // (X * C0) * C => X * (C0*C)
370   if (FMulOrDiv->getOpcode() == Instruction::FMul) {
371     Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
372     if (isNormalFp(cast<ConstantFP>(F)))
373       R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
374   } else {
375     if (C0) {
376       // (C0 / X) * C => (C0 * C) / X
377       if (FMulOrDiv->hasOneUse()) {
378         // It would otherwise introduce another div.
379         ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C));
380         if (isNormalFp(F))
381           R = BinaryOperator::CreateFDiv(F, Opnd1);
382       }
383     } else {
384       // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
385       ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1));
386       if (isNormalFp(F)) {
387         R = BinaryOperator::CreateFMul(Opnd0, F);
388       } else {
389         // (X / C1) * C => X / (C1/C)
390         Constant *F = ConstantExpr::getFDiv(C1, C);
391         if (isNormalFp(cast<ConstantFP>(F)))
392           R = BinaryOperator::CreateFDiv(Opnd0, F);
393       }
394     }
395   }
396
397   if (R) {
398     R->setHasUnsafeAlgebra(true);
399     InsertNewInstWith(R, *InsertBefore);
400   }
401
402   return R;
403 }
404
405 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
406   bool Changed = SimplifyAssociativeOrCommutative(I);
407   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
408
409   if (isa<Constant>(Op0))
410     std::swap(Op0, Op1);
411
412   if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
413     return ReplaceInstUsesWith(I, V);
414
415   bool AllowReassociate = I.hasUnsafeAlgebra();
416
417   // Simplify mul instructions with a constant RHS.
418   if (isa<Constant>(Op1)) {
419     // Try to fold constant mul into select arguments.
420     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
421       if (Instruction *R = FoldOpIntoSelect(I, SI))
422         return R;
423
424     if (isa<PHINode>(Op0))
425       if (Instruction *NV = FoldOpIntoPhi(I))
426         return NV;
427
428     ConstantFP *C = dyn_cast<ConstantFP>(Op1);
429     if (C && AllowReassociate && C->getValueAPF().isFiniteNonZero()) {
430       // Let MDC denote an expression in one of these forms:
431       // X * C, C/X, X/C, where C is a constant.
432       //
433       // Try to simplify "MDC * Constant"
434       if (isFMulOrFDivWithConstant(Op0)) {
435         Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I);
436         if (V)
437           return ReplaceInstUsesWith(I, V);
438       }
439
440       // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
441       Instruction *FAddSub = dyn_cast<Instruction>(Op0);
442       if (FAddSub &&
443           (FAddSub->getOpcode() == Instruction::FAdd ||
444            FAddSub->getOpcode() == Instruction::FSub)) {
445         Value *Opnd0 = FAddSub->getOperand(0);
446         Value *Opnd1 = FAddSub->getOperand(1);
447         ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
448         ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
449         bool Swap = false;
450         if (C0) {
451           std::swap(C0, C1);
452           std::swap(Opnd0, Opnd1);
453           Swap = true;
454         }
455
456         if (C1 && C1->getValueAPF().isFiniteNonZero() &&
457             isFMulOrFDivWithConstant(Opnd0)) {
458           Value *M1 = ConstantExpr::getFMul(C1, C);
459           Value *M0 = isNormalFp(cast<ConstantFP>(M1)) ?
460                       foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
461                       0;
462           if (M0 && M1) {
463             if (Swap && FAddSub->getOpcode() == Instruction::FSub)
464               std::swap(M0, M1);
465
466             Value *R = (FAddSub->getOpcode() == Instruction::FAdd) ?
467                         BinaryOperator::CreateFAdd(M0, M1) :
468                         BinaryOperator::CreateFSub(M0, M1);
469             Instruction *RI = cast<Instruction>(R);
470             RI->copyFastMathFlags(&I);
471             return RI;
472           }
473         }
474       }
475     }
476   }
477
478
479   // Under unsafe algebra do:
480   // X * log2(0.5*Y) = X*log2(Y) - X
481   if (I.hasUnsafeAlgebra()) {
482     Value *OpX = NULL;
483     Value *OpY = NULL;
484     IntrinsicInst *Log2;
485     detectLog2OfHalf(Op0, OpY, Log2);
486     if (OpY) {
487       OpX = Op1;
488     } else {
489       detectLog2OfHalf(Op1, OpY, Log2);
490       if (OpY) {
491         OpX = Op0;
492       }
493     }
494     // if pattern detected emit alternate sequence
495     if (OpX && OpY) {
496       Log2->setArgOperand(0, OpY);
497       Value *FMulVal = Builder->CreateFMul(OpX, Log2);
498       Instruction *FMul = cast<Instruction>(FMulVal);
499       FMul->copyFastMathFlags(Log2);
500       Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
501       FSub->copyFastMathFlags(Log2);
502       return FSub;
503     }
504   }
505
506   // Handle symmetric situation in a 2-iteration loop
507   Value *Opnd0 = Op0;
508   Value *Opnd1 = Op1;
509   for (int i = 0; i < 2; i++) {
510     bool IgnoreZeroSign = I.hasNoSignedZeros();
511     if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
512       Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
513       Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
514
515       // -X * -Y => X*Y
516       if (N1)
517         return BinaryOperator::CreateFMul(N0, N1);
518
519       if (Opnd0->hasOneUse()) {
520         // -X * Y => -(X*Y) (Promote negation as high as possible)
521         Value *T = Builder->CreateFMul(N0, Opnd1);
522         Instruction *Neg = BinaryOperator::CreateFNeg(T);
523         if (I.getFastMathFlags().any()) {
524           if (Instruction *TI = dyn_cast<Instruction>(T))
525             TI->copyFastMathFlags(&I);
526           Neg->copyFastMathFlags(&I);
527         }
528         return Neg;
529       }
530     }
531
532     // (X*Y) * X => (X*X) * Y where Y != X
533     //  The purpose is two-fold:
534     //   1) to form a power expression (of X).
535     //   2) potentially shorten the critical path: After transformation, the
536     //  latency of the instruction Y is amortized by the expression of X*X,
537     //  and therefore Y is in a "less critical" position compared to what it
538     //  was before the transformation.
539     //
540     if (AllowReassociate) {
541       Value *Opnd0_0, *Opnd0_1;
542       if (Opnd0->hasOneUse() &&
543           match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
544         Value *Y = 0;
545         if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
546           Y = Opnd0_1;
547         else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
548           Y = Opnd0_0;
549
550         if (Y) {
551           Instruction *T = cast<Instruction>(Builder->CreateFMul(Opnd1, Opnd1));
552           T->copyFastMathFlags(&I);
553           T->setDebugLoc(I.getDebugLoc());
554
555           Instruction *R = BinaryOperator::CreateFMul(T, Y);
556           R->copyFastMathFlags(&I);
557           return R;
558         }
559       }
560     }
561
562     // B * (uitofp i1 C) -> select C, B, 0
563     if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
564       Value *LHS = Op0, *RHS = Op1;
565       Value *B, *C;
566       if (!match(RHS, m_UIToFP(m_Value(C))))
567         std::swap(LHS, RHS);
568
569       if (match(RHS, m_UIToFP(m_Value(C))) && C->getType()->isIntegerTy(1)) {
570         B = LHS;
571         Value *Zero = ConstantFP::getNegativeZero(B->getType());
572         return SelectInst::Create(C, B, Zero);
573       }
574     }
575
576     // A * (1 - uitofp i1 C) -> select C, 0, A
577     if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
578       Value *LHS = Op0, *RHS = Op1;
579       Value *A, *C;
580       if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
581         std::swap(LHS, RHS);
582
583       if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
584           C->getType()->isIntegerTy(1)) {
585         A = LHS;
586         Value *Zero = ConstantFP::getNegativeZero(A->getType());
587         return SelectInst::Create(C, Zero, A);
588       }
589     }
590
591     if (!isa<Constant>(Op1))
592       std::swap(Opnd0, Opnd1);
593     else
594       break;
595   }
596
597   return Changed ? &I : 0;
598 }
599
600 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
601 /// instruction.
602 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
603   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
604
605   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
606   int NonNullOperand = -1;
607   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
608     if (ST->isNullValue())
609       NonNullOperand = 2;
610   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
611   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
612     if (ST->isNullValue())
613       NonNullOperand = 1;
614
615   if (NonNullOperand == -1)
616     return false;
617
618   Value *SelectCond = SI->getOperand(0);
619
620   // Change the div/rem to use 'Y' instead of the select.
621   I.setOperand(1, SI->getOperand(NonNullOperand));
622
623   // Okay, we know we replace the operand of the div/rem with 'Y' with no
624   // problem.  However, the select, or the condition of the select may have
625   // multiple uses.  Based on our knowledge that the operand must be non-zero,
626   // propagate the known value for the select into other uses of it, and
627   // propagate a known value of the condition into its other users.
628
629   // If the select and condition only have a single use, don't bother with this,
630   // early exit.
631   if (SI->use_empty() && SelectCond->hasOneUse())
632     return true;
633
634   // Scan the current block backward, looking for other uses of SI.
635   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
636
637   while (BBI != BBFront) {
638     --BBI;
639     // If we found a call to a function, we can't assume it will return, so
640     // information from below it cannot be propagated above it.
641     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
642       break;
643
644     // Replace uses of the select or its condition with the known values.
645     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
646          I != E; ++I) {
647       if (*I == SI) {
648         *I = SI->getOperand(NonNullOperand);
649         Worklist.Add(BBI);
650       } else if (*I == SelectCond) {
651         *I = Builder->getInt1(NonNullOperand == 1);
652         Worklist.Add(BBI);
653       }
654     }
655
656     // If we past the instruction, quit looking for it.
657     if (&*BBI == SI)
658       SI = 0;
659     if (&*BBI == SelectCond)
660       SelectCond = 0;
661
662     // If we ran out of things to eliminate, break out of the loop.
663     if (SelectCond == 0 && SI == 0)
664       break;
665
666   }
667   return true;
668 }
669
670
671 /// This function implements the transforms common to both integer division
672 /// instructions (udiv and sdiv). It is called by the visitors to those integer
673 /// division instructions.
674 /// @brief Common integer divide transforms
675 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
676   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
677
678   // The RHS is known non-zero.
679   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
680     I.setOperand(1, V);
681     return &I;
682   }
683
684   // Handle cases involving: [su]div X, (select Cond, Y, Z)
685   // This does not apply for fdiv.
686   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
687     return &I;
688
689   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
690     // (X / C1) / C2  -> X / (C1*C2)
691     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
692       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
693         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
694           if (MultiplyOverflows(RHS, LHSRHS,
695                                 I.getOpcode()==Instruction::SDiv))
696             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
697           return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
698                                         ConstantExpr::getMul(RHS, LHSRHS));
699         }
700
701     if (!RHS->isZero()) { // avoid X udiv 0
702       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
703         if (Instruction *R = FoldOpIntoSelect(I, SI))
704           return R;
705       if (isa<PHINode>(Op0))
706         if (Instruction *NV = FoldOpIntoPhi(I))
707           return NV;
708     }
709   }
710
711   // See if we can fold away this div instruction.
712   if (SimplifyDemandedInstructionBits(I))
713     return &I;
714
715   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
716   Value *X = 0, *Z = 0;
717   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
718     bool isSigned = I.getOpcode() == Instruction::SDiv;
719     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
720         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
721       return BinaryOperator::Create(I.getOpcode(), X, Op1);
722   }
723
724   return 0;
725 }
726
727 /// dyn_castZExtVal - Checks if V is a zext or constant that can
728 /// be truncated to Ty without losing bits.
729 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
730   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
731     if (Z->getSrcTy() == Ty)
732       return Z->getOperand(0);
733   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
734     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
735       return ConstantExpr::getTrunc(C, Ty);
736   }
737   return 0;
738 }
739
740 namespace {
741 const unsigned MaxDepth = 6;
742 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
743                                           const BinaryOperator &I,
744                                           InstCombiner &IC);
745
746 /// \brief Used to maintain state for visitUDivOperand().
747 struct UDivFoldAction {
748   FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
749                                 ///< operand.  This can be zero if this action
750                                 ///< joins two actions together.
751
752   Value *OperandToFold;         ///< Which operand to fold.
753   union {
754     Instruction *FoldResult;    ///< The instruction returned when FoldAction is
755                                 ///< invoked.
756
757     size_t SelectLHSIdx;        ///< Stores the LHS action index if this action
758                                 ///< joins two actions together.
759   };
760
761   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
762       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {}
763   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
764       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
765 };
766 }
767
768 // X udiv 2^C -> X >> C
769 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
770                                     const BinaryOperator &I, InstCombiner &IC) {
771   const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
772   BinaryOperator *LShr = BinaryOperator::CreateLShr(
773       Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
774   if (I.isExact()) LShr->setIsExact();
775   return LShr;
776 }
777
778 // X udiv C, where C >= signbit
779 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
780                                    const BinaryOperator &I, InstCombiner &IC) {
781   Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
782
783   return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
784                             ConstantInt::get(I.getType(), 1));
785 }
786
787 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
788 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
789                                 InstCombiner &IC) {
790   Instruction *ShiftLeft = cast<Instruction>(Op1);
791   if (isa<ZExtInst>(ShiftLeft))
792     ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
793
794   const APInt &CI =
795       cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
796   Value *N = ShiftLeft->getOperand(1);
797   if (CI != 1)
798     N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
799   if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
800     N = IC.Builder->CreateZExt(N, Z->getDestTy());
801   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
802   if (I.isExact()) LShr->setIsExact();
803   return LShr;
804 }
805
806 // \brief Recursively visits the possible right hand operands of a udiv
807 // instruction, seeing through select instructions, to determine if we can
808 // replace the udiv with something simpler.  If we find that an operand is not
809 // able to simplify the udiv, we abort the entire transformation.
810 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
811                                SmallVectorImpl<UDivFoldAction> &Actions,
812                                unsigned Depth = 0) {
813   // Check to see if this is an unsigned division with an exact power of 2,
814   // if so, convert to a right shift.
815   if (match(Op1, m_Power2())) {
816     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
817     return Actions.size();
818   }
819
820   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
821     // X udiv C, where C >= signbit
822     if (C->getValue().isNegative()) {
823       Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
824       return Actions.size();
825     }
826
827   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
828   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
829       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
830     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
831     return Actions.size();
832   }
833
834   // The remaining tests are all recursive, so bail out if we hit the limit.
835   if (Depth++ == MaxDepth)
836     return 0;
837
838   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
839     if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
840       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
841         Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1));
842         return Actions.size();
843       }
844
845   return 0;
846 }
847
848 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
849   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
850
851   if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
852     return ReplaceInstUsesWith(I, V);
853
854   // Handle the integer div common cases
855   if (Instruction *Common = commonIDivTransforms(I))
856     return Common;
857
858   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
859   if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
860     Value *X;
861     ConstantInt *C1;
862     if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
863       APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
864       return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
865     }
866   }
867
868   // (zext A) udiv (zext B) --> zext (A udiv B)
869   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
870     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
871       return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
872                                               I.isExact()),
873                           I.getType());
874
875   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
876   SmallVector<UDivFoldAction, 6> UDivActions;
877   if (visitUDivOperand(Op0, Op1, I, UDivActions))
878     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
879       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
880       Value *ActionOp1 = UDivActions[i].OperandToFold;
881       Instruction *Inst;
882       if (Action)
883         Inst = Action(Op0, ActionOp1, I, *this);
884       else {
885         // This action joins two actions together.  The RHS of this action is
886         // simply the last action we processed, we saved the LHS action index in
887         // the joining action.
888         size_t SelectRHSIdx = i - 1;
889         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
890         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
891         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
892         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
893                                   SelectLHS, SelectRHS);
894       }
895
896       // If this is the last action to process, return it to the InstCombiner.
897       // Otherwise, we insert it before the UDiv and record it so that we may
898       // use it as part of a joining action (i.e., a SelectInst).
899       if (e - i != 1) {
900         Inst->insertBefore(&I);
901         UDivActions[i].FoldResult = Inst;
902       } else
903         return Inst;
904     }
905
906   return 0;
907 }
908
909 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
910   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
911
912   if (Value *V = SimplifySDivInst(Op0, Op1, TD))
913     return ReplaceInstUsesWith(I, V);
914
915   // Handle the integer div common cases
916   if (Instruction *Common = commonIDivTransforms(I))
917     return Common;
918
919   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
920     // sdiv X, -1 == -X
921     if (RHS->isAllOnesValue())
922       return BinaryOperator::CreateNeg(Op0);
923
924     // sdiv X, C  -->  ashr exact X, log2(C)
925     if (I.isExact() && RHS->getValue().isNonNegative() &&
926         RHS->getValue().isPowerOf2()) {
927       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
928                                             RHS->getValue().exactLogBase2());
929       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
930     }
931
932     // -X/C  -->  X/-C  provided the negation doesn't overflow.
933     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
934       if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
935         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
936                                           ConstantExpr::getNeg(RHS));
937   }
938
939   // If the sign bits of both operands are zero (i.e. we can prove they are
940   // unsigned inputs), turn this into a udiv.
941   if (I.getType()->isIntegerTy()) {
942     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
943     if (MaskedValueIsZero(Op0, Mask)) {
944       if (MaskedValueIsZero(Op1, Mask)) {
945         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
946         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
947       }
948
949       if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
950         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
951         // Safe because the only negative value (1 << Y) can take on is
952         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
953         // the sign bit set.
954         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
955       }
956     }
957   }
958
959   return 0;
960 }
961
962 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
963 /// FP value and:
964 ///    1) 1/C is exact, or
965 ///    2) reciprocal is allowed.
966 /// If the conversion was successful, the simplified expression "X * 1/C" is
967 /// returned; otherwise, NULL is returned.
968 ///
969 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
970                                              ConstantFP *Divisor,
971                                              bool AllowReciprocal) {
972   const APFloat &FpVal = Divisor->getValueAPF();
973   APFloat Reciprocal(FpVal.getSemantics());
974   bool Cvt = FpVal.getExactInverse(&Reciprocal);
975
976   if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
977     Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
978     (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
979     Cvt = !Reciprocal.isDenormal();
980   }
981
982   if (!Cvt)
983     return 0;
984
985   ConstantFP *R;
986   R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
987   return BinaryOperator::CreateFMul(Dividend, R);
988 }
989
990 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
991   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
992
993   if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
994     return ReplaceInstUsesWith(I, V);
995
996   if (isa<Constant>(Op0))
997     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
998       if (Instruction *R = FoldOpIntoSelect(I, SI))
999         return R;
1000
1001   bool AllowReassociate = I.hasUnsafeAlgebra();
1002   bool AllowReciprocal = I.hasAllowReciprocal();
1003
1004   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1005     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1006       if (Instruction *R = FoldOpIntoSelect(I, SI))
1007         return R;
1008
1009     if (AllowReassociate) {
1010       ConstantFP *C1 = 0;
1011       ConstantFP *C2 = Op1C;
1012       Value *X;
1013       Instruction *Res = 0;
1014
1015       if (match(Op0, m_FMul(m_Value(X), m_ConstantFP(C1)))) {
1016         // (X*C1)/C2 => X * (C1/C2)
1017         //
1018         Constant *C = ConstantExpr::getFDiv(C1, C2);
1019         const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
1020         if (F.isNormal())
1021           Res = BinaryOperator::CreateFMul(X, C);
1022       } else if (match(Op0, m_FDiv(m_Value(X), m_ConstantFP(C1)))) {
1023         // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1024         //
1025         Constant *C = ConstantExpr::getFMul(C1, C2);
1026         const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
1027         if (F.isNormal()) {
1028           Res = CvtFDivConstToReciprocal(X, cast<ConstantFP>(C),
1029                                          AllowReciprocal);
1030           if (!Res)
1031             Res = BinaryOperator::CreateFDiv(X, C);
1032         }
1033       }
1034
1035       if (Res) {
1036         Res->setFastMathFlags(I.getFastMathFlags());
1037         return Res;
1038       }
1039     }
1040
1041     // X / C => X * 1/C
1042     if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal))
1043       return T;
1044
1045     return 0;
1046   }
1047
1048   if (AllowReassociate && isa<ConstantFP>(Op0)) {
1049     ConstantFP *C1 = cast<ConstantFP>(Op0), *C2;
1050     Constant *Fold = 0;
1051     Value *X;
1052     bool CreateDiv = true;
1053
1054     // C1 / (X*C2) => (C1/C2) / X
1055     if (match(Op1, m_FMul(m_Value(X), m_ConstantFP(C2))))
1056       Fold = ConstantExpr::getFDiv(C1, C2);
1057     else if (match(Op1, m_FDiv(m_Value(X), m_ConstantFP(C2)))) {
1058       // C1 / (X/C2) => (C1*C2) / X
1059       Fold = ConstantExpr::getFMul(C1, C2);
1060     } else if (match(Op1, m_FDiv(m_ConstantFP(C2), m_Value(X)))) {
1061       // C1 / (C2/X) => (C1/C2) * X
1062       Fold = ConstantExpr::getFDiv(C1, C2);
1063       CreateDiv = false;
1064     }
1065
1066     if (Fold) {
1067       const APFloat &FoldC = cast<ConstantFP>(Fold)->getValueAPF();
1068       if (FoldC.isNormal()) {
1069         Instruction *R = CreateDiv ?
1070                          BinaryOperator::CreateFDiv(Fold, X) :
1071                          BinaryOperator::CreateFMul(X, Fold);
1072         R->setFastMathFlags(I.getFastMathFlags());
1073         return R;
1074       }
1075     }
1076     return 0;
1077   }
1078
1079   if (AllowReassociate) {
1080     Value *X, *Y;
1081     Value *NewInst = 0;
1082     Instruction *SimpR = 0;
1083
1084     if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1085       // (X/Y) / Z => X / (Y*Z)
1086       //
1087       if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op1)) {
1088         NewInst = Builder->CreateFMul(Y, Op1);
1089         SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1090       }
1091     } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1092       // Z / (X/Y) => Z*Y / X
1093       //
1094       if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op0)) {
1095         NewInst = Builder->CreateFMul(Op0, Y);
1096         SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1097       }
1098     }
1099
1100     if (NewInst) {
1101       if (Instruction *T = dyn_cast<Instruction>(NewInst))
1102         T->setDebugLoc(I.getDebugLoc());
1103       SimpR->setFastMathFlags(I.getFastMathFlags());
1104       return SimpR;
1105     }
1106   }
1107
1108   return 0;
1109 }
1110
1111 /// This function implements the transforms common to both integer remainder
1112 /// instructions (urem and srem). It is called by the visitors to those integer
1113 /// remainder instructions.
1114 /// @brief Common integer remainder transforms
1115 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1117
1118   // The RHS is known non-zero.
1119   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1120     I.setOperand(1, V);
1121     return &I;
1122   }
1123
1124   // Handle cases involving: rem X, (select Cond, Y, Z)
1125   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1126     return &I;
1127
1128   if (isa<ConstantInt>(Op1)) {
1129     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1130       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1131         if (Instruction *R = FoldOpIntoSelect(I, SI))
1132           return R;
1133       } else if (isa<PHINode>(Op0I)) {
1134         if (Instruction *NV = FoldOpIntoPhi(I))
1135           return NV;
1136       }
1137
1138       // See if we can fold away this rem instruction.
1139       if (SimplifyDemandedInstructionBits(I))
1140         return &I;
1141     }
1142   }
1143
1144   return 0;
1145 }
1146
1147 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1148   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1149
1150   if (Value *V = SimplifyURemInst(Op0, Op1, TD))
1151     return ReplaceInstUsesWith(I, V);
1152
1153   if (Instruction *common = commonIRemTransforms(I))
1154     return common;
1155
1156   // (zext A) urem (zext B) --> zext (A urem B)
1157   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1158     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1159       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1160                           I.getType());
1161
1162   // X urem Y -> X and Y-1, where Y is a power of 2,
1163   if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1164     Constant *N1 = Constant::getAllOnesValue(I.getType());
1165     Value *Add = Builder->CreateAdd(Op1, N1);
1166     return BinaryOperator::CreateAnd(Op0, Add);
1167   }
1168
1169   // 1 urem X -> zext(X != 1)
1170   if (match(Op0, m_One())) {
1171     Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1172     Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1173     return ReplaceInstUsesWith(I, Ext);
1174   }
1175
1176   return 0;
1177 }
1178
1179 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1180   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1181
1182   if (Value *V = SimplifySRemInst(Op0, Op1, TD))
1183     return ReplaceInstUsesWith(I, V);
1184
1185   // Handle the integer rem common cases
1186   if (Instruction *Common = commonIRemTransforms(I))
1187     return Common;
1188
1189   if (Value *RHSNeg = dyn_castNegVal(Op1))
1190     if (!isa<Constant>(RHSNeg) ||
1191         (isa<ConstantInt>(RHSNeg) &&
1192          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1193       // X % -Y -> X % Y
1194       Worklist.AddValue(I.getOperand(1));
1195       I.setOperand(1, RHSNeg);
1196       return &I;
1197     }
1198
1199   // If the sign bits of both operands are zero (i.e. we can prove they are
1200   // unsigned inputs), turn this into a urem.
1201   if (I.getType()->isIntegerTy()) {
1202     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1203     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1204       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1205       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1206     }
1207   }
1208
1209   // If it's a constant vector, flip any negative values positive.
1210   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1211     Constant *C = cast<Constant>(Op1);
1212     unsigned VWidth = C->getType()->getVectorNumElements();
1213
1214     bool hasNegative = false;
1215     bool hasMissing = false;
1216     for (unsigned i = 0; i != VWidth; ++i) {
1217       Constant *Elt = C->getAggregateElement(i);
1218       if (Elt == 0) {
1219         hasMissing = true;
1220         break;
1221       }
1222
1223       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1224         if (RHS->isNegative())
1225           hasNegative = true;
1226     }
1227
1228     if (hasNegative && !hasMissing) {
1229       SmallVector<Constant *, 16> Elts(VWidth);
1230       for (unsigned i = 0; i != VWidth; ++i) {
1231         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
1232         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1233           if (RHS->isNegative())
1234             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1235         }
1236       }
1237
1238       Constant *NewRHSV = ConstantVector::get(Elts);
1239       if (NewRHSV != C) {  // Don't loop on -MININT
1240         Worklist.AddValue(I.getOperand(1));
1241         I.setOperand(1, NewRHSV);
1242         return &I;
1243       }
1244     }
1245   }
1246
1247   return 0;
1248 }
1249
1250 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1251   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1252
1253   if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
1254     return ReplaceInstUsesWith(I, V);
1255
1256   // Handle cases involving: rem X, (select Cond, Y, Z)
1257   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1258     return &I;
1259
1260   return 0;
1261 }