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