blob: 5beaf00c16e54df413f81ece4c7e9831a6ae2769 [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
David Majnemer54c2ca22014-12-26 09:10:14 +0000126/// \brief Return true if we can prove that:
127/// (mul LHS, RHS) === (mul nsw LHS, RHS)
128bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
129 Instruction *CxtI) {
130 // Multiplying n * m significant bits yields a result of n + m significant
131 // bits. If the total number of significant bits does not exceed the
132 // result bit width (minus 1), there is no overflow.
133 // This means if we have enough leading sign bits in the operands
134 // we can guarantee that the result does not overflow.
135 // Ref: "Hacker's Delight" by Henry Warren
136 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
137
138 // Note that underestimating the number of sign bits gives a more
139 // conservative answer.
140 unsigned SignBits = ComputeNumSignBits(LHS, 0, CxtI) +
141 ComputeNumSignBits(RHS, 0, CxtI);
142
143 // First handle the easy case: if we have enough sign bits there's
144 // definitely no overflow.
145 if (SignBits > BitWidth + 1)
146 return true;
147
148 // There are two ambiguous cases where there can be no overflow:
149 // SignBits == BitWidth + 1 and
150 // SignBits == BitWidth
151 // The second case is difficult to check, therefore we only handle the
152 // first case.
153 if (SignBits == BitWidth + 1) {
154 // It overflows only when both arguments are negative and the true
155 // product is exactly the minimum negative number.
156 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
157 // For simplicity we just check if at least one side is not negative.
158 bool LHSNonNegative, LHSNegative;
159 bool RHSNonNegative, RHSNegative;
160 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, CxtI);
161 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, CxtI);
162 if (LHSNonNegative || RHSNonNegative)
163 return true;
164 }
165 return false;
166}
167
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000168Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000169 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
171
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000172 if (Value *V = SimplifyVectorOp(I))
173 return ReplaceInstUsesWith(I, V);
174
Hal Finkel60db0582014-09-07 18:57:58 +0000175 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000176 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000177
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000178 if (Value *V = SimplifyUsingDistributiveLaws(I))
179 return ReplaceInstUsesWith(I, V);
180
David Majnemer027bc802014-11-22 04:52:38 +0000181 // X * -1 == 0 - X
182 if (match(Op1, m_AllOnes())) {
183 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
184 if (I.hasNoSignedWrap())
185 BO->setHasNoSignedWrap();
186 return BO;
187 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000188
Rafael Espindola65281bf2013-05-31 14:27:15 +0000189 // Also allow combining multiply instructions on vectors.
190 {
191 Value *NewOp;
192 Constant *C1, *C2;
193 const APInt *IVal;
194 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
195 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000196 match(C1, m_APInt(IVal))) {
197 // ((X << C2)*C1) == (X * (C1 << C2))
198 Constant *Shl = ConstantExpr::getShl(C1, C2);
199 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
200 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
201 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
202 BO->setHasNoUnsignedWrap();
203 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
204 Shl->isNotMinSignedValue())
205 BO->setHasNoSignedWrap();
206 return BO;
207 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000208
Rafael Espindola65281bf2013-05-31 14:27:15 +0000209 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000210 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000211 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
212 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
213 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
214 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
215 // Replace X*(2^C) with X << C, where C is a vector of known
216 // constant powers of 2.
217 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000218
Rafael Espindola65281bf2013-05-31 14:27:15 +0000219 if (NewCst) {
220 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000221
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000222 if (I.hasNoUnsignedWrap())
223 Shl->setHasNoUnsignedWrap();
David Majnemer80c8f622014-11-22 04:52:55 +0000224 if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
225 Shl->setHasNoSignedWrap();
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000226
Rafael Espindola65281bf2013-05-31 14:27:15 +0000227 return Shl;
228 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000229 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000230 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000231
Rafael Espindola65281bf2013-05-31 14:27:15 +0000232 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000233 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
234 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
235 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000236 {
237 const APInt & Val = CI->getValue();
238 const APInt &PosVal = Val.abs();
239 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000240 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000241 if (Op0->hasOneUse()) {
242 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000243 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000244 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
245 Sub = Builder->CreateSub(X, Y, "suba");
246 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
247 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
248 if (Sub)
249 return
250 BinaryOperator::CreateMul(Sub,
251 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000252 }
253 }
254 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000255 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000256
Chris Lattner6b657ae2011-02-10 05:36:31 +0000257 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000258 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000259 // Try to fold constant mul into select arguments.
260 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
261 if (Instruction *R = FoldOpIntoSelect(I, SI))
262 return R;
263
264 if (isa<PHINode>(Op0))
265 if (Instruction *NV = FoldOpIntoPhi(I))
266 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000267
268 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
269 {
270 Value *X;
271 Constant *C1;
272 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000273 Value *Mul = Builder->CreateMul(C1, Op1);
274 // Only go forward with the transform if C1*CI simplifies to a tidier
275 // constant.
276 if (!match(Mul, m_Mul(m_Value(), m_Value())))
277 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000278 }
279 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000280 }
281
David Majnemer8279a7502014-11-22 07:25:19 +0000282 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
283 if (Value *Op1v = dyn_castNegVal(Op1)) {
284 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
285 if (I.hasNoSignedWrap() &&
286 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
287 match(Op1, m_NSWSub(m_Value(), m_Value())))
288 BO->setHasNoSignedWrap();
289 return BO;
290 }
291 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292
293 // (X / Y) * Y = X - (X % Y)
294 // (X / Y) * -Y = (X % Y) - X
295 {
296 Value *Op1C = Op1;
297 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
298 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000299 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000300 BO->getOpcode() != Instruction::SDiv)) {
301 Op1C = Op0;
302 BO = dyn_cast<BinaryOperator>(Op1);
303 }
304 Value *Neg = dyn_castNegVal(Op1C);
305 if (BO && BO->hasOneUse() &&
306 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
307 (BO->getOpcode() == Instruction::UDiv ||
308 BO->getOpcode() == Instruction::SDiv)) {
309 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
310
Chris Lattner35315d02011-02-06 21:44:57 +0000311 // If the division is exact, X % Y is zero, so we end up with X or -X.
312 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000313 if (SDiv->isExact()) {
314 if (Op1BO == Op1C)
315 return ReplaceInstUsesWith(I, Op0BO);
316 return BinaryOperator::CreateNeg(Op0BO);
317 }
318
319 Value *Rem;
320 if (BO->getOpcode() == Instruction::UDiv)
321 Rem = Builder->CreateURem(Op0BO, Op1BO);
322 else
323 Rem = Builder->CreateSRem(Op0BO, Op1BO);
324 Rem->takeName(BO);
325
326 if (Op1BO == Op1C)
327 return BinaryOperator::CreateSub(Op0BO, Rem);
328 return BinaryOperator::CreateSub(Rem, Op0BO);
329 }
330 }
331
332 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000333 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000334 return BinaryOperator::CreateAnd(Op0, Op1);
335
336 // X*(1 << Y) --> X << Y
337 // (1 << Y)*X --> X << Y
338 {
339 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000340 BinaryOperator *BO = nullptr;
341 bool ShlNSW = false;
342 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
343 BO = BinaryOperator::CreateShl(Op1, Y);
344 ShlNSW = cast<BinaryOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000345 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000346 BO = BinaryOperator::CreateShl(Op0, Y);
347 ShlNSW = cast<BinaryOperator>(Op1)->hasNoSignedWrap();
348 }
349 if (BO) {
350 if (I.hasNoUnsignedWrap())
351 BO->setHasNoUnsignedWrap();
352 if (I.hasNoSignedWrap() && ShlNSW)
353 BO->setHasNoSignedWrap();
354 return BO;
355 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000356 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000357
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000358 // If one of the operands of the multiply is a cast from a boolean value, then
359 // we know the bool is either zero or one, so this is a 'masking' multiply.
360 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000361 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000362 // -2 is "-1 << 1" so it is all bits set except the low one.
363 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000364
Craig Topperf40110f2014-04-25 05:29:35 +0000365 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000366 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000367 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000368 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000369 BoolCast = Op1, OtherOp = Op0;
370
371 if (BoolCast) {
372 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000373 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000374 return BinaryOperator::CreateAnd(V, OtherOp);
375 }
376 }
377
David Majnemer54c2ca22014-12-26 09:10:14 +0000378 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, &I)) {
379 Changed = true;
380 I.setHasNoSignedWrap(true);
381 }
382
Craig Topperf40110f2014-04-25 05:29:35 +0000383 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000384}
385
Sanjay Patel17045f72014-10-14 00:33:23 +0000386/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000387static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000388 if (!Op->hasOneUse())
389 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000390
Sanjay Patel17045f72014-10-14 00:33:23 +0000391 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
392 if (!II)
393 return;
394 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
395 return;
396 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000397
Sanjay Patel17045f72014-10-14 00:33:23 +0000398 Value *OpLog2Of = II->getArgOperand(0);
399 if (!OpLog2Of->hasOneUse())
400 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000401
Sanjay Patel17045f72014-10-14 00:33:23 +0000402 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
403 if (!I)
404 return;
405 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
406 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000407
Sanjay Patel17045f72014-10-14 00:33:23 +0000408 if (match(I->getOperand(0), m_SpecificFP(0.5)))
409 Y = I->getOperand(1);
410 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
411 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000412}
Pedro Artigas993acd02012-11-30 22:07:05 +0000413
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000414static bool isFiniteNonZeroFp(Constant *C) {
415 if (C->getType()->isVectorTy()) {
416 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
417 ++I) {
418 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
419 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
420 return false;
421 }
422 return true;
423 }
424
425 return isa<ConstantFP>(C) &&
426 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
427}
428
429static bool isNormalFp(Constant *C) {
430 if (C->getType()->isVectorTy()) {
431 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
432 ++I) {
433 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
434 if (!CFP || !CFP->getValueAPF().isNormal())
435 return false;
436 }
437 return true;
438 }
439
440 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
441}
442
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000443/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
444/// true iff the given value is FMul or FDiv with one and only one operand
445/// being a normal constant (i.e. not Zero/NaN/Infinity).
446static bool isFMulOrFDivWithConstant(Value *V) {
447 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000448 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000449 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000450 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000451
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000452 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
453 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000454
455 if (C0 && C1)
456 return false;
457
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000458 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000459}
460
461/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
462/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
463/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000464/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000465/// resulting expression. Note that this function could return NULL in
466/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000467///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000468Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000469 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000470 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
471
472 Value *Opnd0 = FMulOrDiv->getOperand(0);
473 Value *Opnd1 = FMulOrDiv->getOperand(1);
474
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000475 Constant *C0 = dyn_cast<Constant>(Opnd0);
476 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000477
Craig Topperf40110f2014-04-25 05:29:35 +0000478 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000479
480 // (X * C0) * C => X * (C0*C)
481 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
482 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000483 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000484 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
485 } else {
486 if (C0) {
487 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000488 if (FMulOrDiv->hasOneUse()) {
489 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000490 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000491 if (isNormalFp(F))
492 R = BinaryOperator::CreateFDiv(F, Opnd1);
493 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000494 } else {
495 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000496 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000497 if (isNormalFp(F)) {
498 R = BinaryOperator::CreateFMul(Opnd0, F);
499 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000500 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000501 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000502 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000503 R = BinaryOperator::CreateFDiv(Opnd0, F);
504 }
505 }
506 }
507
508 if (R) {
509 R->setHasUnsafeAlgebra(true);
510 InsertNewInstWith(R, *InsertBefore);
511 }
512
513 return R;
514}
515
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000516Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000517 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000518 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
519
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000520 if (Value *V = SimplifyVectorOp(I))
521 return ReplaceInstUsesWith(I, V);
522
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000523 if (isa<Constant>(Op0))
524 std::swap(Op0, Op1);
525
Hal Finkel60db0582014-09-07 18:57:58 +0000526 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
527 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000528 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000529
Shuxin Yange8227452013-01-15 21:09:32 +0000530 bool AllowReassociate = I.hasUnsafeAlgebra();
531
Michael Ilsemand5787be2012-12-12 00:28:32 +0000532 // Simplify mul instructions with a constant RHS.
533 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000534 // Try to fold constant mul into select arguments.
535 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
536 if (Instruction *R = FoldOpIntoSelect(I, SI))
537 return R;
538
539 if (isa<PHINode>(Op0))
540 if (Instruction *NV = FoldOpIntoPhi(I))
541 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000542
Owen Andersonf74cfe02014-01-16 20:36:42 +0000543 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000544 if (match(Op1, m_SpecificFP(-1.0))) {
545 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
546 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000547 RI->copyFastMathFlags(&I);
548 return RI;
549 }
550
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000551 Constant *C = cast<Constant>(Op1);
552 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553 // Let MDC denote an expression in one of these forms:
554 // X * C, C/X, X/C, where C is a constant.
555 //
556 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000557 if (isFMulOrFDivWithConstant(Op0))
558 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000559 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000560
Quentin Colombete684a6d2013-02-28 21:12:40 +0000561 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000562 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
563 if (FAddSub &&
564 (FAddSub->getOpcode() == Instruction::FAdd ||
565 FAddSub->getOpcode() == Instruction::FSub)) {
566 Value *Opnd0 = FAddSub->getOperand(0);
567 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000568 Constant *C0 = dyn_cast<Constant>(Opnd0);
569 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000570 bool Swap = false;
571 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000572 std::swap(C0, C1);
573 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000574 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000575 }
576
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000577 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000578 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000579 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000580 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000581 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000582 if (M0 && M1) {
583 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
584 std::swap(M0, M1);
585
Benjamin Kramer67485762013-09-30 15:39:59 +0000586 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
587 ? BinaryOperator::CreateFAdd(M0, M1)
588 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000589 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000590 return RI;
591 }
592 }
593 }
594 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000595 }
596
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000597 // sqrt(X) * sqrt(X) -> X
598 if (AllowReassociate && (Op0 == Op1))
599 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
600 if (II->getIntrinsicID() == Intrinsic::sqrt)
601 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000602
Pedro Artigasd8795042012-11-30 19:09:41 +0000603 // Under unsafe algebra do:
604 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000605 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000606 Value *OpX = nullptr;
607 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000608 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000609 detectLog2OfHalf(Op0, OpY, Log2);
610 if (OpY) {
611 OpX = Op1;
612 } else {
613 detectLog2OfHalf(Op1, OpY, Log2);
614 if (OpY) {
615 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000616 }
617 }
618 // if pattern detected emit alternate sequence
619 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000620 BuilderTy::FastMathFlagGuard Guard(*Builder);
621 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000622 Log2->setArgOperand(0, OpY);
623 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000624 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
625 FSub->takeName(&I);
626 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000627 }
628 }
629
Shuxin Yange8227452013-01-15 21:09:32 +0000630 // Handle symmetric situation in a 2-iteration loop
631 Value *Opnd0 = Op0;
632 Value *Opnd1 = Op1;
633 for (int i = 0; i < 2; i++) {
634 bool IgnoreZeroSign = I.hasNoSignedZeros();
635 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000636 BuilderTy::FastMathFlagGuard Guard(*Builder);
637 Builder->SetFastMathFlags(I.getFastMathFlags());
638
Shuxin Yange8227452013-01-15 21:09:32 +0000639 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
640 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000641
Shuxin Yange8227452013-01-15 21:09:32 +0000642 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000643 if (N1) {
644 Value *FMul = Builder->CreateFMul(N0, N1);
645 FMul->takeName(&I);
646 return ReplaceInstUsesWith(I, FMul);
647 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000648
Shuxin Yange8227452013-01-15 21:09:32 +0000649 if (Opnd0->hasOneUse()) {
650 // -X * Y => -(X*Y) (Promote negation as high as possible)
651 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000652 Value *Neg = Builder->CreateFNeg(T);
653 Neg->takeName(&I);
654 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000655 }
656 }
Shuxin Yange8227452013-01-15 21:09:32 +0000657
658 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000659 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000660 // 1) to form a power expression (of X).
661 // 2) potentially shorten the critical path: After transformation, the
662 // latency of the instruction Y is amortized by the expression of X*X,
663 // and therefore Y is in a "less critical" position compared to what it
664 // was before the transformation.
665 //
666 if (AllowReassociate) {
667 Value *Opnd0_0, *Opnd0_1;
668 if (Opnd0->hasOneUse() &&
669 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000670 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000671 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
672 Y = Opnd0_1;
673 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
674 Y = Opnd0_0;
675
676 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000677 BuilderTy::FastMathFlagGuard Guard(*Builder);
678 Builder->SetFastMathFlags(I.getFastMathFlags());
679 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000680
Benjamin Kramer67485762013-09-30 15:39:59 +0000681 Value *R = Builder->CreateFMul(T, Y);
682 R->takeName(&I);
683 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000684 }
685 }
686 }
687
688 if (!isa<Constant>(Op1))
689 std::swap(Opnd0, Opnd1);
690 else
691 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000692 }
693
Craig Topperf40110f2014-04-25 05:29:35 +0000694 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000695}
696
697/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
698/// instruction.
699bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
700 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000701
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000702 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
703 int NonNullOperand = -1;
704 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
705 if (ST->isNullValue())
706 NonNullOperand = 2;
707 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
708 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
709 if (ST->isNullValue())
710 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000711
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000712 if (NonNullOperand == -1)
713 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000714
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000715 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000716
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000717 // Change the div/rem to use 'Y' instead of the select.
718 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000719
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000720 // Okay, we know we replace the operand of the div/rem with 'Y' with no
721 // problem. However, the select, or the condition of the select may have
722 // multiple uses. Based on our knowledge that the operand must be non-zero,
723 // propagate the known value for the select into other uses of it, and
724 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000725
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000726 // If the select and condition only have a single use, don't bother with this,
727 // early exit.
728 if (SI->use_empty() && SelectCond->hasOneUse())
729 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000730
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000731 // Scan the current block backward, looking for other uses of SI.
732 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000733
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000734 while (BBI != BBFront) {
735 --BBI;
736 // If we found a call to a function, we can't assume it will return, so
737 // information from below it cannot be propagated above it.
738 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
739 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000740
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000741 // Replace uses of the select or its condition with the known values.
742 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
743 I != E; ++I) {
744 if (*I == SI) {
745 *I = SI->getOperand(NonNullOperand);
746 Worklist.Add(BBI);
747 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000748 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000749 Worklist.Add(BBI);
750 }
751 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000752
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000753 // If we past the instruction, quit looking for it.
754 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000755 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000756 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000757 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000758
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000759 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000760 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000761 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000762
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000763 }
764 return true;
765}
766
767
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000768/// This function implements the transforms common to both integer division
769/// instructions (udiv and sdiv). It is called by the visitors to those integer
770/// division instructions.
771/// @brief Common integer divide transforms
772Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
773 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
774
Chris Lattner7c99f192011-05-22 18:18:41 +0000775 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000776 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000777 I.setOperand(1, V);
778 return &I;
779 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000780
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000781 // Handle cases involving: [su]div X, (select Cond, Y, Z)
782 // This does not apply for fdiv.
783 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
784 return &I;
785
David Majnemer27adb122014-10-12 08:34:24 +0000786 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
787 const APInt *C2;
788 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000789 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000790 const APInt *C1;
791 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000792
David Majnemer27adb122014-10-12 08:34:24 +0000793 // (X / C1) / C2 -> X / (C1*C2)
794 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
795 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
796 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
797 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
798 return BinaryOperator::Create(I.getOpcode(), X,
799 ConstantInt::get(I.getType(), Product));
800 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000801
David Majnemer27adb122014-10-12 08:34:24 +0000802 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
803 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
804 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
805
806 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
807 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
808 BinaryOperator *BO = BinaryOperator::Create(
809 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
810 BO->setIsExact(I.isExact());
811 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000812 }
813
David Majnemer27adb122014-10-12 08:34:24 +0000814 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
815 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
816 BinaryOperator *BO = BinaryOperator::Create(
817 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
818 BO->setHasNoUnsignedWrap(
819 !IsSigned &&
820 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
821 BO->setHasNoSignedWrap(
822 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
823 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000824 }
825 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000826
David Majnemer27adb122014-10-12 08:34:24 +0000827 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
828 *C1 != C1->getBitWidth() - 1) ||
829 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
830 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
831 APInt C1Shifted = APInt::getOneBitSet(
832 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
833
834 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
835 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
836 BinaryOperator *BO = BinaryOperator::Create(
837 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
838 BO->setIsExact(I.isExact());
839 return BO;
840 }
841
842 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
843 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
844 BinaryOperator *BO = BinaryOperator::Create(
845 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
846 BO->setHasNoUnsignedWrap(
847 !IsSigned &&
848 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
849 BO->setHasNoSignedWrap(
850 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
851 return BO;
852 }
853 }
854
855 if (*C2 != 0) { // avoid X udiv 0
856 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
857 if (Instruction *R = FoldOpIntoSelect(I, SI))
858 return R;
859 if (isa<PHINode>(Op0))
860 if (Instruction *NV = FoldOpIntoPhi(I))
861 return NV;
862 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000863 }
864 }
865
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000866 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
867 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
868 bool isSigned = I.getOpcode() == Instruction::SDiv;
869 if (isSigned) {
870 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
871 // result is one, if Op1 is -1 then the result is minus one, otherwise
872 // it's zero.
873 Value *Inc = Builder->CreateAdd(Op1, One);
874 Value *Cmp = Builder->CreateICmpULT(
875 Inc, ConstantInt::get(I.getType(), 3));
876 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
877 } else {
878 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
879 // result is one, otherwise it's zero.
880 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
881 }
882 }
883 }
884
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000885 // See if we can fold away this div instruction.
886 if (SimplifyDemandedInstructionBits(I))
887 return &I;
888
Duncan Sands771e82a2011-01-28 16:51:11 +0000889 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000890 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000891 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
892 bool isSigned = I.getOpcode() == Instruction::SDiv;
893 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
894 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
895 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000896 }
897
Craig Topperf40110f2014-04-25 05:29:35 +0000898 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000899}
900
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000901/// dyn_castZExtVal - Checks if V is a zext or constant that can
902/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000903static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000904 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
905 if (Z->getSrcTy() == Ty)
906 return Z->getOperand(0);
907 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
908 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
909 return ConstantExpr::getTrunc(C, Ty);
910 }
Craig Topperf40110f2014-04-25 05:29:35 +0000911 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000912}
913
David Majnemer37f8f442013-07-04 21:17:49 +0000914namespace {
915const unsigned MaxDepth = 6;
916typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
917 const BinaryOperator &I,
918 InstCombiner &IC);
919
920/// \brief Used to maintain state for visitUDivOperand().
921struct UDivFoldAction {
922 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
923 ///< operand. This can be zero if this action
924 ///< joins two actions together.
925
926 Value *OperandToFold; ///< Which operand to fold.
927 union {
928 Instruction *FoldResult; ///< The instruction returned when FoldAction is
929 ///< invoked.
930
931 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
932 ///< joins two actions together.
933 };
934
935 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000936 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000937 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
938 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
939};
940}
941
942// X udiv 2^C -> X >> C
943static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
944 const BinaryOperator &I, InstCombiner &IC) {
945 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
946 BinaryOperator *LShr = BinaryOperator::CreateLShr(
947 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000948 if (I.isExact())
949 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000950 return LShr;
951}
952
953// X udiv C, where C >= signbit
954static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
955 const BinaryOperator &I, InstCombiner &IC) {
956 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
957
958 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
959 ConstantInt::get(I.getType(), 1));
960}
961
962// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
963static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
964 InstCombiner &IC) {
965 Instruction *ShiftLeft = cast<Instruction>(Op1);
966 if (isa<ZExtInst>(ShiftLeft))
967 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
968
969 const APInt &CI =
970 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
971 Value *N = ShiftLeft->getOperand(1);
972 if (CI != 1)
973 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
974 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
975 N = IC.Builder->CreateZExt(N, Z->getDestTy());
976 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000977 if (I.isExact())
978 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000979 return LShr;
980}
981
982// \brief Recursively visits the possible right hand operands of a udiv
983// instruction, seeing through select instructions, to determine if we can
984// replace the udiv with something simpler. If we find that an operand is not
985// able to simplify the udiv, we abort the entire transformation.
986static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
987 SmallVectorImpl<UDivFoldAction> &Actions,
988 unsigned Depth = 0) {
989 // Check to see if this is an unsigned division with an exact power of 2,
990 // if so, convert to a right shift.
991 if (match(Op1, m_Power2())) {
992 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
993 return Actions.size();
994 }
995
996 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
997 // X udiv C, where C >= signbit
998 if (C->getValue().isNegative()) {
999 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1000 return Actions.size();
1001 }
1002
1003 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1004 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1005 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1006 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1007 return Actions.size();
1008 }
1009
1010 // The remaining tests are all recursive, so bail out if we hit the limit.
1011 if (Depth++ == MaxDepth)
1012 return 0;
1013
1014 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001015 if (size_t LHSIdx =
1016 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1017 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1018 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001019 return Actions.size();
1020 }
1021
1022 return 0;
1023}
1024
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001025Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1027
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001028 if (Value *V = SimplifyVectorOp(I))
1029 return ReplaceInstUsesWith(I, V);
1030
Hal Finkel60db0582014-09-07 18:57:58 +00001031 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001032 return ReplaceInstUsesWith(I, V);
1033
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001034 // Handle the integer div common cases
1035 if (Instruction *Common = commonIDivTransforms(I))
1036 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001037
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001038 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001039 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001040 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001041 const APInt *C1, *C2;
1042 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1043 match(Op1, m_APInt(C2))) {
1044 bool Overflow;
1045 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001046 if (!Overflow) {
1047 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1048 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001049 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001050 if (IsExact)
1051 BO->setIsExact();
1052 return BO;
1053 }
David Majnemera2521382014-10-13 21:48:30 +00001054 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001055 }
1056
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001057 // (zext A) udiv (zext B) --> zext (A udiv B)
1058 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1059 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001060 return new ZExtInst(
1061 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1062 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001063
David Majnemer37f8f442013-07-04 21:17:49 +00001064 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1065 SmallVector<UDivFoldAction, 6> UDivActions;
1066 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1067 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1068 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1069 Value *ActionOp1 = UDivActions[i].OperandToFold;
1070 Instruction *Inst;
1071 if (Action)
1072 Inst = Action(Op0, ActionOp1, I, *this);
1073 else {
1074 // This action joins two actions together. The RHS of this action is
1075 // simply the last action we processed, we saved the LHS action index in
1076 // the joining action.
1077 size_t SelectRHSIdx = i - 1;
1078 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1079 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1080 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1081 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1082 SelectLHS, SelectRHS);
1083 }
1084
1085 // If this is the last action to process, return it to the InstCombiner.
1086 // Otherwise, we insert it before the UDiv and record it so that we may
1087 // use it as part of a joining action (i.e., a SelectInst).
1088 if (e - i != 1) {
1089 Inst->insertBefore(&I);
1090 UDivActions[i].FoldResult = Inst;
1091 } else
1092 return Inst;
1093 }
1094
Craig Topperf40110f2014-04-25 05:29:35 +00001095 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001096}
1097
1098Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1100
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001101 if (Value *V = SimplifyVectorOp(I))
1102 return ReplaceInstUsesWith(I, V);
1103
Hal Finkel60db0582014-09-07 18:57:58 +00001104 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001105 return ReplaceInstUsesWith(I, V);
1106
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001107 // Handle the integer div common cases
1108 if (Instruction *Common = commonIDivTransforms(I))
1109 return Common;
1110
Benjamin Kramer72196f32014-01-19 15:24:22 +00001111 // sdiv X, -1 == -X
1112 if (match(Op1, m_AllOnes()))
1113 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001114
Benjamin Kramer72196f32014-01-19 15:24:22 +00001115 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001116 // sdiv X, C --> ashr exact X, log2(C)
1117 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001118 RHS->getValue().isPowerOf2()) {
1119 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1120 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001121 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001122 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001123 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001124
Benjamin Kramer72196f32014-01-19 15:24:22 +00001125 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001126 // X/INT_MIN -> X == INT_MIN
1127 if (RHS->isMinSignedValue())
1128 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1129
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001130 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001131 Value *X;
1132 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1133 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1134 BO->setIsExact(I.isExact());
1135 return BO;
1136 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001137 }
1138
1139 // If the sign bits of both operands are zero (i.e. we can prove they are
1140 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001141 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001142 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001143 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1144 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001145 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
David Majnemerec6e4812014-11-22 20:00:38 +00001146 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1147 BO->setIsExact(I.isExact());
1148 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001149 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001150
David Majnemerfb380552014-11-22 20:00:41 +00001151 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001152 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1153 // Safe because the only negative value (1 << Y) can take on is
1154 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1155 // the sign bit set.
David Majnemerfb380552014-11-22 20:00:41 +00001156 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1157 BO->setIsExact(I.isExact());
1158 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001159 }
1160 }
1161 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001162
Craig Topperf40110f2014-04-25 05:29:35 +00001163 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001164}
1165
Shuxin Yang320f52a2013-01-14 22:48:41 +00001166/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1167/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001168/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001169/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001170/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001171/// returned; otherwise, NULL is returned.
1172///
Suyog Sardaea205512014-10-07 11:56:06 +00001173static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001174 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001175 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001176 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001177
1178 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001179 APFloat Reciprocal(FpVal.getSemantics());
1180 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001181
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001182 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001183 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1184 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1185 Cvt = !Reciprocal.isDenormal();
1186 }
1187
1188 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001189 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001190
1191 ConstantFP *R;
1192 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1193 return BinaryOperator::CreateFMul(Dividend, R);
1194}
1195
Frits van Bommel2a559512011-01-29 17:50:27 +00001196Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1197 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1198
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001199 if (Value *V = SimplifyVectorOp(I))
1200 return ReplaceInstUsesWith(I, V);
1201
Hal Finkel60db0582014-09-07 18:57:58 +00001202 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001203 return ReplaceInstUsesWith(I, V);
1204
Stephen Lina9b57f62013-07-20 07:13:13 +00001205 if (isa<Constant>(Op0))
1206 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1207 if (Instruction *R = FoldOpIntoSelect(I, SI))
1208 return R;
1209
Shuxin Yang320f52a2013-01-14 22:48:41 +00001210 bool AllowReassociate = I.hasUnsafeAlgebra();
1211 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001212
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001213 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001214 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1215 if (Instruction *R = FoldOpIntoSelect(I, SI))
1216 return R;
1217
Shuxin Yang320f52a2013-01-14 22:48:41 +00001218 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001219 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001220 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001221 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001222 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001223
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001224 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001225 // (X*C1)/C2 => X * (C1/C2)
1226 //
1227 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001228 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001229 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001230 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001231 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1232 //
1233 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001234 if (isNormalFp(C)) {
1235 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001236 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001237 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001238 }
1239 }
1240
1241 if (Res) {
1242 Res->setFastMathFlags(I.getFastMathFlags());
1243 return Res;
1244 }
1245 }
1246
1247 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001248 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1249 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001250 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001251 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001252
Craig Topperf40110f2014-04-25 05:29:35 +00001253 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001254 }
1255
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001256 if (AllowReassociate && isa<Constant>(Op0)) {
1257 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001258 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001259 Value *X;
1260 bool CreateDiv = true;
1261
1262 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001263 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001264 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001265 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001266 // C1 / (X/C2) => (C1*C2) / X
1267 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001268 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001269 // C1 / (C2/X) => (C1/C2) * X
1270 Fold = ConstantExpr::getFDiv(C1, C2);
1271 CreateDiv = false;
1272 }
1273
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001274 if (Fold && isNormalFp(Fold)) {
1275 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1276 : BinaryOperator::CreateFMul(X, Fold);
1277 R->setFastMathFlags(I.getFastMathFlags());
1278 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001279 }
Craig Topperf40110f2014-04-25 05:29:35 +00001280 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001281 }
1282
1283 if (AllowReassociate) {
1284 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001285 Value *NewInst = nullptr;
1286 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001287
1288 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1289 // (X/Y) / Z => X / (Y*Z)
1290 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001291 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001292 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001293 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1294 FastMathFlags Flags = I.getFastMathFlags();
1295 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1296 RI->setFastMathFlags(Flags);
1297 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001298 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1299 }
1300 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1301 // Z / (X/Y) => Z*Y / X
1302 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001303 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001304 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001305 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1306 FastMathFlags Flags = I.getFastMathFlags();
1307 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1308 RI->setFastMathFlags(Flags);
1309 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001310 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1311 }
1312 }
1313
1314 if (NewInst) {
1315 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1316 T->setDebugLoc(I.getDebugLoc());
1317 SimpR->setFastMathFlags(I.getFastMathFlags());
1318 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001319 }
1320 }
1321
Craig Topperf40110f2014-04-25 05:29:35 +00001322 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001323}
1324
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001325/// This function implements the transforms common to both integer remainder
1326/// instructions (urem and srem). It is called by the visitors to those integer
1327/// remainder instructions.
1328/// @brief Common integer remainder transforms
1329Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1331
Chris Lattner7c99f192011-05-22 18:18:41 +00001332 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001333 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001334 I.setOperand(1, V);
1335 return &I;
1336 }
1337
Duncan Sandsa3e36992011-05-02 16:27:02 +00001338 // Handle cases involving: rem X, (select Cond, Y, Z)
1339 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1340 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001341
Benjamin Kramer72196f32014-01-19 15:24:22 +00001342 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001343 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1344 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1345 if (Instruction *R = FoldOpIntoSelect(I, SI))
1346 return R;
1347 } else if (isa<PHINode>(Op0I)) {
1348 if (Instruction *NV = FoldOpIntoPhi(I))
1349 return NV;
1350 }
1351
1352 // See if we can fold away this rem instruction.
1353 if (SimplifyDemandedInstructionBits(I))
1354 return &I;
1355 }
1356 }
1357
Craig Topperf40110f2014-04-25 05:29:35 +00001358 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001359}
1360
1361Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1362 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1363
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001364 if (Value *V = SimplifyVectorOp(I))
1365 return ReplaceInstUsesWith(I, V);
1366
Hal Finkel60db0582014-09-07 18:57:58 +00001367 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001368 return ReplaceInstUsesWith(I, V);
1369
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001370 if (Instruction *common = commonIRemTransforms(I))
1371 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001372
David Majnemer6c30f492013-05-12 00:07:05 +00001373 // (zext A) urem (zext B) --> zext (A urem B)
1374 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1375 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1376 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1377 I.getType());
1378
David Majnemer470b0772013-05-11 09:01:28 +00001379 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001380 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001381 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001382 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001383 return BinaryOperator::CreateAnd(Op0, Add);
1384 }
1385
Nick Lewycky7459be62013-07-13 01:16:47 +00001386 // 1 urem X -> zext(X != 1)
1387 if (match(Op0, m_One())) {
1388 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1389 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1390 return ReplaceInstUsesWith(I, Ext);
1391 }
1392
Craig Topperf40110f2014-04-25 05:29:35 +00001393 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001394}
1395
1396Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1397 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1398
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001399 if (Value *V = SimplifyVectorOp(I))
1400 return ReplaceInstUsesWith(I, V);
1401
Hal Finkel60db0582014-09-07 18:57:58 +00001402 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001403 return ReplaceInstUsesWith(I, V);
1404
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001405 // Handle the integer rem common cases
1406 if (Instruction *Common = commonIRemTransforms(I))
1407 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001408
David Majnemerdb077302014-10-13 22:37:51 +00001409 {
1410 const APInt *Y;
1411 // X % -Y -> X % Y
1412 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001413 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001414 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001415 return &I;
1416 }
David Majnemerdb077302014-10-13 22:37:51 +00001417 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001418
1419 // If the sign bits of both operands are zero (i.e. we can prove they are
1420 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001421 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001422 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001423 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1424 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001425 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001426 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1427 }
1428 }
1429
1430 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001431 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1432 Constant *C = cast<Constant>(Op1);
1433 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001434
1435 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001436 bool hasMissing = false;
1437 for (unsigned i = 0; i != VWidth; ++i) {
1438 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001439 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001440 hasMissing = true;
1441 break;
1442 }
1443
1444 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001445 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001446 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001447 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001448
Chris Lattner0256be92012-01-27 03:08:05 +00001449 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001450 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001451 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001452 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001454 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001455 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001456 }
1457 }
1458
1459 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001460 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001461 Worklist.AddValue(I.getOperand(1));
1462 I.setOperand(1, NewRHSV);
1463 return &I;
1464 }
1465 }
1466 }
1467
Craig Topperf40110f2014-04-25 05:29:35 +00001468 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001469}
1470
1471Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001473
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001474 if (Value *V = SimplifyVectorOp(I))
1475 return ReplaceInstUsesWith(I, V);
1476
Hal Finkel60db0582014-09-07 18:57:58 +00001477 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001478 return ReplaceInstUsesWith(I, V);
1479
1480 // Handle cases involving: rem X, (select Cond, Y, Z)
1481 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1482 return &I;
1483
Craig Topperf40110f2014-04-25 05:29:35 +00001484 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001485}