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