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