1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
10 // srem, urem, frem.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/KnownBits.h"
34 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
35 #include "llvm/Transforms/Utils/BuildLibCalls.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       IC.replaceOperand(*I, 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 /// A helper routine of InstCombiner::visitMul().
98 ///
99 /// If C is a scalar/fixed width vector of known powers of 2, then this
100 /// function returns a new scalar/fixed width vector obtained from logBase2
101 /// of C.
102 /// Return a null pointer otherwise.
103 static Constant *getLogBase2(Type *Ty, Constant *C) {
104   const APInt *IVal;
105   if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
106     return ConstantInt::get(Ty, IVal->logBase2());
107 
108   // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
109   if (!isa<FixedVectorType>(Ty))
110     return nullptr;
111 
112   SmallVector<Constant *, 4> Elts;
113   for (unsigned I = 0, E = cast<FixedVectorType>(Ty)->getNumElements(); I != E;
114        ++I) {
115     Constant *Elt = C->getAggregateElement(I);
116     if (!Elt)
117       return nullptr;
118     if (isa<UndefValue>(Elt)) {
119       Elts.push_back(UndefValue::get(Ty->getScalarType()));
120       continue;
121     }
122     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
123       return nullptr;
124     Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
125   }
126 
127   return ConstantVector::get(Elts);
128 }
129 
130 // TODO: This is a specific form of a much more general pattern.
131 //       We could detect a select with any binop identity constant, or we
132 //       could use SimplifyBinOp to see if either arm of the select reduces.
133 //       But that needs to be done carefully and/or while removing potential
134 //       reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
135 static Value *foldMulSelectToNegate(BinaryOperator &I,
136                                     InstCombiner::BuilderTy &Builder) {
137   Value *Cond, *OtherOp;
138 
139   // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
140   // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
141   if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())),
142                         m_Value(OtherOp))))
143     return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp));
144 
145   // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
146   // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
147   if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())),
148                         m_Value(OtherOp))))
149     return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp);
150 
151   // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
152   // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
153   if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0),
154                                            m_SpecificFP(-1.0))),
155                          m_Value(OtherOp)))) {
156     IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
157     Builder.setFastMathFlags(I.getFastMathFlags());
158     return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
159   }
160 
161   // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
162   // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
163   if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0),
164                                            m_SpecificFP(1.0))),
165                          m_Value(OtherOp)))) {
166     IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
167     Builder.setFastMathFlags(I.getFastMathFlags());
168     return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
169   }
170 
171   return nullptr;
172 }
173 
174 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
175   if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1),
176                                  SQ.getWithInstruction(&I)))
177     return replaceInstUsesWith(I, V);
178 
179   if (SimplifyAssociativeOrCommutative(I))
180     return &I;
181 
182   if (Instruction *X = foldVectorBinop(I))
183     return X;
184 
185   if (Value *V = SimplifyUsingDistributiveLaws(I))
186     return replaceInstUsesWith(I, V);
187 
188   // X * -1 == 0 - X
189   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
190   if (match(Op1, m_AllOnes())) {
191     BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
192     if (I.hasNoSignedWrap())
193       BO->setHasNoSignedWrap();
194     return BO;
195   }
196 
197   // Also allow combining multiply instructions on vectors.
198   {
199     Value *NewOp;
200     Constant *C1, *C2;
201     const APInt *IVal;
202     if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
203                         m_Constant(C1))) &&
204         match(C1, m_APInt(IVal))) {
205       // ((X << C2)*C1) == (X * (C1 << C2))
206       Constant *Shl = ConstantExpr::getShl(C1, C2);
207       BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
208       BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
209       if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
210         BO->setHasNoUnsignedWrap();
211       if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
212           Shl->isNotMinSignedValue())
213         BO->setHasNoSignedWrap();
214       return BO;
215     }
216 
217     if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
218       // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
219       if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
220         BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
221 
222         if (I.hasNoUnsignedWrap())
223           Shl->setHasNoUnsignedWrap();
224         if (I.hasNoSignedWrap()) {
225           const APInt *V;
226           if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
227             Shl->setHasNoSignedWrap();
228         }
229 
230         return Shl;
231       }
232     }
233   }
234 
235   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
236     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
237     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
238     // The "* (2**n)" thus becomes a potential shifting opportunity.
239     {
240       const APInt &   Val = CI->getValue();
241       const APInt &PosVal = Val.abs();
242       if (Val.isNegative() && PosVal.isPowerOf2()) {
243         Value *X = nullptr, *Y = nullptr;
244         if (Op0->hasOneUse()) {
245           ConstantInt *C1;
246           Value *Sub = nullptr;
247           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
248             Sub = Builder.CreateSub(X, Y, "suba");
249           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
250             Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
251           if (Sub)
252             return
253               BinaryOperator::CreateMul(Sub,
254                                         ConstantInt::get(Y->getType(), PosVal));
255         }
256       }
257     }
258   }
259 
260   if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
261     return FoldedMul;
262 
263   if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
264     return replaceInstUsesWith(I, FoldedMul);
265 
266   // Simplify mul instructions with a constant RHS.
267   if (isa<Constant>(Op1)) {
268     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
269     Value *X;
270     Constant *C1;
271     if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
272       Value *Mul = Builder.CreateMul(C1, Op1);
273       // Only go forward with the transform if C1*CI simplifies to a tidier
274       // constant.
275       if (!match(Mul, m_Mul(m_Value(), m_Value())))
276         return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
277     }
278   }
279 
280   // abs(X) * abs(X) -> X * X
281   // nabs(X) * nabs(X) -> X * X
282   if (Op0 == Op1) {
283     Value *X, *Y;
284     SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
285     if (SPF == SPF_ABS || SPF == SPF_NABS)
286       return BinaryOperator::CreateMul(X, X);
287   }
288 
289   // -X * C --> X * -C
290   Value *X, *Y;
291   Constant *Op1C;
292   if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
293     return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
294 
295   // -X * -Y --> X * Y
296   if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
297     auto *NewMul = BinaryOperator::CreateMul(X, Y);
298     if (I.hasNoSignedWrap() &&
299         cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
300         cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
301       NewMul->setHasNoSignedWrap();
302     return NewMul;
303   }
304 
305   // -X * Y --> -(X * Y)
306   // X * -Y --> -(X * Y)
307   if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))
308     return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
309 
310   // (X / Y) *  Y = X - (X % Y)
311   // (X / Y) * -Y = (X % Y) - X
312   {
313     Value *Y = Op1;
314     BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
315     if (!Div || (Div->getOpcode() != Instruction::UDiv &&
316                  Div->getOpcode() != Instruction::SDiv)) {
317       Y = Op0;
318       Div = dyn_cast<BinaryOperator>(Op1);
319     }
320     Value *Neg = dyn_castNegVal(Y);
321     if (Div && Div->hasOneUse() &&
322         (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
323         (Div->getOpcode() == Instruction::UDiv ||
324          Div->getOpcode() == Instruction::SDiv)) {
325       Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
326 
327       // If the division is exact, X % Y is zero, so we end up with X or -X.
328       if (Div->isExact()) {
329         if (DivOp1 == Y)
330           return replaceInstUsesWith(I, X);
331         return BinaryOperator::CreateNeg(X);
332       }
333 
334       auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
335                                                           : Instruction::SRem;
336       Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
337       if (DivOp1 == Y)
338         return BinaryOperator::CreateSub(X, Rem);
339       return BinaryOperator::CreateSub(Rem, X);
340     }
341   }
342 
343   /// i1 mul -> i1 and.
344   if (I.getType()->isIntOrIntVectorTy(1))
345     return BinaryOperator::CreateAnd(Op0, Op1);
346 
347   // X*(1 << Y) --> X << Y
348   // (1 << Y)*X --> X << Y
349   {
350     Value *Y;
351     BinaryOperator *BO = nullptr;
352     bool ShlNSW = false;
353     if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
354       BO = BinaryOperator::CreateShl(Op1, Y);
355       ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
356     } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
357       BO = BinaryOperator::CreateShl(Op0, Y);
358       ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
359     }
360     if (BO) {
361       if (I.hasNoUnsignedWrap())
362         BO->setHasNoUnsignedWrap();
363       if (I.hasNoSignedWrap() && ShlNSW)
364         BO->setHasNoSignedWrap();
365       return BO;
366     }
367   }
368 
369   // (bool X) * Y --> X ? Y : 0
370   // Y * (bool X) --> X ? Y : 0
371   if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
372     return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
373   if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
374     return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
375 
376   // (lshr X, 31) * Y --> (ashr X, 31) & Y
377   // Y * (lshr X, 31) --> (ashr X, 31) & Y
378   // TODO: We are not checking one-use because the elimination of the multiply
379   //       is better for analysis?
380   // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
381   //       more similar to what we're doing above.
382   const APInt *C;
383   if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
384     return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
385   if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
386     return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
387 
388   if (Instruction *Ext = narrowMathIfNoOverflow(I))
389     return Ext;
390 
391   bool Changed = false;
392   if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
393     Changed = true;
394     I.setHasNoSignedWrap(true);
395   }
396 
397   if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
398     Changed = true;
399     I.setHasNoUnsignedWrap(true);
400   }
401 
402   return Changed ? &I : nullptr;
403 }
404 
405 static Instruction *foldFPSignBitOps(BinaryOperator &I) {
406   BinaryOperator::BinaryOps Opcode = I.getOpcode();
407   assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
408          "Expected fmul or fdiv");
409 
410   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
411   Value *X, *Y;
412 
413   // -X * -Y --> X * Y
414   // -X / -Y --> X / Y
415   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
416     return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
417 
418   // fabs(X) * fabs(X) -> X * X
419   // fabs(X) / fabs(X) -> X / X
420   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))))
421     return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
422 
423   return nullptr;
424 }
425 
426 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
427   if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1),
428                                   I.getFastMathFlags(),
429                                   SQ.getWithInstruction(&I)))
430     return replaceInstUsesWith(I, V);
431 
432   if (SimplifyAssociativeOrCommutative(I))
433     return &I;
434 
435   if (Instruction *X = foldVectorBinop(I))
436     return X;
437 
438   if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
439     return FoldedMul;
440 
441   if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
442     return replaceInstUsesWith(I, FoldedMul);
443 
444   if (Instruction *R = foldFPSignBitOps(I))
445     return R;
446 
447   // X * -1.0 --> -X
448   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
449   if (match(Op1, m_SpecificFP(-1.0)))
450     return UnaryOperator::CreateFNegFMF(Op0, &I);
451 
452   // -X * C --> X * -C
453   Value *X, *Y;
454   Constant *C;
455   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
456     return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
457 
458   // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
459   if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
460     return replaceInstUsesWith(I, V);
461 
462   if (I.hasAllowReassoc()) {
463     // Reassociate constant RHS with another constant to form constant
464     // expression.
465     if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
466       Constant *C1;
467       if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
468         // (C1 / X) * C --> (C * C1) / X
469         Constant *CC1 = ConstantExpr::getFMul(C, C1);
470         if (CC1->isNormalFP())
471           return BinaryOperator::CreateFDivFMF(CC1, X, &I);
472       }
473       if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
474         // (X / C1) * C --> X * (C / C1)
475         Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
476         if (CDivC1->isNormalFP())
477           return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
478 
479         // If the constant was a denormal, try reassociating differently.
480         // (X / C1) * C --> X / (C1 / C)
481         Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
482         if (Op0->hasOneUse() && C1DivC->isNormalFP())
483           return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
484       }
485 
486       // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
487       // canonicalized to 'fadd X, C'. Distributing the multiply may allow
488       // further folds and (X * C) + C2 is 'fma'.
489       if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
490         // (X + C1) * C --> (X * C) + (C * C1)
491         Constant *CC1 = ConstantExpr::getFMul(C, C1);
492         Value *XC = Builder.CreateFMulFMF(X, C, &I);
493         return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
494       }
495       if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
496         // (C1 - X) * C --> (C * C1) - (X * C)
497         Constant *CC1 = ConstantExpr::getFMul(C, C1);
498         Value *XC = Builder.CreateFMulFMF(X, C, &I);
499         return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
500       }
501     }
502 
503     Value *Z;
504     if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))),
505                            m_Value(Z)))) {
506       // Sink division: (X / Y) * Z --> (X * Z) / Y
507       Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
508       return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
509     }
510 
511     // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
512     // nnan disallows the possibility of returning a number if both operands are
513     // negative (in that case, we should return NaN).
514     if (I.hasNoNaNs() &&
515         match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
516         match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
517       Value *XY = Builder.CreateFMulFMF(X, Y, &I);
518       Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
519       return replaceInstUsesWith(I, Sqrt);
520     }
521 
522     // Like the similar transform in instsimplify, this requires 'nsz' because
523     // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
524     if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 &&
525         Op0->hasNUses(2)) {
526       // Peek through fdiv to find squaring of square root:
527       // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
528       if (match(Op0, m_FDiv(m_Value(X),
529                             m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
530         Value *XX = Builder.CreateFMulFMF(X, X, &I);
531         return BinaryOperator::CreateFDivFMF(XX, Y, &I);
532       }
533       // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
534       if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)),
535                             m_Value(X)))) {
536         Value *XX = Builder.CreateFMulFMF(X, X, &I);
537         return BinaryOperator::CreateFDivFMF(Y, XX, &I);
538       }
539     }
540 
541     // exp(X) * exp(Y) -> exp(X + Y)
542     // Match as long as at least one of exp has only one use.
543     if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
544         match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) &&
545         (Op0->hasOneUse() || Op1->hasOneUse())) {
546       Value *XY = Builder.CreateFAddFMF(X, Y, &I);
547       Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
548       return replaceInstUsesWith(I, Exp);
549     }
550 
551     // exp2(X) * exp2(Y) -> exp2(X + Y)
552     // Match as long as at least one of exp2 has only one use.
553     if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
554         match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) &&
555         (Op0->hasOneUse() || Op1->hasOneUse())) {
556       Value *XY = Builder.CreateFAddFMF(X, Y, &I);
557       Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
558       return replaceInstUsesWith(I, Exp2);
559     }
560 
561     // (X*Y) * X => (X*X) * Y where Y != X
562     //  The purpose is two-fold:
563     //   1) to form a power expression (of X).
564     //   2) potentially shorten the critical path: After transformation, the
565     //  latency of the instruction Y is amortized by the expression of X*X,
566     //  and therefore Y is in a "less critical" position compared to what it
567     //  was before the transformation.
568     if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
569         Op1 != Y) {
570       Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
571       return BinaryOperator::CreateFMulFMF(XX, Y, &I);
572     }
573     if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
574         Op0 != Y) {
575       Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
576       return BinaryOperator::CreateFMulFMF(XX, Y, &I);
577     }
578   }
579 
580   // log2(X * 0.5) * Y = log2(X) * Y - Y
581   if (I.isFast()) {
582     IntrinsicInst *Log2 = nullptr;
583     if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
584             m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
585       Log2 = cast<IntrinsicInst>(Op0);
586       Y = Op1;
587     }
588     if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
589             m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
590       Log2 = cast<IntrinsicInst>(Op1);
591       Y = Op0;
592     }
593     if (Log2) {
594       Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
595       Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
596       return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
597     }
598   }
599 
600   return nullptr;
601 }
602 
603 /// Fold a divide or remainder with a select instruction divisor when one of the
604 /// select operands is zero. In that case, we can use the other select operand
605 /// because div/rem by zero is undefined.
606 bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
607   SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
608   if (!SI)
609     return false;
610 
611   int NonNullOperand;
612   if (match(SI->getTrueValue(), m_Zero()))
613     // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
614     NonNullOperand = 2;
615   else if (match(SI->getFalseValue(), m_Zero()))
616     // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
617     NonNullOperand = 1;
618   else
619     return false;
620 
621   // Change the div/rem to use 'Y' instead of the select.
622   replaceOperand(I, 1, SI->getOperand(NonNullOperand));
623 
624   // Okay, we know we replace the operand of the div/rem with 'Y' with no
625   // problem.  However, the select, or the condition of the select may have
626   // multiple uses.  Based on our knowledge that the operand must be non-zero,
627   // propagate the known value for the select into other uses of it, and
628   // propagate a known value of the condition into its other users.
629 
630   // If the select and condition only have a single use, don't bother with this,
631   // early exit.
632   Value *SelectCond = SI->getCondition();
633   if (SI->use_empty() && SelectCond->hasOneUse())
634     return true;
635 
636   // Scan the current block backward, looking for other uses of SI.
637   BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
638   Type *CondTy = SelectCond->getType();
639   while (BBI != BBFront) {
640     --BBI;
641     // If we found an instruction that we can't assume will return, so
642     // information from below it cannot be propagated above it.
643     if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
644       break;
645 
646     // Replace uses of the select or its condition with the known values.
647     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
648          I != E; ++I) {
649       if (*I == SI) {
650         replaceUse(*I, SI->getOperand(NonNullOperand));
651         Worklist.push(&*BBI);
652       } else if (*I == SelectCond) {
653         replaceUse(*I, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
654                                            : ConstantInt::getFalse(CondTy));
655         Worklist.push(&*BBI);
656       }
657     }
658 
659     // If we past the instruction, quit looking for it.
660     if (&*BBI == SI)
661       SI = nullptr;
662     if (&*BBI == SelectCond)
663       SelectCond = nullptr;
664 
665     // If we ran out of things to eliminate, break out of the loop.
666     if (!SelectCond && !SI)
667       break;
668 
669   }
670   return true;
671 }
672 
673 /// True if the multiply can not be expressed in an int this size.
674 static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
675                               bool IsSigned) {
676   bool Overflow;
677   Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
678   return Overflow;
679 }
680 
681 /// True if C1 is a multiple of C2. Quotient contains C1/C2.
682 static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
683                        bool IsSigned) {
684   assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
685 
686   // Bail if we will divide by zero.
687   if (C2.isNullValue())
688     return false;
689 
690   // Bail if we would divide INT_MIN by -1.
691   if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
692     return false;
693 
694   APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
695   if (IsSigned)
696     APInt::sdivrem(C1, C2, Quotient, Remainder);
697   else
698     APInt::udivrem(C1, C2, Quotient, Remainder);
699 
700   return Remainder.isMinValue();
701 }
702 
703 /// This function implements the transforms common to both integer division
704 /// instructions (udiv and sdiv). It is called by the visitors to those integer
705 /// division instructions.
706 /// Common integer divide transforms
707 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
708   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
709   bool IsSigned = I.getOpcode() == Instruction::SDiv;
710   Type *Ty = I.getType();
711 
712   // The RHS is known non-zero.
713   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
714     return replaceOperand(I, 1, V);
715 
716   // Handle cases involving: [su]div X, (select Cond, Y, Z)
717   // This does not apply for fdiv.
718   if (simplifyDivRemOfSelectWithZeroOp(I))
719     return &I;
720 
721   const APInt *C2;
722   if (match(Op1, m_APInt(C2))) {
723     Value *X;
724     const APInt *C1;
725 
726     // (X / C1) / C2  -> X / (C1*C2)
727     if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
728         (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
729       APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
730       if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
731         return BinaryOperator::Create(I.getOpcode(), X,
732                                       ConstantInt::get(Ty, Product));
733     }
734 
735     if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
736         (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
737       APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
738 
739       // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
740       if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
741         auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
742                                               ConstantInt::get(Ty, Quotient));
743         NewDiv->setIsExact(I.isExact());
744         return NewDiv;
745       }
746 
747       // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
748       if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
749         auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
750                                            ConstantInt::get(Ty, Quotient));
751         auto *OBO = cast<OverflowingBinaryOperator>(Op0);
752         Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
753         Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
754         return Mul;
755       }
756     }
757 
758     if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
759          *C1 != C1->getBitWidth() - 1) ||
760         (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
761       APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
762       APInt C1Shifted = APInt::getOneBitSet(
763           C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
764 
765       // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
766       if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
767         auto *BO = BinaryOperator::Create(I.getOpcode(), X,
768                                           ConstantInt::get(Ty, Quotient));
769         BO->setIsExact(I.isExact());
770         return BO;
771       }
772 
773       // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
774       if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
775         auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
776                                            ConstantInt::get(Ty, Quotient));
777         auto *OBO = cast<OverflowingBinaryOperator>(Op0);
778         Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
779         Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
780         return Mul;
781       }
782     }
783 
784     if (!C2->isNullValue()) // avoid X udiv 0
785       if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
786         return FoldedDiv;
787   }
788 
789   if (match(Op0, m_One())) {
790     assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
791     if (IsSigned) {
792       // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
793       // result is one, if Op1 is -1 then the result is minus one, otherwise
794       // it's zero.
795       Value *Inc = Builder.CreateAdd(Op1, Op0);
796       Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
797       return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
798     } else {
799       // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
800       // result is one, otherwise it's zero.
801       return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
802     }
803   }
804 
805   // See if we can fold away this div instruction.
806   if (SimplifyDemandedInstructionBits(I))
807     return &I;
808 
809   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
810   Value *X, *Z;
811   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
812     if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
813         (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
814       return BinaryOperator::Create(I.getOpcode(), X, Op1);
815 
816   // (X << Y) / X -> 1 << Y
817   Value *Y;
818   if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
819     return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
820   if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
821     return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
822 
823   // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
824   if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
825     bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
826     bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
827     if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
828       replaceOperand(I, 0, ConstantInt::get(Ty, 1));
829       replaceOperand(I, 1, Y);
830       return &I;
831     }
832   }
833 
834   return nullptr;
835 }
836 
837 static const unsigned MaxDepth = 6;
838 
839 namespace {
840 
841 using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
842                                            const BinaryOperator &I,
843                                            InstCombiner &IC);
844 
845 /// Used to maintain state for visitUDivOperand().
846 struct UDivFoldAction {
847   /// Informs visitUDiv() how to fold this operand.  This can be zero if this
848   /// action joins two actions together.
849   FoldUDivOperandCb FoldAction;
850 
851   /// Which operand to fold.
852   Value *OperandToFold;
853 
854   union {
855     /// The instruction returned when FoldAction is invoked.
856     Instruction *FoldResult;
857 
858     /// Stores the LHS action index if this action joins two actions together.
859     size_t SelectLHSIdx;
860   };
861 
862   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
863       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
864   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
865       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
866 };
867 
868 } // end anonymous namespace
869 
870 // X udiv 2^C -> X >> C
871 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
872                                     const BinaryOperator &I, InstCombiner &IC) {
873   Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
874   if (!C1)
875     llvm_unreachable("Failed to constant fold udiv -> logbase2");
876   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
877   if (I.isExact())
878     LShr->setIsExact();
879   return LShr;
880 }
881 
882 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
883 // X udiv (zext (C1 << N)), where C1 is "1<<C2"  -->  X >> (N+C2)
884 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
885                                 InstCombiner &IC) {
886   Value *ShiftLeft;
887   if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
888     ShiftLeft = Op1;
889 
890   Constant *CI;
891   Value *N;
892   if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
893     llvm_unreachable("match should never fail here!");
894   Constant *Log2Base = getLogBase2(N->getType(), CI);
895   if (!Log2Base)
896     llvm_unreachable("getLogBase2 should never fail here!");
897   N = IC.Builder.CreateAdd(N, Log2Base);
898   if (Op1 != ShiftLeft)
899     N = IC.Builder.CreateZExt(N, Op1->getType());
900   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
901   if (I.isExact())
902     LShr->setIsExact();
903   return LShr;
904 }
905 
906 // Recursively visits the possible right hand operands of a udiv
907 // instruction, seeing through select instructions, to determine if we can
908 // replace the udiv with something simpler.  If we find that an operand is not
909 // able to simplify the udiv, we abort the entire transformation.
910 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
911                                SmallVectorImpl<UDivFoldAction> &Actions,
912                                unsigned Depth = 0) {
913   // Check to see if this is an unsigned division with an exact power of 2,
914   // if so, convert to a right shift.
915   if (match(Op1, m_Power2())) {
916     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
917     return Actions.size();
918   }
919 
920   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
921   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
922       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
923     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
924     return Actions.size();
925   }
926 
927   // The remaining tests are all recursive, so bail out if we hit the limit.
928   if (Depth++ == MaxDepth)
929     return 0;
930 
931   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
932     if (size_t LHSIdx =
933             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
934       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
935         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
936         return Actions.size();
937       }
938 
939   return 0;
940 }
941 
942 /// If we have zero-extended operands of an unsigned div or rem, we may be able
943 /// to narrow the operation (sink the zext below the math).
944 static Instruction *narrowUDivURem(BinaryOperator &I,
945                                    InstCombiner::BuilderTy &Builder) {
946   Instruction::BinaryOps Opcode = I.getOpcode();
947   Value *N = I.getOperand(0);
948   Value *D = I.getOperand(1);
949   Type *Ty = I.getType();
950   Value *X, *Y;
951   if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
952       X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
953     // udiv (zext X), (zext Y) --> zext (udiv X, Y)
954     // urem (zext X), (zext Y) --> zext (urem X, Y)
955     Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
956     return new ZExtInst(NarrowOp, Ty);
957   }
958 
959   Constant *C;
960   if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
961       (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
962     // If the constant is the same in the smaller type, use the narrow version.
963     Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
964     if (ConstantExpr::getZExt(TruncC, Ty) != C)
965       return nullptr;
966 
967     // udiv (zext X), C --> zext (udiv X, C')
968     // urem (zext X), C --> zext (urem X, C')
969     // udiv C, (zext X) --> zext (udiv C', X)
970     // urem C, (zext X) --> zext (urem C', X)
971     Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
972                                        : Builder.CreateBinOp(Opcode, TruncC, X);
973     return new ZExtInst(NarrowOp, Ty);
974   }
975 
976   return nullptr;
977 }
978 
979 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
980   if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
981                                   SQ.getWithInstruction(&I)))
982     return replaceInstUsesWith(I, V);
983 
984   if (Instruction *X = foldVectorBinop(I))
985     return X;
986 
987   // Handle the integer div common cases
988   if (Instruction *Common = commonIDivTransforms(I))
989     return Common;
990 
991   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
992   Value *X;
993   const APInt *C1, *C2;
994   if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
995     // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
996     bool Overflow;
997     APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
998     if (!Overflow) {
999       bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1000       BinaryOperator *BO = BinaryOperator::CreateUDiv(
1001           X, ConstantInt::get(X->getType(), C2ShlC1));
1002       if (IsExact)
1003         BO->setIsExact();
1004       return BO;
1005     }
1006   }
1007 
1008   // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1009   // TODO: Could use isKnownNegative() to handle non-constant values.
1010   Type *Ty = I.getType();
1011   if (match(Op1, m_Negative())) {
1012     Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1013     return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1014   }
1015   // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1016   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1017     Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1018     return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1019   }
1020 
1021   if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1022     return NarrowDiv;
1023 
1024   // If the udiv operands are non-overflowing multiplies with a common operand,
1025   // then eliminate the common factor:
1026   // (A * B) / (A * X) --> B / X (and commuted variants)
1027   // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1028   // TODO: If -reassociation handled this generally, we could remove this.
1029   Value *A, *B;
1030   if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1031     if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1032         match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1033       return BinaryOperator::CreateUDiv(B, X);
1034     if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1035         match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1036       return BinaryOperator::CreateUDiv(A, X);
1037   }
1038 
1039   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1040   SmallVector<UDivFoldAction, 6> UDivActions;
1041   if (visitUDivOperand(Op0, Op1, I, UDivActions))
1042     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1043       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1044       Value *ActionOp1 = UDivActions[i].OperandToFold;
1045       Instruction *Inst;
1046       if (Action)
1047         Inst = Action(Op0, ActionOp1, I, *this);
1048       else {
1049         // This action joins two actions together.  The RHS of this action is
1050         // simply the last action we processed, we saved the LHS action index in
1051         // the joining action.
1052         size_t SelectRHSIdx = i - 1;
1053         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1054         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1055         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1056         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1057                                   SelectLHS, SelectRHS);
1058       }
1059 
1060       // If this is the last action to process, return it to the InstCombiner.
1061       // Otherwise, we insert it before the UDiv and record it so that we may
1062       // use it as part of a joining action (i.e., a SelectInst).
1063       if (e - i != 1) {
1064         Inst->insertBefore(&I);
1065         UDivActions[i].FoldResult = Inst;
1066       } else
1067         return Inst;
1068     }
1069 
1070   return nullptr;
1071 }
1072 
1073 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1074   if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1075                                   SQ.getWithInstruction(&I)))
1076     return replaceInstUsesWith(I, V);
1077 
1078   if (Instruction *X = foldVectorBinop(I))
1079     return X;
1080 
1081   // Handle the integer div common cases
1082   if (Instruction *Common = commonIDivTransforms(I))
1083     return Common;
1084 
1085   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1086   Value *X;
1087   // sdiv Op0, -1 --> -Op0
1088   // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1089   if (match(Op1, m_AllOnes()) ||
1090       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1091     return BinaryOperator::CreateNeg(Op0);
1092 
1093   // X / INT_MIN --> X == INT_MIN
1094   if (match(Op1, m_SignMask()))
1095     return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
1096 
1097   const APInt *Op1C;
1098   if (match(Op1, m_APInt(Op1C))) {
1099     // sdiv exact X, C  -->  ashr exact X, log2(C)
1100     if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1101       Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1102       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1103     }
1104 
1105     // If the dividend is sign-extended and the constant divisor is small enough
1106     // to fit in the source type, shrink the division to the narrower type:
1107     // (sext X) sdiv C --> sext (X sdiv C)
1108     Value *Op0Src;
1109     if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1110         Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1111 
1112       // In the general case, we need to make sure that the dividend is not the
1113       // minimum signed value because dividing that by -1 is UB. But here, we
1114       // know that the -1 divisor case is already handled above.
1115 
1116       Constant *NarrowDivisor =
1117           ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1118       Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1119       return new SExtInst(NarrowOp, Op0->getType());
1120     }
1121 
1122     // -X / C --> X / -C (if the negation doesn't overflow).
1123     // TODO: This could be enhanced to handle arbitrary vector constants by
1124     //       checking if all elements are not the min-signed-val.
1125     if (!Op1C->isMinSignedValue() &&
1126         match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1127       Constant *NegC = ConstantInt::get(I.getType(), -(*Op1C));
1128       Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1129       BO->setIsExact(I.isExact());
1130       return BO;
1131     }
1132   }
1133 
1134   // -X / Y --> -(X / Y)
1135   Value *Y;
1136   if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1137     return BinaryOperator::CreateNSWNeg(
1138         Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1139 
1140   // If the sign bits of both operands are zero (i.e. we can prove they are
1141   // unsigned inputs), turn this into a udiv.
1142   APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1143   if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1144     if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1145       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1146       auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1147       BO->setIsExact(I.isExact());
1148       return BO;
1149     }
1150 
1151     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1152       // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1153       // Safe because the only negative value (1 << Y) can take on is
1154       // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1155       // the sign bit set.
1156       auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1157       BO->setIsExact(I.isExact());
1158       return BO;
1159     }
1160   }
1161 
1162   return nullptr;
1163 }
1164 
1165 /// Remove negation and try to convert division into multiplication.
1166 static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1167   Constant *C;
1168   if (!match(I.getOperand(1), m_Constant(C)))
1169     return nullptr;
1170 
1171   // -X / C --> X / -C
1172   Value *X;
1173   if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1174     return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
1175 
1176   // If the constant divisor has an exact inverse, this is always safe. If not,
1177   // then we can still create a reciprocal if fast-math-flags allow it and the
1178   // constant is a regular number (not zero, infinite, or denormal).
1179   if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1180     return nullptr;
1181 
1182   // Disallow denormal constants because we don't know what would happen
1183   // on all targets.
1184   // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1185   // denorms are flushed?
1186   auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1187   if (!RecipC->isNormalFP())
1188     return nullptr;
1189 
1190   // X / C --> X * (1 / C)
1191   return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1192 }
1193 
1194 /// Remove negation and try to reassociate constant math.
1195 static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
1196   Constant *C;
1197   if (!match(I.getOperand(0), m_Constant(C)))
1198     return nullptr;
1199 
1200   // C / -X --> -C / X
1201   Value *X;
1202   if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1203     return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
1204 
1205   if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1206     return nullptr;
1207 
1208   // Try to reassociate C / X expressions where X includes another constant.
1209   Constant *C2, *NewC = nullptr;
1210   if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1211     // C / (X * C2) --> (C / C2) / X
1212     NewC = ConstantExpr::getFDiv(C, C2);
1213   } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1214     // C / (X / C2) --> (C * C2) / X
1215     NewC = ConstantExpr::getFMul(C, C2);
1216   }
1217   // Disallow denormal constants because we don't know what would happen
1218   // on all targets.
1219   // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1220   // denorms are flushed?
1221   if (!NewC || !NewC->isNormalFP())
1222     return nullptr;
1223 
1224   return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1225 }
1226 
1227 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1228   if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1229                                   I.getFastMathFlags(),
1230                                   SQ.getWithInstruction(&I)))
1231     return replaceInstUsesWith(I, V);
1232 
1233   if (Instruction *X = foldVectorBinop(I))
1234     return X;
1235 
1236   if (Instruction *R = foldFDivConstantDivisor(I))
1237     return R;
1238 
1239   if (Instruction *R = foldFDivConstantDividend(I))
1240     return R;
1241 
1242   if (Instruction *R = foldFPSignBitOps(I))
1243     return R;
1244 
1245   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1246   if (isa<Constant>(Op0))
1247     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1248       if (Instruction *R = FoldOpIntoSelect(I, SI))
1249         return R;
1250 
1251   if (isa<Constant>(Op1))
1252     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1253       if (Instruction *R = FoldOpIntoSelect(I, SI))
1254         return R;
1255 
1256   if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1257     Value *X, *Y;
1258     if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1259         (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1260       // (X / Y) / Z => X / (Y * Z)
1261       Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1262       return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1263     }
1264     if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1265         (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1266       // Z / (X / Y) => (Y * Z) / X
1267       Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1268       return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1269     }
1270     // Z / (1.0 / Y) => (Y * Z)
1271     //
1272     // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1273     // m_OneUse check is avoided because even in the case of the multiple uses
1274     // for 1.0/Y, the number of instructions remain the same and a division is
1275     // replaced by a multiplication.
1276     if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1277       return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1278   }
1279 
1280   if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1281     // sin(X) / cos(X) -> tan(X)
1282     // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1283     Value *X;
1284     bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1285                  match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1286     bool IsCot =
1287         !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1288                   match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1289 
1290     if ((IsTan || IsCot) &&
1291         hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) {
1292       IRBuilder<> B(&I);
1293       IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1294       B.setFastMathFlags(I.getFastMathFlags());
1295       AttributeList Attrs =
1296           cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1297       Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1298                                         LibFunc_tanl, B, Attrs);
1299       if (IsCot)
1300         Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1301       return replaceInstUsesWith(I, Res);
1302     }
1303   }
1304 
1305   // X / (X * Y) --> 1.0 / Y
1306   // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1307   // We can ignore the possibility that X is infinity because INF/INF is NaN.
1308   Value *X, *Y;
1309   if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1310       match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1311     replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1312     replaceOperand(I, 1, Y);
1313     return &I;
1314   }
1315 
1316   // X / fabs(X) -> copysign(1.0, X)
1317   // fabs(X) / X -> copysign(1.0, X)
1318   if (I.hasNoNaNs() && I.hasNoInfs() &&
1319       (match(&I,
1320              m_FDiv(m_Value(X), m_Intrinsic<Intrinsic::fabs>(m_Deferred(X)))) ||
1321        match(&I, m_FDiv(m_Intrinsic<Intrinsic::fabs>(m_Value(X)),
1322                         m_Deferred(X))))) {
1323     Value *V = Builder.CreateBinaryIntrinsic(
1324         Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1325     return replaceInstUsesWith(I, V);
1326   }
1327   return nullptr;
1328 }
1329 
1330 /// This function implements the transforms common to both integer remainder
1331 /// instructions (urem and srem). It is called by the visitors to those integer
1332 /// remainder instructions.
1333 /// Common integer remainder transforms
1334 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1335   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1336 
1337   // The RHS is known non-zero.
1338   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1339     return replaceOperand(I, 1, V);
1340 
1341   // Handle cases involving: rem X, (select Cond, Y, Z)
1342   if (simplifyDivRemOfSelectWithZeroOp(I))
1343     return &I;
1344 
1345   if (isa<Constant>(Op1)) {
1346     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1347       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1348         if (Instruction *R = FoldOpIntoSelect(I, SI))
1349           return R;
1350       } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1351         const APInt *Op1Int;
1352         if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1353             (I.getOpcode() == Instruction::URem ||
1354              !Op1Int->isMinSignedValue())) {
1355           // foldOpIntoPhi will speculate instructions to the end of the PHI's
1356           // predecessor blocks, so do this only if we know the srem or urem
1357           // will not fault.
1358           if (Instruction *NV = foldOpIntoPhi(I, PN))
1359             return NV;
1360         }
1361       }
1362 
1363       // See if we can fold away this rem instruction.
1364       if (SimplifyDemandedInstructionBits(I))
1365         return &I;
1366     }
1367   }
1368 
1369   return nullptr;
1370 }
1371 
1372 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1373   if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1374                                   SQ.getWithInstruction(&I)))
1375     return replaceInstUsesWith(I, V);
1376 
1377   if (Instruction *X = foldVectorBinop(I))
1378     return X;
1379 
1380   if (Instruction *common = commonIRemTransforms(I))
1381     return common;
1382 
1383   if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1384     return NarrowRem;
1385 
1386   // X urem Y -> X and Y-1, where Y is a power of 2,
1387   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1388   Type *Ty = I.getType();
1389   if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1390     // This may increase instruction count, we don't enforce that Y is a
1391     // constant.
1392     Constant *N1 = Constant::getAllOnesValue(Ty);
1393     Value *Add = Builder.CreateAdd(Op1, N1);
1394     return BinaryOperator::CreateAnd(Op0, Add);
1395   }
1396 
1397   // 1 urem X -> zext(X != 1)
1398   if (match(Op0, m_One())) {
1399     Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1400     return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1401   }
1402 
1403   // X urem C -> X < C ? X : X - C, where C >= signbit.
1404   if (match(Op1, m_Negative())) {
1405     Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1406     Value *Sub = Builder.CreateSub(Op0, Op1);
1407     return SelectInst::Create(Cmp, Op0, Sub);
1408   }
1409 
1410   // If the divisor is a sext of a boolean, then the divisor must be max
1411   // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1412   // max unsigned value. In that case, the remainder is 0:
1413   // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1414   Value *X;
1415   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1416     Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1417     return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1418   }
1419 
1420   return nullptr;
1421 }
1422 
1423 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1424   if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1425                                   SQ.getWithInstruction(&I)))
1426     return replaceInstUsesWith(I, V);
1427 
1428   if (Instruction *X = foldVectorBinop(I))
1429     return X;
1430 
1431   // Handle the integer rem common cases
1432   if (Instruction *Common = commonIRemTransforms(I))
1433     return Common;
1434 
1435   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1436   {
1437     const APInt *Y;
1438     // X % -Y -> X % Y
1439     if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1440       return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
1441   }
1442 
1443   // -X srem Y --> -(X srem Y)
1444   Value *X, *Y;
1445   if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1446     return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
1447 
1448   // If the sign bits of both operands are zero (i.e. we can prove they are
1449   // unsigned inputs), turn this into a urem.
1450   APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1451   if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1452       MaskedValueIsZero(Op0, Mask, 0, &I)) {
1453     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1454     return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1455   }
1456 
1457   // If it's a constant vector, flip any negative values positive.
1458   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1459     Constant *C = cast<Constant>(Op1);
1460     unsigned VWidth = cast<VectorType>(C->getType())->getNumElements();
1461 
1462     bool hasNegative = false;
1463     bool hasMissing = false;
1464     for (unsigned i = 0; i != VWidth; ++i) {
1465       Constant *Elt = C->getAggregateElement(i);
1466       if (!Elt) {
1467         hasMissing = true;
1468         break;
1469       }
1470 
1471       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1472         if (RHS->isNegative())
1473           hasNegative = true;
1474     }
1475 
1476     if (hasNegative && !hasMissing) {
1477       SmallVector<Constant *, 16> Elts(VWidth);
1478       for (unsigned i = 0; i != VWidth; ++i) {
1479         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
1480         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1481           if (RHS->isNegative())
1482             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1483         }
1484       }
1485 
1486       Constant *NewRHSV = ConstantVector::get(Elts);
1487       if (NewRHSV != C)  // Don't loop on -MININT
1488         return replaceOperand(I, 1, NewRHSV);
1489     }
1490   }
1491 
1492   return nullptr;
1493 }
1494 
1495 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1496   if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1497                                   I.getFastMathFlags(),
1498                                   SQ.getWithInstruction(&I)))
1499     return replaceInstUsesWith(I, V);
1500 
1501   if (Instruction *X = foldVectorBinop(I))
1502     return X;
1503 
1504   return nullptr;
1505 }
1506