blob: acfc96efa23a8bf9437bca48a39f3d6075c0c03a [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.
28static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
29 // If V has multiple uses, then we would have to do more analysis to determine
30 // if this is safe. For example, the use could be in dynamically unreached
31 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000032 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000033
Chris Lattner388cb8a2011-05-23 00:32:19 +000034 bool MadeChange = false;
35
Chris Lattner7c99f192011-05-22 18:18:41 +000036 // ((1 << A) >>u B) --> (1 << (A-B))
37 // Because V cannot be zero, we know that B is less than A.
Craig Topperf40110f2014-04-25 05:29:35 +000038 Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr;
Chris Lattner321c58f2011-05-23 00:09:55 +000039 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000040 m_Value(B))) &&
41 // The "1" can be any value known to be a power of 2.
Rafael Espindola319f74c2012-12-13 03:37:24 +000042 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000043 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000044 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000045 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000046
Chris Lattner388cb8a2011-05-23 00:32:19 +000047 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
48 // inexact. Similarly for <<.
49 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Rafael Espindola319f74c2012-12-13 03:37:24 +000050 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000051 // We know that this is an exact/nuw shift and that the input is a
52 // non-zero context as well.
53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
54 I->setOperand(0, V2);
55 MadeChange = true;
56 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000057
Chris Lattner388cb8a2011-05-23 00:32:19 +000058 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
59 I->setIsExact();
60 MadeChange = true;
61 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Chris Lattner388cb8a2011-05-23 00:32:19 +000063 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
64 I->setHasNoUnsignedWrap();
65 MadeChange = true;
66 }
67 }
68
Chris Lattner162dfc32011-05-22 18:26:48 +000069 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000070 // If V is a phi node, we can call this on each of its operands.
71 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072
Craig Topperf40110f2014-04-25 05:29:35 +000073 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000074}
75
76
Chris Lattnerdc054bf2010-01-05 06:09:35 +000077/// MultiplyOverflows - True if the multiply can not be expressed in an int
78/// this size.
79static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
80 uint32_t W = C1->getBitWidth();
81 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 if (sign) {
Jay Foad583abbc2010-12-07 08:25:19 +000083 LHSExt = LHSExt.sext(W * 2);
84 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000085 } else {
Jay Foad583abbc2010-12-07 08:25:19 +000086 LHSExt = LHSExt.zext(W * 2);
87 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000088 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090 APInt MulExt = LHSExt * RHSExt;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000091
Chris Lattnerdc054bf2010-01-05 06:09:35 +000092 if (!sign)
93 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094
Chris Lattnerdc054bf2010-01-05 06:09:35 +000095 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
96 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
97 return MulExt.slt(Min) || MulExt.sgt(Max);
98}
99
David Majnemerf9a095d2014-08-16 08:55:06 +0000100/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
101static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
102 bool IsSigned) {
103 assert(C1.getBitWidth() == C2.getBitWidth() &&
104 "Inconsistent width of constants!");
105
106 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
107 if (IsSigned)
108 APInt::sdivrem(C1, C2, Quotient, Remainder);
109 else
110 APInt::udivrem(C1, C2, Quotient, Remainder);
111
112 return Remainder.isMinValue();
113}
114
Rafael Espindola65281bf2013-05-31 14:27:15 +0000115/// \brief A helper routine of InstCombiner::visitMul().
116///
117/// If C is a vector of known powers of 2, then this function returns
118/// a new vector obtained from C replacing each element with its logBase2.
119/// Return a null pointer otherwise.
120static Constant *getLogBase2Vector(ConstantDataVector *CV) {
121 const APInt *IVal;
122 SmallVector<Constant *, 4> Elts;
123
124 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
125 Constant *Elt = CV->getElementAsConstant(I);
126 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000127 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000128 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
129 }
130
131 return ConstantVector::get(Elts);
132}
133
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000134Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000135 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
137
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000138 if (Value *V = SimplifyVectorOp(I))
139 return ReplaceInstUsesWith(I, V);
140
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000141 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000142 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000143
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000144 if (Value *V = SimplifyUsingDistributiveLaws(I))
145 return ReplaceInstUsesWith(I, V);
146
Chris Lattner6b657ae2011-02-10 05:36:31 +0000147 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
148 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000149
Rafael Espindola65281bf2013-05-31 14:27:15 +0000150 // Also allow combining multiply instructions on vectors.
151 {
152 Value *NewOp;
153 Constant *C1, *C2;
154 const APInt *IVal;
155 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
156 m_Constant(C1))) &&
157 match(C1, m_APInt(IVal)))
158 // ((X << C1)*C2) == (X * (C2 << C1))
159 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000160
Rafael Espindola65281bf2013-05-31 14:27:15 +0000161 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000162 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000163 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
164 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
165 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
166 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
167 // Replace X*(2^C) with X << C, where C is a vector of known
168 // constant powers of 2.
169 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000170
Rafael Espindola65281bf2013-05-31 14:27:15 +0000171 if (NewCst) {
172 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
173 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
174 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
175 return Shl;
176 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000177 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000178 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000179
Rafael Espindola65281bf2013-05-31 14:27:15 +0000180 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000181 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
182 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
183 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000184 {
185 const APInt & Val = CI->getValue();
186 const APInt &PosVal = Val.abs();
187 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000188 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000189 if (Op0->hasOneUse()) {
190 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000191 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000192 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
193 Sub = Builder->CreateSub(X, Y, "suba");
194 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
195 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
196 if (Sub)
197 return
198 BinaryOperator::CreateMul(Sub,
199 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000200 }
201 }
202 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000203 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000204
Chris Lattner6b657ae2011-02-10 05:36:31 +0000205 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000206 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000207 // Try to fold constant mul into select arguments.
208 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
209 if (Instruction *R = FoldOpIntoSelect(I, SI))
210 return R;
211
212 if (isa<PHINode>(Op0))
213 if (Instruction *NV = FoldOpIntoPhi(I))
214 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000215
216 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
217 {
218 Value *X;
219 Constant *C1;
220 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000221 Value *Mul = Builder->CreateMul(C1, Op1);
222 // Only go forward with the transform if C1*CI simplifies to a tidier
223 // constant.
224 if (!match(Mul, m_Mul(m_Value(), m_Value())))
225 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000226 }
227 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000228 }
229
230 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
231 if (Value *Op1v = dyn_castNegVal(Op1))
232 return BinaryOperator::CreateMul(Op0v, Op1v);
233
234 // (X / Y) * Y = X - (X % Y)
235 // (X / Y) * -Y = (X % Y) - X
236 {
237 Value *Op1C = Op1;
238 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
239 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000240 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000241 BO->getOpcode() != Instruction::SDiv)) {
242 Op1C = Op0;
243 BO = dyn_cast<BinaryOperator>(Op1);
244 }
245 Value *Neg = dyn_castNegVal(Op1C);
246 if (BO && BO->hasOneUse() &&
247 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
248 (BO->getOpcode() == Instruction::UDiv ||
249 BO->getOpcode() == Instruction::SDiv)) {
250 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
251
Chris Lattner35315d02011-02-06 21:44:57 +0000252 // If the division is exact, X % Y is zero, so we end up with X or -X.
253 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000254 if (SDiv->isExact()) {
255 if (Op1BO == Op1C)
256 return ReplaceInstUsesWith(I, Op0BO);
257 return BinaryOperator::CreateNeg(Op0BO);
258 }
259
260 Value *Rem;
261 if (BO->getOpcode() == Instruction::UDiv)
262 Rem = Builder->CreateURem(Op0BO, Op1BO);
263 else
264 Rem = Builder->CreateSRem(Op0BO, Op1BO);
265 Rem->takeName(BO);
266
267 if (Op1BO == Op1C)
268 return BinaryOperator::CreateSub(Op0BO, Rem);
269 return BinaryOperator::CreateSub(Rem, Op0BO);
270 }
271 }
272
273 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000274 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000275 return BinaryOperator::CreateAnd(Op0, Op1);
276
277 // X*(1 << Y) --> X << Y
278 // (1 << Y)*X --> X << Y
279 {
280 Value *Y;
281 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
282 return BinaryOperator::CreateShl(Op1, Y);
283 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
284 return BinaryOperator::CreateShl(Op0, Y);
285 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000286
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000287 // If one of the operands of the multiply is a cast from a boolean value, then
288 // we know the bool is either zero or one, so this is a 'masking' multiply.
289 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000290 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000291 // -2 is "-1 << 1" so it is all bits set except the low one.
292 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000293
Craig Topperf40110f2014-04-25 05:29:35 +0000294 Value *BoolCast = nullptr, *OtherOp = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000295 if (MaskedValueIsZero(Op0, Negative2))
296 BoolCast = Op0, OtherOp = Op1;
297 else if (MaskedValueIsZero(Op1, Negative2))
298 BoolCast = Op1, OtherOp = Op0;
299
300 if (BoolCast) {
301 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000302 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000303 return BinaryOperator::CreateAnd(V, OtherOp);
304 }
305 }
306
Craig Topperf40110f2014-04-25 05:29:35 +0000307 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000308}
309
Pedro Artigas993acd02012-11-30 22:07:05 +0000310//
311// Detect pattern:
312//
313// log2(Y*0.5)
314//
315// And check for corresponding fast math flags
316//
317
318static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000319
320 if (!Op->hasOneUse())
321 return;
322
323 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
324 if (!II)
325 return;
326 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
327 return;
328 Log2 = II;
329
330 Value *OpLog2Of = II->getArgOperand(0);
331 if (!OpLog2Of->hasOneUse())
332 return;
333
334 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
335 if (!I)
336 return;
337 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
338 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000339
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000340 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000341 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000342 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000343 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000344}
Pedro Artigas993acd02012-11-30 22:07:05 +0000345
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000346static bool isFiniteNonZeroFp(Constant *C) {
347 if (C->getType()->isVectorTy()) {
348 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
349 ++I) {
350 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
351 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
352 return false;
353 }
354 return true;
355 }
356
357 return isa<ConstantFP>(C) &&
358 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
359}
360
361static bool isNormalFp(Constant *C) {
362 if (C->getType()->isVectorTy()) {
363 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
364 ++I) {
365 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
366 if (!CFP || !CFP->getValueAPF().isNormal())
367 return false;
368 }
369 return true;
370 }
371
372 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
373}
374
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000375/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
376/// true iff the given value is FMul or FDiv with one and only one operand
377/// being a normal constant (i.e. not Zero/NaN/Infinity).
378static bool isFMulOrFDivWithConstant(Value *V) {
379 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000380 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000381 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000382 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000383
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000384 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
385 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000386
387 if (C0 && C1)
388 return false;
389
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000390 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000391}
392
393/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
394/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
395/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000396/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000397/// resulting expression. Note that this function could return NULL in
398/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000399///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000400Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000401 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000402 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
403
404 Value *Opnd0 = FMulOrDiv->getOperand(0);
405 Value *Opnd1 = FMulOrDiv->getOperand(1);
406
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000407 Constant *C0 = dyn_cast<Constant>(Opnd0);
408 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000409
Craig Topperf40110f2014-04-25 05:29:35 +0000410 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000411
412 // (X * C0) * C => X * (C0*C)
413 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
414 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000415 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000416 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
417 } else {
418 if (C0) {
419 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000420 if (FMulOrDiv->hasOneUse()) {
421 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000422 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000423 if (isNormalFp(F))
424 R = BinaryOperator::CreateFDiv(F, Opnd1);
425 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000426 } else {
427 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000428 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000429 if (isNormalFp(F)) {
430 R = BinaryOperator::CreateFMul(Opnd0, F);
431 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000432 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000433 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000434 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000435 R = BinaryOperator::CreateFDiv(Opnd0, F);
436 }
437 }
438 }
439
440 if (R) {
441 R->setHasUnsafeAlgebra(true);
442 InsertNewInstWith(R, *InsertBefore);
443 }
444
445 return R;
446}
447
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000448Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000449 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
451
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000452 if (Value *V = SimplifyVectorOp(I))
453 return ReplaceInstUsesWith(I, V);
454
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000455 if (isa<Constant>(Op0))
456 std::swap(Op0, Op1);
457
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000458 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000459 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000460
Shuxin Yange8227452013-01-15 21:09:32 +0000461 bool AllowReassociate = I.hasUnsafeAlgebra();
462
Michael Ilsemand5787be2012-12-12 00:28:32 +0000463 // Simplify mul instructions with a constant RHS.
464 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000465 // Try to fold constant mul into select arguments.
466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
467 if (Instruction *R = FoldOpIntoSelect(I, SI))
468 return R;
469
470 if (isa<PHINode>(Op0))
471 if (Instruction *NV = FoldOpIntoPhi(I))
472 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000473
Owen Andersonf74cfe02014-01-16 20:36:42 +0000474 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000475 if (match(Op1, m_SpecificFP(-1.0))) {
476 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
477 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000478 RI->copyFastMathFlags(&I);
479 return RI;
480 }
481
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000482 Constant *C = cast<Constant>(Op1);
483 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000484 // Let MDC denote an expression in one of these forms:
485 // X * C, C/X, X/C, where C is a constant.
486 //
487 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000488 if (isFMulOrFDivWithConstant(Op0))
489 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000490 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000491
Quentin Colombete684a6d2013-02-28 21:12:40 +0000492 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000493 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
494 if (FAddSub &&
495 (FAddSub->getOpcode() == Instruction::FAdd ||
496 FAddSub->getOpcode() == Instruction::FSub)) {
497 Value *Opnd0 = FAddSub->getOperand(0);
498 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000499 Constant *C0 = dyn_cast<Constant>(Opnd0);
500 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000501 bool Swap = false;
502 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000503 std::swap(C0, C1);
504 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000505 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000506 }
507
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000508 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000509 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000510 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000511 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000512 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000513 if (M0 && M1) {
514 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
515 std::swap(M0, M1);
516
Benjamin Kramer67485762013-09-30 15:39:59 +0000517 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
518 ? BinaryOperator::CreateFAdd(M0, M1)
519 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000520 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000521 return RI;
522 }
523 }
524 }
525 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000526 }
527
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000528
Pedro Artigasd8795042012-11-30 19:09:41 +0000529 // Under unsafe algebra do:
530 // X * log2(0.5*Y) = X*log2(Y) - X
531 if (I.hasUnsafeAlgebra()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000532 Value *OpX = nullptr;
533 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000534 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000535 detectLog2OfHalf(Op0, OpY, Log2);
536 if (OpY) {
537 OpX = Op1;
538 } else {
539 detectLog2OfHalf(Op1, OpY, Log2);
540 if (OpY) {
541 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000542 }
543 }
544 // if pattern detected emit alternate sequence
545 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000546 BuilderTy::FastMathFlagGuard Guard(*Builder);
547 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000548 Log2->setArgOperand(0, OpY);
549 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000550 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
551 FSub->takeName(&I);
552 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000553 }
554 }
555
Shuxin Yange8227452013-01-15 21:09:32 +0000556 // Handle symmetric situation in a 2-iteration loop
557 Value *Opnd0 = Op0;
558 Value *Opnd1 = Op1;
559 for (int i = 0; i < 2; i++) {
560 bool IgnoreZeroSign = I.hasNoSignedZeros();
561 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000562 BuilderTy::FastMathFlagGuard Guard(*Builder);
563 Builder->SetFastMathFlags(I.getFastMathFlags());
564
Shuxin Yange8227452013-01-15 21:09:32 +0000565 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
566 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000567
Shuxin Yange8227452013-01-15 21:09:32 +0000568 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000569 if (N1) {
570 Value *FMul = Builder->CreateFMul(N0, N1);
571 FMul->takeName(&I);
572 return ReplaceInstUsesWith(I, FMul);
573 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000574
Shuxin Yange8227452013-01-15 21:09:32 +0000575 if (Opnd0->hasOneUse()) {
576 // -X * Y => -(X*Y) (Promote negation as high as possible)
577 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000578 Value *Neg = Builder->CreateFNeg(T);
579 Neg->takeName(&I);
580 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000581 }
582 }
Shuxin Yange8227452013-01-15 21:09:32 +0000583
584 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000585 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000586 // 1) to form a power expression (of X).
587 // 2) potentially shorten the critical path: After transformation, the
588 // latency of the instruction Y is amortized by the expression of X*X,
589 // and therefore Y is in a "less critical" position compared to what it
590 // was before the transformation.
591 //
592 if (AllowReassociate) {
593 Value *Opnd0_0, *Opnd0_1;
594 if (Opnd0->hasOneUse() &&
595 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000596 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000597 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
598 Y = Opnd0_1;
599 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
600 Y = Opnd0_0;
601
602 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000603 BuilderTy::FastMathFlagGuard Guard(*Builder);
604 Builder->SetFastMathFlags(I.getFastMathFlags());
605 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000606
Benjamin Kramer67485762013-09-30 15:39:59 +0000607 Value *R = Builder->CreateFMul(T, Y);
608 R->takeName(&I);
609 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000610 }
611 }
612 }
613
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000614 // B * (uitofp i1 C) -> select C, B, 0
615 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
616 Value *LHS = Op0, *RHS = Op1;
617 Value *B, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000618 if (!match(RHS, m_UIToFP(m_Value(C))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000619 std::swap(LHS, RHS);
620
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000621 if (match(RHS, m_UIToFP(m_Value(C))) &&
622 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000623 B = LHS;
624 Value *Zero = ConstantFP::getNegativeZero(B->getType());
625 return SelectInst::Create(C, B, Zero);
626 }
627 }
628
629 // A * (1 - uitofp i1 C) -> select C, 0, A
630 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
631 Value *LHS = Op0, *RHS = Op1;
632 Value *A, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000633 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000634 std::swap(LHS, RHS);
635
Stephen Lin4ef13872013-07-26 17:55:00 +0000636 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000637 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000638 A = LHS;
639 Value *Zero = ConstantFP::getNegativeZero(A->getType());
640 return SelectInst::Create(C, Zero, A);
641 }
642 }
643
Shuxin Yange8227452013-01-15 21:09:32 +0000644 if (!isa<Constant>(Op1))
645 std::swap(Opnd0, Opnd1);
646 else
647 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000648 }
649
Craig Topperf40110f2014-04-25 05:29:35 +0000650 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000651}
652
653/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
654/// instruction.
655bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
656 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000658 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
659 int NonNullOperand = -1;
660 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
661 if (ST->isNullValue())
662 NonNullOperand = 2;
663 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
664 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
665 if (ST->isNullValue())
666 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000667
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000668 if (NonNullOperand == -1)
669 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000671 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000672
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000673 // Change the div/rem to use 'Y' instead of the select.
674 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000675
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000676 // Okay, we know we replace the operand of the div/rem with 'Y' with no
677 // problem. However, the select, or the condition of the select may have
678 // multiple uses. Based on our knowledge that the operand must be non-zero,
679 // propagate the known value for the select into other uses of it, and
680 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 // If the select and condition only have a single use, don't bother with this,
683 // early exit.
684 if (SI->use_empty() && SelectCond->hasOneUse())
685 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000686
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000687 // Scan the current block backward, looking for other uses of SI.
688 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000689
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 while (BBI != BBFront) {
691 --BBI;
692 // If we found a call to a function, we can't assume it will return, so
693 // information from below it cannot be propagated above it.
694 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
695 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000696
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697 // Replace uses of the select or its condition with the known values.
698 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
699 I != E; ++I) {
700 if (*I == SI) {
701 *I = SI->getOperand(NonNullOperand);
702 Worklist.Add(BBI);
703 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000704 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000705 Worklist.Add(BBI);
706 }
707 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000708
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000709 // If we past the instruction, quit looking for it.
710 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000711 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000712 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000713 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000714
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000715 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000716 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000717 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000718
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000719 }
720 return true;
721}
722
723
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000724/// This function implements the transforms common to both integer division
725/// instructions (udiv and sdiv). It is called by the visitors to those integer
726/// division instructions.
727/// @brief Common integer divide transforms
728Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
730
Chris Lattner7c99f192011-05-22 18:18:41 +0000731 // The RHS is known non-zero.
732 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
733 I.setOperand(1, V);
734 return &I;
735 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000736
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000737 // Handle cases involving: [su]div X, (select Cond, Y, Z)
738 // This does not apply for fdiv.
739 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
740 return &I;
741
742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000743 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
744 // (X / C1) / C2 -> X / (C1*C2)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000745 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
746 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
747 if (MultiplyOverflows(RHS, LHSRHS,
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000748 I.getOpcode() == Instruction::SDiv))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000749 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000750 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
751 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000752 }
753
David Majnemerf9a095d2014-08-16 08:55:06 +0000754 Value *X;
755 const APInt *C1, *C2;
756 if (match(RHS, m_APInt(C2))) {
757 bool IsSigned = I.getOpcode() == Instruction::SDiv;
758 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
759 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
760 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
761
762 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
763 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
764 BinaryOperator *BO = BinaryOperator::Create(
765 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
766 BO->setIsExact(I.isExact());
767 return BO;
768 }
769
770 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
771 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
772 BinaryOperator *BO = BinaryOperator::Create(
773 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
774 BO->setHasNoUnsignedWrap(
775 !IsSigned &&
776 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
777 BO->setHasNoSignedWrap(
778 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
779 return BO;
780 }
781 }
782
783 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1)))) ||
784 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
785 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
786 APInt C1Shifted = APInt::getOneBitSet(
787 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
788
789 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
790 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
791 BinaryOperator *BO = BinaryOperator::Create(
792 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
793 BO->setIsExact(I.isExact());
794 return BO;
795 }
796
797 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
798 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
799 BinaryOperator *BO = BinaryOperator::Create(
800 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
801 BO->setHasNoUnsignedWrap(
802 !IsSigned &&
803 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
804 BO->setHasNoSignedWrap(
805 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
806 return BO;
807 }
808 }
809 }
810 }
811
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000812 if (!RHS->isZero()) { // avoid X udiv 0
813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
814 if (Instruction *R = FoldOpIntoSelect(I, SI))
815 return R;
816 if (isa<PHINode>(Op0))
817 if (Instruction *NV = FoldOpIntoPhi(I))
818 return NV;
819 }
820 }
821
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000822 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
823 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
824 bool isSigned = I.getOpcode() == Instruction::SDiv;
825 if (isSigned) {
826 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
827 // result is one, if Op1 is -1 then the result is minus one, otherwise
828 // it's zero.
829 Value *Inc = Builder->CreateAdd(Op1, One);
830 Value *Cmp = Builder->CreateICmpULT(
831 Inc, ConstantInt::get(I.getType(), 3));
832 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
833 } else {
834 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
835 // result is one, otherwise it's zero.
836 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
837 }
838 }
839 }
840
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000841 // See if we can fold away this div instruction.
842 if (SimplifyDemandedInstructionBits(I))
843 return &I;
844
Duncan Sands771e82a2011-01-28 16:51:11 +0000845 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000846 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000847 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
848 bool isSigned = I.getOpcode() == Instruction::SDiv;
849 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
850 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
851 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000852 }
853
Craig Topperf40110f2014-04-25 05:29:35 +0000854 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000855}
856
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000857/// dyn_castZExtVal - Checks if V is a zext or constant that can
858/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000859static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000860 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
861 if (Z->getSrcTy() == Ty)
862 return Z->getOperand(0);
863 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
864 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
865 return ConstantExpr::getTrunc(C, Ty);
866 }
Craig Topperf40110f2014-04-25 05:29:35 +0000867 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000868}
869
David Majnemer37f8f442013-07-04 21:17:49 +0000870namespace {
871const unsigned MaxDepth = 6;
872typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
873 const BinaryOperator &I,
874 InstCombiner &IC);
875
876/// \brief Used to maintain state for visitUDivOperand().
877struct UDivFoldAction {
878 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
879 ///< operand. This can be zero if this action
880 ///< joins two actions together.
881
882 Value *OperandToFold; ///< Which operand to fold.
883 union {
884 Instruction *FoldResult; ///< The instruction returned when FoldAction is
885 ///< invoked.
886
887 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
888 ///< joins two actions together.
889 };
890
891 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000892 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000893 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
894 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
895};
896}
897
898// X udiv 2^C -> X >> C
899static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
900 const BinaryOperator &I, InstCombiner &IC) {
901 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
902 BinaryOperator *LShr = BinaryOperator::CreateLShr(
903 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
904 if (I.isExact()) LShr->setIsExact();
905 return LShr;
906}
907
908// X udiv C, where C >= signbit
909static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
910 const BinaryOperator &I, InstCombiner &IC) {
911 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
912
913 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
914 ConstantInt::get(I.getType(), 1));
915}
916
917// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
918static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
919 InstCombiner &IC) {
920 Instruction *ShiftLeft = cast<Instruction>(Op1);
921 if (isa<ZExtInst>(ShiftLeft))
922 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
923
924 const APInt &CI =
925 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
926 Value *N = ShiftLeft->getOperand(1);
927 if (CI != 1)
928 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
929 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
930 N = IC.Builder->CreateZExt(N, Z->getDestTy());
931 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
932 if (I.isExact()) LShr->setIsExact();
933 return LShr;
934}
935
936// \brief Recursively visits the possible right hand operands of a udiv
937// instruction, seeing through select instructions, to determine if we can
938// replace the udiv with something simpler. If we find that an operand is not
939// able to simplify the udiv, we abort the entire transformation.
940static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
941 SmallVectorImpl<UDivFoldAction> &Actions,
942 unsigned Depth = 0) {
943 // Check to see if this is an unsigned division with an exact power of 2,
944 // if so, convert to a right shift.
945 if (match(Op1, m_Power2())) {
946 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
947 return Actions.size();
948 }
949
950 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
951 // X udiv C, where C >= signbit
952 if (C->getValue().isNegative()) {
953 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
954 return Actions.size();
955 }
956
957 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
958 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
959 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
960 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
961 return Actions.size();
962 }
963
964 // The remaining tests are all recursive, so bail out if we hit the limit.
965 if (Depth++ == MaxDepth)
966 return 0;
967
968 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
969 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
970 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000971 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)nullptr, Op1,
972 LHSIdx-1));
David Majnemer37f8f442013-07-04 21:17:49 +0000973 return Actions.size();
974 }
975
976 return 0;
977}
978
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000979Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
981
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000982 if (Value *V = SimplifyVectorOp(I))
983 return ReplaceInstUsesWith(I, V);
984
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000985 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +0000986 return ReplaceInstUsesWith(I, V);
987
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000988 // Handle the integer div common cases
989 if (Instruction *Common = commonIDivTransforms(I))
990 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000991
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000992 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Benjamin Kramer72196f32014-01-19 15:24:22 +0000993 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000994 Value *X;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000995 Constant *C1;
996 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
997 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
Nadav Rotem11935b22012-08-28 10:01:43 +0000998 }
999
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001000 // (zext A) udiv (zext B) --> zext (A udiv B)
1001 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1002 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1003 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
1004 I.isExact()),
1005 I.getType());
1006
David Majnemer37f8f442013-07-04 21:17:49 +00001007 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1008 SmallVector<UDivFoldAction, 6> UDivActions;
1009 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1010 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1011 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1012 Value *ActionOp1 = UDivActions[i].OperandToFold;
1013 Instruction *Inst;
1014 if (Action)
1015 Inst = Action(Op0, ActionOp1, I, *this);
1016 else {
1017 // This action joins two actions together. The RHS of this action is
1018 // simply the last action we processed, we saved the LHS action index in
1019 // the joining action.
1020 size_t SelectRHSIdx = i - 1;
1021 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1022 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1023 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1024 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1025 SelectLHS, SelectRHS);
1026 }
1027
1028 // If this is the last action to process, return it to the InstCombiner.
1029 // Otherwise, we insert it before the UDiv and record it so that we may
1030 // use it as part of a joining action (i.e., a SelectInst).
1031 if (e - i != 1) {
1032 Inst->insertBefore(&I);
1033 UDivActions[i].FoldResult = Inst;
1034 } else
1035 return Inst;
1036 }
1037
Craig Topperf40110f2014-04-25 05:29:35 +00001038 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001039}
1040
1041Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1042 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1043
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001044 if (Value *V = SimplifyVectorOp(I))
1045 return ReplaceInstUsesWith(I, V);
1046
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001047 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +00001048 return ReplaceInstUsesWith(I, V);
1049
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001050 // Handle the integer div common cases
1051 if (Instruction *Common = commonIDivTransforms(I))
1052 return Common;
1053
Benjamin Kramer72196f32014-01-19 15:24:22 +00001054 // sdiv X, -1 == -X
1055 if (match(Op1, m_AllOnes()))
1056 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001057
Benjamin Kramer72196f32014-01-19 15:24:22 +00001058 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001059 // sdiv X, C --> ashr exact X, log2(C)
1060 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001061 RHS->getValue().isPowerOf2()) {
1062 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1063 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001064 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001065 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001066 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001067
Benjamin Kramer72196f32014-01-19 15:24:22 +00001068 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001069 // X/INT_MIN -> X == INT_MIN
1070 if (RHS->isMinSignedValue())
1071 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1072
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001073 // -X/C --> X/-C provided the negation doesn't overflow.
1074 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001075 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001076 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1077 ConstantExpr::getNeg(RHS));
1078 }
1079
1080 // If the sign bits of both operands are zero (i.e. we can prove they are
1081 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001082 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001083 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1084 if (MaskedValueIsZero(Op0, Mask)) {
1085 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001086 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001087 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1088 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001089
Chris Lattner6b657ae2011-02-10 05:36:31 +00001090 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001091 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1092 // Safe because the only negative value (1 << Y) can take on is
1093 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1094 // the sign bit set.
1095 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1096 }
1097 }
1098 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001099
Craig Topperf40110f2014-04-25 05:29:35 +00001100 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001101}
1102
Shuxin Yang320f52a2013-01-14 22:48:41 +00001103/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1104/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001105/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001106/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001107/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001108/// returned; otherwise, NULL is returned.
1109///
1110static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001111 Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001112 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001113 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001114 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001115
1116 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001117 APFloat Reciprocal(FpVal.getSemantics());
1118 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001119
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001120 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001121 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1122 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1123 Cvt = !Reciprocal.isDenormal();
1124 }
1125
1126 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001127 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001128
1129 ConstantFP *R;
1130 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1131 return BinaryOperator::CreateFMul(Dividend, R);
1132}
1133
Frits van Bommel2a559512011-01-29 17:50:27 +00001134Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1136
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001137 if (Value *V = SimplifyVectorOp(I))
1138 return ReplaceInstUsesWith(I, V);
1139
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001140 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
Frits van Bommel2a559512011-01-29 17:50:27 +00001141 return ReplaceInstUsesWith(I, V);
1142
Stephen Lina9b57f62013-07-20 07:13:13 +00001143 if (isa<Constant>(Op0))
1144 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1145 if (Instruction *R = FoldOpIntoSelect(I, SI))
1146 return R;
1147
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148 bool AllowReassociate = I.hasUnsafeAlgebra();
1149 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001150
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001151 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001152 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1153 if (Instruction *R = FoldOpIntoSelect(I, SI))
1154 return R;
1155
Shuxin Yang320f52a2013-01-14 22:48:41 +00001156 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001157 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001158 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001159 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001160 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001161
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001162 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001163 // (X*C1)/C2 => X * (C1/C2)
1164 //
1165 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001166 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001167 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001168 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001169 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1170 //
1171 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001172 if (isNormalFp(C)) {
1173 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001174 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001175 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001176 }
1177 }
1178
1179 if (Res) {
1180 Res->setFastMathFlags(I.getFastMathFlags());
1181 return Res;
1182 }
1183 }
1184
1185 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001186 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1187 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001188 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001189 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001190
Craig Topperf40110f2014-04-25 05:29:35 +00001191 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001192 }
1193
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001194 if (AllowReassociate && isa<Constant>(Op0)) {
1195 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001196 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001197 Value *X;
1198 bool CreateDiv = true;
1199
1200 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001201 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001202 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001203 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001204 // C1 / (X/C2) => (C1*C2) / X
1205 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001206 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001207 // C1 / (C2/X) => (C1/C2) * X
1208 Fold = ConstantExpr::getFDiv(C1, C2);
1209 CreateDiv = false;
1210 }
1211
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001212 if (Fold && isNormalFp(Fold)) {
1213 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1214 : BinaryOperator::CreateFMul(X, Fold);
1215 R->setFastMathFlags(I.getFastMathFlags());
1216 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001217 }
Craig Topperf40110f2014-04-25 05:29:35 +00001218 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001219 }
1220
1221 if (AllowReassociate) {
1222 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001223 Value *NewInst = nullptr;
1224 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001225
1226 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1227 // (X/Y) / Z => X / (Y*Z)
1228 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001229 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001230 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001231 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1232 FastMathFlags Flags = I.getFastMathFlags();
1233 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1234 RI->setFastMathFlags(Flags);
1235 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001236 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1237 }
1238 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1239 // Z / (X/Y) => Z*Y / X
1240 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001241 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001242 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001243 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1244 FastMathFlags Flags = I.getFastMathFlags();
1245 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1246 RI->setFastMathFlags(Flags);
1247 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001248 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1249 }
1250 }
1251
1252 if (NewInst) {
1253 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1254 T->setDebugLoc(I.getDebugLoc());
1255 SimpR->setFastMathFlags(I.getFastMathFlags());
1256 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001257 }
1258 }
1259
Craig Topperf40110f2014-04-25 05:29:35 +00001260 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001261}
1262
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001263/// This function implements the transforms common to both integer remainder
1264/// instructions (urem and srem). It is called by the visitors to those integer
1265/// remainder instructions.
1266/// @brief Common integer remainder transforms
1267Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1268 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1269
Chris Lattner7c99f192011-05-22 18:18:41 +00001270 // The RHS is known non-zero.
1271 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1272 I.setOperand(1, V);
1273 return &I;
1274 }
1275
Duncan Sandsa3e36992011-05-02 16:27:02 +00001276 // Handle cases involving: rem X, (select Cond, Y, Z)
1277 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1278 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001279
Benjamin Kramer72196f32014-01-19 15:24:22 +00001280 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001281 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1282 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1283 if (Instruction *R = FoldOpIntoSelect(I, SI))
1284 return R;
1285 } else if (isa<PHINode>(Op0I)) {
1286 if (Instruction *NV = FoldOpIntoPhi(I))
1287 return NV;
1288 }
1289
1290 // See if we can fold away this rem instruction.
1291 if (SimplifyDemandedInstructionBits(I))
1292 return &I;
1293 }
1294 }
1295
Craig Topperf40110f2014-04-25 05:29:35 +00001296 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001297}
1298
1299Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1300 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1301
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001302 if (Value *V = SimplifyVectorOp(I))
1303 return ReplaceInstUsesWith(I, V);
1304
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001305 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001306 return ReplaceInstUsesWith(I, V);
1307
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001308 if (Instruction *common = commonIRemTransforms(I))
1309 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001310
David Majnemer6c30f492013-05-12 00:07:05 +00001311 // (zext A) urem (zext B) --> zext (A urem B)
1312 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1313 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1314 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1315 I.getType());
1316
David Majnemer470b0772013-05-11 09:01:28 +00001317 // X urem Y -> X and Y-1, where Y is a power of 2,
1318 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001319 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001320 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001321 return BinaryOperator::CreateAnd(Op0, Add);
1322 }
1323
Nick Lewycky7459be62013-07-13 01:16:47 +00001324 // 1 urem X -> zext(X != 1)
1325 if (match(Op0, m_One())) {
1326 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1327 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1328 return ReplaceInstUsesWith(I, Ext);
1329 }
1330
Craig Topperf40110f2014-04-25 05:29:35 +00001331 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001332}
1333
1334Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1336
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001337 if (Value *V = SimplifyVectorOp(I))
1338 return ReplaceInstUsesWith(I, V);
1339
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001340 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001341 return ReplaceInstUsesWith(I, V);
1342
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001343 // Handle the integer rem common cases
1344 if (Instruction *Common = commonIRemTransforms(I))
1345 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001346
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001347 if (Value *RHSNeg = dyn_castNegVal(Op1))
1348 if (!isa<Constant>(RHSNeg) ||
1349 (isa<ConstantInt>(RHSNeg) &&
1350 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1351 // X % -Y -> X % Y
1352 Worklist.AddValue(I.getOperand(1));
1353 I.setOperand(1, RHSNeg);
1354 return &I;
1355 }
1356
1357 // If the sign bits of both operands are zero (i.e. we can prove they are
1358 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001359 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001360 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1361 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001362 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001363 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1364 }
1365 }
1366
1367 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001368 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1369 Constant *C = cast<Constant>(Op1);
1370 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001371
1372 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001373 bool hasMissing = false;
1374 for (unsigned i = 0; i != VWidth; ++i) {
1375 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001376 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001377 hasMissing = true;
1378 break;
1379 }
1380
1381 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001382 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001383 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001384 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001385
Chris Lattner0256be92012-01-27 03:08:05 +00001386 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001387 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001388 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001389 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001390 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001391 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001392 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001393 }
1394 }
1395
1396 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001397 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001398 Worklist.AddValue(I.getOperand(1));
1399 I.setOperand(1, NewRHSV);
1400 return &I;
1401 }
1402 }
1403 }
1404
Craig Topperf40110f2014-04-25 05:29:35 +00001405 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001406}
1407
1408Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001410
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001411 if (Value *V = SimplifyVectorOp(I))
1412 return ReplaceInstUsesWith(I, V);
1413
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001414 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001415 return ReplaceInstUsesWith(I, V);
1416
1417 // Handle cases involving: rem X, (select Cond, Y, Z)
1418 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1419 return &I;
1420
Craig Topperf40110f2014-04-25 05:29:35 +00001421 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001422}