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