blob: f1ac82057e6cff23049b7b1e31edd883a1c992e4 [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)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000270 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
271 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000272
273 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
274 {
275 Value *X;
276 Constant *C1;
277 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000278 Value *Mul = Builder->CreateMul(C1, Op1);
279 // Only go forward with the transform if C1*CI simplifies to a tidier
280 // constant.
281 if (!match(Mul, m_Mul(m_Value(), m_Value())))
282 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000283 }
284 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000285 }
286
David Majnemer8279a7502014-11-22 07:25:19 +0000287 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
288 if (Value *Op1v = dyn_castNegVal(Op1)) {
289 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
290 if (I.hasNoSignedWrap() &&
291 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
292 match(Op1, m_NSWSub(m_Value(), m_Value())))
293 BO->setHasNoSignedWrap();
294 return BO;
295 }
296 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000297
298 // (X / Y) * Y = X - (X % Y)
299 // (X / Y) * -Y = (X % Y) - X
300 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000301 Value *Y = Op1;
302 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
303 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
304 Div->getOpcode() != Instruction::SDiv)) {
305 Y = Op0;
306 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000307 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000308 Value *Neg = dyn_castNegVal(Y);
309 if (Div && Div->hasOneUse() &&
310 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
311 (Div->getOpcode() == Instruction::UDiv ||
312 Div->getOpcode() == Instruction::SDiv)) {
313 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000314
Chris Lattner35315d02011-02-06 21:44:57 +0000315 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000316 if (Div->isExact()) {
317 if (DivOp1 == Y)
318 return replaceInstUsesWith(I, X);
319 return BinaryOperator::CreateNeg(X);
320 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000321
Sanjay Patela0a56822017-03-14 17:27:27 +0000322 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
323 : Instruction::SRem;
324 Value *Rem = Builder->CreateBinOp(RemOpc, X, DivOp1);
325 if (DivOp1 == Y)
326 return BinaryOperator::CreateSub(X, Rem);
327 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000328 }
329 }
330
331 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000332 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000333 return BinaryOperator::CreateAnd(Op0, Op1);
334
335 // X*(1 << Y) --> X << Y
336 // (1 << Y)*X --> X << Y
337 {
338 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000339 BinaryOperator *BO = nullptr;
340 bool ShlNSW = false;
341 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
342 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000343 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000344 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000345 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000346 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000347 }
348 if (BO) {
349 if (I.hasNoUnsignedWrap())
350 BO->setHasNoUnsignedWrap();
351 if (I.hasNoSignedWrap() && ShlNSW)
352 BO->setHasNoSignedWrap();
353 return BO;
354 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000355 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000357 // If one of the operands of the multiply is a cast from a boolean value, then
358 // we know the bool is either zero or one, so this is a 'masking' multiply.
359 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000360 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000361 // -2 is "-1 << 1" so it is all bits set except the low one.
362 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000363
Craig Topperf40110f2014-04-25 05:29:35 +0000364 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000365 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
366 BoolCast = Op0;
367 OtherOp = Op1;
368 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
369 BoolCast = Op1;
370 OtherOp = Op0;
371 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000372
373 if (BoolCast) {
374 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000375 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000376 return BinaryOperator::CreateAnd(V, OtherOp);
377 }
378 }
379
David Majnemera1cfd7c2016-12-30 00:28:58 +0000380 // Check for (mul (sext x), y), see if we can merge this into an
381 // integer mul followed by a sext.
382 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
383 // (mul (sext x), cst) --> (sext (mul x, cst'))
384 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
385 if (Op0Conv->hasOneUse()) {
386 Constant *CI =
387 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
388 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
389 WillNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
390 // Insert the new, smaller mul.
391 Value *NewMul =
392 Builder->CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
393 return new SExtInst(NewMul, I.getType());
394 }
395 }
396 }
397
398 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
399 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
400 // Only do this if x/y have the same type, if at last one of them has a
401 // single use (so we don't increase the number of sexts), and if the
402 // integer mul will not overflow.
403 if (Op0Conv->getOperand(0)->getType() ==
404 Op1Conv->getOperand(0)->getType() &&
405 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
406 WillNotOverflowSignedMul(Op0Conv->getOperand(0),
407 Op1Conv->getOperand(0), I)) {
408 // Insert the new integer mul.
409 Value *NewMul = Builder->CreateNSWMul(
410 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
411 return new SExtInst(NewMul, I.getType());
412 }
413 }
414 }
415
416 // Check for (mul (zext x), y), see if we can merge this into an
417 // integer mul followed by a zext.
418 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
419 // (mul (zext x), cst) --> (zext (mul x, cst'))
420 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
421 if (Op0Conv->hasOneUse()) {
422 Constant *CI =
423 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
424 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
David Majnemer5ec5f272016-12-30 03:36:17 +0000425 computeOverflowForUnsignedMul(Op0Conv->getOperand(0), CI, &I) ==
426 OverflowResult::NeverOverflows) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000427 // Insert the new, smaller mul.
428 Value *NewMul =
429 Builder->CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
430 return new ZExtInst(NewMul, I.getType());
431 }
432 }
433 }
434
435 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
436 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
437 // Only do this if x/y have the same type, if at last one of them has a
438 // single use (so we don't increase the number of zexts), and if the
439 // integer mul will not overflow.
440 if (Op0Conv->getOperand(0)->getType() ==
441 Op1Conv->getOperand(0)->getType() &&
442 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
443 computeOverflowForUnsignedMul(Op0Conv->getOperand(0),
444 Op1Conv->getOperand(0),
445 &I) == OverflowResult::NeverOverflows) {
446 // Insert the new integer mul.
447 Value *NewMul = Builder->CreateNUWMul(
448 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
449 return new ZExtInst(NewMul, I.getType());
450 }
451 }
452 }
453
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000454 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000455 Changed = true;
456 I.setHasNoSignedWrap(true);
457 }
458
David Majnemer491331a2015-01-02 07:29:43 +0000459 if (!I.hasNoUnsignedWrap() &&
460 computeOverflowForUnsignedMul(Op0, Op1, &I) ==
461 OverflowResult::NeverOverflows) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000462 Changed = true;
463 I.setHasNoUnsignedWrap(true);
464 }
465
Craig Topperf40110f2014-04-25 05:29:35 +0000466 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000467}
468
Sanjay Patel17045f72014-10-14 00:33:23 +0000469/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000470static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000471 if (!Op->hasOneUse())
472 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000473
Sanjay Patel17045f72014-10-14 00:33:23 +0000474 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
475 if (!II)
476 return;
477 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
478 return;
479 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000480
Sanjay Patel17045f72014-10-14 00:33:23 +0000481 Value *OpLog2Of = II->getArgOperand(0);
482 if (!OpLog2Of->hasOneUse())
483 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000484
Sanjay Patel17045f72014-10-14 00:33:23 +0000485 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
486 if (!I)
487 return;
488 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
489 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000490
Sanjay Patel17045f72014-10-14 00:33:23 +0000491 if (match(I->getOperand(0), m_SpecificFP(0.5)))
492 Y = I->getOperand(1);
493 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
494 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000495}
Pedro Artigas993acd02012-11-30 22:07:05 +0000496
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000497static bool isFiniteNonZeroFp(Constant *C) {
498 if (C->getType()->isVectorTy()) {
499 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
500 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000501 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000502 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
503 return false;
504 }
505 return true;
506 }
507
508 return isa<ConstantFP>(C) &&
509 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
510}
511
512static bool isNormalFp(Constant *C) {
513 if (C->getType()->isVectorTy()) {
514 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
515 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000516 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000517 if (!CFP || !CFP->getValueAPF().isNormal())
518 return false;
519 }
520 return true;
521 }
522
523 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
524}
525
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000526/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
527/// true iff the given value is FMul or FDiv with one and only one operand
528/// being a normal constant (i.e. not Zero/NaN/Infinity).
529static bool isFMulOrFDivWithConstant(Value *V) {
530 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000531 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000532 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000533 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000534
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000535 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
536 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000537
538 if (C0 && C1)
539 return false;
540
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000541 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000542}
543
544/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
545/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
546/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000547/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000548/// resulting expression. Note that this function could return NULL in
549/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000550///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000551Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000552 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
554
555 Value *Opnd0 = FMulOrDiv->getOperand(0);
556 Value *Opnd1 = FMulOrDiv->getOperand(1);
557
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000558 Constant *C0 = dyn_cast<Constant>(Opnd0);
559 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000560
Craig Topperf40110f2014-04-25 05:29:35 +0000561 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000562
563 // (X * C0) * C => X * (C0*C)
564 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
565 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000566 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000567 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
568 } else {
569 if (C0) {
570 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000571 if (FMulOrDiv->hasOneUse()) {
572 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000573 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000574 if (isNormalFp(F))
575 R = BinaryOperator::CreateFDiv(F, Opnd1);
576 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000577 } else {
578 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000579 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000580 if (isNormalFp(F)) {
581 R = BinaryOperator::CreateFMul(Opnd0, F);
582 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000583 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000584 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000585 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000586 R = BinaryOperator::CreateFDiv(Opnd0, F);
587 }
588 }
589 }
590
591 if (R) {
592 R->setHasUnsafeAlgebra(true);
593 InsertNewInstWith(R, *InsertBefore);
594 }
595
596 return R;
597}
598
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000599Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000600 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000601 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
602
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000603 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000604 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000605
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000606 if (isa<Constant>(Op0))
607 std::swap(Op0, Op1);
608
Chandler Carruth66b31302015-01-04 12:03:27 +0000609 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000610 SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000611 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000612
Shuxin Yange8227452013-01-15 21:09:32 +0000613 bool AllowReassociate = I.hasUnsafeAlgebra();
614
Michael Ilsemand5787be2012-12-12 00:28:32 +0000615 // Simplify mul instructions with a constant RHS.
616 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000617 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
618 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000619
Owen Andersonf74cfe02014-01-16 20:36:42 +0000620 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000621 if (match(Op1, m_SpecificFP(-1.0))) {
622 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
623 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000624 RI->copyFastMathFlags(&I);
625 return RI;
626 }
627
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000628 Constant *C = cast<Constant>(Op1);
629 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000630 // Let MDC denote an expression in one of these forms:
631 // X * C, C/X, X/C, where C is a constant.
632 //
633 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000634 if (isFMulOrFDivWithConstant(Op0))
635 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000636 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000637
Quentin Colombete684a6d2013-02-28 21:12:40 +0000638 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000639 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
640 if (FAddSub &&
641 (FAddSub->getOpcode() == Instruction::FAdd ||
642 FAddSub->getOpcode() == Instruction::FSub)) {
643 Value *Opnd0 = FAddSub->getOperand(0);
644 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000645 Constant *C0 = dyn_cast<Constant>(Opnd0);
646 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000647 bool Swap = false;
648 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000649 std::swap(C0, C1);
650 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000652 }
653
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000654 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000655 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000656 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000657 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000658 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000659 if (M0 && M1) {
660 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
661 std::swap(M0, M1);
662
Benjamin Kramer67485762013-09-30 15:39:59 +0000663 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
664 ? BinaryOperator::CreateFAdd(M0, M1)
665 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000666 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000667 return RI;
668 }
669 }
670 }
671 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000672 }
673
Matt Arsenault56c079f2016-01-30 05:02:00 +0000674 if (Op0 == Op1) {
675 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
676 // sqrt(X) * sqrt(X) -> X
677 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000678 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000679
Matt Arsenault56c079f2016-01-30 05:02:00 +0000680 // fabs(X) * fabs(X) -> X * X
681 if (II->getIntrinsicID() == Intrinsic::fabs) {
682 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
683 II->getOperand(0),
684 I.getName());
685 FMulVal->copyFastMathFlags(&I);
686 return FMulVal;
687 }
688 }
689 }
690
Pedro Artigasd8795042012-11-30 19:09:41 +0000691 // Under unsafe algebra do:
692 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000693 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000694 Value *OpX = nullptr;
695 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000696 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000697 detectLog2OfHalf(Op0, OpY, Log2);
698 if (OpY) {
699 OpX = Op1;
700 } else {
701 detectLog2OfHalf(Op1, OpY, Log2);
702 if (OpY) {
703 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000704 }
705 }
706 // if pattern detected emit alternate sequence
707 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000708 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000709 Builder->setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000710 Log2->setArgOperand(0, OpY);
711 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000712 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
713 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000714 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000715 }
716 }
717
Shuxin Yange8227452013-01-15 21:09:32 +0000718 // Handle symmetric situation in a 2-iteration loop
719 Value *Opnd0 = Op0;
720 Value *Opnd1 = Op1;
721 for (int i = 0; i < 2; i++) {
722 bool IgnoreZeroSign = I.hasNoSignedZeros();
723 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000724 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000725 Builder->setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000726
Shuxin Yange8227452013-01-15 21:09:32 +0000727 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
728 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000729
Shuxin Yange8227452013-01-15 21:09:32 +0000730 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000731 if (N1) {
732 Value *FMul = Builder->CreateFMul(N0, N1);
733 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000734 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000735 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000736
Shuxin Yange8227452013-01-15 21:09:32 +0000737 if (Opnd0->hasOneUse()) {
738 // -X * Y => -(X*Y) (Promote negation as high as possible)
739 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000740 Value *Neg = Builder->CreateFNeg(T);
741 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000742 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000743 }
744 }
Shuxin Yange8227452013-01-15 21:09:32 +0000745
746 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000747 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000748 // 1) to form a power expression (of X).
749 // 2) potentially shorten the critical path: After transformation, the
750 // latency of the instruction Y is amortized by the expression of X*X,
751 // and therefore Y is in a "less critical" position compared to what it
752 // was before the transformation.
753 //
754 if (AllowReassociate) {
755 Value *Opnd0_0, *Opnd0_1;
756 if (Opnd0->hasOneUse() &&
757 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000758 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000759 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
760 Y = Opnd0_1;
761 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
762 Y = Opnd0_0;
763
764 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000765 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000766 Builder->setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000767 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000768 Value *R = Builder->CreateFMul(T, Y);
769 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000770 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000771 }
772 }
773 }
774
775 if (!isa<Constant>(Op1))
776 std::swap(Opnd0, Opnd1);
777 else
778 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000779 }
780
Craig Topperf40110f2014-04-25 05:29:35 +0000781 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000782}
783
Sanjay Patel6eccf482015-09-09 15:24:36 +0000784/// Try to fold a divide or remainder of a select instruction.
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000785bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
786 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000787
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000788 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
789 int NonNullOperand = -1;
790 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
791 if (ST->isNullValue())
792 NonNullOperand = 2;
793 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
794 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
795 if (ST->isNullValue())
796 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000797
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000798 if (NonNullOperand == -1)
799 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000800
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000801 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000802
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000803 // Change the div/rem to use 'Y' instead of the select.
804 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000805
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000806 // Okay, we know we replace the operand of the div/rem with 'Y' with no
807 // problem. However, the select, or the condition of the select may have
808 // multiple uses. Based on our knowledge that the operand must be non-zero,
809 // propagate the known value for the select into other uses of it, and
810 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000811
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000812 // If the select and condition only have a single use, don't bother with this,
813 // early exit.
814 if (SI->use_empty() && SelectCond->hasOneUse())
815 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000816
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000817 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000818 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000819
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000820 while (BBI != BBFront) {
821 --BBI;
822 // If we found a call to a function, we can't assume it will return, so
823 // information from below it cannot be propagated above it.
824 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
825 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000826
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000827 // Replace uses of the select or its condition with the known values.
828 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
829 I != E; ++I) {
830 if (*I == SI) {
831 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000832 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000833 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000834 *I = Builder->getInt1(NonNullOperand == 1);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000835 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000836 }
837 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000838
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000839 // If we past the instruction, quit looking for it.
840 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000841 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000842 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000843 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000844
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000845 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000846 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000847 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000848
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000849 }
850 return true;
851}
852
853
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000854/// This function implements the transforms common to both integer division
855/// instructions (udiv and sdiv). It is called by the visitors to those integer
856/// division instructions.
857/// @brief Common integer divide transforms
858Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
859 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
860
Chris Lattner7c99f192011-05-22 18:18:41 +0000861 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000862 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000863 I.setOperand(1, V);
864 return &I;
865 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000866
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000867 // Handle cases involving: [su]div X, (select Cond, Y, Z)
868 // This does not apply for fdiv.
869 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
870 return &I;
871
David Majnemer27adb122014-10-12 08:34:24 +0000872 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
873 const APInt *C2;
874 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000875 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000876 const APInt *C1;
877 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000878
David Majnemer27adb122014-10-12 08:34:24 +0000879 // (X / C1) / C2 -> X / (C1*C2)
880 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
881 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
882 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
883 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
884 return BinaryOperator::Create(I.getOpcode(), X,
885 ConstantInt::get(I.getType(), Product));
886 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000887
David Majnemer27adb122014-10-12 08:34:24 +0000888 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
889 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
890 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
891
892 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
893 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
894 BinaryOperator *BO = BinaryOperator::Create(
895 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
896 BO->setIsExact(I.isExact());
897 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000898 }
899
David Majnemer27adb122014-10-12 08:34:24 +0000900 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
901 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
902 BinaryOperator *BO = BinaryOperator::Create(
903 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
904 BO->setHasNoUnsignedWrap(
905 !IsSigned &&
906 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
907 BO->setHasNoSignedWrap(
908 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
909 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000910 }
911 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000912
David Majnemer27adb122014-10-12 08:34:24 +0000913 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
914 *C1 != C1->getBitWidth() - 1) ||
915 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
916 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
917 APInt C1Shifted = APInt::getOneBitSet(
918 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
919
920 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
921 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
922 BinaryOperator *BO = BinaryOperator::Create(
923 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
924 BO->setIsExact(I.isExact());
925 return BO;
926 }
927
928 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
929 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
930 BinaryOperator *BO = BinaryOperator::Create(
931 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
932 BO->setHasNoUnsignedWrap(
933 !IsSigned &&
934 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
935 BO->setHasNoSignedWrap(
936 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
937 return BO;
938 }
939 }
940
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000941 if (*C2 != 0) // avoid X udiv 0
942 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
943 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000944 }
945 }
946
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000947 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
948 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
949 bool isSigned = I.getOpcode() == Instruction::SDiv;
950 if (isSigned) {
951 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
952 // result is one, if Op1 is -1 then the result is minus one, otherwise
953 // it's zero.
954 Value *Inc = Builder->CreateAdd(Op1, One);
955 Value *Cmp = Builder->CreateICmpULT(
956 Inc, ConstantInt::get(I.getType(), 3));
957 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
958 } else {
959 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
960 // result is one, otherwise it's zero.
961 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
962 }
963 }
964 }
965
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000966 // See if we can fold away this div instruction.
967 if (SimplifyDemandedInstructionBits(I))
968 return &I;
969
Duncan Sands771e82a2011-01-28 16:51:11 +0000970 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000971 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000972 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
973 bool isSigned = I.getOpcode() == Instruction::SDiv;
974 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
975 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
976 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000977 }
978
Craig Topperf40110f2014-04-25 05:29:35 +0000979 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000980}
981
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000982/// dyn_castZExtVal - Checks if V is a zext or constant that can
983/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000984static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000985 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
986 if (Z->getSrcTy() == Ty)
987 return Z->getOperand(0);
988 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
989 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
990 return ConstantExpr::getTrunc(C, Ty);
991 }
Craig Topperf40110f2014-04-25 05:29:35 +0000992 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000993}
994
David Majnemer37f8f442013-07-04 21:17:49 +0000995namespace {
996const unsigned MaxDepth = 6;
997typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
998 const BinaryOperator &I,
999 InstCombiner &IC);
1000
1001/// \brief Used to maintain state for visitUDivOperand().
1002struct UDivFoldAction {
1003 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
1004 ///< operand. This can be zero if this action
1005 ///< joins two actions together.
1006
1007 Value *OperandToFold; ///< Which operand to fold.
1008 union {
1009 Instruction *FoldResult; ///< The instruction returned when FoldAction is
1010 ///< invoked.
1011
1012 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
1013 ///< joins two actions together.
1014 };
1015
1016 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001017 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001018 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1019 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1020};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001021}
David Majnemer37f8f442013-07-04 21:17:49 +00001022
1023// X udiv 2^C -> X >> C
1024static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1025 const BinaryOperator &I, InstCombiner &IC) {
1026 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1027 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1028 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001029 if (I.isExact())
1030 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001031 return LShr;
1032}
1033
1034// X udiv C, where C >= signbit
1035static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1036 const BinaryOperator &I, InstCombiner &IC) {
1037 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
1038
1039 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1040 ConstantInt::get(I.getType(), 1));
1041}
1042
1043// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001044// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001045static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1046 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001047 Value *ShiftLeft;
1048 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1049 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001050
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001051 const APInt *CI;
1052 Value *N;
1053 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1054 llvm_unreachable("match should never fail here!");
1055 if (*CI != 1)
1056 N = IC.Builder->CreateAdd(N,
1057 ConstantInt::get(N->getType(), CI->logBase2()));
1058 if (Op1 != ShiftLeft)
1059 N = IC.Builder->CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001060 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001061 if (I.isExact())
1062 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001063 return LShr;
1064}
1065
1066// \brief Recursively visits the possible right hand operands of a udiv
1067// instruction, seeing through select instructions, to determine if we can
1068// replace the udiv with something simpler. If we find that an operand is not
1069// able to simplify the udiv, we abort the entire transformation.
1070static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1071 SmallVectorImpl<UDivFoldAction> &Actions,
1072 unsigned Depth = 0) {
1073 // Check to see if this is an unsigned division with an exact power of 2,
1074 // if so, convert to a right shift.
1075 if (match(Op1, m_Power2())) {
1076 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1077 return Actions.size();
1078 }
1079
1080 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1081 // X udiv C, where C >= signbit
1082 if (C->getValue().isNegative()) {
1083 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1084 return Actions.size();
1085 }
1086
1087 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1088 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1089 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1090 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1091 return Actions.size();
1092 }
1093
1094 // The remaining tests are all recursive, so bail out if we hit the limit.
1095 if (Depth++ == MaxDepth)
1096 return 0;
1097
1098 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001099 if (size_t LHSIdx =
1100 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1101 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1102 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001103 return Actions.size();
1104 }
1105
1106 return 0;
1107}
1108
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001109Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1111
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001112 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001113 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001114
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001115 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001116 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001117
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001118 // Handle the integer div common cases
1119 if (Instruction *Common = commonIDivTransforms(I))
1120 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001121
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001122 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001123 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001124 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001125 const APInt *C1, *C2;
1126 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1127 match(Op1, m_APInt(C2))) {
1128 bool Overflow;
1129 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001130 if (!Overflow) {
1131 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1132 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001133 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001134 if (IsExact)
1135 BO->setIsExact();
1136 return BO;
1137 }
David Majnemera2521382014-10-13 21:48:30 +00001138 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001139 }
1140
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001141 // (zext A) udiv (zext B) --> zext (A udiv B)
1142 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1143 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001144 return new ZExtInst(
1145 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1146 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001147
David Majnemer37f8f442013-07-04 21:17:49 +00001148 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1149 SmallVector<UDivFoldAction, 6> UDivActions;
1150 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1151 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1152 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1153 Value *ActionOp1 = UDivActions[i].OperandToFold;
1154 Instruction *Inst;
1155 if (Action)
1156 Inst = Action(Op0, ActionOp1, I, *this);
1157 else {
1158 // This action joins two actions together. The RHS of this action is
1159 // simply the last action we processed, we saved the LHS action index in
1160 // the joining action.
1161 size_t SelectRHSIdx = i - 1;
1162 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1163 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1164 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1165 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1166 SelectLHS, SelectRHS);
1167 }
1168
1169 // If this is the last action to process, return it to the InstCombiner.
1170 // Otherwise, we insert it before the UDiv and record it so that we may
1171 // use it as part of a joining action (i.e., a SelectInst).
1172 if (e - i != 1) {
1173 Inst->insertBefore(&I);
1174 UDivActions[i].FoldResult = Inst;
1175 } else
1176 return Inst;
1177 }
1178
Craig Topperf40110f2014-04-25 05:29:35 +00001179 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001180}
1181
1182Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1183 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1184
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001185 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001186 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001187
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001188 if (Value *V = SimplifySDivInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001189 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001190
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001191 // Handle the integer div common cases
1192 if (Instruction *Common = commonIDivTransforms(I))
1193 return Common;
1194
Sanjay Patelc6ada532016-06-27 17:25:57 +00001195 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001196 if (match(Op1, m_APInt(Op1C))) {
1197 // sdiv X, -1 == -X
1198 if (Op1C->isAllOnesValue())
1199 return BinaryOperator::CreateNeg(Op0);
1200
1201 // sdiv exact X, C --> ashr exact X, log2(C)
1202 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1203 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1204 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1205 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001206
1207 // If the dividend is sign-extended and the constant divisor is small enough
1208 // to fit in the source type, shrink the division to the narrower type:
1209 // (sext X) sdiv C --> sext (X sdiv C)
1210 Value *Op0Src;
1211 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1212 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1213
1214 // In the general case, we need to make sure that the dividend is not the
1215 // minimum signed value because dividing that by -1 is UB. But here, we
1216 // know that the -1 divisor case is already handled above.
1217
1218 Constant *NarrowDivisor =
1219 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1220 Value *NarrowOp = Builder->CreateSDiv(Op0Src, NarrowDivisor);
1221 return new SExtInst(NarrowOp, Op0->getType());
1222 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001223 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001224
Benjamin Kramer72196f32014-01-19 15:24:22 +00001225 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001226 // X/INT_MIN -> X == INT_MIN
1227 if (RHS->isMinSignedValue())
1228 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1229
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001230 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001231 Value *X;
1232 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1233 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1234 BO->setIsExact(I.isExact());
1235 return BO;
1236 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001237 }
1238
1239 // If the sign bits of both operands are zero (i.e. we can prove they are
1240 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001241 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001242 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001243 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1244 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001245 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
David Majnemerec6e4812014-11-22 20:00:38 +00001246 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1247 BO->setIsExact(I.isExact());
1248 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001249 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001250
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001251 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001252 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1253 // Safe because the only negative value (1 << Y) can take on is
1254 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1255 // the sign bit set.
David Majnemerfb380552014-11-22 20:00:41 +00001256 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1257 BO->setIsExact(I.isExact());
1258 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001259 }
1260 }
1261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001262
Craig Topperf40110f2014-04-25 05:29:35 +00001263 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264}
1265
Shuxin Yang320f52a2013-01-14 22:48:41 +00001266/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1267/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001268/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001269/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001270/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001271/// returned; otherwise, NULL is returned.
1272///
Suyog Sardaea205512014-10-07 11:56:06 +00001273static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001274 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001275 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001276 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001277
1278 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001279 APFloat Reciprocal(FpVal.getSemantics());
1280 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001281
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001282 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001283 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1284 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1285 Cvt = !Reciprocal.isDenormal();
1286 }
1287
1288 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001289 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001290
1291 ConstantFP *R;
1292 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1293 return BinaryOperator::CreateFMul(Dividend, R);
1294}
1295
Frits van Bommel2a559512011-01-29 17:50:27 +00001296Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1298
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001299 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001300 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001301
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001302 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001303 DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001304 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001305
Stephen Lina9b57f62013-07-20 07:13:13 +00001306 if (isa<Constant>(Op0))
1307 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1308 if (Instruction *R = FoldOpIntoSelect(I, SI))
1309 return R;
1310
Shuxin Yang320f52a2013-01-14 22:48:41 +00001311 bool AllowReassociate = I.hasUnsafeAlgebra();
1312 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001313
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001314 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001315 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1316 if (Instruction *R = FoldOpIntoSelect(I, SI))
1317 return R;
1318
Shuxin Yang320f52a2013-01-14 22:48:41 +00001319 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001320 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001321 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001322 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001323 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001324
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001325 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001326 // (X*C1)/C2 => X * (C1/C2)
1327 //
1328 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001329 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001330 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001331 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001332 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1333 //
1334 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001335 if (isNormalFp(C)) {
1336 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001337 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001338 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001339 }
1340 }
1341
1342 if (Res) {
1343 Res->setFastMathFlags(I.getFastMathFlags());
1344 return Res;
1345 }
1346 }
1347
1348 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001349 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1350 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001351 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001352 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001353
Craig Topperf40110f2014-04-25 05:29:35 +00001354 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001355 }
1356
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001357 if (AllowReassociate && isa<Constant>(Op0)) {
1358 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001359 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001360 Value *X;
1361 bool CreateDiv = true;
1362
1363 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001364 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001365 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001366 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001367 // C1 / (X/C2) => (C1*C2) / X
1368 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001369 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001370 // C1 / (C2/X) => (C1/C2) * X
1371 Fold = ConstantExpr::getFDiv(C1, C2);
1372 CreateDiv = false;
1373 }
1374
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001375 if (Fold && isNormalFp(Fold)) {
1376 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1377 : BinaryOperator::CreateFMul(X, Fold);
1378 R->setFastMathFlags(I.getFastMathFlags());
1379 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001380 }
Craig Topperf40110f2014-04-25 05:29:35 +00001381 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001382 }
1383
1384 if (AllowReassociate) {
1385 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001386 Value *NewInst = nullptr;
1387 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001388
1389 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1390 // (X/Y) / Z => X / (Y*Z)
1391 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001392 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001393 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001394 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1395 FastMathFlags Flags = I.getFastMathFlags();
1396 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1397 RI->setFastMathFlags(Flags);
1398 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001399 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1400 }
1401 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1402 // Z / (X/Y) => Z*Y / X
1403 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001404 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001405 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001406 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1407 FastMathFlags Flags = I.getFastMathFlags();
1408 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1409 RI->setFastMathFlags(Flags);
1410 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001411 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1412 }
1413 }
1414
1415 if (NewInst) {
1416 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1417 T->setDebugLoc(I.getDebugLoc());
1418 SimpR->setFastMathFlags(I.getFastMathFlags());
1419 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001420 }
1421 }
1422
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001423 Value *LHS;
1424 Value *RHS;
1425
1426 // -x / -y -> x / y
1427 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1428 I.setOperand(0, LHS);
1429 I.setOperand(1, RHS);
1430 return &I;
1431 }
1432
Craig Topperf40110f2014-04-25 05:29:35 +00001433 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001434}
1435
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001436/// This function implements the transforms common to both integer remainder
1437/// instructions (urem and srem). It is called by the visitors to those integer
1438/// remainder instructions.
1439/// @brief Common integer remainder transforms
1440Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1441 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1442
Chris Lattner7c99f192011-05-22 18:18:41 +00001443 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001444 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001445 I.setOperand(1, V);
1446 return &I;
1447 }
1448
Duncan Sandsa3e36992011-05-02 16:27:02 +00001449 // Handle cases involving: rem X, (select Cond, Y, Z)
1450 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1451 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001452
Benjamin Kramer72196f32014-01-19 15:24:22 +00001453 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001454 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1455 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1456 if (Instruction *R = FoldOpIntoSelect(I, SI))
1457 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001458 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001459 using namespace llvm::PatternMatch;
1460 const APInt *Op1Int;
1461 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1462 (I.getOpcode() == Instruction::URem ||
1463 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001464 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001465 // predecessor blocks, so do this only if we know the srem or urem
1466 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001467 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001468 return NV;
1469 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001470 }
1471
1472 // See if we can fold away this rem instruction.
1473 if (SimplifyDemandedInstructionBits(I))
1474 return &I;
1475 }
1476 }
1477
Craig Topperf40110f2014-04-25 05:29:35 +00001478 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001479}
1480
1481Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1483
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001484 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001485 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001486
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001487 if (Value *V = SimplifyURemInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001488 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001489
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001490 if (Instruction *common = commonIRemTransforms(I))
1491 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001492
David Majnemer6c30f492013-05-12 00:07:05 +00001493 // (zext A) urem (zext B) --> zext (A urem B)
1494 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1495 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1496 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1497 I.getType());
1498
David Majnemer470b0772013-05-11 09:01:28 +00001499 // X urem Y -> X and Y-1, where Y is a power of 2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001500 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001501 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001502 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001503 return BinaryOperator::CreateAnd(Op0, Add);
1504 }
1505
Nick Lewycky7459be62013-07-13 01:16:47 +00001506 // 1 urem X -> zext(X != 1)
1507 if (match(Op0, m_One())) {
1508 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1509 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001510 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001511 }
1512
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001513 // X urem C -> X < C ? X : X - C, where C >= signbit.
1514 const APInt *DivisorC;
1515 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
1516 Value *Cmp = Builder->CreateICmpULT(Op0, Op1);
1517 Value *Sub = Builder->CreateSub(Op0, Op1);
1518 return SelectInst::Create(Cmp, Op0, Sub);
1519 }
1520
Craig Topperf40110f2014-04-25 05:29:35 +00001521 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001522}
1523
1524Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1525 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1526
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001527 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001528 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001529
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001530 if (Value *V = SimplifySRemInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001531 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001532
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001533 // Handle the integer rem common cases
1534 if (Instruction *Common = commonIRemTransforms(I))
1535 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001536
David Majnemerdb077302014-10-13 22:37:51 +00001537 {
1538 const APInt *Y;
1539 // X % -Y -> X % Y
1540 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001541 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001542 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001543 return &I;
1544 }
David Majnemerdb077302014-10-13 22:37:51 +00001545 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001546
1547 // If the sign bits of both operands are zero (i.e. we can prove they are
1548 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001549 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001550 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001551 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1552 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001553 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001554 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1555 }
1556 }
1557
1558 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001559 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1560 Constant *C = cast<Constant>(Op1);
1561 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001562
1563 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001564 bool hasMissing = false;
1565 for (unsigned i = 0; i != VWidth; ++i) {
1566 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001567 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001568 hasMissing = true;
1569 break;
1570 }
1571
1572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001573 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001574 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001575 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001576
Chris Lattner0256be92012-01-27 03:08:05 +00001577 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001578 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001579 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001580 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001582 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001583 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001584 }
1585 }
1586
1587 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001588 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001589 Worklist.AddValue(I.getOperand(1));
1590 I.setOperand(1, NewRHSV);
1591 return &I;
1592 }
1593 }
1594 }
1595
Craig Topperf40110f2014-04-25 05:29:35 +00001596 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001597}
1598
1599Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001600 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001601
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001602 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001603 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001604
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001605 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001606 DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001607 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001608
1609 // Handle cases involving: rem X, (select Cond, Y, Z)
1610 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1611 return &I;
1612
Craig Topperf40110f2014-04-25 05:29:35 +00001613 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001614}