blob: 78f585f6f73117cee2a0ef51660a884cd1953119 [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
15#include "InstCombine.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
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000028static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
29 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 <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +000049 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
50 0, IC.getAssumptionTracker(),
51 CxtI,
52 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000055 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 I->setOperand(0, V2);
57 MadeChange = true;
58 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000059
Chris Lattner388cb8a2011-05-23 00:32:19 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattner388cb8a2011-05-23 00:32:19 +000065 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
Chris Lattnerdc054bf2010-01-05 06:09:35 +000079/// MultiplyOverflows - True if the multiply can not be expressed in an int
80/// this size.
David Majnemer27adb122014-10-12 08:34:24 +000081static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
82 bool IsSigned) {
83 bool Overflow;
84 if (IsSigned)
85 Product = C1.smul_ov(C2, Overflow);
86 else
87 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088
David Majnemer27adb122014-10-12 08:34:24 +000089 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090}
91
David Majnemerf9a095d2014-08-16 08:55:06 +000092/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94 bool IsSigned) {
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
97
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
99 if (IsSigned)
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
101 else
102 APInt::udivrem(C1, C2, Quotient, Remainder);
103
104 return Remainder.isMinValue();
105}
106
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107/// \brief A helper routine of InstCombiner::visitMul().
108///
109/// If C is a vector of known powers of 2, then this function returns
110/// a new vector obtained from C replacing each element with its logBase2.
111/// Return a null pointer otherwise.
112static Constant *getLogBase2Vector(ConstantDataVector *CV) {
113 const APInt *IVal;
114 SmallVector<Constant *, 4> Elts;
115
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
121 }
122
123 return ConstantVector::get(Elts);
124}
125
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000126Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000127 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
129
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000130 if (Value *V = SimplifyVectorOp(I))
131 return ReplaceInstUsesWith(I, V);
132
Hal Finkel60db0582014-09-07 18:57:58 +0000133 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000134 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000135
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000136 if (Value *V = SimplifyUsingDistributiveLaws(I))
137 return ReplaceInstUsesWith(I, V);
138
David Majnemer027bc802014-11-22 04:52:38 +0000139 // X * -1 == 0 - X
140 if (match(Op1, m_AllOnes())) {
141 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
142 if (I.hasNoSignedWrap())
143 BO->setHasNoSignedWrap();
144 return BO;
145 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000146
Rafael Espindola65281bf2013-05-31 14:27:15 +0000147 // Also allow combining multiply instructions on vectors.
148 {
149 Value *NewOp;
150 Constant *C1, *C2;
151 const APInt *IVal;
152 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
153 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000154 match(C1, m_APInt(IVal))) {
155 // ((X << C2)*C1) == (X * (C1 << C2))
156 Constant *Shl = ConstantExpr::getShl(C1, C2);
157 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
158 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
159 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
160 BO->setHasNoUnsignedWrap();
161 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
162 Shl->isNotMinSignedValue())
163 BO->setHasNoSignedWrap();
164 return BO;
165 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000166
Rafael Espindola65281bf2013-05-31 14:27:15 +0000167 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000168 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000169 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
170 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
171 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
172 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
173 // Replace X*(2^C) with X << C, where C is a vector of known
174 // constant powers of 2.
175 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000176
Rafael Espindola65281bf2013-05-31 14:27:15 +0000177 if (NewCst) {
178 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000179
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000180 if (I.hasNoUnsignedWrap())
181 Shl->setHasNoUnsignedWrap();
David Majnemer80c8f622014-11-22 04:52:55 +0000182 if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
183 Shl->setHasNoSignedWrap();
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000184
Rafael Espindola65281bf2013-05-31 14:27:15 +0000185 return Shl;
186 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000187 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Rafael Espindola65281bf2013-05-31 14:27:15 +0000190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000191 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
192 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
193 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000194 {
195 const APInt & Val = CI->getValue();
196 const APInt &PosVal = Val.abs();
197 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000198 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000199 if (Op0->hasOneUse()) {
200 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000201 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000202 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
203 Sub = Builder->CreateSub(X, Y, "suba");
204 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
205 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
206 if (Sub)
207 return
208 BinaryOperator::CreateMul(Sub,
209 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000210 }
211 }
212 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000213 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000214
Chris Lattner6b657ae2011-02-10 05:36:31 +0000215 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000216 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000217 // Try to fold constant mul into select arguments.
218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
219 if (Instruction *R = FoldOpIntoSelect(I, SI))
220 return R;
221
222 if (isa<PHINode>(Op0))
223 if (Instruction *NV = FoldOpIntoPhi(I))
224 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000225
226 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
227 {
228 Value *X;
229 Constant *C1;
230 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000231 Value *Mul = Builder->CreateMul(C1, Op1);
232 // Only go forward with the transform if C1*CI simplifies to a tidier
233 // constant.
234 if (!match(Mul, m_Mul(m_Value(), m_Value())))
235 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000236 }
237 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000238 }
239
David Majnemer8279a7502014-11-22 07:25:19 +0000240 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
241 if (Value *Op1v = dyn_castNegVal(Op1)) {
242 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
243 if (I.hasNoSignedWrap() &&
244 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
245 match(Op1, m_NSWSub(m_Value(), m_Value())))
246 BO->setHasNoSignedWrap();
247 return BO;
248 }
249 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000250
251 // (X / Y) * Y = X - (X % Y)
252 // (X / Y) * -Y = (X % Y) - X
253 {
254 Value *Op1C = Op1;
255 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
256 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000257 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000258 BO->getOpcode() != Instruction::SDiv)) {
259 Op1C = Op0;
260 BO = dyn_cast<BinaryOperator>(Op1);
261 }
262 Value *Neg = dyn_castNegVal(Op1C);
263 if (BO && BO->hasOneUse() &&
264 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
265 (BO->getOpcode() == Instruction::UDiv ||
266 BO->getOpcode() == Instruction::SDiv)) {
267 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
268
Chris Lattner35315d02011-02-06 21:44:57 +0000269 // If the division is exact, X % Y is zero, so we end up with X or -X.
270 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000271 if (SDiv->isExact()) {
272 if (Op1BO == Op1C)
273 return ReplaceInstUsesWith(I, Op0BO);
274 return BinaryOperator::CreateNeg(Op0BO);
275 }
276
277 Value *Rem;
278 if (BO->getOpcode() == Instruction::UDiv)
279 Rem = Builder->CreateURem(Op0BO, Op1BO);
280 else
281 Rem = Builder->CreateSRem(Op0BO, Op1BO);
282 Rem->takeName(BO);
283
284 if (Op1BO == Op1C)
285 return BinaryOperator::CreateSub(Op0BO, Rem);
286 return BinaryOperator::CreateSub(Rem, Op0BO);
287 }
288 }
289
290 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000291 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292 return BinaryOperator::CreateAnd(Op0, Op1);
293
294 // X*(1 << Y) --> X << Y
295 // (1 << Y)*X --> X << Y
296 {
297 Value *Y;
298 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
299 return BinaryOperator::CreateShl(Op1, Y);
300 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
301 return BinaryOperator::CreateShl(Op0, Y);
302 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000303
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000304 // If one of the operands of the multiply is a cast from a boolean value, then
305 // we know the bool is either zero or one, so this is a 'masking' multiply.
306 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000307 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000308 // -2 is "-1 << 1" so it is all bits set except the low one.
309 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000310
Craig Topperf40110f2014-04-25 05:29:35 +0000311 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000312 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000313 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000314 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000315 BoolCast = Op1, OtherOp = Op0;
316
317 if (BoolCast) {
318 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000319 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000320 return BinaryOperator::CreateAnd(V, OtherOp);
321 }
322 }
323
Craig Topperf40110f2014-04-25 05:29:35 +0000324 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000325}
326
Sanjay Patel17045f72014-10-14 00:33:23 +0000327/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000328static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000329 if (!Op->hasOneUse())
330 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000331
Sanjay Patel17045f72014-10-14 00:33:23 +0000332 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
333 if (!II)
334 return;
335 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
336 return;
337 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000338
Sanjay Patel17045f72014-10-14 00:33:23 +0000339 Value *OpLog2Of = II->getArgOperand(0);
340 if (!OpLog2Of->hasOneUse())
341 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000342
Sanjay Patel17045f72014-10-14 00:33:23 +0000343 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
344 if (!I)
345 return;
346 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
347 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000348
Sanjay Patel17045f72014-10-14 00:33:23 +0000349 if (match(I->getOperand(0), m_SpecificFP(0.5)))
350 Y = I->getOperand(1);
351 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
352 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000353}
Pedro Artigas993acd02012-11-30 22:07:05 +0000354
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000355static bool isFiniteNonZeroFp(Constant *C) {
356 if (C->getType()->isVectorTy()) {
357 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
358 ++I) {
359 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
360 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
361 return false;
362 }
363 return true;
364 }
365
366 return isa<ConstantFP>(C) &&
367 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
368}
369
370static bool isNormalFp(Constant *C) {
371 if (C->getType()->isVectorTy()) {
372 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
373 ++I) {
374 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
375 if (!CFP || !CFP->getValueAPF().isNormal())
376 return false;
377 }
378 return true;
379 }
380
381 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
382}
383
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000384/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
385/// true iff the given value is FMul or FDiv with one and only one operand
386/// being a normal constant (i.e. not Zero/NaN/Infinity).
387static bool isFMulOrFDivWithConstant(Value *V) {
388 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000389 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000390 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000391 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000392
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000393 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
394 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000395
396 if (C0 && C1)
397 return false;
398
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000399 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000400}
401
402/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
403/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
404/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000405/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000406/// resulting expression. Note that this function could return NULL in
407/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000408///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000409Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000410 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000411 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
412
413 Value *Opnd0 = FMulOrDiv->getOperand(0);
414 Value *Opnd1 = FMulOrDiv->getOperand(1);
415
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000416 Constant *C0 = dyn_cast<Constant>(Opnd0);
417 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000418
Craig Topperf40110f2014-04-25 05:29:35 +0000419 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000420
421 // (X * C0) * C => X * (C0*C)
422 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
423 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000424 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000425 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
426 } else {
427 if (C0) {
428 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000429 if (FMulOrDiv->hasOneUse()) {
430 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000431 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000432 if (isNormalFp(F))
433 R = BinaryOperator::CreateFDiv(F, Opnd1);
434 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000435 } else {
436 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000437 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000438 if (isNormalFp(F)) {
439 R = BinaryOperator::CreateFMul(Opnd0, F);
440 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000441 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000442 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000443 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000444 R = BinaryOperator::CreateFDiv(Opnd0, F);
445 }
446 }
447 }
448
449 if (R) {
450 R->setHasUnsafeAlgebra(true);
451 InsertNewInstWith(R, *InsertBefore);
452 }
453
454 return R;
455}
456
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000457Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000458 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000459 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
460
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000461 if (Value *V = SimplifyVectorOp(I))
462 return ReplaceInstUsesWith(I, V);
463
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000464 if (isa<Constant>(Op0))
465 std::swap(Op0, Op1);
466
Hal Finkel60db0582014-09-07 18:57:58 +0000467 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
468 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000469 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000470
Shuxin Yange8227452013-01-15 21:09:32 +0000471 bool AllowReassociate = I.hasUnsafeAlgebra();
472
Michael Ilsemand5787be2012-12-12 00:28:32 +0000473 // Simplify mul instructions with a constant RHS.
474 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000475 // Try to fold constant mul into select arguments.
476 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
477 if (Instruction *R = FoldOpIntoSelect(I, SI))
478 return R;
479
480 if (isa<PHINode>(Op0))
481 if (Instruction *NV = FoldOpIntoPhi(I))
482 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000483
Owen Andersonf74cfe02014-01-16 20:36:42 +0000484 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000485 if (match(Op1, m_SpecificFP(-1.0))) {
486 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
487 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000488 RI->copyFastMathFlags(&I);
489 return RI;
490 }
491
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000492 Constant *C = cast<Constant>(Op1);
493 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000494 // Let MDC denote an expression in one of these forms:
495 // X * C, C/X, X/C, where C is a constant.
496 //
497 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000498 if (isFMulOrFDivWithConstant(Op0))
499 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000500 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000501
Quentin Colombete684a6d2013-02-28 21:12:40 +0000502 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000503 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
504 if (FAddSub &&
505 (FAddSub->getOpcode() == Instruction::FAdd ||
506 FAddSub->getOpcode() == Instruction::FSub)) {
507 Value *Opnd0 = FAddSub->getOperand(0);
508 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000509 Constant *C0 = dyn_cast<Constant>(Opnd0);
510 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000511 bool Swap = false;
512 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000513 std::swap(C0, C1);
514 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000515 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000516 }
517
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000518 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000519 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000520 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000521 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000522 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000523 if (M0 && M1) {
524 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
525 std::swap(M0, M1);
526
Benjamin Kramer67485762013-09-30 15:39:59 +0000527 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
528 ? BinaryOperator::CreateFAdd(M0, M1)
529 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000530 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000531 return RI;
532 }
533 }
534 }
535 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000536 }
537
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000538 // sqrt(X) * sqrt(X) -> X
539 if (AllowReassociate && (Op0 == Op1))
540 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
541 if (II->getIntrinsicID() == Intrinsic::sqrt)
542 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000543
Pedro Artigasd8795042012-11-30 19:09:41 +0000544 // Under unsafe algebra do:
545 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000546 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000547 Value *OpX = nullptr;
548 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000549 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000550 detectLog2OfHalf(Op0, OpY, Log2);
551 if (OpY) {
552 OpX = Op1;
553 } else {
554 detectLog2OfHalf(Op1, OpY, Log2);
555 if (OpY) {
556 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000557 }
558 }
559 // if pattern detected emit alternate sequence
560 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000561 BuilderTy::FastMathFlagGuard Guard(*Builder);
562 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000563 Log2->setArgOperand(0, OpY);
564 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000565 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
566 FSub->takeName(&I);
567 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000568 }
569 }
570
Shuxin Yange8227452013-01-15 21:09:32 +0000571 // Handle symmetric situation in a 2-iteration loop
572 Value *Opnd0 = Op0;
573 Value *Opnd1 = Op1;
574 for (int i = 0; i < 2; i++) {
575 bool IgnoreZeroSign = I.hasNoSignedZeros();
576 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000577 BuilderTy::FastMathFlagGuard Guard(*Builder);
578 Builder->SetFastMathFlags(I.getFastMathFlags());
579
Shuxin Yange8227452013-01-15 21:09:32 +0000580 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
581 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000582
Shuxin Yange8227452013-01-15 21:09:32 +0000583 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000584 if (N1) {
585 Value *FMul = Builder->CreateFMul(N0, N1);
586 FMul->takeName(&I);
587 return ReplaceInstUsesWith(I, FMul);
588 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000589
Shuxin Yange8227452013-01-15 21:09:32 +0000590 if (Opnd0->hasOneUse()) {
591 // -X * Y => -(X*Y) (Promote negation as high as possible)
592 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000593 Value *Neg = Builder->CreateFNeg(T);
594 Neg->takeName(&I);
595 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000596 }
597 }
Shuxin Yange8227452013-01-15 21:09:32 +0000598
599 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000600 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000601 // 1) to form a power expression (of X).
602 // 2) potentially shorten the critical path: After transformation, the
603 // latency of the instruction Y is amortized by the expression of X*X,
604 // and therefore Y is in a "less critical" position compared to what it
605 // was before the transformation.
606 //
607 if (AllowReassociate) {
608 Value *Opnd0_0, *Opnd0_1;
609 if (Opnd0->hasOneUse() &&
610 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000611 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000612 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
613 Y = Opnd0_1;
614 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
615 Y = Opnd0_0;
616
617 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000618 BuilderTy::FastMathFlagGuard Guard(*Builder);
619 Builder->SetFastMathFlags(I.getFastMathFlags());
620 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000621
Benjamin Kramer67485762013-09-30 15:39:59 +0000622 Value *R = Builder->CreateFMul(T, Y);
623 R->takeName(&I);
624 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000625 }
626 }
627 }
628
629 if (!isa<Constant>(Op1))
630 std::swap(Opnd0, Opnd1);
631 else
632 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000633 }
634
Craig Topperf40110f2014-04-25 05:29:35 +0000635 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000636}
637
638/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
639/// instruction.
640bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
641 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000642
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000643 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
644 int NonNullOperand = -1;
645 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
646 if (ST->isNullValue())
647 NonNullOperand = 2;
648 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
649 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
650 if (ST->isNullValue())
651 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000652
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000653 if (NonNullOperand == -1)
654 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000655
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000656 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000658 // Change the div/rem to use 'Y' instead of the select.
659 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000660
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000661 // Okay, we know we replace the operand of the div/rem with 'Y' with no
662 // problem. However, the select, or the condition of the select may have
663 // multiple uses. Based on our knowledge that the operand must be non-zero,
664 // propagate the known value for the select into other uses of it, and
665 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000666
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000667 // If the select and condition only have a single use, don't bother with this,
668 // early exit.
669 if (SI->use_empty() && SelectCond->hasOneUse())
670 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000671
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000672 // Scan the current block backward, looking for other uses of SI.
673 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000674
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000675 while (BBI != BBFront) {
676 --BBI;
677 // If we found a call to a function, we can't assume it will return, so
678 // information from below it cannot be propagated above it.
679 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
680 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 // Replace uses of the select or its condition with the known values.
683 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
684 I != E; ++I) {
685 if (*I == SI) {
686 *I = SI->getOperand(NonNullOperand);
687 Worklist.Add(BBI);
688 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000689 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 Worklist.Add(BBI);
691 }
692 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000693
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000694 // If we past the instruction, quit looking for it.
695 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000696 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000698 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000699
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000700 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000701 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000702 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000704 }
705 return true;
706}
707
708
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000709/// This function implements the transforms common to both integer division
710/// instructions (udiv and sdiv). It is called by the visitors to those integer
711/// division instructions.
712/// @brief Common integer divide transforms
713Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
715
Chris Lattner7c99f192011-05-22 18:18:41 +0000716 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000717 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000718 I.setOperand(1, V);
719 return &I;
720 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000721
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000722 // Handle cases involving: [su]div X, (select Cond, Y, Z)
723 // This does not apply for fdiv.
724 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
725 return &I;
726
David Majnemer27adb122014-10-12 08:34:24 +0000727 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
728 const APInt *C2;
729 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000730 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000731 const APInt *C1;
732 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000733
David Majnemer27adb122014-10-12 08:34:24 +0000734 // (X / C1) / C2 -> X / (C1*C2)
735 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
736 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
737 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
738 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
739 return BinaryOperator::Create(I.getOpcode(), X,
740 ConstantInt::get(I.getType(), Product));
741 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000742
David Majnemer27adb122014-10-12 08:34:24 +0000743 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
744 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
745 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
746
747 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
748 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
749 BinaryOperator *BO = BinaryOperator::Create(
750 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
751 BO->setIsExact(I.isExact());
752 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000753 }
754
David Majnemer27adb122014-10-12 08:34:24 +0000755 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
756 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
757 BinaryOperator *BO = BinaryOperator::Create(
758 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
759 BO->setHasNoUnsignedWrap(
760 !IsSigned &&
761 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
762 BO->setHasNoSignedWrap(
763 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
764 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000765 }
766 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000767
David Majnemer27adb122014-10-12 08:34:24 +0000768 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
769 *C1 != C1->getBitWidth() - 1) ||
770 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
771 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
772 APInt C1Shifted = APInt::getOneBitSet(
773 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
774
775 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
776 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
777 BinaryOperator *BO = BinaryOperator::Create(
778 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
779 BO->setIsExact(I.isExact());
780 return BO;
781 }
782
783 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
784 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
785 BinaryOperator *BO = BinaryOperator::Create(
786 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
787 BO->setHasNoUnsignedWrap(
788 !IsSigned &&
789 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
790 BO->setHasNoSignedWrap(
791 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
792 return BO;
793 }
794 }
795
796 if (*C2 != 0) { // avoid X udiv 0
797 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
798 if (Instruction *R = FoldOpIntoSelect(I, SI))
799 return R;
800 if (isa<PHINode>(Op0))
801 if (Instruction *NV = FoldOpIntoPhi(I))
802 return NV;
803 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000804 }
805 }
806
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000807 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
808 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
809 bool isSigned = I.getOpcode() == Instruction::SDiv;
810 if (isSigned) {
811 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
812 // result is one, if Op1 is -1 then the result is minus one, otherwise
813 // it's zero.
814 Value *Inc = Builder->CreateAdd(Op1, One);
815 Value *Cmp = Builder->CreateICmpULT(
816 Inc, ConstantInt::get(I.getType(), 3));
817 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
818 } else {
819 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
820 // result is one, otherwise it's zero.
821 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
822 }
823 }
824 }
825
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000826 // See if we can fold away this div instruction.
827 if (SimplifyDemandedInstructionBits(I))
828 return &I;
829
Duncan Sands771e82a2011-01-28 16:51:11 +0000830 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000831 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000832 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
833 bool isSigned = I.getOpcode() == Instruction::SDiv;
834 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
835 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
836 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000837 }
838
Craig Topperf40110f2014-04-25 05:29:35 +0000839 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000840}
841
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000842/// dyn_castZExtVal - Checks if V is a zext or constant that can
843/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000844static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000845 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
846 if (Z->getSrcTy() == Ty)
847 return Z->getOperand(0);
848 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
849 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
850 return ConstantExpr::getTrunc(C, Ty);
851 }
Craig Topperf40110f2014-04-25 05:29:35 +0000852 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000853}
854
David Majnemer37f8f442013-07-04 21:17:49 +0000855namespace {
856const unsigned MaxDepth = 6;
857typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
858 const BinaryOperator &I,
859 InstCombiner &IC);
860
861/// \brief Used to maintain state for visitUDivOperand().
862struct UDivFoldAction {
863 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
864 ///< operand. This can be zero if this action
865 ///< joins two actions together.
866
867 Value *OperandToFold; ///< Which operand to fold.
868 union {
869 Instruction *FoldResult; ///< The instruction returned when FoldAction is
870 ///< invoked.
871
872 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
873 ///< joins two actions together.
874 };
875
876 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000877 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000878 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
879 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
880};
881}
882
883// X udiv 2^C -> X >> C
884static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
885 const BinaryOperator &I, InstCombiner &IC) {
886 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
887 BinaryOperator *LShr = BinaryOperator::CreateLShr(
888 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000889 if (I.isExact())
890 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000891 return LShr;
892}
893
894// X udiv C, where C >= signbit
895static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
896 const BinaryOperator &I, InstCombiner &IC) {
897 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
898
899 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
900 ConstantInt::get(I.getType(), 1));
901}
902
903// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
904static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
905 InstCombiner &IC) {
906 Instruction *ShiftLeft = cast<Instruction>(Op1);
907 if (isa<ZExtInst>(ShiftLeft))
908 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
909
910 const APInt &CI =
911 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
912 Value *N = ShiftLeft->getOperand(1);
913 if (CI != 1)
914 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
915 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
916 N = IC.Builder->CreateZExt(N, Z->getDestTy());
917 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000918 if (I.isExact())
919 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000920 return LShr;
921}
922
923// \brief Recursively visits the possible right hand operands of a udiv
924// instruction, seeing through select instructions, to determine if we can
925// replace the udiv with something simpler. If we find that an operand is not
926// able to simplify the udiv, we abort the entire transformation.
927static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
928 SmallVectorImpl<UDivFoldAction> &Actions,
929 unsigned Depth = 0) {
930 // Check to see if this is an unsigned division with an exact power of 2,
931 // if so, convert to a right shift.
932 if (match(Op1, m_Power2())) {
933 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
934 return Actions.size();
935 }
936
937 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
938 // X udiv C, where C >= signbit
939 if (C->getValue().isNegative()) {
940 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
941 return Actions.size();
942 }
943
944 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
945 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
946 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
947 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
948 return Actions.size();
949 }
950
951 // The remaining tests are all recursive, so bail out if we hit the limit.
952 if (Depth++ == MaxDepth)
953 return 0;
954
955 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000956 if (size_t LHSIdx =
957 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
958 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
959 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000960 return Actions.size();
961 }
962
963 return 0;
964}
965
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000966Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
968
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000969 if (Value *V = SimplifyVectorOp(I))
970 return ReplaceInstUsesWith(I, V);
971
Hal Finkel60db0582014-09-07 18:57:58 +0000972 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000973 return ReplaceInstUsesWith(I, V);
974
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000975 // Handle the integer div common cases
976 if (Instruction *Common = commonIDivTransforms(I))
977 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000978
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000979 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000980 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000981 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000982 const APInt *C1, *C2;
983 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
984 match(Op1, m_APInt(C2))) {
985 bool Overflow;
986 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
987 if (!Overflow)
988 return BinaryOperator::CreateUDiv(
989 X, ConstantInt::get(X->getType(), C2ShlC1));
990 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000991 }
992
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000993 // (zext A) udiv (zext B) --> zext (A udiv B)
994 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
995 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +0000996 return new ZExtInst(
997 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
998 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000999
David Majnemer37f8f442013-07-04 21:17:49 +00001000 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1001 SmallVector<UDivFoldAction, 6> UDivActions;
1002 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1003 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1004 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1005 Value *ActionOp1 = UDivActions[i].OperandToFold;
1006 Instruction *Inst;
1007 if (Action)
1008 Inst = Action(Op0, ActionOp1, I, *this);
1009 else {
1010 // This action joins two actions together. The RHS of this action is
1011 // simply the last action we processed, we saved the LHS action index in
1012 // the joining action.
1013 size_t SelectRHSIdx = i - 1;
1014 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1015 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1016 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1017 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1018 SelectLHS, SelectRHS);
1019 }
1020
1021 // If this is the last action to process, return it to the InstCombiner.
1022 // Otherwise, we insert it before the UDiv and record it so that we may
1023 // use it as part of a joining action (i.e., a SelectInst).
1024 if (e - i != 1) {
1025 Inst->insertBefore(&I);
1026 UDivActions[i].FoldResult = Inst;
1027 } else
1028 return Inst;
1029 }
1030
Craig Topperf40110f2014-04-25 05:29:35 +00001031 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001032}
1033
1034Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1035 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1036
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001037 if (Value *V = SimplifyVectorOp(I))
1038 return ReplaceInstUsesWith(I, V);
1039
Hal Finkel60db0582014-09-07 18:57:58 +00001040 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001041 return ReplaceInstUsesWith(I, V);
1042
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001043 // Handle the integer div common cases
1044 if (Instruction *Common = commonIDivTransforms(I))
1045 return Common;
1046
Benjamin Kramer72196f32014-01-19 15:24:22 +00001047 // sdiv X, -1 == -X
1048 if (match(Op1, m_AllOnes()))
1049 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001050
Benjamin Kramer72196f32014-01-19 15:24:22 +00001051 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001052 // sdiv X, C --> ashr exact X, log2(C)
1053 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001054 RHS->getValue().isPowerOf2()) {
1055 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1056 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001057 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001058 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001059 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001060
Benjamin Kramer72196f32014-01-19 15:24:22 +00001061 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001062 // X/INT_MIN -> X == INT_MIN
1063 if (RHS->isMinSignedValue())
1064 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1065
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001066 // -X/C --> X/-C provided the negation doesn't overflow.
1067 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001068 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001069 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1070 ConstantExpr::getNeg(RHS));
1071 }
1072
1073 // If the sign bits of both operands are zero (i.e. we can prove they are
1074 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001075 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001076 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001077 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1078 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001079 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001080 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1081 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001082
Chris Lattner6b657ae2011-02-10 05:36:31 +00001083 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001084 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1085 // Safe because the only negative value (1 << Y) can take on is
1086 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1087 // the sign bit set.
1088 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1089 }
1090 }
1091 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001092
Craig Topperf40110f2014-04-25 05:29:35 +00001093 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001094}
1095
Shuxin Yang320f52a2013-01-14 22:48:41 +00001096/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1097/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001098/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001099/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001100/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001101/// returned; otherwise, NULL is returned.
1102///
Suyog Sardaea205512014-10-07 11:56:06 +00001103static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001104 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001105 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001106 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001107
1108 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001109 APFloat Reciprocal(FpVal.getSemantics());
1110 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001111
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001112 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001113 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1114 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1115 Cvt = !Reciprocal.isDenormal();
1116 }
1117
1118 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001119 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001120
1121 ConstantFP *R;
1122 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1123 return BinaryOperator::CreateFMul(Dividend, R);
1124}
1125
Frits van Bommel2a559512011-01-29 17:50:27 +00001126Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1127 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1128
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001129 if (Value *V = SimplifyVectorOp(I))
1130 return ReplaceInstUsesWith(I, V);
1131
Hal Finkel60db0582014-09-07 18:57:58 +00001132 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001133 return ReplaceInstUsesWith(I, V);
1134
Stephen Lina9b57f62013-07-20 07:13:13 +00001135 if (isa<Constant>(Op0))
1136 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1137 if (Instruction *R = FoldOpIntoSelect(I, SI))
1138 return R;
1139
Shuxin Yang320f52a2013-01-14 22:48:41 +00001140 bool AllowReassociate = I.hasUnsafeAlgebra();
1141 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001142
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001143 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001144 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1145 if (Instruction *R = FoldOpIntoSelect(I, SI))
1146 return R;
1147
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001149 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001150 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001151 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001152 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001153
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001154 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001155 // (X*C1)/C2 => X * (C1/C2)
1156 //
1157 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001158 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001159 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001160 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001161 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1162 //
1163 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001164 if (isNormalFp(C)) {
1165 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001166 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001167 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001168 }
1169 }
1170
1171 if (Res) {
1172 Res->setFastMathFlags(I.getFastMathFlags());
1173 return Res;
1174 }
1175 }
1176
1177 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001178 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1179 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001180 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001181 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001182
Craig Topperf40110f2014-04-25 05:29:35 +00001183 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001184 }
1185
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001186 if (AllowReassociate && isa<Constant>(Op0)) {
1187 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001188 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001189 Value *X;
1190 bool CreateDiv = true;
1191
1192 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001193 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001194 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001195 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001196 // C1 / (X/C2) => (C1*C2) / X
1197 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001198 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001199 // C1 / (C2/X) => (C1/C2) * X
1200 Fold = ConstantExpr::getFDiv(C1, C2);
1201 CreateDiv = false;
1202 }
1203
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001204 if (Fold && isNormalFp(Fold)) {
1205 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1206 : BinaryOperator::CreateFMul(X, Fold);
1207 R->setFastMathFlags(I.getFastMathFlags());
1208 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001209 }
Craig Topperf40110f2014-04-25 05:29:35 +00001210 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001211 }
1212
1213 if (AllowReassociate) {
1214 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001215 Value *NewInst = nullptr;
1216 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001217
1218 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1219 // (X/Y) / Z => X / (Y*Z)
1220 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001221 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001222 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001223 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1224 FastMathFlags Flags = I.getFastMathFlags();
1225 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1226 RI->setFastMathFlags(Flags);
1227 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001228 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1229 }
1230 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1231 // Z / (X/Y) => Z*Y / X
1232 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001233 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001234 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001235 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1236 FastMathFlags Flags = I.getFastMathFlags();
1237 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1238 RI->setFastMathFlags(Flags);
1239 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001240 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1241 }
1242 }
1243
1244 if (NewInst) {
1245 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1246 T->setDebugLoc(I.getDebugLoc());
1247 SimpR->setFastMathFlags(I.getFastMathFlags());
1248 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001249 }
1250 }
1251
Craig Topperf40110f2014-04-25 05:29:35 +00001252 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001253}
1254
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001255/// This function implements the transforms common to both integer remainder
1256/// instructions (urem and srem). It is called by the visitors to those integer
1257/// remainder instructions.
1258/// @brief Common integer remainder transforms
1259Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1260 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1261
Chris Lattner7c99f192011-05-22 18:18:41 +00001262 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001263 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001264 I.setOperand(1, V);
1265 return &I;
1266 }
1267
Duncan Sandsa3e36992011-05-02 16:27:02 +00001268 // Handle cases involving: rem X, (select Cond, Y, Z)
1269 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1270 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001271
Benjamin Kramer72196f32014-01-19 15:24:22 +00001272 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001273 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1274 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1275 if (Instruction *R = FoldOpIntoSelect(I, SI))
1276 return R;
1277 } else if (isa<PHINode>(Op0I)) {
1278 if (Instruction *NV = FoldOpIntoPhi(I))
1279 return NV;
1280 }
1281
1282 // See if we can fold away this rem instruction.
1283 if (SimplifyDemandedInstructionBits(I))
1284 return &I;
1285 }
1286 }
1287
Craig Topperf40110f2014-04-25 05:29:35 +00001288 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001289}
1290
1291Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1293
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001294 if (Value *V = SimplifyVectorOp(I))
1295 return ReplaceInstUsesWith(I, V);
1296
Hal Finkel60db0582014-09-07 18:57:58 +00001297 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001298 return ReplaceInstUsesWith(I, V);
1299
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001300 if (Instruction *common = commonIRemTransforms(I))
1301 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001302
David Majnemer6c30f492013-05-12 00:07:05 +00001303 // (zext A) urem (zext B) --> zext (A urem B)
1304 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1305 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1306 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1307 I.getType());
1308
David Majnemer470b0772013-05-11 09:01:28 +00001309 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001310 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001311 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001312 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001313 return BinaryOperator::CreateAnd(Op0, Add);
1314 }
1315
Nick Lewycky7459be62013-07-13 01:16:47 +00001316 // 1 urem X -> zext(X != 1)
1317 if (match(Op0, m_One())) {
1318 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1319 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1320 return ReplaceInstUsesWith(I, Ext);
1321 }
1322
Craig Topperf40110f2014-04-25 05:29:35 +00001323 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001324}
1325
1326Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1327 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1328
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001329 if (Value *V = SimplifyVectorOp(I))
1330 return ReplaceInstUsesWith(I, V);
1331
Hal Finkel60db0582014-09-07 18:57:58 +00001332 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001333 return ReplaceInstUsesWith(I, V);
1334
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001335 // Handle the integer rem common cases
1336 if (Instruction *Common = commonIRemTransforms(I))
1337 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001338
David Majnemerdb077302014-10-13 22:37:51 +00001339 {
1340 const APInt *Y;
1341 // X % -Y -> X % Y
1342 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001343 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001344 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001345 return &I;
1346 }
David Majnemerdb077302014-10-13 22:37:51 +00001347 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001348
1349 // If the sign bits of both operands are zero (i.e. we can prove they are
1350 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001351 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001352 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001353 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1354 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001355 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001356 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1357 }
1358 }
1359
1360 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001361 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1362 Constant *C = cast<Constant>(Op1);
1363 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001364
1365 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001366 bool hasMissing = false;
1367 for (unsigned i = 0; i != VWidth; ++i) {
1368 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001369 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001370 hasMissing = true;
1371 break;
1372 }
1373
1374 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001375 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001376 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001377 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001378
Chris Lattner0256be92012-01-27 03:08:05 +00001379 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001380 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001381 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001382 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001384 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001385 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001386 }
1387 }
1388
1389 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001390 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001391 Worklist.AddValue(I.getOperand(1));
1392 I.setOperand(1, NewRHSV);
1393 return &I;
1394 }
1395 }
1396 }
1397
Craig Topperf40110f2014-04-25 05:29:35 +00001398 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001399}
1400
1401Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001402 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001403
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001404 if (Value *V = SimplifyVectorOp(I))
1405 return ReplaceInstUsesWith(I, V);
1406
Hal Finkel60db0582014-09-07 18:57:58 +00001407 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001408 return ReplaceInstUsesWith(I, V);
1409
1410 // Handle cases involving: rem X, (select Cond, Y, Z)
1411 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1412 return &I;
1413
Craig Topperf40110f2014-04-25 05:29:35 +00001414 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001415}