blob: 2f72e0ab6e9a0687b9344896bfdddbb652498ed9 [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())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000042 A = IC.Builder->CreateSub(A, B);
David Majnemerdad21032014-10-14 20:28:40 +000043 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() &&
50 isKnownToBeAPowerOfTwo(I->getOperand(0), IC.getDataLayout(), false, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000051 &IC.getAssumptionCache(), &CxtI,
52 &IC.getDominatorTree())) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
55 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
56 I->setOperand(0, V2);
57 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000058 }
59
Sanjay Patela8ef4a52016-05-22 17:08:52 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
64
65 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
67 MadeChange = true;
68 }
69 }
70
Chris Lattner162dfc32011-05-22 18:26:48 +000071 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000072 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000074
Craig Topperf40110f2014-04-25 05:29:35 +000075 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000076}
77
78
Sanjay Patel6eccf482015-09-09 15:24:36 +000079/// True if the multiply can not be expressed in an int this size.
David Majnemer27adb122014-10-12 08:34:24 +000080static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
81 bool IsSigned) {
82 bool Overflow;
83 if (IsSigned)
84 Product = C1.smul_ov(C2, Overflow);
85 else
86 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000087
David Majnemer27adb122014-10-12 08:34:24 +000088 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000089}
90
David Majnemerf9a095d2014-08-16 08:55:06 +000091/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
92static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
93 bool IsSigned) {
94 assert(C1.getBitWidth() == C2.getBitWidth() &&
95 "Inconsistent width of constants!");
96
David Majnemer135ca402015-09-06 06:49:59 +000097 // Bail if we will divide by zero.
98 if (C2.isMinValue())
99 return false;
100
101 // Bail if we would divide INT_MIN by -1.
102 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
103 return false;
104
David Majnemerf9a095d2014-08-16 08:55:06 +0000105 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
106 if (IsSigned)
107 APInt::sdivrem(C1, C2, Quotient, Remainder);
108 else
109 APInt::udivrem(C1, C2, Quotient, Remainder);
110
111 return Remainder.isMinValue();
112}
113
Rafael Espindola65281bf2013-05-31 14:27:15 +0000114/// \brief A helper routine of InstCombiner::visitMul().
115///
116/// If C is a vector of known powers of 2, then this function returns
117/// a new vector obtained from C replacing each element with its logBase2.
118/// Return a null pointer otherwise.
119static Constant *getLogBase2Vector(ConstantDataVector *CV) {
120 const APInt *IVal;
121 SmallVector<Constant *, 4> Elts;
122
123 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
124 Constant *Elt = CV->getElementAsConstant(I);
125 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000126 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000127 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
128 }
129
130 return ConstantVector::get(Elts);
131}
132
David Majnemer54c2ca22014-12-26 09:10:14 +0000133/// \brief Return true if we can prove that:
134/// (mul LHS, RHS) === (mul nsw LHS, RHS)
135bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000136 Instruction &CxtI) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000137 // Multiplying n * m significant bits yields a result of n + m significant
138 // bits. If the total number of significant bits does not exceed the
139 // result bit width (minus 1), there is no overflow.
140 // This means if we have enough leading sign bits in the operands
141 // we can guarantee that the result does not overflow.
142 // Ref: "Hacker's Delight" by Henry Warren
143 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
144
145 // Note that underestimating the number of sign bits gives a more
146 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000147 unsigned SignBits =
148 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000149
150 // First handle the easy case: if we have enough sign bits there's
151 // definitely no overflow.
152 if (SignBits > BitWidth + 1)
153 return true;
154
155 // There are two ambiguous cases where there can be no overflow:
156 // SignBits == BitWidth + 1 and
157 // SignBits == BitWidth
158 // The second case is difficult to check, therefore we only handle the
159 // first case.
160 if (SignBits == BitWidth + 1) {
161 // It overflows only when both arguments are negative and the true
162 // product is exactly the minimum negative number.
163 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
164 // For simplicity we just check if at least one side is not negative.
165 bool LHSNonNegative, LHSNegative;
166 bool RHSNonNegative, RHSNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000167 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
168 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000169 if (LHSNonNegative || RHSNonNegative)
170 return true;
171 }
172 return false;
173}
174
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000175Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000176 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
178
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000179 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000180 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000181
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000182 if (Value *V = SimplifyMulInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000183 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000184
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000185 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000186 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000187
David Majnemer027bc802014-11-22 04:52:38 +0000188 // X * -1 == 0 - X
189 if (match(Op1, m_AllOnes())) {
190 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
191 if (I.hasNoSignedWrap())
192 BO->setHasNoSignedWrap();
193 return BO;
194 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000195
Rafael Espindola65281bf2013-05-31 14:27:15 +0000196 // Also allow combining multiply instructions on vectors.
197 {
198 Value *NewOp;
199 Constant *C1, *C2;
200 const APInt *IVal;
201 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
202 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000203 match(C1, m_APInt(IVal))) {
204 // ((X << C2)*C1) == (X * (C1 << C2))
205 Constant *Shl = ConstantExpr::getShl(C1, C2);
206 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
207 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
208 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
209 BO->setHasNoUnsignedWrap();
210 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
211 Shl->isNotMinSignedValue())
212 BO->setHasNoSignedWrap();
213 return BO;
214 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000215
Rafael Espindola65281bf2013-05-31 14:27:15 +0000216 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000217 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000218 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
219 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
220 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
221 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
222 // Replace X*(2^C) with X << C, where C is a vector of known
223 // constant powers of 2.
224 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000225
Rafael Espindola65281bf2013-05-31 14:27:15 +0000226 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000227 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000228 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000229
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000230 if (I.hasNoUnsignedWrap())
231 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000232 if (I.hasNoSignedWrap()) {
233 uint64_t V;
234 if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
235 Shl->setHasNoSignedWrap();
236 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000237
Rafael Espindola65281bf2013-05-31 14:27:15 +0000238 return Shl;
239 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000240 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000241 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000242
Rafael Espindola65281bf2013-05-31 14:27:15 +0000243 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000244 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
245 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
246 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000247 {
248 const APInt & Val = CI->getValue();
249 const APInt &PosVal = Val.abs();
250 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000251 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000252 if (Op0->hasOneUse()) {
253 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000254 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000255 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
256 Sub = Builder->CreateSub(X, Y, "suba");
257 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
258 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
259 if (Sub)
260 return
261 BinaryOperator::CreateMul(Sub,
262 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000263 }
264 }
265 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000266 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000267
Chris Lattner6b657ae2011-02-10 05:36:31 +0000268 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000269 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000270 // Try to fold constant mul into select arguments.
271 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
272 if (Instruction *R = FoldOpIntoSelect(I, SI))
273 return R;
274
275 if (isa<PHINode>(Op0))
276 if (Instruction *NV = FoldOpIntoPhi(I))
277 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000278
279 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
280 {
281 Value *X;
282 Constant *C1;
283 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000284 Value *Mul = Builder->CreateMul(C1, Op1);
285 // Only go forward with the transform if C1*CI simplifies to a tidier
286 // constant.
287 if (!match(Mul, m_Mul(m_Value(), m_Value())))
288 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000289 }
290 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000291 }
292
David Majnemer8279a7502014-11-22 07:25:19 +0000293 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
294 if (Value *Op1v = dyn_castNegVal(Op1)) {
295 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
296 if (I.hasNoSignedWrap() &&
297 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
298 match(Op1, m_NSWSub(m_Value(), m_Value())))
299 BO->setHasNoSignedWrap();
300 return BO;
301 }
302 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000303
304 // (X / Y) * Y = X - (X % Y)
305 // (X / Y) * -Y = (X % Y) - X
306 {
307 Value *Op1C = Op1;
308 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
309 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000310 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000311 BO->getOpcode() != Instruction::SDiv)) {
312 Op1C = Op0;
313 BO = dyn_cast<BinaryOperator>(Op1);
314 }
315 Value *Neg = dyn_castNegVal(Op1C);
316 if (BO && BO->hasOneUse() &&
317 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
318 (BO->getOpcode() == Instruction::UDiv ||
319 BO->getOpcode() == Instruction::SDiv)) {
320 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
321
Chris Lattner35315d02011-02-06 21:44:57 +0000322 // If the division is exact, X % Y is zero, so we end up with X or -X.
323 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000324 if (SDiv->isExact()) {
325 if (Op1BO == Op1C)
Sanjay Patel4b198802016-02-01 22:23:39 +0000326 return replaceInstUsesWith(I, Op0BO);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000327 return BinaryOperator::CreateNeg(Op0BO);
328 }
329
330 Value *Rem;
331 if (BO->getOpcode() == Instruction::UDiv)
332 Rem = Builder->CreateURem(Op0BO, Op1BO);
333 else
334 Rem = Builder->CreateSRem(Op0BO, Op1BO);
335 Rem->takeName(BO);
336
337 if (Op1BO == Op1C)
338 return BinaryOperator::CreateSub(Op0BO, Rem);
339 return BinaryOperator::CreateSub(Rem, Op0BO);
340 }
341 }
342
343 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000344 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000345 return BinaryOperator::CreateAnd(Op0, Op1);
346
347 // X*(1 << Y) --> X << Y
348 // (1 << Y)*X --> X << Y
349 {
350 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000351 BinaryOperator *BO = nullptr;
352 bool ShlNSW = false;
353 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
354 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000355 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000356 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000357 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000358 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000359 }
360 if (BO) {
361 if (I.hasNoUnsignedWrap())
362 BO->setHasNoUnsignedWrap();
363 if (I.hasNoSignedWrap() && ShlNSW)
364 BO->setHasNoSignedWrap();
365 return BO;
366 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000367 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000368
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000369 // If one of the operands of the multiply is a cast from a boolean value, then
370 // we know the bool is either zero or one, so this is a 'masking' multiply.
371 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000372 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000373 // -2 is "-1 << 1" so it is all bits set except the low one.
374 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000375
Craig Topperf40110f2014-04-25 05:29:35 +0000376 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000377 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
378 BoolCast = Op0;
379 OtherOp = Op1;
380 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
381 BoolCast = Op1;
382 OtherOp = Op0;
383 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000384
385 if (BoolCast) {
386 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000387 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000388 return BinaryOperator::CreateAnd(V, OtherOp);
389 }
390 }
391
David Majnemera1cfd7c2016-12-30 00:28:58 +0000392 // Check for (mul (sext x), y), see if we can merge this into an
393 // integer mul followed by a sext.
394 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
395 // (mul (sext x), cst) --> (sext (mul x, cst'))
396 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
397 if (Op0Conv->hasOneUse()) {
398 Constant *CI =
399 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
400 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
401 WillNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
402 // Insert the new, smaller mul.
403 Value *NewMul =
404 Builder->CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
405 return new SExtInst(NewMul, I.getType());
406 }
407 }
408 }
409
410 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
411 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
412 // Only do this if x/y have the same type, if at last one of them has a
413 // single use (so we don't increase the number of sexts), and if the
414 // integer mul will not overflow.
415 if (Op0Conv->getOperand(0)->getType() ==
416 Op1Conv->getOperand(0)->getType() &&
417 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
418 WillNotOverflowSignedMul(Op0Conv->getOperand(0),
419 Op1Conv->getOperand(0), I)) {
420 // Insert the new integer mul.
421 Value *NewMul = Builder->CreateNSWMul(
422 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
423 return new SExtInst(NewMul, I.getType());
424 }
425 }
426 }
427
428 // Check for (mul (zext x), y), see if we can merge this into an
429 // integer mul followed by a zext.
430 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
431 // (mul (zext x), cst) --> (zext (mul x, cst'))
432 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
433 if (Op0Conv->hasOneUse()) {
434 Constant *CI =
435 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
436 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
437 WillNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
438 // Insert the new, smaller mul.
439 Value *NewMul =
440 Builder->CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
441 return new ZExtInst(NewMul, I.getType());
442 }
443 }
444 }
445
446 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
447 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
448 // Only do this if x/y have the same type, if at last one of them has a
449 // single use (so we don't increase the number of zexts), and if the
450 // integer mul will not overflow.
451 if (Op0Conv->getOperand(0)->getType() ==
452 Op1Conv->getOperand(0)->getType() &&
453 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
454 computeOverflowForUnsignedMul(Op0Conv->getOperand(0),
455 Op1Conv->getOperand(0),
456 &I) == OverflowResult::NeverOverflows) {
457 // Insert the new integer mul.
458 Value *NewMul = Builder->CreateNUWMul(
459 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
460 return new ZExtInst(NewMul, I.getType());
461 }
462 }
463 }
464
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000465 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000466 Changed = true;
467 I.setHasNoSignedWrap(true);
468 }
469
David Majnemer491331a2015-01-02 07:29:43 +0000470 if (!I.hasNoUnsignedWrap() &&
471 computeOverflowForUnsignedMul(Op0, Op1, &I) ==
472 OverflowResult::NeverOverflows) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000473 Changed = true;
474 I.setHasNoUnsignedWrap(true);
475 }
476
Craig Topperf40110f2014-04-25 05:29:35 +0000477 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000478}
479
Sanjay Patel17045f72014-10-14 00:33:23 +0000480/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000481static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000482 if (!Op->hasOneUse())
483 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000484
Sanjay Patel17045f72014-10-14 00:33:23 +0000485 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
486 if (!II)
487 return;
488 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
489 return;
490 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000491
Sanjay Patel17045f72014-10-14 00:33:23 +0000492 Value *OpLog2Of = II->getArgOperand(0);
493 if (!OpLog2Of->hasOneUse())
494 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000495
Sanjay Patel17045f72014-10-14 00:33:23 +0000496 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
497 if (!I)
498 return;
499 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
500 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000501
Sanjay Patel17045f72014-10-14 00:33:23 +0000502 if (match(I->getOperand(0), m_SpecificFP(0.5)))
503 Y = I->getOperand(1);
504 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
505 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000506}
Pedro Artigas993acd02012-11-30 22:07:05 +0000507
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000508static bool isFiniteNonZeroFp(Constant *C) {
509 if (C->getType()->isVectorTy()) {
510 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
511 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000512 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000513 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
514 return false;
515 }
516 return true;
517 }
518
519 return isa<ConstantFP>(C) &&
520 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
521}
522
523static bool isNormalFp(Constant *C) {
524 if (C->getType()->isVectorTy()) {
525 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
526 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000527 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000528 if (!CFP || !CFP->getValueAPF().isNormal())
529 return false;
530 }
531 return true;
532 }
533
534 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
535}
536
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000537/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
538/// true iff the given value is FMul or FDiv with one and only one operand
539/// being a normal constant (i.e. not Zero/NaN/Infinity).
540static bool isFMulOrFDivWithConstant(Value *V) {
541 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000542 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000543 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000544 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000545
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000546 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
547 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000548
549 if (C0 && C1)
550 return false;
551
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000552 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553}
554
555/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
556/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
557/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000558/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000559/// resulting expression. Note that this function could return NULL in
560/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000561///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000562Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000563 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000564 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
565
566 Value *Opnd0 = FMulOrDiv->getOperand(0);
567 Value *Opnd1 = FMulOrDiv->getOperand(1);
568
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000569 Constant *C0 = dyn_cast<Constant>(Opnd0);
570 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000571
Craig Topperf40110f2014-04-25 05:29:35 +0000572 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000573
574 // (X * C0) * C => X * (C0*C)
575 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
576 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000577 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000578 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
579 } else {
580 if (C0) {
581 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000582 if (FMulOrDiv->hasOneUse()) {
583 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000584 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000585 if (isNormalFp(F))
586 R = BinaryOperator::CreateFDiv(F, Opnd1);
587 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000588 } else {
589 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000590 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000591 if (isNormalFp(F)) {
592 R = BinaryOperator::CreateFMul(Opnd0, F);
593 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000594 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000595 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000596 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000597 R = BinaryOperator::CreateFDiv(Opnd0, F);
598 }
599 }
600 }
601
602 if (R) {
603 R->setHasUnsafeAlgebra(true);
604 InsertNewInstWith(R, *InsertBefore);
605 }
606
607 return R;
608}
609
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000610Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000611 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000612 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
613
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000614 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000615 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000616
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000617 if (isa<Constant>(Op0))
618 std::swap(Op0, Op1);
619
Chandler Carruth66b31302015-01-04 12:03:27 +0000620 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000621 SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000622 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000623
Shuxin Yange8227452013-01-15 21:09:32 +0000624 bool AllowReassociate = I.hasUnsafeAlgebra();
625
Michael Ilsemand5787be2012-12-12 00:28:32 +0000626 // Simplify mul instructions with a constant RHS.
627 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000628 // Try to fold constant mul into select arguments.
629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
630 if (Instruction *R = FoldOpIntoSelect(I, SI))
631 return R;
632
633 if (isa<PHINode>(Op0))
634 if (Instruction *NV = FoldOpIntoPhi(I))
635 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000636
Owen Andersonf74cfe02014-01-16 20:36:42 +0000637 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000638 if (match(Op1, m_SpecificFP(-1.0))) {
639 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
640 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000641 RI->copyFastMathFlags(&I);
642 return RI;
643 }
644
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000645 Constant *C = cast<Constant>(Op1);
646 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000647 // Let MDC denote an expression in one of these forms:
648 // X * C, C/X, X/C, where C is a constant.
649 //
650 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000651 if (isFMulOrFDivWithConstant(Op0))
652 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000653 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000654
Quentin Colombete684a6d2013-02-28 21:12:40 +0000655 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000656 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
657 if (FAddSub &&
658 (FAddSub->getOpcode() == Instruction::FAdd ||
659 FAddSub->getOpcode() == Instruction::FSub)) {
660 Value *Opnd0 = FAddSub->getOperand(0);
661 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000662 Constant *C0 = dyn_cast<Constant>(Opnd0);
663 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000664 bool Swap = false;
665 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000666 std::swap(C0, C1);
667 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000668 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000669 }
670
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000671 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000672 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000673 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000674 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000675 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000676 if (M0 && M1) {
677 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
678 std::swap(M0, M1);
679
Benjamin Kramer67485762013-09-30 15:39:59 +0000680 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
681 ? BinaryOperator::CreateFAdd(M0, M1)
682 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000683 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000684 return RI;
685 }
686 }
687 }
688 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000689 }
690
Matt Arsenault56c079f2016-01-30 05:02:00 +0000691 if (Op0 == Op1) {
692 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
693 // sqrt(X) * sqrt(X) -> X
694 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000695 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000696
Matt Arsenault56c079f2016-01-30 05:02:00 +0000697 // fabs(X) * fabs(X) -> X * X
698 if (II->getIntrinsicID() == Intrinsic::fabs) {
699 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
700 II->getOperand(0),
701 I.getName());
702 FMulVal->copyFastMathFlags(&I);
703 return FMulVal;
704 }
705 }
706 }
707
Pedro Artigasd8795042012-11-30 19:09:41 +0000708 // Under unsafe algebra do:
709 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000710 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000711 Value *OpX = nullptr;
712 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000713 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000714 detectLog2OfHalf(Op0, OpY, Log2);
715 if (OpY) {
716 OpX = Op1;
717 } else {
718 detectLog2OfHalf(Op1, OpY, Log2);
719 if (OpY) {
720 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000721 }
722 }
723 // if pattern detected emit alternate sequence
724 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000725 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000726 Builder->setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000727 Log2->setArgOperand(0, OpY);
728 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000729 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
730 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000731 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000732 }
733 }
734
Shuxin Yange8227452013-01-15 21:09:32 +0000735 // Handle symmetric situation in a 2-iteration loop
736 Value *Opnd0 = Op0;
737 Value *Opnd1 = Op1;
738 for (int i = 0; i < 2; i++) {
739 bool IgnoreZeroSign = I.hasNoSignedZeros();
740 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000741 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000742 Builder->setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000743
Shuxin Yange8227452013-01-15 21:09:32 +0000744 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
745 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000746
Shuxin Yange8227452013-01-15 21:09:32 +0000747 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000748 if (N1) {
749 Value *FMul = Builder->CreateFMul(N0, N1);
750 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000751 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000752 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000753
Shuxin Yange8227452013-01-15 21:09:32 +0000754 if (Opnd0->hasOneUse()) {
755 // -X * Y => -(X*Y) (Promote negation as high as possible)
756 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000757 Value *Neg = Builder->CreateFNeg(T);
758 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000759 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000760 }
761 }
Shuxin Yange8227452013-01-15 21:09:32 +0000762
763 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000764 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000765 // 1) to form a power expression (of X).
766 // 2) potentially shorten the critical path: After transformation, the
767 // latency of the instruction Y is amortized by the expression of X*X,
768 // and therefore Y is in a "less critical" position compared to what it
769 // was before the transformation.
770 //
771 if (AllowReassociate) {
772 Value *Opnd0_0, *Opnd0_1;
773 if (Opnd0->hasOneUse() &&
774 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000775 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000776 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
777 Y = Opnd0_1;
778 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
779 Y = Opnd0_0;
780
781 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000782 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000783 Builder->setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000784 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000785 Value *R = Builder->CreateFMul(T, Y);
786 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000787 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000788 }
789 }
790 }
791
792 if (!isa<Constant>(Op1))
793 std::swap(Opnd0, Opnd1);
794 else
795 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000796 }
797
Craig Topperf40110f2014-04-25 05:29:35 +0000798 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000799}
800
Sanjay Patel6eccf482015-09-09 15:24:36 +0000801/// Try to fold a divide or remainder of a select instruction.
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000802bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
803 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000804
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000805 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
806 int NonNullOperand = -1;
807 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
808 if (ST->isNullValue())
809 NonNullOperand = 2;
810 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
811 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
812 if (ST->isNullValue())
813 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000814
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000815 if (NonNullOperand == -1)
816 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000817
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000818 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000819
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000820 // Change the div/rem to use 'Y' instead of the select.
821 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000822
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000823 // Okay, we know we replace the operand of the div/rem with 'Y' with no
824 // problem. However, the select, or the condition of the select may have
825 // multiple uses. Based on our knowledge that the operand must be non-zero,
826 // propagate the known value for the select into other uses of it, and
827 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000828
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000829 // If the select and condition only have a single use, don't bother with this,
830 // early exit.
831 if (SI->use_empty() && SelectCond->hasOneUse())
832 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000833
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000834 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000835 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000836
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000837 while (BBI != BBFront) {
838 --BBI;
839 // If we found a call to a function, we can't assume it will return, so
840 // information from below it cannot be propagated above it.
841 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
842 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000843
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000844 // Replace uses of the select or its condition with the known values.
845 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
846 I != E; ++I) {
847 if (*I == SI) {
848 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000849 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000850 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000851 *I = Builder->getInt1(NonNullOperand == 1);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000852 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000853 }
854 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000855
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000856 // If we past the instruction, quit looking for it.
857 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000858 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000859 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000860 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000861
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000862 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000863 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000864 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000865
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000866 }
867 return true;
868}
869
870
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000871/// This function implements the transforms common to both integer division
872/// instructions (udiv and sdiv). It is called by the visitors to those integer
873/// division instructions.
874/// @brief Common integer divide transforms
875Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
877
Chris Lattner7c99f192011-05-22 18:18:41 +0000878 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000879 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000880 I.setOperand(1, V);
881 return &I;
882 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000883
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000884 // Handle cases involving: [su]div X, (select Cond, Y, Z)
885 // This does not apply for fdiv.
886 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
887 return &I;
888
David Majnemer27adb122014-10-12 08:34:24 +0000889 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
890 const APInt *C2;
891 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000892 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000893 const APInt *C1;
894 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000895
David Majnemer27adb122014-10-12 08:34:24 +0000896 // (X / C1) / C2 -> X / (C1*C2)
897 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
898 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
899 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
900 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
901 return BinaryOperator::Create(I.getOpcode(), X,
902 ConstantInt::get(I.getType(), Product));
903 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000904
David Majnemer27adb122014-10-12 08:34:24 +0000905 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
906 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
907 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
908
909 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
910 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
911 BinaryOperator *BO = BinaryOperator::Create(
912 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
913 BO->setIsExact(I.isExact());
914 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000915 }
916
David Majnemer27adb122014-10-12 08:34:24 +0000917 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
918 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
919 BinaryOperator *BO = BinaryOperator::Create(
920 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
921 BO->setHasNoUnsignedWrap(
922 !IsSigned &&
923 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
924 BO->setHasNoSignedWrap(
925 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
926 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000927 }
928 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000929
David Majnemer27adb122014-10-12 08:34:24 +0000930 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
931 *C1 != C1->getBitWidth() - 1) ||
932 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
933 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
934 APInt C1Shifted = APInt::getOneBitSet(
935 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
936
937 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
938 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
939 BinaryOperator *BO = BinaryOperator::Create(
940 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
941 BO->setIsExact(I.isExact());
942 return BO;
943 }
944
945 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
946 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
947 BinaryOperator *BO = BinaryOperator::Create(
948 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
949 BO->setHasNoUnsignedWrap(
950 !IsSigned &&
951 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
952 BO->setHasNoSignedWrap(
953 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
954 return BO;
955 }
956 }
957
958 if (*C2 != 0) { // avoid X udiv 0
959 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
960 if (Instruction *R = FoldOpIntoSelect(I, SI))
961 return R;
962 if (isa<PHINode>(Op0))
963 if (Instruction *NV = FoldOpIntoPhi(I))
964 return NV;
965 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000966 }
967 }
968
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000969 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
970 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
971 bool isSigned = I.getOpcode() == Instruction::SDiv;
972 if (isSigned) {
973 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
974 // result is one, if Op1 is -1 then the result is minus one, otherwise
975 // it's zero.
976 Value *Inc = Builder->CreateAdd(Op1, One);
977 Value *Cmp = Builder->CreateICmpULT(
978 Inc, ConstantInt::get(I.getType(), 3));
979 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
980 } else {
981 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
982 // result is one, otherwise it's zero.
983 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
984 }
985 }
986 }
987
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000988 // See if we can fold away this div instruction.
989 if (SimplifyDemandedInstructionBits(I))
990 return &I;
991
Duncan Sands771e82a2011-01-28 16:51:11 +0000992 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000993 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000994 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
995 bool isSigned = I.getOpcode() == Instruction::SDiv;
996 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
997 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
998 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000999 }
1000
Craig Topperf40110f2014-04-25 05:29:35 +00001001 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001002}
1003
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001004/// dyn_castZExtVal - Checks if V is a zext or constant that can
1005/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +00001006static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001007 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
1008 if (Z->getSrcTy() == Ty)
1009 return Z->getOperand(0);
1010 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
1011 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
1012 return ConstantExpr::getTrunc(C, Ty);
1013 }
Craig Topperf40110f2014-04-25 05:29:35 +00001014 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001015}
1016
David Majnemer37f8f442013-07-04 21:17:49 +00001017namespace {
1018const unsigned MaxDepth = 6;
1019typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
1020 const BinaryOperator &I,
1021 InstCombiner &IC);
1022
1023/// \brief Used to maintain state for visitUDivOperand().
1024struct UDivFoldAction {
1025 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
1026 ///< operand. This can be zero if this action
1027 ///< joins two actions together.
1028
1029 Value *OperandToFold; ///< Which operand to fold.
1030 union {
1031 Instruction *FoldResult; ///< The instruction returned when FoldAction is
1032 ///< invoked.
1033
1034 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
1035 ///< joins two actions together.
1036 };
1037
1038 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001039 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001040 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1041 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1042};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001043}
David Majnemer37f8f442013-07-04 21:17:49 +00001044
1045// X udiv 2^C -> X >> C
1046static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1047 const BinaryOperator &I, InstCombiner &IC) {
1048 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1049 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1050 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001051 if (I.isExact())
1052 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001053 return LShr;
1054}
1055
1056// X udiv C, where C >= signbit
1057static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1058 const BinaryOperator &I, InstCombiner &IC) {
1059 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
1060
1061 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1062 ConstantInt::get(I.getType(), 1));
1063}
1064
1065// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001066// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001067static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1068 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001069 Value *ShiftLeft;
1070 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1071 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001072
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001073 const APInt *CI;
1074 Value *N;
1075 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1076 llvm_unreachable("match should never fail here!");
1077 if (*CI != 1)
1078 N = IC.Builder->CreateAdd(N,
1079 ConstantInt::get(N->getType(), CI->logBase2()));
1080 if (Op1 != ShiftLeft)
1081 N = IC.Builder->CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001082 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001083 if (I.isExact())
1084 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001085 return LShr;
1086}
1087
1088// \brief Recursively visits the possible right hand operands of a udiv
1089// instruction, seeing through select instructions, to determine if we can
1090// replace the udiv with something simpler. If we find that an operand is not
1091// able to simplify the udiv, we abort the entire transformation.
1092static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1093 SmallVectorImpl<UDivFoldAction> &Actions,
1094 unsigned Depth = 0) {
1095 // Check to see if this is an unsigned division with an exact power of 2,
1096 // if so, convert to a right shift.
1097 if (match(Op1, m_Power2())) {
1098 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1099 return Actions.size();
1100 }
1101
1102 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1103 // X udiv C, where C >= signbit
1104 if (C->getValue().isNegative()) {
1105 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1106 return Actions.size();
1107 }
1108
1109 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1110 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1111 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1112 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1113 return Actions.size();
1114 }
1115
1116 // The remaining tests are all recursive, so bail out if we hit the limit.
1117 if (Depth++ == MaxDepth)
1118 return 0;
1119
1120 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001121 if (size_t LHSIdx =
1122 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1123 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1124 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001125 return Actions.size();
1126 }
1127
1128 return 0;
1129}
1130
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001131Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1132 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1133
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001134 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001135 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001136
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001137 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001138 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001139
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001140 // Handle the integer div common cases
1141 if (Instruction *Common = commonIDivTransforms(I))
1142 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001143
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001144 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001145 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001146 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001147 const APInt *C1, *C2;
1148 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1149 match(Op1, m_APInt(C2))) {
1150 bool Overflow;
1151 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001152 if (!Overflow) {
1153 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1154 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001155 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001156 if (IsExact)
1157 BO->setIsExact();
1158 return BO;
1159 }
David Majnemera2521382014-10-13 21:48:30 +00001160 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001161 }
1162
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001163 // (zext A) udiv (zext B) --> zext (A udiv B)
1164 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1165 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001166 return new ZExtInst(
1167 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1168 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001169
David Majnemer37f8f442013-07-04 21:17:49 +00001170 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1171 SmallVector<UDivFoldAction, 6> UDivActions;
1172 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1173 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1174 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1175 Value *ActionOp1 = UDivActions[i].OperandToFold;
1176 Instruction *Inst;
1177 if (Action)
1178 Inst = Action(Op0, ActionOp1, I, *this);
1179 else {
1180 // This action joins two actions together. The RHS of this action is
1181 // simply the last action we processed, we saved the LHS action index in
1182 // the joining action.
1183 size_t SelectRHSIdx = i - 1;
1184 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1185 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1186 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1187 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1188 SelectLHS, SelectRHS);
1189 }
1190
1191 // If this is the last action to process, return it to the InstCombiner.
1192 // Otherwise, we insert it before the UDiv and record it so that we may
1193 // use it as part of a joining action (i.e., a SelectInst).
1194 if (e - i != 1) {
1195 Inst->insertBefore(&I);
1196 UDivActions[i].FoldResult = Inst;
1197 } else
1198 return Inst;
1199 }
1200
Craig Topperf40110f2014-04-25 05:29:35 +00001201 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001202}
1203
1204Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1206
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001207 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001208 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001209
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001210 if (Value *V = SimplifySDivInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001211 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001212
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001213 // Handle the integer div common cases
1214 if (Instruction *Common = commonIDivTransforms(I))
1215 return Common;
1216
Sanjay Patelc6ada532016-06-27 17:25:57 +00001217 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001218 if (match(Op1, m_APInt(Op1C))) {
1219 // sdiv X, -1 == -X
1220 if (Op1C->isAllOnesValue())
1221 return BinaryOperator::CreateNeg(Op0);
1222
1223 // sdiv exact X, C --> ashr exact X, log2(C)
1224 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1225 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1226 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1227 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001228
1229 // If the dividend is sign-extended and the constant divisor is small enough
1230 // to fit in the source type, shrink the division to the narrower type:
1231 // (sext X) sdiv C --> sext (X sdiv C)
1232 Value *Op0Src;
1233 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1234 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1235
1236 // In the general case, we need to make sure that the dividend is not the
1237 // minimum signed value because dividing that by -1 is UB. But here, we
1238 // know that the -1 divisor case is already handled above.
1239
1240 Constant *NarrowDivisor =
1241 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1242 Value *NarrowOp = Builder->CreateSDiv(Op0Src, NarrowDivisor);
1243 return new SExtInst(NarrowOp, Op0->getType());
1244 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001245 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001246
Benjamin Kramer72196f32014-01-19 15:24:22 +00001247 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001248 // X/INT_MIN -> X == INT_MIN
1249 if (RHS->isMinSignedValue())
1250 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1251
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001252 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001253 Value *X;
1254 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1255 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1256 BO->setIsExact(I.isExact());
1257 return BO;
1258 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001259 }
1260
1261 // If the sign bits of both operands are zero (i.e. we can prove they are
1262 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001263 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001265 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1266 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001267 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
David Majnemerec6e4812014-11-22 20:00:38 +00001268 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1269 BO->setIsExact(I.isExact());
1270 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001271 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001272
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001273 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001274 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1275 // Safe because the only negative value (1 << Y) can take on is
1276 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1277 // the sign bit set.
David Majnemerfb380552014-11-22 20:00:41 +00001278 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1279 BO->setIsExact(I.isExact());
1280 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001281 }
1282 }
1283 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001284
Craig Topperf40110f2014-04-25 05:29:35 +00001285 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001286}
1287
Shuxin Yang320f52a2013-01-14 22:48:41 +00001288/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1289/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001290/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001291/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001292/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001293/// returned; otherwise, NULL is returned.
1294///
Suyog Sardaea205512014-10-07 11:56:06 +00001295static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001296 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001297 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001298 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001299
1300 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001301 APFloat Reciprocal(FpVal.getSemantics());
1302 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001303
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001304 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001305 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1306 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1307 Cvt = !Reciprocal.isDenormal();
1308 }
1309
1310 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001311 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001312
1313 ConstantFP *R;
1314 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1315 return BinaryOperator::CreateFMul(Dividend, R);
1316}
1317
Frits van Bommel2a559512011-01-29 17:50:27 +00001318Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1320
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001321 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001322 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001323
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001324 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001325 DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001326 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001327
Stephen Lina9b57f62013-07-20 07:13:13 +00001328 if (isa<Constant>(Op0))
1329 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1330 if (Instruction *R = FoldOpIntoSelect(I, SI))
1331 return R;
1332
Shuxin Yang320f52a2013-01-14 22:48:41 +00001333 bool AllowReassociate = I.hasUnsafeAlgebra();
1334 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001335
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001336 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001337 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1338 if (Instruction *R = FoldOpIntoSelect(I, SI))
1339 return R;
1340
Shuxin Yang320f52a2013-01-14 22:48:41 +00001341 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001342 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001343 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001344 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001345 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001346
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001347 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001348 // (X*C1)/C2 => X * (C1/C2)
1349 //
1350 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001351 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001352 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001353 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001354 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1355 //
1356 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001357 if (isNormalFp(C)) {
1358 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001359 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001360 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001361 }
1362 }
1363
1364 if (Res) {
1365 Res->setFastMathFlags(I.getFastMathFlags());
1366 return Res;
1367 }
1368 }
1369
1370 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001371 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1372 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001373 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001374 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001375
Craig Topperf40110f2014-04-25 05:29:35 +00001376 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001377 }
1378
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001379 if (AllowReassociate && isa<Constant>(Op0)) {
1380 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001381 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001382 Value *X;
1383 bool CreateDiv = true;
1384
1385 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001386 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001387 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001388 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001389 // C1 / (X/C2) => (C1*C2) / X
1390 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001391 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001392 // C1 / (C2/X) => (C1/C2) * X
1393 Fold = ConstantExpr::getFDiv(C1, C2);
1394 CreateDiv = false;
1395 }
1396
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001397 if (Fold && isNormalFp(Fold)) {
1398 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1399 : BinaryOperator::CreateFMul(X, Fold);
1400 R->setFastMathFlags(I.getFastMathFlags());
1401 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001402 }
Craig Topperf40110f2014-04-25 05:29:35 +00001403 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001404 }
1405
1406 if (AllowReassociate) {
1407 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001408 Value *NewInst = nullptr;
1409 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001410
1411 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1412 // (X/Y) / Z => X / (Y*Z)
1413 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001414 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001415 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001416 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1417 FastMathFlags Flags = I.getFastMathFlags();
1418 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1419 RI->setFastMathFlags(Flags);
1420 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001421 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1422 }
1423 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1424 // Z / (X/Y) => Z*Y / X
1425 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001426 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001427 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001428 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1429 FastMathFlags Flags = I.getFastMathFlags();
1430 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1431 RI->setFastMathFlags(Flags);
1432 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001433 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1434 }
1435 }
1436
1437 if (NewInst) {
1438 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1439 T->setDebugLoc(I.getDebugLoc());
1440 SimpR->setFastMathFlags(I.getFastMathFlags());
1441 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001442 }
1443 }
1444
Craig Topperf40110f2014-04-25 05:29:35 +00001445 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001446}
1447
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001448/// This function implements the transforms common to both integer remainder
1449/// instructions (urem and srem). It is called by the visitors to those integer
1450/// remainder instructions.
1451/// @brief Common integer remainder transforms
1452Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1454
Chris Lattner7c99f192011-05-22 18:18:41 +00001455 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001456 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001457 I.setOperand(1, V);
1458 return &I;
1459 }
1460
Duncan Sandsa3e36992011-05-02 16:27:02 +00001461 // Handle cases involving: rem X, (select Cond, Y, Z)
1462 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1463 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001464
Benjamin Kramer72196f32014-01-19 15:24:22 +00001465 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001466 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1467 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1468 if (Instruction *R = FoldOpIntoSelect(I, SI))
1469 return R;
1470 } else if (isa<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001471 using namespace llvm::PatternMatch;
1472 const APInt *Op1Int;
1473 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1474 (I.getOpcode() == Instruction::URem ||
1475 !Op1Int->isMinSignedValue())) {
1476 // FoldOpIntoPhi will speculate instructions to the end of the PHI's
1477 // predecessor blocks, so do this only if we know the srem or urem
1478 // will not fault.
1479 if (Instruction *NV = FoldOpIntoPhi(I))
1480 return NV;
1481 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001482 }
1483
1484 // See if we can fold away this rem instruction.
1485 if (SimplifyDemandedInstructionBits(I))
1486 return &I;
1487 }
1488 }
1489
Craig Topperf40110f2014-04-25 05:29:35 +00001490 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001491}
1492
1493Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1495
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001496 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001497 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001498
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001499 if (Value *V = SimplifyURemInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001500 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001501
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001502 if (Instruction *common = commonIRemTransforms(I))
1503 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001504
David Majnemer6c30f492013-05-12 00:07:05 +00001505 // (zext A) urem (zext B) --> zext (A urem B)
1506 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1507 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1508 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1509 I.getType());
1510
David Majnemer470b0772013-05-11 09:01:28 +00001511 // X urem Y -> X and Y-1, where Y is a power of 2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001512 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001513 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001514 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001515 return BinaryOperator::CreateAnd(Op0, Add);
1516 }
1517
Nick Lewycky7459be62013-07-13 01:16:47 +00001518 // 1 urem X -> zext(X != 1)
1519 if (match(Op0, m_One())) {
1520 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1521 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001522 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001523 }
1524
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001525 // X urem C -> X < C ? X : X - C, where C >= signbit.
1526 const APInt *DivisorC;
1527 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
1528 Value *Cmp = Builder->CreateICmpULT(Op0, Op1);
1529 Value *Sub = Builder->CreateSub(Op0, Op1);
1530 return SelectInst::Create(Cmp, Op0, Sub);
1531 }
1532
Craig Topperf40110f2014-04-25 05:29:35 +00001533 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001534}
1535
1536Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1538
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001539 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001540 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001541
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001542 if (Value *V = SimplifySRemInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001543 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001544
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001545 // Handle the integer rem common cases
1546 if (Instruction *Common = commonIRemTransforms(I))
1547 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001548
David Majnemerdb077302014-10-13 22:37:51 +00001549 {
1550 const APInt *Y;
1551 // X % -Y -> X % Y
1552 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001553 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001554 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001555 return &I;
1556 }
David Majnemerdb077302014-10-13 22:37:51 +00001557 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001558
1559 // If the sign bits of both operands are zero (i.e. we can prove they are
1560 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001561 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001562 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001563 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1564 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001565 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001566 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1567 }
1568 }
1569
1570 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001571 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1572 Constant *C = cast<Constant>(Op1);
1573 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001574
1575 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001576 bool hasMissing = false;
1577 for (unsigned i = 0; i != VWidth; ++i) {
1578 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001579 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001580 hasMissing = true;
1581 break;
1582 }
1583
1584 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001585 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001586 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001587 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001588
Chris Lattner0256be92012-01-27 03:08:05 +00001589 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001590 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001591 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001592 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001593 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001594 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001595 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001596 }
1597 }
1598
1599 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001600 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001601 Worklist.AddValue(I.getOperand(1));
1602 I.setOperand(1, NewRHSV);
1603 return &I;
1604 }
1605 }
1606 }
1607
Craig Topperf40110f2014-04-25 05:29:35 +00001608 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001609}
1610
1611Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001612 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001613
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001614 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001615 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001616
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001617 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001618 DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001619 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001620
1621 // Handle cases involving: rem X, (select Cond, Y, Z)
1622 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1623 return &I;
1624
Craig Topperf40110f2014-04-25 05:29:35 +00001625 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001626}