Add an Assumption-Tracking Pass
[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     if (!isa<Constant>(Op1))
615       std::swap(Opnd0, Opnd1);
616     else
617       break;
618   }
619
620   return Changed ? &I : nullptr;
621 }
622
623 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
624 /// instruction.
625 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
626   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
627
628   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
629   int NonNullOperand = -1;
630   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
631     if (ST->isNullValue())
632       NonNullOperand = 2;
633   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
634   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
635     if (ST->isNullValue())
636       NonNullOperand = 1;
637
638   if (NonNullOperand == -1)
639     return false;
640
641   Value *SelectCond = SI->getOperand(0);
642
643   // Change the div/rem to use 'Y' instead of the select.
644   I.setOperand(1, SI->getOperand(NonNullOperand));
645
646   // Okay, we know we replace the operand of the div/rem with 'Y' with no
647   // problem.  However, the select, or the condition of the select may have
648   // multiple uses.  Based on our knowledge that the operand must be non-zero,
649   // propagate the known value for the select into other uses of it, and
650   // propagate a known value of the condition into its other users.
651
652   // If the select and condition only have a single use, don't bother with this,
653   // early exit.
654   if (SI->use_empty() && SelectCond->hasOneUse())
655     return true;
656
657   // Scan the current block backward, looking for other uses of SI.
658   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
659
660   while (BBI != BBFront) {
661     --BBI;
662     // If we found a call to a function, we can't assume it will return, so
663     // information from below it cannot be propagated above it.
664     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
665       break;
666
667     // Replace uses of the select or its condition with the known values.
668     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
669          I != E; ++I) {
670       if (*I == SI) {
671         *I = SI->getOperand(NonNullOperand);
672         Worklist.Add(BBI);
673       } else if (*I == SelectCond) {
674         *I = Builder->getInt1(NonNullOperand == 1);
675         Worklist.Add(BBI);
676       }
677     }
678
679     // If we past the instruction, quit looking for it.
680     if (&*BBI == SI)
681       SI = nullptr;
682     if (&*BBI == SelectCond)
683       SelectCond = nullptr;
684
685     // If we ran out of things to eliminate, break out of the loop.
686     if (!SelectCond && !SI)
687       break;
688
689   }
690   return true;
691 }
692
693
694 /// This function implements the transforms common to both integer division
695 /// instructions (udiv and sdiv). It is called by the visitors to those integer
696 /// division instructions.
697 /// @brief Common integer divide transforms
698 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
699   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
700
701   // The RHS is known non-zero.
702   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
703     I.setOperand(1, V);
704     return &I;
705   }
706
707   // Handle cases involving: [su]div X, (select Cond, Y, Z)
708   // This does not apply for fdiv.
709   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
710     return &I;
711
712   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
713     if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
714       // (X / C1) / C2  -> X / (C1*C2)
715       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
716         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
717           if (MultiplyOverflows(RHS, LHSRHS,
718                                 I.getOpcode() == Instruction::SDiv))
719             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
720           return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
721                                         ConstantExpr::getMul(RHS, LHSRHS));
722         }
723
724       Value *X;
725       const APInt *C1, *C2;
726       if (match(RHS, m_APInt(C2))) {
727         bool IsSigned = I.getOpcode() == Instruction::SDiv;
728         if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
729             (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
730           APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
731
732           // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
733           if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
734             BinaryOperator *BO = BinaryOperator::Create(
735                 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
736             BO->setIsExact(I.isExact());
737             return BO;
738           }
739
740           // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
741           if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
742             BinaryOperator *BO = BinaryOperator::Create(
743                 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
744             BO->setHasNoUnsignedWrap(
745                 !IsSigned &&
746                 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
747             BO->setHasNoSignedWrap(
748                 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
749             return BO;
750           }
751         }
752
753         if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1)))) ||
754             (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
755           APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
756           APInt C1Shifted = APInt::getOneBitSet(
757               C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
758
759           // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
760           if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
761             BinaryOperator *BO = BinaryOperator::Create(
762                 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
763             BO->setIsExact(I.isExact());
764             return BO;
765           }
766
767           // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
768           if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
769             BinaryOperator *BO = BinaryOperator::Create(
770                 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
771             BO->setHasNoUnsignedWrap(
772                 !IsSigned &&
773                 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
774             BO->setHasNoSignedWrap(
775                 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
776             return BO;
777           }
778         }
779       }
780     }
781
782     if (!RHS->isZero()) { // avoid X udiv 0
783       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
784         if (Instruction *R = FoldOpIntoSelect(I, SI))
785           return R;
786       if (isa<PHINode>(Op0))
787         if (Instruction *NV = FoldOpIntoPhi(I))
788           return NV;
789     }
790   }
791
792   if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
793     if (One->isOne() && !I.getType()->isIntegerTy(1)) {
794       bool isSigned = I.getOpcode() == Instruction::SDiv;
795       if (isSigned) {
796         // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
797         // result is one, if Op1 is -1 then the result is minus one, otherwise
798         // it's zero.
799         Value *Inc = Builder->CreateAdd(Op1, One);
800         Value *Cmp = Builder->CreateICmpULT(
801                          Inc, ConstantInt::get(I.getType(), 3));
802         return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
803       } else {
804         // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
805         // result is one, otherwise it's zero.
806         return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
807       }
808     }
809   }
810
811   // See if we can fold away this div instruction.
812   if (SimplifyDemandedInstructionBits(I))
813     return &I;
814
815   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
816   Value *X = nullptr, *Z = nullptr;
817   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
818     bool isSigned = I.getOpcode() == Instruction::SDiv;
819     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
820         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
821       return BinaryOperator::Create(I.getOpcode(), X, Op1);
822   }
823
824   return nullptr;
825 }
826
827 /// dyn_castZExtVal - Checks if V is a zext or constant that can
828 /// be truncated to Ty without losing bits.
829 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
830   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
831     if (Z->getSrcTy() == Ty)
832       return Z->getOperand(0);
833   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
834     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
835       return ConstantExpr::getTrunc(C, Ty);
836   }
837   return nullptr;
838 }
839
840 namespace {
841 const unsigned MaxDepth = 6;
842 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
843                                           const BinaryOperator &I,
844                                           InstCombiner &IC);
845
846 /// \brief Used to maintain state for visitUDivOperand().
847 struct UDivFoldAction {
848   FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
849                                 ///< operand.  This can be zero if this action
850                                 ///< joins two actions together.
851
852   Value *OperandToFold;         ///< Which operand to fold.
853   union {
854     Instruction *FoldResult;    ///< The instruction returned when FoldAction is
855                                 ///< invoked.
856
857     size_t SelectLHSIdx;        ///< Stores the LHS action index if this action
858                                 ///< joins two actions together.
859   };
860
861   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
862       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
863   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
864       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
865 };
866 }
867
868 // X udiv 2^C -> X >> C
869 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
870                                     const BinaryOperator &I, InstCombiner &IC) {
871   const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
872   BinaryOperator *LShr = BinaryOperator::CreateLShr(
873       Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
874   if (I.isExact()) LShr->setIsExact();
875   return LShr;
876 }
877
878 // X udiv C, where C >= signbit
879 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
880                                    const BinaryOperator &I, InstCombiner &IC) {
881   Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
882
883   return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
884                             ConstantInt::get(I.getType(), 1));
885 }
886
887 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
888 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
889                                 InstCombiner &IC) {
890   Instruction *ShiftLeft = cast<Instruction>(Op1);
891   if (isa<ZExtInst>(ShiftLeft))
892     ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
893
894   const APInt &CI =
895       cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
896   Value *N = ShiftLeft->getOperand(1);
897   if (CI != 1)
898     N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
899   if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
900     N = IC.Builder->CreateZExt(N, Z->getDestTy());
901   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
902   if (I.isExact()) LShr->setIsExact();
903   return LShr;
904 }
905
906 // \brief Recursively visits the possible right hand operands of a udiv
907 // instruction, seeing through select instructions, to determine if we can
908 // replace the udiv with something simpler.  If we find that an operand is not
909 // able to simplify the udiv, we abort the entire transformation.
910 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
911                                SmallVectorImpl<UDivFoldAction> &Actions,
912                                unsigned Depth = 0) {
913   // Check to see if this is an unsigned division with an exact power of 2,
914   // if so, convert to a right shift.
915   if (match(Op1, m_Power2())) {
916     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
917     return Actions.size();
918   }
919
920   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
921     // X udiv C, where C >= signbit
922     if (C->getValue().isNegative()) {
923       Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
924       return Actions.size();
925     }
926
927   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
928   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
929       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
930     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
931     return Actions.size();
932   }
933
934   // The remaining tests are all recursive, so bail out if we hit the limit.
935   if (Depth++ == MaxDepth)
936     return 0;
937
938   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
939     if (size_t LHSIdx =
940             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
941       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
942         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
943         return Actions.size();
944       }
945
946   return 0;
947 }
948
949 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
951
952   if (Value *V = SimplifyVectorOp(I))
953     return ReplaceInstUsesWith(I, V);
954
955   if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
956     return ReplaceInstUsesWith(I, V);
957
958   // Handle the integer div common cases
959   if (Instruction *Common = commonIDivTransforms(I))
960     return Common;
961
962   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
963   if (Constant *C2 = dyn_cast<Constant>(Op1)) {
964     Value *X;
965     Constant *C1;
966     if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
967       return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
968   }
969
970   // (zext A) udiv (zext B) --> zext (A udiv B)
971   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
972     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
973       return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
974                                               I.isExact()),
975                           I.getType());
976
977   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
978   SmallVector<UDivFoldAction, 6> UDivActions;
979   if (visitUDivOperand(Op0, Op1, I, UDivActions))
980     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
981       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
982       Value *ActionOp1 = UDivActions[i].OperandToFold;
983       Instruction *Inst;
984       if (Action)
985         Inst = Action(Op0, ActionOp1, I, *this);
986       else {
987         // This action joins two actions together.  The RHS of this action is
988         // simply the last action we processed, we saved the LHS action index in
989         // the joining action.
990         size_t SelectRHSIdx = i - 1;
991         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
992         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
993         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
994         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
995                                   SelectLHS, SelectRHS);
996       }
997
998       // If this is the last action to process, return it to the InstCombiner.
999       // Otherwise, we insert it before the UDiv and record it so that we may
1000       // use it as part of a joining action (i.e., a SelectInst).
1001       if (e - i != 1) {
1002         Inst->insertBefore(&I);
1003         UDivActions[i].FoldResult = Inst;
1004       } else
1005         return Inst;
1006     }
1007
1008   return nullptr;
1009 }
1010
1011 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1012   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1013
1014   if (Value *V = SimplifyVectorOp(I))
1015     return ReplaceInstUsesWith(I, V);
1016
1017   if (Value *V = SimplifySDivInst(Op0, Op1, DL))
1018     return ReplaceInstUsesWith(I, V);
1019
1020   // Handle the integer div common cases
1021   if (Instruction *Common = commonIDivTransforms(I))
1022     return Common;
1023
1024   // sdiv X, -1 == -X
1025   if (match(Op1, m_AllOnes()))
1026     return BinaryOperator::CreateNeg(Op0);
1027
1028   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1029     // sdiv X, C  -->  ashr exact X, log2(C)
1030     if (I.isExact() && RHS->getValue().isNonNegative() &&
1031         RHS->getValue().isPowerOf2()) {
1032       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1033                                             RHS->getValue().exactLogBase2());
1034       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1035     }
1036   }
1037
1038   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1039     // X/INT_MIN -> X == INT_MIN
1040     if (RHS->isMinSignedValue())
1041       return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1042
1043     // -X/C  -->  X/-C  provided the negation doesn't overflow.
1044     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1045       if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1046         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1047                                           ConstantExpr::getNeg(RHS));
1048   }
1049
1050   // If the sign bits of both operands are zero (i.e. we can prove they are
1051   // unsigned inputs), turn this into a udiv.
1052   if (I.getType()->isIntegerTy()) {
1053     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1054     if (MaskedValueIsZero(Op0, Mask)) {
1055       if (MaskedValueIsZero(Op1, Mask)) {
1056         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1057         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1058       }
1059
1060       if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1061         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1062         // Safe because the only negative value (1 << Y) can take on is
1063         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1064         // the sign bit set.
1065         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1066       }
1067     }
1068   }
1069
1070   return nullptr;
1071 }
1072
1073 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1074 /// FP value and:
1075 ///    1) 1/C is exact, or
1076 ///    2) reciprocal is allowed.
1077 /// If the conversion was successful, the simplified expression "X * 1/C" is
1078 /// returned; otherwise, NULL is returned.
1079 ///
1080 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
1081                                              Constant *Divisor,
1082                                              bool AllowReciprocal) {
1083   if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1084     return nullptr;
1085
1086   const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1087   APFloat Reciprocal(FpVal.getSemantics());
1088   bool Cvt = FpVal.getExactInverse(&Reciprocal);
1089
1090   if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1091     Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1092     (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1093     Cvt = !Reciprocal.isDenormal();
1094   }
1095
1096   if (!Cvt)
1097     return nullptr;
1098
1099   ConstantFP *R;
1100   R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1101   return BinaryOperator::CreateFMul(Dividend, R);
1102 }
1103
1104 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1105   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1106
1107   if (Value *V = SimplifyVectorOp(I))
1108     return ReplaceInstUsesWith(I, V);
1109
1110   if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
1111     return ReplaceInstUsesWith(I, V);
1112
1113   if (isa<Constant>(Op0))
1114     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1115       if (Instruction *R = FoldOpIntoSelect(I, SI))
1116         return R;
1117
1118   bool AllowReassociate = I.hasUnsafeAlgebra();
1119   bool AllowReciprocal = I.hasAllowReciprocal();
1120
1121   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1122     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1123       if (Instruction *R = FoldOpIntoSelect(I, SI))
1124         return R;
1125
1126     if (AllowReassociate) {
1127       Constant *C1 = nullptr;
1128       Constant *C2 = Op1C;
1129       Value *X;
1130       Instruction *Res = nullptr;
1131
1132       if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1133         // (X*C1)/C2 => X * (C1/C2)
1134         //
1135         Constant *C = ConstantExpr::getFDiv(C1, C2);
1136         if (isNormalFp(C))
1137           Res = BinaryOperator::CreateFMul(X, C);
1138       } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1139         // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1140         //
1141         Constant *C = ConstantExpr::getFMul(C1, C2);
1142         if (isNormalFp(C)) {
1143           Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1144           if (!Res)
1145             Res = BinaryOperator::CreateFDiv(X, C);
1146         }
1147       }
1148
1149       if (Res) {
1150         Res->setFastMathFlags(I.getFastMathFlags());
1151         return Res;
1152       }
1153     }
1154
1155     // X / C => X * 1/C
1156     if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1157       T->copyFastMathFlags(&I);
1158       return T;
1159     }
1160
1161     return nullptr;
1162   }
1163
1164   if (AllowReassociate && isa<Constant>(Op0)) {
1165     Constant *C1 = cast<Constant>(Op0), *C2;
1166     Constant *Fold = nullptr;
1167     Value *X;
1168     bool CreateDiv = true;
1169
1170     // C1 / (X*C2) => (C1/C2) / X
1171     if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1172       Fold = ConstantExpr::getFDiv(C1, C2);
1173     else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1174       // C1 / (X/C2) => (C1*C2) / X
1175       Fold = ConstantExpr::getFMul(C1, C2);
1176     } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1177       // C1 / (C2/X) => (C1/C2) * X
1178       Fold = ConstantExpr::getFDiv(C1, C2);
1179       CreateDiv = false;
1180     }
1181
1182     if (Fold && isNormalFp(Fold)) {
1183       Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1184                                  : BinaryOperator::CreateFMul(X, Fold);
1185       R->setFastMathFlags(I.getFastMathFlags());
1186       return R;
1187     }
1188     return nullptr;
1189   }
1190
1191   if (AllowReassociate) {
1192     Value *X, *Y;
1193     Value *NewInst = nullptr;
1194     Instruction *SimpR = nullptr;
1195
1196     if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1197       // (X/Y) / Z => X / (Y*Z)
1198       //
1199       if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1200         NewInst = Builder->CreateFMul(Y, Op1);
1201         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1202           FastMathFlags Flags = I.getFastMathFlags();
1203           Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1204           RI->setFastMathFlags(Flags);
1205         }
1206         SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1207       }
1208     } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1209       // Z / (X/Y) => Z*Y / X
1210       //
1211       if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1212         NewInst = Builder->CreateFMul(Op0, Y);
1213         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1214           FastMathFlags Flags = I.getFastMathFlags();
1215           Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1216           RI->setFastMathFlags(Flags);
1217         }
1218         SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1219       }
1220     }
1221
1222     if (NewInst) {
1223       if (Instruction *T = dyn_cast<Instruction>(NewInst))
1224         T->setDebugLoc(I.getDebugLoc());
1225       SimpR->setFastMathFlags(I.getFastMathFlags());
1226       return SimpR;
1227     }
1228   }
1229
1230   return nullptr;
1231 }
1232
1233 /// This function implements the transforms common to both integer remainder
1234 /// instructions (urem and srem). It is called by the visitors to those integer
1235 /// remainder instructions.
1236 /// @brief Common integer remainder transforms
1237 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1238   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1239
1240   // The RHS is known non-zero.
1241   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1242     I.setOperand(1, V);
1243     return &I;
1244   }
1245
1246   // Handle cases involving: rem X, (select Cond, Y, Z)
1247   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1248     return &I;
1249
1250   if (isa<Constant>(Op1)) {
1251     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1252       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1253         if (Instruction *R = FoldOpIntoSelect(I, SI))
1254           return R;
1255       } else if (isa<PHINode>(Op0I)) {
1256         if (Instruction *NV = FoldOpIntoPhi(I))
1257           return NV;
1258       }
1259
1260       // See if we can fold away this rem instruction.
1261       if (SimplifyDemandedInstructionBits(I))
1262         return &I;
1263     }
1264   }
1265
1266   return nullptr;
1267 }
1268
1269 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1270   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1271
1272   if (Value *V = SimplifyVectorOp(I))
1273     return ReplaceInstUsesWith(I, V);
1274
1275   if (Value *V = SimplifyURemInst(Op0, Op1, DL))
1276     return ReplaceInstUsesWith(I, V);
1277
1278   if (Instruction *common = commonIRemTransforms(I))
1279     return common;
1280
1281   // (zext A) urem (zext B) --> zext (A urem B)
1282   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1283     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1284       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1285                           I.getType());
1286
1287   // X urem Y -> X and Y-1, where Y is a power of 2,
1288   if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1289     Constant *N1 = Constant::getAllOnesValue(I.getType());
1290     Value *Add = Builder->CreateAdd(Op1, N1);
1291     return BinaryOperator::CreateAnd(Op0, Add);
1292   }
1293
1294   // 1 urem X -> zext(X != 1)
1295   if (match(Op0, m_One())) {
1296     Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1297     Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1298     return ReplaceInstUsesWith(I, Ext);
1299   }
1300
1301   return nullptr;
1302 }
1303
1304 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1305   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1306
1307   if (Value *V = SimplifyVectorOp(I))
1308     return ReplaceInstUsesWith(I, V);
1309
1310   if (Value *V = SimplifySRemInst(Op0, Op1, DL))
1311     return ReplaceInstUsesWith(I, V);
1312
1313   // Handle the integer rem common cases
1314   if (Instruction *Common = commonIRemTransforms(I))
1315     return Common;
1316
1317   if (Value *RHSNeg = dyn_castNegVal(Op1))
1318     if (!isa<Constant>(RHSNeg) ||
1319         (isa<ConstantInt>(RHSNeg) &&
1320          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1321       // X % -Y -> X % Y
1322       Worklist.AddValue(I.getOperand(1));
1323       I.setOperand(1, RHSNeg);
1324       return &I;
1325     }
1326
1327   // If the sign bits of both operands are zero (i.e. we can prove they are
1328   // unsigned inputs), turn this into a urem.
1329   if (I.getType()->isIntegerTy()) {
1330     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1331     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1332       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1333       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1334     }
1335   }
1336
1337   // If it's a constant vector, flip any negative values positive.
1338   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1339     Constant *C = cast<Constant>(Op1);
1340     unsigned VWidth = C->getType()->getVectorNumElements();
1341
1342     bool hasNegative = false;
1343     bool hasMissing = false;
1344     for (unsigned i = 0; i != VWidth; ++i) {
1345       Constant *Elt = C->getAggregateElement(i);
1346       if (!Elt) {
1347         hasMissing = true;
1348         break;
1349       }
1350
1351       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1352         if (RHS->isNegative())
1353           hasNegative = true;
1354     }
1355
1356     if (hasNegative && !hasMissing) {
1357       SmallVector<Constant *, 16> Elts(VWidth);
1358       for (unsigned i = 0; i != VWidth; ++i) {
1359         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
1360         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1361           if (RHS->isNegative())
1362             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1363         }
1364       }
1365
1366       Constant *NewRHSV = ConstantVector::get(Elts);
1367       if (NewRHSV != C) {  // Don't loop on -MININT
1368         Worklist.AddValue(I.getOperand(1));
1369         I.setOperand(1, NewRHSV);
1370         return &I;
1371       }
1372     }
1373   }
1374
1375   return nullptr;
1376 }
1377
1378 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1379   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1380
1381   if (Value *V = SimplifyVectorOp(I))
1382     return ReplaceInstUsesWith(I, V);
1383
1384   if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
1385     return ReplaceInstUsesWith(I, V);
1386
1387   // Handle cases involving: rem X, (select Cond, Y, Z)
1388   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1389     return &I;
1390
1391   return nullptr;
1392 }