xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp (revision d56accc7c3dcc897489b6a07834763a03b9f3d68)
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 namespace {
904 
905 using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
906                                            const BinaryOperator &I,
907                                            InstCombinerImpl &IC);
908 
909 /// Used to maintain state for visitUDivOperand().
910 struct UDivFoldAction {
911   /// Informs visitUDiv() how to fold this operand.  This can be zero if this
912   /// action joins two actions together.
913   FoldUDivOperandCb FoldAction;
914 
915   /// Which operand to fold.
916   Value *OperandToFold;
917 
918   union {
919     /// The instruction returned when FoldAction is invoked.
920     Instruction *FoldResult;
921 
922     /// Stores the LHS action index if this action joins two actions together.
923     size_t SelectLHSIdx;
924   };
925 
926   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
927       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
928   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
929       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
930 };
931 
932 } // end anonymous namespace
933 
934 // X udiv 2^C -> X >> C
935 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
936                                     const BinaryOperator &I,
937                                     InstCombinerImpl &IC) {
938   Constant *C1 = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
939   if (!C1)
940     llvm_unreachable("Failed to constant fold udiv -> logbase2");
941   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
942   if (I.isExact())
943     LShr->setIsExact();
944   return LShr;
945 }
946 
947 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
948 // X udiv (zext (C1 << N)), where C1 is "1<<C2"  -->  X >> (N+C2)
949 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
950                                 InstCombinerImpl &IC) {
951   Value *ShiftLeft;
952   if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
953     ShiftLeft = Op1;
954 
955   Constant *CI;
956   Value *N;
957   if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
958     llvm_unreachable("match should never fail here!");
959   Constant *Log2Base = ConstantExpr::getExactLogBase2(CI);
960   if (!Log2Base)
961     llvm_unreachable("getLogBase2 should never fail here!");
962   N = IC.Builder.CreateAdd(N, Log2Base);
963   if (Op1 != ShiftLeft)
964     N = IC.Builder.CreateZExt(N, Op1->getType());
965   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
966   if (I.isExact())
967     LShr->setIsExact();
968   return LShr;
969 }
970 
971 // Recursively visits the possible right hand operands of a udiv
972 // instruction, seeing through select instructions, to determine if we can
973 // replace the udiv with something simpler.  If we find that an operand is not
974 // able to simplify the udiv, we abort the entire transformation.
975 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
976                                SmallVectorImpl<UDivFoldAction> &Actions,
977                                unsigned Depth = 0) {
978   // FIXME: assert that Op1 isn't/doesn't contain undef.
979 
980   // Check to see if this is an unsigned division with an exact power of 2,
981   // if so, convert to a right shift.
982   if (match(Op1, m_Power2())) {
983     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
984     return Actions.size();
985   }
986 
987   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
988   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
989       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
990     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
991     return Actions.size();
992   }
993 
994   // The remaining tests are all recursive, so bail out if we hit the limit.
995   if (Depth++ == MaxDepth)
996     return 0;
997 
998   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
999     // FIXME: missed optimization: if one of the hands of select is/contains
1000     //        undef, just directly pick the other one.
1001     // FIXME: can both hands contain undef?
1002     if (size_t LHSIdx =
1003             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1004       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1005         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1006         return Actions.size();
1007       }
1008 
1009   return 0;
1010 }
1011 
1012 /// If we have zero-extended operands of an unsigned div or rem, we may be able
1013 /// to narrow the operation (sink the zext below the math).
1014 static Instruction *narrowUDivURem(BinaryOperator &I,
1015                                    InstCombiner::BuilderTy &Builder) {
1016   Instruction::BinaryOps Opcode = I.getOpcode();
1017   Value *N = I.getOperand(0);
1018   Value *D = I.getOperand(1);
1019   Type *Ty = I.getType();
1020   Value *X, *Y;
1021   if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1022       X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1023     // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1024     // urem (zext X), (zext Y) --> zext (urem X, Y)
1025     Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1026     return new ZExtInst(NarrowOp, Ty);
1027   }
1028 
1029   Constant *C;
1030   if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1031       (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1032     // If the constant is the same in the smaller type, use the narrow version.
1033     Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1034     if (ConstantExpr::getZExt(TruncC, Ty) != C)
1035       return nullptr;
1036 
1037     // udiv (zext X), C --> zext (udiv X, C')
1038     // urem (zext X), C --> zext (urem X, C')
1039     // udiv C, (zext X) --> zext (udiv C', X)
1040     // urem C, (zext X) --> zext (urem C', X)
1041     Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1042                                        : Builder.CreateBinOp(Opcode, TruncC, X);
1043     return new ZExtInst(NarrowOp, Ty);
1044   }
1045 
1046   return nullptr;
1047 }
1048 
1049 Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) {
1050   if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
1051                                   SQ.getWithInstruction(&I)))
1052     return replaceInstUsesWith(I, V);
1053 
1054   if (Instruction *X = foldVectorBinop(I))
1055     return X;
1056 
1057   // Handle the integer div common cases
1058   if (Instruction *Common = commonIDivTransforms(I))
1059     return Common;
1060 
1061   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1062   Value *X;
1063   const APInt *C1, *C2;
1064   if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1065     // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1066     bool Overflow;
1067     APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1068     if (!Overflow) {
1069       bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1070       BinaryOperator *BO = BinaryOperator::CreateUDiv(
1071           X, ConstantInt::get(X->getType(), C2ShlC1));
1072       if (IsExact)
1073         BO->setIsExact();
1074       return BO;
1075     }
1076   }
1077 
1078   // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1079   // TODO: Could use isKnownNegative() to handle non-constant values.
1080   Type *Ty = I.getType();
1081   if (match(Op1, m_Negative())) {
1082     Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1083     return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1084   }
1085   // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1086   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1087     Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1088     return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1089   }
1090 
1091   if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1092     return NarrowDiv;
1093 
1094   // If the udiv operands are non-overflowing multiplies with a common operand,
1095   // then eliminate the common factor:
1096   // (A * B) / (A * X) --> B / X (and commuted variants)
1097   // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1098   // TODO: If -reassociation handled this generally, we could remove this.
1099   Value *A, *B;
1100   if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1101     if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1102         match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1103       return BinaryOperator::CreateUDiv(B, X);
1104     if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1105         match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1106       return BinaryOperator::CreateUDiv(A, X);
1107   }
1108 
1109   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1110   SmallVector<UDivFoldAction, 6> UDivActions;
1111   if (visitUDivOperand(Op0, Op1, I, UDivActions))
1112     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1113       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1114       Value *ActionOp1 = UDivActions[i].OperandToFold;
1115       Instruction *Inst;
1116       if (Action)
1117         Inst = Action(Op0, ActionOp1, I, *this);
1118       else {
1119         // This action joins two actions together.  The RHS of this action is
1120         // simply the last action we processed, we saved the LHS action index in
1121         // the joining action.
1122         size_t SelectRHSIdx = i - 1;
1123         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1124         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1125         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1126         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1127                                   SelectLHS, SelectRHS);
1128       }
1129 
1130       // If this is the last action to process, return it to the InstCombiner.
1131       // Otherwise, we insert it before the UDiv and record it so that we may
1132       // use it as part of a joining action (i.e., a SelectInst).
1133       if (e - i != 1) {
1134         Inst->insertBefore(&I);
1135         UDivActions[i].FoldResult = Inst;
1136       } else
1137         return Inst;
1138     }
1139 
1140   return nullptr;
1141 }
1142 
1143 Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
1144   if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1145                                   SQ.getWithInstruction(&I)))
1146     return replaceInstUsesWith(I, V);
1147 
1148   if (Instruction *X = foldVectorBinop(I))
1149     return X;
1150 
1151   // Handle the integer div common cases
1152   if (Instruction *Common = commonIDivTransforms(I))
1153     return Common;
1154 
1155   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1156   Type *Ty = I.getType();
1157   Value *X;
1158   // sdiv Op0, -1 --> -Op0
1159   // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1160   if (match(Op1, m_AllOnes()) ||
1161       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1162     return BinaryOperator::CreateNeg(Op0);
1163 
1164   // X / INT_MIN --> X == INT_MIN
1165   if (match(Op1, m_SignMask()))
1166     return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1167 
1168   // sdiv exact X,  1<<C  -->    ashr exact X, C   iff  1<<C  is non-negative
1169   // sdiv exact X, -1<<C  -->  -(ashr exact X, C)
1170   if (I.isExact() && ((match(Op1, m_Power2()) && match(Op1, m_NonNegative())) ||
1171                       match(Op1, m_NegatedPower2()))) {
1172     bool DivisorWasNegative = match(Op1, m_NegatedPower2());
1173     if (DivisorWasNegative)
1174       Op1 = ConstantExpr::getNeg(cast<Constant>(Op1));
1175     auto *AShr = BinaryOperator::CreateExactAShr(
1176         Op0, ConstantExpr::getExactLogBase2(cast<Constant>(Op1)), I.getName());
1177     if (!DivisorWasNegative)
1178       return AShr;
1179     Builder.Insert(AShr);
1180     AShr->setName(I.getName() + ".neg");
1181     return BinaryOperator::CreateNeg(AShr, I.getName());
1182   }
1183 
1184   const APInt *Op1C;
1185   if (match(Op1, m_APInt(Op1C))) {
1186     // If the dividend is sign-extended and the constant divisor is small enough
1187     // to fit in the source type, shrink the division to the narrower type:
1188     // (sext X) sdiv C --> sext (X sdiv C)
1189     Value *Op0Src;
1190     if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1191         Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1192 
1193       // In the general case, we need to make sure that the dividend is not the
1194       // minimum signed value because dividing that by -1 is UB. But here, we
1195       // know that the -1 divisor case is already handled above.
1196 
1197       Constant *NarrowDivisor =
1198           ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1199       Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1200       return new SExtInst(NarrowOp, Ty);
1201     }
1202 
1203     // -X / C --> X / -C (if the negation doesn't overflow).
1204     // TODO: This could be enhanced to handle arbitrary vector constants by
1205     //       checking if all elements are not the min-signed-val.
1206     if (!Op1C->isMinSignedValue() &&
1207         match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1208       Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1209       Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1210       BO->setIsExact(I.isExact());
1211       return BO;
1212     }
1213   }
1214 
1215   // -X / Y --> -(X / Y)
1216   Value *Y;
1217   if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1218     return BinaryOperator::CreateNSWNeg(
1219         Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1220 
1221   // abs(X) / X --> X > -1 ? 1 : -1
1222   // X / abs(X) --> X > -1 ? 1 : -1
1223   if (match(&I, m_c_BinOp(
1224                     m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1225                     m_Deferred(X)))) {
1226     Constant *NegOne = ConstantInt::getAllOnesValue(Ty);
1227     Value *Cond = Builder.CreateICmpSGT(X, NegOne);
1228     return SelectInst::Create(Cond, ConstantInt::get(Ty, 1), NegOne);
1229   }
1230 
1231   // If the sign bits of both operands are zero (i.e. we can prove they are
1232   // unsigned inputs), turn this into a udiv.
1233   APInt Mask(APInt::getSignMask(Ty->getScalarSizeInBits()));
1234   if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1235     if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1236       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1237       auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1238       BO->setIsExact(I.isExact());
1239       return BO;
1240     }
1241 
1242     if (match(Op1, m_NegatedPower2())) {
1243       // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1244       //                    -> -(X udiv (1 << C)) -> -(X u>> C)
1245       return BinaryOperator::CreateNeg(Builder.Insert(foldUDivPow2Cst(
1246           Op0, ConstantExpr::getNeg(cast<Constant>(Op1)), I, *this)));
1247     }
1248 
1249     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1250       // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1251       // Safe because the only negative value (1 << Y) can take on is
1252       // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1253       // the sign bit set.
1254       auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1255       BO->setIsExact(I.isExact());
1256       return BO;
1257     }
1258   }
1259 
1260   return nullptr;
1261 }
1262 
1263 /// Remove negation and try to convert division into multiplication.
1264 static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1265   Constant *C;
1266   if (!match(I.getOperand(1), m_Constant(C)))
1267     return nullptr;
1268 
1269   // -X / C --> X / -C
1270   Value *X;
1271   if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1272     return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
1273 
1274   // If the constant divisor has an exact inverse, this is always safe. If not,
1275   // then we can still create a reciprocal if fast-math-flags allow it and the
1276   // constant is a regular number (not zero, infinite, or denormal).
1277   if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1278     return nullptr;
1279 
1280   // Disallow denormal constants because we don't know what would happen
1281   // on all targets.
1282   // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1283   // denorms are flushed?
1284   auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1285   if (!RecipC->isNormalFP())
1286     return nullptr;
1287 
1288   // X / C --> X * (1 / C)
1289   return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1290 }
1291 
1292 /// Remove negation and try to reassociate constant math.
1293 static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
1294   Constant *C;
1295   if (!match(I.getOperand(0), m_Constant(C)))
1296     return nullptr;
1297 
1298   // C / -X --> -C / X
1299   Value *X;
1300   if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1301     return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
1302 
1303   if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1304     return nullptr;
1305 
1306   // Try to reassociate C / X expressions where X includes another constant.
1307   Constant *C2, *NewC = nullptr;
1308   if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1309     // C / (X * C2) --> (C / C2) / X
1310     NewC = ConstantExpr::getFDiv(C, C2);
1311   } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1312     // C / (X / C2) --> (C * C2) / X
1313     NewC = ConstantExpr::getFMul(C, C2);
1314   }
1315   // Disallow denormal constants because we don't know what would happen
1316   // on all targets.
1317   // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1318   // denorms are flushed?
1319   if (!NewC || !NewC->isNormalFP())
1320     return nullptr;
1321 
1322   return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1323 }
1324 
1325 /// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1326 static Instruction *foldFDivPowDivisor(BinaryOperator &I,
1327                                        InstCombiner::BuilderTy &Builder) {
1328   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1329   auto *II = dyn_cast<IntrinsicInst>(Op1);
1330   if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1331       !I.hasAllowReciprocal())
1332     return nullptr;
1333 
1334   // Z / pow(X, Y) --> Z * pow(X, -Y)
1335   // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1336   // In the general case, this creates an extra instruction, but fmul allows
1337   // for better canonicalization and optimization than fdiv.
1338   Intrinsic::ID IID = II->getIntrinsicID();
1339   SmallVector<Value *> Args;
1340   switch (IID) {
1341   case Intrinsic::pow:
1342     Args.push_back(II->getArgOperand(0));
1343     Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1344     break;
1345   case Intrinsic::powi: {
1346     // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1347     // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1348     // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1349     // non-standard results, so this corner case should be acceptable if the
1350     // code rules out INF values.
1351     if (!I.hasNoInfs())
1352       return nullptr;
1353     Args.push_back(II->getArgOperand(0));
1354     Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1355     Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
1356     Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
1357     return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1358   }
1359   case Intrinsic::exp:
1360   case Intrinsic::exp2:
1361     Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1362     break;
1363   default:
1364     return nullptr;
1365   }
1366   Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1367   return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1368 }
1369 
1370 Instruction *InstCombinerImpl::visitFDiv(BinaryOperator &I) {
1371   if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1372                                   I.getFastMathFlags(),
1373                                   SQ.getWithInstruction(&I)))
1374     return replaceInstUsesWith(I, V);
1375 
1376   if (Instruction *X = foldVectorBinop(I))
1377     return X;
1378 
1379   if (Instruction *Phi = foldBinopWithPhiOperands(I))
1380     return Phi;
1381 
1382   if (Instruction *R = foldFDivConstantDivisor(I))
1383     return R;
1384 
1385   if (Instruction *R = foldFDivConstantDividend(I))
1386     return R;
1387 
1388   if (Instruction *R = foldFPSignBitOps(I))
1389     return R;
1390 
1391   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1392   if (isa<Constant>(Op0))
1393     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1394       if (Instruction *R = FoldOpIntoSelect(I, SI))
1395         return R;
1396 
1397   if (isa<Constant>(Op1))
1398     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1399       if (Instruction *R = FoldOpIntoSelect(I, SI))
1400         return R;
1401 
1402   if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1403     Value *X, *Y;
1404     if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1405         (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1406       // (X / Y) / Z => X / (Y * Z)
1407       Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1408       return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1409     }
1410     if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1411         (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1412       // Z / (X / Y) => (Y * Z) / X
1413       Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1414       return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1415     }
1416     // Z / (1.0 / Y) => (Y * Z)
1417     //
1418     // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1419     // m_OneUse check is avoided because even in the case of the multiple uses
1420     // for 1.0/Y, the number of instructions remain the same and a division is
1421     // replaced by a multiplication.
1422     if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1423       return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1424   }
1425 
1426   if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1427     // sin(X) / cos(X) -> tan(X)
1428     // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1429     Value *X;
1430     bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1431                  match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1432     bool IsCot =
1433         !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1434                   match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1435 
1436     if ((IsTan || IsCot) &&
1437         hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) {
1438       IRBuilder<> B(&I);
1439       IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1440       B.setFastMathFlags(I.getFastMathFlags());
1441       AttributeList Attrs =
1442           cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1443       Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1444                                         LibFunc_tanl, B, Attrs);
1445       if (IsCot)
1446         Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1447       return replaceInstUsesWith(I, Res);
1448     }
1449   }
1450 
1451   // X / (X * Y) --> 1.0 / Y
1452   // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1453   // We can ignore the possibility that X is infinity because INF/INF is NaN.
1454   Value *X, *Y;
1455   if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1456       match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1457     replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1458     replaceOperand(I, 1, Y);
1459     return &I;
1460   }
1461 
1462   // X / fabs(X) -> copysign(1.0, X)
1463   // fabs(X) / X -> copysign(1.0, X)
1464   if (I.hasNoNaNs() && I.hasNoInfs() &&
1465       (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1466        match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1467     Value *V = Builder.CreateBinaryIntrinsic(
1468         Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1469     return replaceInstUsesWith(I, V);
1470   }
1471 
1472   if (Instruction *Mul = foldFDivPowDivisor(I, Builder))
1473     return Mul;
1474 
1475   return nullptr;
1476 }
1477 
1478 /// This function implements the transforms common to both integer remainder
1479 /// instructions (urem and srem). It is called by the visitors to those integer
1480 /// remainder instructions.
1481 /// Common integer remainder transforms
1482 Instruction *InstCombinerImpl::commonIRemTransforms(BinaryOperator &I) {
1483   if (Instruction *Phi = foldBinopWithPhiOperands(I))
1484     return Phi;
1485 
1486   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1487 
1488   // The RHS is known non-zero.
1489   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1490     return replaceOperand(I, 1, V);
1491 
1492   // Handle cases involving: rem X, (select Cond, Y, Z)
1493   if (simplifyDivRemOfSelectWithZeroOp(I))
1494     return &I;
1495 
1496   // If the divisor is a select-of-constants, try to constant fold all rem ops:
1497   // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC)
1498   // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1499   if (match(Op0, m_ImmConstant()) &&
1500       match(Op1, m_Select(m_Value(), m_ImmConstant(), m_ImmConstant()))) {
1501     if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1)))
1502       return R;
1503   }
1504 
1505   if (isa<Constant>(Op1)) {
1506     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1507       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1508         if (Instruction *R = FoldOpIntoSelect(I, SI))
1509           return R;
1510       } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1511         const APInt *Op1Int;
1512         if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1513             (I.getOpcode() == Instruction::URem ||
1514              !Op1Int->isMinSignedValue())) {
1515           // foldOpIntoPhi will speculate instructions to the end of the PHI's
1516           // predecessor blocks, so do this only if we know the srem or urem
1517           // will not fault.
1518           if (Instruction *NV = foldOpIntoPhi(I, PN))
1519             return NV;
1520         }
1521       }
1522 
1523       // See if we can fold away this rem instruction.
1524       if (SimplifyDemandedInstructionBits(I))
1525         return &I;
1526     }
1527   }
1528 
1529   return nullptr;
1530 }
1531 
1532 Instruction *InstCombinerImpl::visitURem(BinaryOperator &I) {
1533   if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1534                                   SQ.getWithInstruction(&I)))
1535     return replaceInstUsesWith(I, V);
1536 
1537   if (Instruction *X = foldVectorBinop(I))
1538     return X;
1539 
1540   if (Instruction *common = commonIRemTransforms(I))
1541     return common;
1542 
1543   if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1544     return NarrowRem;
1545 
1546   // X urem Y -> X and Y-1, where Y is a power of 2,
1547   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1548   Type *Ty = I.getType();
1549   if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1550     // This may increase instruction count, we don't enforce that Y is a
1551     // constant.
1552     Constant *N1 = Constant::getAllOnesValue(Ty);
1553     Value *Add = Builder.CreateAdd(Op1, N1);
1554     return BinaryOperator::CreateAnd(Op0, Add);
1555   }
1556 
1557   // 1 urem X -> zext(X != 1)
1558   if (match(Op0, m_One())) {
1559     Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1560     return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1561   }
1562 
1563   // X urem C -> X < C ? X : X - C, where C >= signbit.
1564   if (match(Op1, m_Negative())) {
1565     Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1566     Value *Sub = Builder.CreateSub(Op0, Op1);
1567     return SelectInst::Create(Cmp, Op0, Sub);
1568   }
1569 
1570   // If the divisor is a sext of a boolean, then the divisor must be max
1571   // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1572   // max unsigned value. In that case, the remainder is 0:
1573   // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1574   Value *X;
1575   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1576     Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1577     return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1578   }
1579 
1580   return nullptr;
1581 }
1582 
1583 Instruction *InstCombinerImpl::visitSRem(BinaryOperator &I) {
1584   if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1585                                   SQ.getWithInstruction(&I)))
1586     return replaceInstUsesWith(I, V);
1587 
1588   if (Instruction *X = foldVectorBinop(I))
1589     return X;
1590 
1591   // Handle the integer rem common cases
1592   if (Instruction *Common = commonIRemTransforms(I))
1593     return Common;
1594 
1595   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1596   {
1597     const APInt *Y;
1598     // X % -Y -> X % Y
1599     if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1600       return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
1601   }
1602 
1603   // -X srem Y --> -(X srem Y)
1604   Value *X, *Y;
1605   if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1606     return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
1607 
1608   // If the sign bits of both operands are zero (i.e. we can prove they are
1609   // unsigned inputs), turn this into a urem.
1610   APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1611   if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1612       MaskedValueIsZero(Op0, Mask, 0, &I)) {
1613     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1614     return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1615   }
1616 
1617   // If it's a constant vector, flip any negative values positive.
1618   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1619     Constant *C = cast<Constant>(Op1);
1620     unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
1621 
1622     bool hasNegative = false;
1623     bool hasMissing = false;
1624     for (unsigned i = 0; i != VWidth; ++i) {
1625       Constant *Elt = C->getAggregateElement(i);
1626       if (!Elt) {
1627         hasMissing = true;
1628         break;
1629       }
1630 
1631       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1632         if (RHS->isNegative())
1633           hasNegative = true;
1634     }
1635 
1636     if (hasNegative && !hasMissing) {
1637       SmallVector<Constant *, 16> Elts(VWidth);
1638       for (unsigned i = 0; i != VWidth; ++i) {
1639         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
1640         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1641           if (RHS->isNegative())
1642             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1643         }
1644       }
1645 
1646       Constant *NewRHSV = ConstantVector::get(Elts);
1647       if (NewRHSV != C)  // Don't loop on -MININT
1648         return replaceOperand(I, 1, NewRHSV);
1649     }
1650   }
1651 
1652   return nullptr;
1653 }
1654 
1655 Instruction *InstCombinerImpl::visitFRem(BinaryOperator &I) {
1656   if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1657                                   I.getFastMathFlags(),
1658                                   SQ.getWithInstruction(&I)))
1659     return replaceInstUsesWith(I, V);
1660 
1661   if (Instruction *X = foldVectorBinop(I))
1662     return X;
1663 
1664   if (Instruction *Phi = foldBinopWithPhiOperands(I))
1665     return Phi;
1666 
1667   return nullptr;
1668 }
1669