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