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