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