blob: 4290d8db9898d4ffdb1d0f8cf866594cf1ff49f0 [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- 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
Chandler Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner7c99f192011-05-22 18:18:41 +000024
Sanjay Patel6eccf482015-09-09 15:24:36 +000025/// The specific integer value is used in a context where it is known to be
26/// non-zero. If this allows us to simplify the computation, do so and return
27/// the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000028static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000029 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000030 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
32 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000033 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner388cb8a2011-05-23 00:32:19 +000035 bool MadeChange = false;
36
Chris Lattner7c99f192011-05-22 18:18:41 +000037 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000039 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +000042 A = IC.Builder.CreateSub(A, B);
43 return IC.Builder.CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000044 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045
Chris Lattner388cb8a2011-05-23 00:32:19 +000046 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000048 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
49 if (I && I->isLogicalShift() &&
Craig Topperd4039f72017-05-25 21:51:12 +000050 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000051 // We know that this is an exact/nuw shift and that the input is a
52 // non-zero context as well.
53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
54 I->setOperand(0, V2);
55 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 }
57
Sanjay Patela8ef4a52016-05-22 17:08:52 +000058 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
59 I->setIsExact();
60 MadeChange = true;
61 }
62
63 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
64 I->setHasNoUnsignedWrap();
65 MadeChange = true;
66 }
67 }
68
Chris Lattner162dfc32011-05-22 18:26:48 +000069 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000070 // If V is a phi node, we can call this on each of its operands.
71 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072
Craig Topperf40110f2014-04-25 05:29:35 +000073 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000074}
75
76
Sanjay Patel6eccf482015-09-09 15:24:36 +000077/// True if the multiply can not be expressed in an int this size.
David Majnemer27adb122014-10-12 08:34:24 +000078static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
79 bool IsSigned) {
80 bool Overflow;
81 if (IsSigned)
82 Product = C1.smul_ov(C2, Overflow);
83 else
84 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000085
David Majnemer27adb122014-10-12 08:34:24 +000086 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000087}
88
David Majnemerf9a095d2014-08-16 08:55:06 +000089/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
90static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
91 bool IsSigned) {
92 assert(C1.getBitWidth() == C2.getBitWidth() &&
93 "Inconsistent width of constants!");
94
David Majnemer135ca402015-09-06 06:49:59 +000095 // Bail if we will divide by zero.
96 if (C2.isMinValue())
97 return false;
98
99 // Bail if we would divide INT_MIN by -1.
100 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
101 return false;
102
David Majnemerf9a095d2014-08-16 08:55:06 +0000103 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
104 if (IsSigned)
105 APInt::sdivrem(C1, C2, Quotient, Remainder);
106 else
107 APInt::udivrem(C1, C2, Quotient, Remainder);
108
109 return Remainder.isMinValue();
110}
111
Rafael Espindola65281bf2013-05-31 14:27:15 +0000112/// \brief A helper routine of InstCombiner::visitMul().
113///
114/// If C is a vector of known powers of 2, then this function returns
115/// a new vector obtained from C replacing each element with its logBase2.
116/// Return a null pointer otherwise.
117static Constant *getLogBase2Vector(ConstantDataVector *CV) {
118 const APInt *IVal;
119 SmallVector<Constant *, 4> Elts;
120
121 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
122 Constant *Elt = CV->getElementAsConstant(I);
123 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000124 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000125 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
126 }
127
128 return ConstantVector::get(Elts);
129}
130
David Majnemer54c2ca22014-12-26 09:10:14 +0000131/// \brief Return true if we can prove that:
132/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000133bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
134 const Value *RHS,
135 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000136 // Multiplying n * m significant bits yields a result of n + m significant
137 // bits. If the total number of significant bits does not exceed the
138 // result bit width (minus 1), there is no overflow.
139 // This means if we have enough leading sign bits in the operands
140 // we can guarantee that the result does not overflow.
141 // Ref: "Hacker's Delight" by Henry Warren
142 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
143
144 // Note that underestimating the number of sign bits gives a more
145 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000146 unsigned SignBits =
147 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000148
149 // First handle the easy case: if we have enough sign bits there's
150 // definitely no overflow.
151 if (SignBits > BitWidth + 1)
152 return true;
153
154 // There are two ambiguous cases where there can be no overflow:
155 // SignBits == BitWidth + 1 and
156 // SignBits == BitWidth
157 // The second case is difficult to check, therefore we only handle the
158 // first case.
159 if (SignBits == BitWidth + 1) {
160 // It overflows only when both arguments are negative and the true
161 // product is exactly the minimum negative number.
162 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
163 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000164 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
165 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
166 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000167 return true;
168 }
169 return false;
170}
171
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000172Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000173 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000174 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
175
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000176 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000177 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000178
Craig Toppera4205622017-06-09 03:21:29 +0000179 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000180 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000181
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000182 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000183 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000184
David Majnemer027bc802014-11-22 04:52:38 +0000185 // X * -1 == 0 - X
186 if (match(Op1, m_AllOnes())) {
187 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
188 if (I.hasNoSignedWrap())
189 BO->setHasNoSignedWrap();
190 return BO;
191 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000192
Rafael Espindola65281bf2013-05-31 14:27:15 +0000193 // Also allow combining multiply instructions on vectors.
194 {
195 Value *NewOp;
196 Constant *C1, *C2;
197 const APInt *IVal;
198 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
199 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000200 match(C1, m_APInt(IVal))) {
201 // ((X << C2)*C1) == (X * (C1 << C2))
202 Constant *Shl = ConstantExpr::getShl(C1, C2);
203 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
204 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
205 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
206 BO->setHasNoUnsignedWrap();
207 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
208 Shl->isNotMinSignedValue())
209 BO->setHasNoSignedWrap();
210 return BO;
211 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000212
Rafael Espindola65281bf2013-05-31 14:27:15 +0000213 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000214 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000215 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
216 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
217 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
218 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
219 // Replace X*(2^C) with X << C, where C is a vector of known
220 // constant powers of 2.
221 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000222
Rafael Espindola65281bf2013-05-31 14:27:15 +0000223 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000224 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000225 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000226
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000227 if (I.hasNoUnsignedWrap())
228 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000229 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000230 const APInt *V;
231 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000232 Shl->setHasNoSignedWrap();
233 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000234
Rafael Espindola65281bf2013-05-31 14:27:15 +0000235 return Shl;
236 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000237 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000238 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000239
Rafael Espindola65281bf2013-05-31 14:27:15 +0000240 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000241 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
242 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
243 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000244 {
245 const APInt & Val = CI->getValue();
246 const APInt &PosVal = Val.abs();
247 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000248 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000249 if (Op0->hasOneUse()) {
250 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000251 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000252 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000253 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000254 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000255 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000256 if (Sub)
257 return
258 BinaryOperator::CreateMul(Sub,
259 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000260 }
261 }
262 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000263 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000264
Chris Lattner6b657ae2011-02-10 05:36:31 +0000265 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000266 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000267 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
268 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000269
270 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
271 {
272 Value *X;
273 Constant *C1;
274 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000275 Value *Mul = Builder.CreateMul(C1, Op1);
David Majnemer6cf6c052014-06-19 07:14:33 +0000276 // Only go forward with the transform if C1*CI simplifies to a tidier
277 // constant.
278 if (!match(Mul, m_Mul(m_Value(), m_Value())))
Craig Topperbb4069e2017-07-07 23:16:26 +0000279 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000280 }
281 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000282 }
283
David Majnemer8279a7502014-11-22 07:25:19 +0000284 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
285 if (Value *Op1v = dyn_castNegVal(Op1)) {
286 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
287 if (I.hasNoSignedWrap() &&
288 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
289 match(Op1, m_NSWSub(m_Value(), m_Value())))
290 BO->setHasNoSignedWrap();
291 return BO;
292 }
293 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000294
295 // (X / Y) * Y = X - (X % Y)
296 // (X / Y) * -Y = (X % Y) - X
297 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000298 Value *Y = Op1;
299 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
300 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
301 Div->getOpcode() != Instruction::SDiv)) {
302 Y = Op0;
303 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000304 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000305 Value *Neg = dyn_castNegVal(Y);
306 if (Div && Div->hasOneUse() &&
307 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
308 (Div->getOpcode() == Instruction::UDiv ||
309 Div->getOpcode() == Instruction::SDiv)) {
310 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000311
Chris Lattner35315d02011-02-06 21:44:57 +0000312 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000313 if (Div->isExact()) {
314 if (DivOp1 == Y)
315 return replaceInstUsesWith(I, X);
316 return BinaryOperator::CreateNeg(X);
317 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000318
Sanjay Patela0a56822017-03-14 17:27:27 +0000319 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
320 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000321 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000322 if (DivOp1 == Y)
323 return BinaryOperator::CreateSub(X, Rem);
324 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000325 }
326 }
327
328 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000329 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000330 return BinaryOperator::CreateAnd(Op0, Op1);
331
332 // X*(1 << Y) --> X << Y
333 // (1 << Y)*X --> X << Y
334 {
335 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000336 BinaryOperator *BO = nullptr;
337 bool ShlNSW = false;
338 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
339 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000340 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000341 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000342 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000343 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000344 }
345 if (BO) {
346 if (I.hasNoUnsignedWrap())
347 BO->setHasNoUnsignedWrap();
348 if (I.hasNoSignedWrap() && ShlNSW)
349 BO->setHasNoSignedWrap();
350 return BO;
351 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000352 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000353
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000354 // If one of the operands of the multiply is a cast from a boolean value, then
355 // we know the bool is either zero or one, so this is a 'masking' multiply.
356 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000357 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000358 // -2 is "-1 << 1" so it is all bits set except the low one.
359 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000360
Craig Topperf40110f2014-04-25 05:29:35 +0000361 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000362 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
363 BoolCast = Op0;
364 OtherOp = Op1;
365 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
366 BoolCast = Op1;
367 OtherOp = Op0;
368 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000369
370 if (BoolCast) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000371 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000372 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000373 return BinaryOperator::CreateAnd(V, OtherOp);
374 }
375 }
376
David Majnemera1cfd7c2016-12-30 00:28:58 +0000377 // Check for (mul (sext x), y), see if we can merge this into an
378 // integer mul followed by a sext.
379 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
380 // (mul (sext x), cst) --> (sext (mul x, cst'))
381 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
382 if (Op0Conv->hasOneUse()) {
383 Constant *CI =
384 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
385 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000386 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000387 // Insert the new, smaller mul.
388 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000389 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000390 return new SExtInst(NewMul, I.getType());
391 }
392 }
393 }
394
395 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
396 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
397 // Only do this if x/y have the same type, if at last one of them has a
398 // single use (so we don't increase the number of sexts), and if the
399 // integer mul will not overflow.
400 if (Op0Conv->getOperand(0)->getType() ==
401 Op1Conv->getOperand(0)->getType() &&
402 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000403 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000404 Op1Conv->getOperand(0), I)) {
405 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000406 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000407 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
408 return new SExtInst(NewMul, I.getType());
409 }
410 }
411 }
412
413 // Check for (mul (zext x), y), see if we can merge this into an
414 // integer mul followed by a zext.
415 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
416 // (mul (zext x), cst) --> (zext (mul x, cst'))
417 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
418 if (Op0Conv->hasOneUse()) {
419 Constant *CI =
420 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
421 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000422 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000423 // Insert the new, smaller mul.
424 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000425 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000426 return new ZExtInst(NewMul, I.getType());
427 }
428 }
429 }
430
431 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
432 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
433 // Only do this if x/y have the same type, if at last one of them has a
434 // single use (so we don't increase the number of zexts), and if the
435 // integer mul will not overflow.
436 if (Op0Conv->getOperand(0)->getType() ==
437 Op1Conv->getOperand(0)->getType() &&
438 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000439 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
440 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000441 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000442 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000443 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
444 return new ZExtInst(NewMul, I.getType());
445 }
446 }
447 }
448
Craig Topper2b1fc322017-05-22 06:25:31 +0000449 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000450 Changed = true;
451 I.setHasNoSignedWrap(true);
452 }
453
Craig Topperbb973722017-05-15 02:44:08 +0000454 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000455 Changed = true;
456 I.setHasNoUnsignedWrap(true);
457 }
458
Craig Topperf40110f2014-04-25 05:29:35 +0000459 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000460}
461
Sanjay Patel17045f72014-10-14 00:33:23 +0000462/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000463static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000464 if (!Op->hasOneUse())
465 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000466
Sanjay Patel17045f72014-10-14 00:33:23 +0000467 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
468 if (!II)
469 return;
470 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
471 return;
472 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000473
Sanjay Patel17045f72014-10-14 00:33:23 +0000474 Value *OpLog2Of = II->getArgOperand(0);
475 if (!OpLog2Of->hasOneUse())
476 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000477
Sanjay Patel17045f72014-10-14 00:33:23 +0000478 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
479 if (!I)
480 return;
481 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
482 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000483
Sanjay Patel17045f72014-10-14 00:33:23 +0000484 if (match(I->getOperand(0), m_SpecificFP(0.5)))
485 Y = I->getOperand(1);
486 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
487 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000488}
Pedro Artigas993acd02012-11-30 22:07:05 +0000489
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000490static bool isFiniteNonZeroFp(Constant *C) {
491 if (C->getType()->isVectorTy()) {
492 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
493 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000494 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000495 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
496 return false;
497 }
498 return true;
499 }
500
501 return isa<ConstantFP>(C) &&
502 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
503}
504
505static bool isNormalFp(Constant *C) {
506 if (C->getType()->isVectorTy()) {
507 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
508 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000509 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000510 if (!CFP || !CFP->getValueAPF().isNormal())
511 return false;
512 }
513 return true;
514 }
515
516 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
517}
518
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000519/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
520/// true iff the given value is FMul or FDiv with one and only one operand
521/// being a normal constant (i.e. not Zero/NaN/Infinity).
522static bool isFMulOrFDivWithConstant(Value *V) {
523 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000524 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000525 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000526 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000527
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000528 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
529 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000530
531 if (C0 && C1)
532 return false;
533
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000534 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000535}
536
537/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
538/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
539/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000540/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000541/// resulting expression. Note that this function could return NULL in
542/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000543///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000544Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000545 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000546 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
547
548 Value *Opnd0 = FMulOrDiv->getOperand(0);
549 Value *Opnd1 = FMulOrDiv->getOperand(1);
550
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000551 Constant *C0 = dyn_cast<Constant>(Opnd0);
552 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553
Craig Topperf40110f2014-04-25 05:29:35 +0000554 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000555
556 // (X * C0) * C => X * (C0*C)
557 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
558 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000559 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000560 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
561 } else {
562 if (C0) {
563 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000564 if (FMulOrDiv->hasOneUse()) {
565 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000566 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000567 if (isNormalFp(F))
568 R = BinaryOperator::CreateFDiv(F, Opnd1);
569 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000570 } else {
571 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000572 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000573 if (isNormalFp(F)) {
574 R = BinaryOperator::CreateFMul(Opnd0, F);
575 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000576 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000577 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000578 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000579 R = BinaryOperator::CreateFDiv(Opnd0, F);
580 }
581 }
582 }
583
584 if (R) {
585 R->setHasUnsafeAlgebra(true);
586 InsertNewInstWith(R, *InsertBefore);
587 }
588
589 return R;
590}
591
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000592Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000593 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
595
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000596 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000597 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000598
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000599 if (isa<Constant>(Op0))
600 std::swap(Op0, Op1);
601
Craig Toppera4205622017-06-09 03:21:29 +0000602 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
603 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000604 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000605
Shuxin Yange8227452013-01-15 21:09:32 +0000606 bool AllowReassociate = I.hasUnsafeAlgebra();
607
Michael Ilsemand5787be2012-12-12 00:28:32 +0000608 // Simplify mul instructions with a constant RHS.
609 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000610 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
611 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000612
Owen Andersonf74cfe02014-01-16 20:36:42 +0000613 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000614 if (match(Op1, m_SpecificFP(-1.0))) {
615 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
616 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000617 RI->copyFastMathFlags(&I);
618 return RI;
619 }
620
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000621 Constant *C = cast<Constant>(Op1);
622 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000623 // Let MDC denote an expression in one of these forms:
624 // X * C, C/X, X/C, where C is a constant.
625 //
626 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000627 if (isFMulOrFDivWithConstant(Op0))
628 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000629 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000630
Quentin Colombete684a6d2013-02-28 21:12:40 +0000631 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000632 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
633 if (FAddSub &&
634 (FAddSub->getOpcode() == Instruction::FAdd ||
635 FAddSub->getOpcode() == Instruction::FSub)) {
636 Value *Opnd0 = FAddSub->getOperand(0);
637 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000638 Constant *C0 = dyn_cast<Constant>(Opnd0);
639 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000640 bool Swap = false;
641 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000642 std::swap(C0, C1);
643 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000644 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000645 }
646
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000647 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000648 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000649 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000650 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000651 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000652 if (M0 && M1) {
653 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
654 std::swap(M0, M1);
655
Benjamin Kramer67485762013-09-30 15:39:59 +0000656 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
657 ? BinaryOperator::CreateFAdd(M0, M1)
658 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000659 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000660 return RI;
661 }
662 }
663 }
664 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000665 }
666
Matt Arsenault56c079f2016-01-30 05:02:00 +0000667 if (Op0 == Op1) {
668 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
669 // sqrt(X) * sqrt(X) -> X
670 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000671 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000672
Matt Arsenault56c079f2016-01-30 05:02:00 +0000673 // fabs(X) * fabs(X) -> X * X
674 if (II->getIntrinsicID() == Intrinsic::fabs) {
675 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
676 II->getOperand(0),
677 I.getName());
678 FMulVal->copyFastMathFlags(&I);
679 return FMulVal;
680 }
681 }
682 }
683
Pedro Artigasd8795042012-11-30 19:09:41 +0000684 // Under unsafe algebra do:
685 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000686 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000687 Value *OpX = nullptr;
688 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000689 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000690 detectLog2OfHalf(Op0, OpY, Log2);
691 if (OpY) {
692 OpX = Op1;
693 } else {
694 detectLog2OfHalf(Op1, OpY, Log2);
695 if (OpY) {
696 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000697 }
698 }
699 // if pattern detected emit alternate sequence
700 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000701 BuilderTy::FastMathFlagGuard Guard(Builder);
702 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000703 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000704 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
705 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000706 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000707 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000708 }
709 }
710
Shuxin Yange8227452013-01-15 21:09:32 +0000711 // Handle symmetric situation in a 2-iteration loop
712 Value *Opnd0 = Op0;
713 Value *Opnd1 = Op1;
714 for (int i = 0; i < 2; i++) {
715 bool IgnoreZeroSign = I.hasNoSignedZeros();
716 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000717 BuilderTy::FastMathFlagGuard Guard(Builder);
718 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000719
Shuxin Yange8227452013-01-15 21:09:32 +0000720 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
721 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000722
Shuxin Yange8227452013-01-15 21:09:32 +0000723 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000724 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000725 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000726 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000727 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000728 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000729
Shuxin Yange8227452013-01-15 21:09:32 +0000730 if (Opnd0->hasOneUse()) {
731 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000732 Value *T = Builder.CreateFMul(N0, Opnd1);
733 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000734 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000735 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000736 }
737 }
Shuxin Yange8227452013-01-15 21:09:32 +0000738
Quentin Colombetaa103b32017-09-20 17:32:16 +0000739 // Handle specials cases for FMul with selects feeding the operation
740 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
741 return replaceInstUsesWith(I, V);
742
Shuxin Yange8227452013-01-15 21:09:32 +0000743 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000744 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000745 // 1) to form a power expression (of X).
746 // 2) potentially shorten the critical path: After transformation, the
747 // latency of the instruction Y is amortized by the expression of X*X,
748 // and therefore Y is in a "less critical" position compared to what it
749 // was before the transformation.
750 //
751 if (AllowReassociate) {
752 Value *Opnd0_0, *Opnd0_1;
753 if (Opnd0->hasOneUse() &&
754 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000755 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000756 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
757 Y = Opnd0_1;
758 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
759 Y = Opnd0_0;
760
761 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000762 BuilderTy::FastMathFlagGuard Guard(Builder);
763 Builder.setFastMathFlags(I.getFastMathFlags());
764 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
765 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000766 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000767 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000768 }
769 }
770 }
771
772 if (!isa<Constant>(Op1))
773 std::swap(Opnd0, Opnd1);
774 else
775 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000776 }
777
Craig Topperf40110f2014-04-25 05:29:35 +0000778 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000779}
780
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000781/// Fold a divide or remainder with a select instruction divisor when one of the
782/// select operands is zero. In that case, we can use the other select operand
783/// because div/rem by zero is undefined.
784bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
785 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
786 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000787 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000788
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000789 int NonNullOperand;
790 if (match(SI->getTrueValue(), m_Zero()))
791 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
792 NonNullOperand = 2;
793 else if (match(SI->getFalseValue(), m_Zero()))
794 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
795 NonNullOperand = 1;
796 else
797 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000798
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000799 // Change the div/rem to use 'Y' instead of the select.
800 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000801
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000802 // Okay, we know we replace the operand of the div/rem with 'Y' with no
803 // problem. However, the select, or the condition of the select may have
804 // multiple uses. Based on our knowledge that the operand must be non-zero,
805 // propagate the known value for the select into other uses of it, and
806 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000807
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000808 // If the select and condition only have a single use, don't bother with this,
809 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000810 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000811 if (SI->use_empty() && SelectCond->hasOneUse())
812 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000813
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000814 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000815 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000816
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000817 while (BBI != BBFront) {
818 --BBI;
819 // If we found a call to a function, we can't assume it will return, so
820 // information from below it cannot be propagated above it.
821 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
822 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000823
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000824 // Replace uses of the select or its condition with the known values.
825 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
826 I != E; ++I) {
827 if (*I == SI) {
828 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000829 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000830 } else if (*I == SelectCond) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000831 *I = Builder.getInt1(NonNullOperand == 1);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000832 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000833 }
834 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000835
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000836 // If we past the instruction, quit looking for it.
837 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000838 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000839 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000840 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000841
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000842 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000843 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000844 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000845
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000846 }
847 return true;
848}
849
850
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000851/// This function implements the transforms common to both integer division
852/// instructions (udiv and sdiv). It is called by the visitors to those integer
853/// division instructions.
854/// @brief Common integer divide transforms
855Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
856 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
857
Chris Lattner7c99f192011-05-22 18:18:41 +0000858 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000859 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000860 I.setOperand(1, V);
861 return &I;
862 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000863
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000864 // Handle cases involving: [su]div X, (select Cond, Y, Z)
865 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000866 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000867 return &I;
868
David Majnemer27adb122014-10-12 08:34:24 +0000869 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
870 const APInt *C2;
871 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000872 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000873 const APInt *C1;
874 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000875
David Majnemer27adb122014-10-12 08:34:24 +0000876 // (X / C1) / C2 -> X / (C1*C2)
877 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
878 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
879 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
880 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
881 return BinaryOperator::Create(I.getOpcode(), X,
882 ConstantInt::get(I.getType(), Product));
883 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000884
David Majnemer27adb122014-10-12 08:34:24 +0000885 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
886 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
887 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
888
889 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
890 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
891 BinaryOperator *BO = BinaryOperator::Create(
892 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
893 BO->setIsExact(I.isExact());
894 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000895 }
896
David Majnemer27adb122014-10-12 08:34:24 +0000897 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
898 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
899 BinaryOperator *BO = BinaryOperator::Create(
900 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
901 BO->setHasNoUnsignedWrap(
902 !IsSigned &&
903 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
904 BO->setHasNoSignedWrap(
905 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
906 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000907 }
908 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000909
David Majnemer27adb122014-10-12 08:34:24 +0000910 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
911 *C1 != C1->getBitWidth() - 1) ||
912 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
913 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
914 APInt C1Shifted = APInt::getOneBitSet(
915 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
916
917 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
918 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
919 BinaryOperator *BO = BinaryOperator::Create(
920 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
921 BO->setIsExact(I.isExact());
922 return BO;
923 }
924
925 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
926 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
927 BinaryOperator *BO = BinaryOperator::Create(
928 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
929 BO->setHasNoUnsignedWrap(
930 !IsSigned &&
931 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
932 BO->setHasNoSignedWrap(
933 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
934 return BO;
935 }
936 }
937
Craig Topper73ba1c82017-06-07 07:40:37 +0000938 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000939 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
940 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000941 }
942 }
943
Craig Topper218a3592017-04-17 03:41:47 +0000944 if (match(Op0, m_One())) {
Craig Topperfde47232017-07-09 07:04:03 +0000945 assert(!I.getType()->isIntOrIntVectorTy(1) && "i1 divide not removed?");
Craig Topper218a3592017-04-17 03:41:47 +0000946 if (I.getOpcode() == Instruction::SDiv) {
947 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
948 // result is one, if Op1 is -1 then the result is minus one, otherwise
949 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000950 Value *Inc = Builder.CreateAdd(Op1, Op0);
951 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(I.getType(), 3));
Craig Topper218a3592017-04-17 03:41:47 +0000952 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
953 } else {
954 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
955 // result is one, otherwise it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000956 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), I.getType());
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000957 }
958 }
959
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000960 // See if we can fold away this div instruction.
961 if (SimplifyDemandedInstructionBits(I))
962 return &I;
963
Duncan Sands771e82a2011-01-28 16:51:11 +0000964 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000965 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000966 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
967 bool isSigned = I.getOpcode() == Instruction::SDiv;
968 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
969 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
970 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000971 }
972
Craig Topperf40110f2014-04-25 05:29:35 +0000973 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000974}
975
David Majnemer37f8f442013-07-04 21:17:49 +0000976namespace {
977const unsigned MaxDepth = 6;
978typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
979 const BinaryOperator &I,
980 InstCombiner &IC);
981
982/// \brief Used to maintain state for visitUDivOperand().
983struct UDivFoldAction {
984 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
985 ///< operand. This can be zero if this action
986 ///< joins two actions together.
987
988 Value *OperandToFold; ///< Which operand to fold.
989 union {
990 Instruction *FoldResult; ///< The instruction returned when FoldAction is
991 ///< invoked.
992
993 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
994 ///< joins two actions together.
995 };
996
997 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000998 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000999 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1000 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1001};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001002}
David Majnemer37f8f442013-07-04 21:17:49 +00001003
1004// X udiv 2^C -> X >> C
1005static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1006 const BinaryOperator &I, InstCombiner &IC) {
1007 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1008 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1009 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001010 if (I.isExact())
1011 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001012 return LShr;
1013}
1014
1015// X udiv C, where C >= signbit
1016static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1017 const BinaryOperator &I, InstCombiner &IC) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001018 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<ConstantInt>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001019
1020 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1021 ConstantInt::get(I.getType(), 1));
1022}
1023
1024// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001025// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001026static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1027 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001028 Value *ShiftLeft;
1029 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1030 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001031
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001032 const APInt *CI;
1033 Value *N;
1034 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1035 llvm_unreachable("match should never fail here!");
1036 if (*CI != 1)
Craig Topperbb4069e2017-07-07 23:16:26 +00001037 N = IC.Builder.CreateAdd(N, ConstantInt::get(N->getType(), CI->logBase2()));
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001038 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001039 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001040 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001041 if (I.isExact())
1042 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001043 return LShr;
1044}
1045
1046// \brief Recursively visits the possible right hand operands of a udiv
1047// instruction, seeing through select instructions, to determine if we can
1048// replace the udiv with something simpler. If we find that an operand is not
1049// able to simplify the udiv, we abort the entire transformation.
1050static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1051 SmallVectorImpl<UDivFoldAction> &Actions,
1052 unsigned Depth = 0) {
1053 // Check to see if this is an unsigned division with an exact power of 2,
1054 // if so, convert to a right shift.
1055 if (match(Op1, m_Power2())) {
1056 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1057 return Actions.size();
1058 }
1059
1060 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1061 // X udiv C, where C >= signbit
1062 if (C->getValue().isNegative()) {
1063 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1064 return Actions.size();
1065 }
1066
1067 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1068 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1069 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1070 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1071 return Actions.size();
1072 }
1073
1074 // The remaining tests are all recursive, so bail out if we hit the limit.
1075 if (Depth++ == MaxDepth)
1076 return 0;
1077
1078 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001079 if (size_t LHSIdx =
1080 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1081 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1082 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001083 return Actions.size();
1084 }
1085
1086 return 0;
1087}
1088
Sanjay Patelbb789382017-08-24 22:54:01 +00001089/// If we have zero-extended operands of an unsigned div or rem, we may be able
1090/// to narrow the operation (sink the zext below the math).
1091static Instruction *narrowUDivURem(BinaryOperator &I,
1092 InstCombiner::BuilderTy &Builder) {
1093 Instruction::BinaryOps Opcode = I.getOpcode();
1094 Value *N = I.getOperand(0);
1095 Value *D = I.getOperand(1);
1096 Type *Ty = I.getType();
1097 Value *X, *Y;
1098 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1099 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1100 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1101 // urem (zext X), (zext Y) --> zext (urem X, Y)
1102 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1103 return new ZExtInst(NarrowOp, Ty);
1104 }
1105
1106 Constant *C;
1107 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1108 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1109 // If the constant is the same in the smaller type, use the narrow version.
1110 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1111 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1112 return nullptr;
1113
1114 // udiv (zext X), C --> zext (udiv X, C')
1115 // urem (zext X), C --> zext (urem X, C')
1116 // udiv C, (zext X) --> zext (udiv C', X)
1117 // urem C, (zext X) --> zext (urem C', X)
1118 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1119 : Builder.CreateBinOp(Opcode, TruncC, X);
1120 return new ZExtInst(NarrowOp, Ty);
1121 }
1122
1123 return nullptr;
1124}
1125
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001126Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1127 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1128
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001129 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001130 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001131
Craig Toppera4205622017-06-09 03:21:29 +00001132 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001133 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001134
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001135 // Handle the integer div common cases
1136 if (Instruction *Common = commonIDivTransforms(I))
1137 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001138
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001139 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001140 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001141 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001142 const APInt *C1, *C2;
1143 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1144 match(Op1, m_APInt(C2))) {
1145 bool Overflow;
1146 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001147 if (!Overflow) {
1148 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1149 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001150 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001151 if (IsExact)
1152 BO->setIsExact();
1153 return BO;
1154 }
David Majnemera2521382014-10-13 21:48:30 +00001155 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001156 }
1157
Sanjay Patelbb789382017-08-24 22:54:01 +00001158 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1159 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001160
David Majnemer37f8f442013-07-04 21:17:49 +00001161 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1162 SmallVector<UDivFoldAction, 6> UDivActions;
1163 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1164 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1165 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1166 Value *ActionOp1 = UDivActions[i].OperandToFold;
1167 Instruction *Inst;
1168 if (Action)
1169 Inst = Action(Op0, ActionOp1, I, *this);
1170 else {
1171 // This action joins two actions together. The RHS of this action is
1172 // simply the last action we processed, we saved the LHS action index in
1173 // the joining action.
1174 size_t SelectRHSIdx = i - 1;
1175 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1176 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1177 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1178 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1179 SelectLHS, SelectRHS);
1180 }
1181
1182 // If this is the last action to process, return it to the InstCombiner.
1183 // Otherwise, we insert it before the UDiv and record it so that we may
1184 // use it as part of a joining action (i.e., a SelectInst).
1185 if (e - i != 1) {
1186 Inst->insertBefore(&I);
1187 UDivActions[i].FoldResult = Inst;
1188 } else
1189 return Inst;
1190 }
1191
Craig Topperf40110f2014-04-25 05:29:35 +00001192 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001193}
1194
1195Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1196 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1197
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001198 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001199 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001200
Craig Toppera4205622017-06-09 03:21:29 +00001201 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001202 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001203
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001204 // Handle the integer div common cases
1205 if (Instruction *Common = commonIDivTransforms(I))
1206 return Common;
1207
Sanjay Patelc6ada532016-06-27 17:25:57 +00001208 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001209 if (match(Op1, m_APInt(Op1C))) {
1210 // sdiv X, -1 == -X
1211 if (Op1C->isAllOnesValue())
1212 return BinaryOperator::CreateNeg(Op0);
1213
1214 // sdiv exact X, C --> ashr exact X, log2(C)
1215 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1216 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1217 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1218 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001219
1220 // If the dividend is sign-extended and the constant divisor is small enough
1221 // to fit in the source type, shrink the division to the narrower type:
1222 // (sext X) sdiv C --> sext (X sdiv C)
1223 Value *Op0Src;
1224 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1225 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1226
1227 // In the general case, we need to make sure that the dividend is not the
1228 // minimum signed value because dividing that by -1 is UB. But here, we
1229 // know that the -1 divisor case is already handled above.
1230
1231 Constant *NarrowDivisor =
1232 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001233 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001234 return new SExtInst(NarrowOp, Op0->getType());
1235 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001236 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001237
Benjamin Kramer72196f32014-01-19 15:24:22 +00001238 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001239 // X/INT_MIN -> X == INT_MIN
1240 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001241 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001242
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001243 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001244 Value *X;
1245 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1246 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1247 BO->setIsExact(I.isExact());
1248 return BO;
1249 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001250 }
1251
1252 // If the sign bits of both operands are zero (i.e. we can prove they are
1253 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001254 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001255 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1256 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1257 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1258 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1259 BO->setIsExact(I.isExact());
1260 return BO;
1261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001262
Craig Topperd4039f72017-05-25 21:51:12 +00001263 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001264 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1265 // Safe because the only negative value (1 << Y) can take on is
1266 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1267 // the sign bit set.
1268 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1269 BO->setIsExact(I.isExact());
1270 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001271 }
1272 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001273
Craig Topperf40110f2014-04-25 05:29:35 +00001274 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001275}
1276
Shuxin Yang320f52a2013-01-14 22:48:41 +00001277/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1278/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001279/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001280/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001281/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001282/// returned; otherwise, NULL is returned.
1283///
Suyog Sardaea205512014-10-07 11:56:06 +00001284static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001285 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001286 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001287 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001288
1289 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001290 APFloat Reciprocal(FpVal.getSemantics());
1291 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001292
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001293 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001294 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1295 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1296 Cvt = !Reciprocal.isDenormal();
1297 }
1298
1299 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001300 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001301
1302 ConstantFP *R;
1303 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1304 return BinaryOperator::CreateFMul(Dividend, R);
1305}
1306
Frits van Bommel2a559512011-01-29 17:50:27 +00001307Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1309
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001310 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001311 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001312
Craig Toppera4205622017-06-09 03:21:29 +00001313 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1314 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001315 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001316
Stephen Lina9b57f62013-07-20 07:13:13 +00001317 if (isa<Constant>(Op0))
1318 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1319 if (Instruction *R = FoldOpIntoSelect(I, SI))
1320 return R;
1321
Shuxin Yang320f52a2013-01-14 22:48:41 +00001322 bool AllowReassociate = I.hasUnsafeAlgebra();
1323 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001324
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001325 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001326 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1327 if (Instruction *R = FoldOpIntoSelect(I, SI))
1328 return R;
1329
Shuxin Yang320f52a2013-01-14 22:48:41 +00001330 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001331 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001332 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001333 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001334 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001335
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001336 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001337 // (X*C1)/C2 => X * (C1/C2)
1338 //
1339 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001340 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001341 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001342 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001343 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1344 //
1345 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001346 if (isNormalFp(C)) {
1347 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001348 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001349 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001350 }
1351 }
1352
1353 if (Res) {
1354 Res->setFastMathFlags(I.getFastMathFlags());
1355 return Res;
1356 }
1357 }
1358
1359 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001360 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1361 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001362 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001363 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001364
Craig Topperf40110f2014-04-25 05:29:35 +00001365 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001366 }
1367
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001368 if (AllowReassociate && isa<Constant>(Op0)) {
1369 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001370 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001371 Value *X;
1372 bool CreateDiv = true;
1373
1374 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001375 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001376 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001377 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001378 // C1 / (X/C2) => (C1*C2) / X
1379 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001380 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001381 // C1 / (C2/X) => (C1/C2) * X
1382 Fold = ConstantExpr::getFDiv(C1, C2);
1383 CreateDiv = false;
1384 }
1385
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001386 if (Fold && isNormalFp(Fold)) {
1387 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1388 : BinaryOperator::CreateFMul(X, Fold);
1389 R->setFastMathFlags(I.getFastMathFlags());
1390 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001391 }
Craig Topperf40110f2014-04-25 05:29:35 +00001392 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001393 }
1394
1395 if (AllowReassociate) {
1396 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001397 Value *NewInst = nullptr;
1398 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001399
1400 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1401 // (X/Y) / Z => X / (Y*Z)
1402 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001403 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001404 NewInst = Builder.CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001405 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1406 FastMathFlags Flags = I.getFastMathFlags();
1407 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1408 RI->setFastMathFlags(Flags);
1409 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001410 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1411 }
1412 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1413 // Z / (X/Y) => Z*Y / X
1414 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001415 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001416 NewInst = Builder.CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001417 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1418 FastMathFlags Flags = I.getFastMathFlags();
1419 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1420 RI->setFastMathFlags(Flags);
1421 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001422 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1423 }
1424 }
1425
1426 if (NewInst) {
1427 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1428 T->setDebugLoc(I.getDebugLoc());
1429 SimpR->setFastMathFlags(I.getFastMathFlags());
1430 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001431 }
1432 }
1433
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001434 Value *LHS;
1435 Value *RHS;
1436
1437 // -x / -y -> x / y
1438 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1439 I.setOperand(0, LHS);
1440 I.setOperand(1, RHS);
1441 return &I;
1442 }
1443
Craig Topperf40110f2014-04-25 05:29:35 +00001444 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001445}
1446
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001447/// This function implements the transforms common to both integer remainder
1448/// instructions (urem and srem). It is called by the visitors to those integer
1449/// remainder instructions.
1450/// @brief Common integer remainder transforms
1451Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1452 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1453
Chris Lattner7c99f192011-05-22 18:18:41 +00001454 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001455 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001456 I.setOperand(1, V);
1457 return &I;
1458 }
1459
Duncan Sandsa3e36992011-05-02 16:27:02 +00001460 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001461 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001462 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001463
Benjamin Kramer72196f32014-01-19 15:24:22 +00001464 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001465 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1467 if (Instruction *R = FoldOpIntoSelect(I, SI))
1468 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001469 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001470 using namespace llvm::PatternMatch;
1471 const APInt *Op1Int;
1472 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1473 (I.getOpcode() == Instruction::URem ||
1474 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001475 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001476 // predecessor blocks, so do this only if we know the srem or urem
1477 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001478 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001479 return NV;
1480 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001481 }
1482
1483 // See if we can fold away this rem instruction.
1484 if (SimplifyDemandedInstructionBits(I))
1485 return &I;
1486 }
1487 }
1488
Craig Topperf40110f2014-04-25 05:29:35 +00001489 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001490}
1491
1492Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1494
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001495 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001496 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001497
Craig Toppera4205622017-06-09 03:21:29 +00001498 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001499 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001500
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001501 if (Instruction *common = commonIRemTransforms(I))
1502 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001503
Sanjay Patelbb789382017-08-24 22:54:01 +00001504 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1505 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001506
David Majnemer470b0772013-05-11 09:01:28 +00001507 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001508 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001509 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001510 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001511 return BinaryOperator::CreateAnd(Op0, Add);
1512 }
1513
Nick Lewycky7459be62013-07-13 01:16:47 +00001514 // 1 urem X -> zext(X != 1)
1515 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001516 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1517 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001518 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001519 }
1520
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001521 // X urem C -> X < C ? X : X - C, where C >= signbit.
1522 const APInt *DivisorC;
1523 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001524 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1525 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001526 return SelectInst::Create(Cmp, Op0, Sub);
1527 }
1528
Craig Topperf40110f2014-04-25 05:29:35 +00001529 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001530}
1531
1532Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1534
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001535 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001536 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001537
Craig Toppera4205622017-06-09 03:21:29 +00001538 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001539 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001540
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001541 // Handle the integer rem common cases
1542 if (Instruction *Common = commonIRemTransforms(I))
1543 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001544
David Majnemerdb077302014-10-13 22:37:51 +00001545 {
1546 const APInt *Y;
1547 // X % -Y -> X % Y
1548 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001549 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001550 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001551 return &I;
1552 }
David Majnemerdb077302014-10-13 22:37:51 +00001553 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001554
1555 // If the sign bits of both operands are zero (i.e. we can prove they are
1556 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001557 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001558 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1559 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1560 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1561 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001562 }
1563
1564 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001565 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1566 Constant *C = cast<Constant>(Op1);
1567 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001568
1569 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001570 bool hasMissing = false;
1571 for (unsigned i = 0; i != VWidth; ++i) {
1572 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001573 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001574 hasMissing = true;
1575 break;
1576 }
1577
1578 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001579 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001580 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001581 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001582
Chris Lattner0256be92012-01-27 03:08:05 +00001583 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001584 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001585 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001586 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001587 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001588 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001589 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001590 }
1591 }
1592
1593 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001594 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001595 Worklist.AddValue(I.getOperand(1));
1596 I.setOperand(1, NewRHSV);
1597 return &I;
1598 }
1599 }
1600 }
1601
Craig Topperf40110f2014-04-25 05:29:35 +00001602 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001603}
1604
1605Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001606 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001607
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001608 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001609 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001610
Craig Toppera4205622017-06-09 03:21:29 +00001611 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1612 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001613 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001614
1615 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001616 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001617 return &I;
1618
Craig Topperf40110f2014-04-25 05:29:35 +00001619 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001620}