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