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