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