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