blob: 530a66dab9c1a8e807d35ff050049fa1c91c5eb5 [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.
Craig Topperf40110f2014-04-25 05:29:35 +000039 Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr;
Chris Lattner321c58f2011-05-23 00:09:55 +000040 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000041 m_Value(B))) &&
42 // The "1" can be any value known to be a power of 2.
Hal Finkel60db0582014-09-07 18:57:58 +000043 isKnownToBeAPowerOfTwo(PowerOf2, false, 0, IC.getAssumptionTracker(),
44 CxtI, IC.getDominatorTree())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000045 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000046 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000047 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000048
Chris Lattner388cb8a2011-05-23 00:32:19 +000049 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
50 // inexact. Similarly for <<.
51 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +000052 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
53 0, IC.getAssumptionTracker(),
54 CxtI,
55 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 // We know that this is an exact/nuw shift and that the input is a
57 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000058 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000059 I->setOperand(0, V2);
60 MadeChange = true;
61 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Chris Lattner388cb8a2011-05-23 00:32:19 +000063 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
64 I->setIsExact();
65 MadeChange = true;
66 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000067
Chris Lattner388cb8a2011-05-23 00:32:19 +000068 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
69 I->setHasNoUnsignedWrap();
70 MadeChange = true;
71 }
72 }
73
Chris Lattner162dfc32011-05-22 18:26:48 +000074 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000075 // If V is a phi node, we can call this on each of its operands.
76 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000077
Craig Topperf40110f2014-04-25 05:29:35 +000078 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000079}
80
81
Chris Lattnerdc054bf2010-01-05 06:09:35 +000082/// MultiplyOverflows - True if the multiply can not be expressed in an int
83/// this size.
David Majnemer27adb122014-10-12 08:34:24 +000084static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
85 bool IsSigned) {
86 bool Overflow;
87 if (IsSigned)
88 Product = C1.smul_ov(C2, Overflow);
89 else
90 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000091
David Majnemer27adb122014-10-12 08:34:24 +000092 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000093}
94
David Majnemerf9a095d2014-08-16 08:55:06 +000095/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
96static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
97 bool IsSigned) {
98 assert(C1.getBitWidth() == C2.getBitWidth() &&
99 "Inconsistent width of constants!");
100
101 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
102 if (IsSigned)
103 APInt::sdivrem(C1, C2, Quotient, Remainder);
104 else
105 APInt::udivrem(C1, C2, Quotient, Remainder);
106
107 return Remainder.isMinValue();
108}
109
Rafael Espindola65281bf2013-05-31 14:27:15 +0000110/// \brief A helper routine of InstCombiner::visitMul().
111///
112/// If C is a vector of known powers of 2, then this function returns
113/// a new vector obtained from C replacing each element with its logBase2.
114/// Return a null pointer otherwise.
115static Constant *getLogBase2Vector(ConstantDataVector *CV) {
116 const APInt *IVal;
117 SmallVector<Constant *, 4> Elts;
118
119 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
120 Constant *Elt = CV->getElementAsConstant(I);
121 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000122 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000123 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
124 }
125
126 return ConstantVector::get(Elts);
127}
128
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000129Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000130 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000131 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
132
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000133 if (Value *V = SimplifyVectorOp(I))
134 return ReplaceInstUsesWith(I, V);
135
Hal Finkel60db0582014-09-07 18:57:58 +0000136 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000137 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000138
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000139 if (Value *V = SimplifyUsingDistributiveLaws(I))
140 return ReplaceInstUsesWith(I, V);
141
Chris Lattner6b657ae2011-02-10 05:36:31 +0000142 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
143 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000144
Rafael Espindola65281bf2013-05-31 14:27:15 +0000145 // Also allow combining multiply instructions on vectors.
146 {
147 Value *NewOp;
148 Constant *C1, *C2;
149 const APInt *IVal;
150 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
151 m_Constant(C1))) &&
152 match(C1, m_APInt(IVal)))
153 // ((X << C1)*C2) == (X * (C2 << C1))
154 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000155
Rafael Espindola65281bf2013-05-31 14:27:15 +0000156 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000157 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000158 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
159 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
160 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
161 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
162 // Replace X*(2^C) with X << C, where C is a vector of known
163 // constant powers of 2.
164 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000165
Rafael Espindola65281bf2013-05-31 14:27:15 +0000166 if (NewCst) {
167 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000168
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000169 if (I.hasNoUnsignedWrap())
170 Shl->setHasNoUnsignedWrap();
171
Rafael Espindola65281bf2013-05-31 14:27:15 +0000172 return Shl;
173 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000174 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000175 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000176
Rafael Espindola65281bf2013-05-31 14:27:15 +0000177 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000178 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
179 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
180 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000181 {
182 const APInt & Val = CI->getValue();
183 const APInt &PosVal = Val.abs();
184 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000185 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000186 if (Op0->hasOneUse()) {
187 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000188 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000189 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
190 Sub = Builder->CreateSub(X, Y, "suba");
191 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
192 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
193 if (Sub)
194 return
195 BinaryOperator::CreateMul(Sub,
196 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000197 }
198 }
199 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000200 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000201
Chris Lattner6b657ae2011-02-10 05:36:31 +0000202 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000203 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000204 // Try to fold constant mul into select arguments.
205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
206 if (Instruction *R = FoldOpIntoSelect(I, SI))
207 return R;
208
209 if (isa<PHINode>(Op0))
210 if (Instruction *NV = FoldOpIntoPhi(I))
211 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000212
213 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
214 {
215 Value *X;
216 Constant *C1;
217 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000218 Value *Mul = Builder->CreateMul(C1, Op1);
219 // Only go forward with the transform if C1*CI simplifies to a tidier
220 // constant.
221 if (!match(Mul, m_Mul(m_Value(), m_Value())))
222 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000223 }
224 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000225 }
226
227 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
228 if (Value *Op1v = dyn_castNegVal(Op1))
229 return BinaryOperator::CreateMul(Op0v, Op1v);
230
231 // (X / Y) * Y = X - (X % Y)
232 // (X / Y) * -Y = (X % Y) - X
233 {
234 Value *Op1C = Op1;
235 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
236 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000237 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000238 BO->getOpcode() != Instruction::SDiv)) {
239 Op1C = Op0;
240 BO = dyn_cast<BinaryOperator>(Op1);
241 }
242 Value *Neg = dyn_castNegVal(Op1C);
243 if (BO && BO->hasOneUse() &&
244 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
245 (BO->getOpcode() == Instruction::UDiv ||
246 BO->getOpcode() == Instruction::SDiv)) {
247 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
248
Chris Lattner35315d02011-02-06 21:44:57 +0000249 // If the division is exact, X % Y is zero, so we end up with X or -X.
250 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000251 if (SDiv->isExact()) {
252 if (Op1BO == Op1C)
253 return ReplaceInstUsesWith(I, Op0BO);
254 return BinaryOperator::CreateNeg(Op0BO);
255 }
256
257 Value *Rem;
258 if (BO->getOpcode() == Instruction::UDiv)
259 Rem = Builder->CreateURem(Op0BO, Op1BO);
260 else
261 Rem = Builder->CreateSRem(Op0BO, Op1BO);
262 Rem->takeName(BO);
263
264 if (Op1BO == Op1C)
265 return BinaryOperator::CreateSub(Op0BO, Rem);
266 return BinaryOperator::CreateSub(Rem, Op0BO);
267 }
268 }
269
270 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000271 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000272 return BinaryOperator::CreateAnd(Op0, Op1);
273
274 // X*(1 << Y) --> X << Y
275 // (1 << Y)*X --> X << Y
276 {
277 Value *Y;
278 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
279 return BinaryOperator::CreateShl(Op1, Y);
280 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
281 return BinaryOperator::CreateShl(Op0, Y);
282 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000283
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000284 // If one of the operands of the multiply is a cast from a boolean value, then
285 // we know the bool is either zero or one, so this is a 'masking' multiply.
286 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000287 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000288 // -2 is "-1 << 1" so it is all bits set except the low one.
289 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000290
Craig Topperf40110f2014-04-25 05:29:35 +0000291 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000292 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000293 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000294 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000295 BoolCast = Op1, OtherOp = Op0;
296
297 if (BoolCast) {
298 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000299 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000300 return BinaryOperator::CreateAnd(V, OtherOp);
301 }
302 }
303
Craig Topperf40110f2014-04-25 05:29:35 +0000304 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000305}
306
Sanjay Patel17045f72014-10-14 00:33:23 +0000307/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000308static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000309 if (!Op->hasOneUse())
310 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000311
Sanjay Patel17045f72014-10-14 00:33:23 +0000312 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
313 if (!II)
314 return;
315 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
316 return;
317 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000318
Sanjay Patel17045f72014-10-14 00:33:23 +0000319 Value *OpLog2Of = II->getArgOperand(0);
320 if (!OpLog2Of->hasOneUse())
321 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000322
Sanjay Patel17045f72014-10-14 00:33:23 +0000323 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
324 if (!I)
325 return;
326 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
327 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000328
Sanjay Patel17045f72014-10-14 00:33:23 +0000329 if (match(I->getOperand(0), m_SpecificFP(0.5)))
330 Y = I->getOperand(1);
331 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
332 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000333}
Pedro Artigas993acd02012-11-30 22:07:05 +0000334
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000335static bool isFiniteNonZeroFp(Constant *C) {
336 if (C->getType()->isVectorTy()) {
337 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
338 ++I) {
339 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
340 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
341 return false;
342 }
343 return true;
344 }
345
346 return isa<ConstantFP>(C) &&
347 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
348}
349
350static bool isNormalFp(Constant *C) {
351 if (C->getType()->isVectorTy()) {
352 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
353 ++I) {
354 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
355 if (!CFP || !CFP->getValueAPF().isNormal())
356 return false;
357 }
358 return true;
359 }
360
361 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
362}
363
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000364/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
365/// true iff the given value is FMul or FDiv with one and only one operand
366/// being a normal constant (i.e. not Zero/NaN/Infinity).
367static bool isFMulOrFDivWithConstant(Value *V) {
368 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000369 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000370 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000371 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000372
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000373 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
374 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000375
376 if (C0 && C1)
377 return false;
378
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000379 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000380}
381
382/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
383/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
384/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000386/// resulting expression. Note that this function could return NULL in
387/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000388///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000389Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000390 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000391 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
392
393 Value *Opnd0 = FMulOrDiv->getOperand(0);
394 Value *Opnd1 = FMulOrDiv->getOperand(1);
395
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000396 Constant *C0 = dyn_cast<Constant>(Opnd0);
397 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000398
Craig Topperf40110f2014-04-25 05:29:35 +0000399 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000400
401 // (X * C0) * C => X * (C0*C)
402 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
403 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000404 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000405 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
406 } else {
407 if (C0) {
408 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000409 if (FMulOrDiv->hasOneUse()) {
410 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000411 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000412 if (isNormalFp(F))
413 R = BinaryOperator::CreateFDiv(F, Opnd1);
414 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000415 } else {
416 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000417 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000418 if (isNormalFp(F)) {
419 R = BinaryOperator::CreateFMul(Opnd0, F);
420 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000421 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000422 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000423 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000424 R = BinaryOperator::CreateFDiv(Opnd0, F);
425 }
426 }
427 }
428
429 if (R) {
430 R->setHasUnsafeAlgebra(true);
431 InsertNewInstWith(R, *InsertBefore);
432 }
433
434 return R;
435}
436
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000437Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000438 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
440
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000441 if (Value *V = SimplifyVectorOp(I))
442 return ReplaceInstUsesWith(I, V);
443
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000444 if (isa<Constant>(Op0))
445 std::swap(Op0, Op1);
446
Hal Finkel60db0582014-09-07 18:57:58 +0000447 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
448 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000449 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000450
Shuxin Yange8227452013-01-15 21:09:32 +0000451 bool AllowReassociate = I.hasUnsafeAlgebra();
452
Michael Ilsemand5787be2012-12-12 00:28:32 +0000453 // Simplify mul instructions with a constant RHS.
454 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000455 // Try to fold constant mul into select arguments.
456 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
457 if (Instruction *R = FoldOpIntoSelect(I, SI))
458 return R;
459
460 if (isa<PHINode>(Op0))
461 if (Instruction *NV = FoldOpIntoPhi(I))
462 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000463
Owen Andersonf74cfe02014-01-16 20:36:42 +0000464 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000465 if (match(Op1, m_SpecificFP(-1.0))) {
466 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
467 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000468 RI->copyFastMathFlags(&I);
469 return RI;
470 }
471
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000472 Constant *C = cast<Constant>(Op1);
473 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000474 // Let MDC denote an expression in one of these forms:
475 // X * C, C/X, X/C, where C is a constant.
476 //
477 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000478 if (isFMulOrFDivWithConstant(Op0))
479 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000480 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000481
Quentin Colombete684a6d2013-02-28 21:12:40 +0000482 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000483 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
484 if (FAddSub &&
485 (FAddSub->getOpcode() == Instruction::FAdd ||
486 FAddSub->getOpcode() == Instruction::FSub)) {
487 Value *Opnd0 = FAddSub->getOperand(0);
488 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000489 Constant *C0 = dyn_cast<Constant>(Opnd0);
490 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000491 bool Swap = false;
492 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000493 std::swap(C0, C1);
494 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000495 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000496 }
497
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000498 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000499 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000500 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000501 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000502 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000503 if (M0 && M1) {
504 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
505 std::swap(M0, M1);
506
Benjamin Kramer67485762013-09-30 15:39:59 +0000507 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
508 ? BinaryOperator::CreateFAdd(M0, M1)
509 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000510 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000511 return RI;
512 }
513 }
514 }
515 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000516 }
517
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000518 // sqrt(X) * sqrt(X) -> X
519 if (AllowReassociate && (Op0 == Op1))
520 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
521 if (II->getIntrinsicID() == Intrinsic::sqrt)
522 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000523
Pedro Artigasd8795042012-11-30 19:09:41 +0000524 // Under unsafe algebra do:
525 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000526 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000527 Value *OpX = nullptr;
528 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000529 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000530 detectLog2OfHalf(Op0, OpY, Log2);
531 if (OpY) {
532 OpX = Op1;
533 } else {
534 detectLog2OfHalf(Op1, OpY, Log2);
535 if (OpY) {
536 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000537 }
538 }
539 // if pattern detected emit alternate sequence
540 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000541 BuilderTy::FastMathFlagGuard Guard(*Builder);
542 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000543 Log2->setArgOperand(0, OpY);
544 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000545 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
546 FSub->takeName(&I);
547 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000548 }
549 }
550
Shuxin Yange8227452013-01-15 21:09:32 +0000551 // Handle symmetric situation in a 2-iteration loop
552 Value *Opnd0 = Op0;
553 Value *Opnd1 = Op1;
554 for (int i = 0; i < 2; i++) {
555 bool IgnoreZeroSign = I.hasNoSignedZeros();
556 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000557 BuilderTy::FastMathFlagGuard Guard(*Builder);
558 Builder->SetFastMathFlags(I.getFastMathFlags());
559
Shuxin Yange8227452013-01-15 21:09:32 +0000560 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
561 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000562
Shuxin Yange8227452013-01-15 21:09:32 +0000563 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000564 if (N1) {
565 Value *FMul = Builder->CreateFMul(N0, N1);
566 FMul->takeName(&I);
567 return ReplaceInstUsesWith(I, FMul);
568 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000569
Shuxin Yange8227452013-01-15 21:09:32 +0000570 if (Opnd0->hasOneUse()) {
571 // -X * Y => -(X*Y) (Promote negation as high as possible)
572 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000573 Value *Neg = Builder->CreateFNeg(T);
574 Neg->takeName(&I);
575 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000576 }
577 }
Shuxin Yange8227452013-01-15 21:09:32 +0000578
579 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000580 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000581 // 1) to form a power expression (of X).
582 // 2) potentially shorten the critical path: After transformation, the
583 // latency of the instruction Y is amortized by the expression of X*X,
584 // and therefore Y is in a "less critical" position compared to what it
585 // was before the transformation.
586 //
587 if (AllowReassociate) {
588 Value *Opnd0_0, *Opnd0_1;
589 if (Opnd0->hasOneUse() &&
590 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000591 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000592 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
593 Y = Opnd0_1;
594 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
595 Y = Opnd0_0;
596
597 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000598 BuilderTy::FastMathFlagGuard Guard(*Builder);
599 Builder->SetFastMathFlags(I.getFastMathFlags());
600 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000601
Benjamin Kramer67485762013-09-30 15:39:59 +0000602 Value *R = Builder->CreateFMul(T, Y);
603 R->takeName(&I);
604 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000605 }
606 }
607 }
608
609 if (!isa<Constant>(Op1))
610 std::swap(Opnd0, Opnd1);
611 else
612 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000613 }
614
Craig Topperf40110f2014-04-25 05:29:35 +0000615 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000616}
617
618/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
619/// instruction.
620bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
621 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000622
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000623 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
624 int NonNullOperand = -1;
625 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
626 if (ST->isNullValue())
627 NonNullOperand = 2;
628 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
629 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
630 if (ST->isNullValue())
631 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000632
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000633 if (NonNullOperand == -1)
634 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000635
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000636 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000637
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000638 // Change the div/rem to use 'Y' instead of the select.
639 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000641 // Okay, we know we replace the operand of the div/rem with 'Y' with no
642 // problem. However, the select, or the condition of the select may have
643 // multiple uses. Based on our knowledge that the operand must be non-zero,
644 // propagate the known value for the select into other uses of it, and
645 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000646
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000647 // If the select and condition only have a single use, don't bother with this,
648 // early exit.
649 if (SI->use_empty() && SelectCond->hasOneUse())
650 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 // Scan the current block backward, looking for other uses of SI.
653 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000654
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000655 while (BBI != BBFront) {
656 --BBI;
657 // If we found a call to a function, we can't assume it will return, so
658 // information from below it cannot be propagated above it.
659 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
660 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000661
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000662 // Replace uses of the select or its condition with the known values.
663 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
664 I != E; ++I) {
665 if (*I == SI) {
666 *I = SI->getOperand(NonNullOperand);
667 Worklist.Add(BBI);
668 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000669 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000670 Worklist.Add(BBI);
671 }
672 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000673
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000674 // If we past the instruction, quit looking for it.
675 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000676 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000677 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000678 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000679
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000680 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000681 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000683
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000684 }
685 return true;
686}
687
688
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000689/// This function implements the transforms common to both integer division
690/// instructions (udiv and sdiv). It is called by the visitors to those integer
691/// division instructions.
692/// @brief Common integer divide transforms
693Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
694 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
695
Chris Lattner7c99f192011-05-22 18:18:41 +0000696 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000697 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000698 I.setOperand(1, V);
699 return &I;
700 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000701
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000702 // Handle cases involving: [su]div X, (select Cond, Y, Z)
703 // This does not apply for fdiv.
704 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
705 return &I;
706
David Majnemer27adb122014-10-12 08:34:24 +0000707 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
708 const APInt *C2;
709 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000710 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000711 const APInt *C1;
712 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000713
David Majnemer27adb122014-10-12 08:34:24 +0000714 // (X / C1) / C2 -> X / (C1*C2)
715 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
716 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
717 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
718 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
719 return BinaryOperator::Create(I.getOpcode(), X,
720 ConstantInt::get(I.getType(), Product));
721 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000722
David Majnemer27adb122014-10-12 08:34:24 +0000723 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
724 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
725 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
726
727 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
728 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
729 BinaryOperator *BO = BinaryOperator::Create(
730 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
731 BO->setIsExact(I.isExact());
732 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000733 }
734
David Majnemer27adb122014-10-12 08:34:24 +0000735 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
736 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
737 BinaryOperator *BO = BinaryOperator::Create(
738 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
739 BO->setHasNoUnsignedWrap(
740 !IsSigned &&
741 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
742 BO->setHasNoSignedWrap(
743 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
744 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000745 }
746 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000747
David Majnemer27adb122014-10-12 08:34:24 +0000748 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
749 *C1 != C1->getBitWidth() - 1) ||
750 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
751 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
752 APInt C1Shifted = APInt::getOneBitSet(
753 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
754
755 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
756 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
757 BinaryOperator *BO = BinaryOperator::Create(
758 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
759 BO->setIsExact(I.isExact());
760 return BO;
761 }
762
763 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
764 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
765 BinaryOperator *BO = BinaryOperator::Create(
766 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
767 BO->setHasNoUnsignedWrap(
768 !IsSigned &&
769 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
770 BO->setHasNoSignedWrap(
771 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
772 return BO;
773 }
774 }
775
776 if (*C2 != 0) { // avoid X udiv 0
777 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
778 if (Instruction *R = FoldOpIntoSelect(I, SI))
779 return R;
780 if (isa<PHINode>(Op0))
781 if (Instruction *NV = FoldOpIntoPhi(I))
782 return NV;
783 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000784 }
785 }
786
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000787 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
788 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
789 bool isSigned = I.getOpcode() == Instruction::SDiv;
790 if (isSigned) {
791 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
792 // result is one, if Op1 is -1 then the result is minus one, otherwise
793 // it's zero.
794 Value *Inc = Builder->CreateAdd(Op1, One);
795 Value *Cmp = Builder->CreateICmpULT(
796 Inc, ConstantInt::get(I.getType(), 3));
797 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
798 } else {
799 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
800 // result is one, otherwise it's zero.
801 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
802 }
803 }
804 }
805
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000806 // See if we can fold away this div instruction.
807 if (SimplifyDemandedInstructionBits(I))
808 return &I;
809
Duncan Sands771e82a2011-01-28 16:51:11 +0000810 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000811 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000812 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
813 bool isSigned = I.getOpcode() == Instruction::SDiv;
814 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
815 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
816 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000817 }
818
Craig Topperf40110f2014-04-25 05:29:35 +0000819 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000820}
821
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000822/// dyn_castZExtVal - Checks if V is a zext or constant that can
823/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000824static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000825 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
826 if (Z->getSrcTy() == Ty)
827 return Z->getOperand(0);
828 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
829 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
830 return ConstantExpr::getTrunc(C, Ty);
831 }
Craig Topperf40110f2014-04-25 05:29:35 +0000832 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000833}
834
David Majnemer37f8f442013-07-04 21:17:49 +0000835namespace {
836const unsigned MaxDepth = 6;
837typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
838 const BinaryOperator &I,
839 InstCombiner &IC);
840
841/// \brief Used to maintain state for visitUDivOperand().
842struct UDivFoldAction {
843 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
844 ///< operand. This can be zero if this action
845 ///< joins two actions together.
846
847 Value *OperandToFold; ///< Which operand to fold.
848 union {
849 Instruction *FoldResult; ///< The instruction returned when FoldAction is
850 ///< invoked.
851
852 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
853 ///< joins two actions together.
854 };
855
856 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000857 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000858 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
859 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
860};
861}
862
863// X udiv 2^C -> X >> C
864static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
865 const BinaryOperator &I, InstCombiner &IC) {
866 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
867 BinaryOperator *LShr = BinaryOperator::CreateLShr(
868 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000869 if (I.isExact())
870 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000871 return LShr;
872}
873
874// X udiv C, where C >= signbit
875static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
876 const BinaryOperator &I, InstCombiner &IC) {
877 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
878
879 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
880 ConstantInt::get(I.getType(), 1));
881}
882
883// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
884static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
885 InstCombiner &IC) {
886 Instruction *ShiftLeft = cast<Instruction>(Op1);
887 if (isa<ZExtInst>(ShiftLeft))
888 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
889
890 const APInt &CI =
891 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
892 Value *N = ShiftLeft->getOperand(1);
893 if (CI != 1)
894 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
895 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
896 N = IC.Builder->CreateZExt(N, Z->getDestTy());
897 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000898 if (I.isExact())
899 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000900 return LShr;
901}
902
903// \brief Recursively visits the possible right hand operands of a udiv
904// instruction, seeing through select instructions, to determine if we can
905// replace the udiv with something simpler. If we find that an operand is not
906// able to simplify the udiv, we abort the entire transformation.
907static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
908 SmallVectorImpl<UDivFoldAction> &Actions,
909 unsigned Depth = 0) {
910 // Check to see if this is an unsigned division with an exact power of 2,
911 // if so, convert to a right shift.
912 if (match(Op1, m_Power2())) {
913 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
914 return Actions.size();
915 }
916
917 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
918 // X udiv C, where C >= signbit
919 if (C->getValue().isNegative()) {
920 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
921 return Actions.size();
922 }
923
924 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
925 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
926 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
927 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
928 return Actions.size();
929 }
930
931 // The remaining tests are all recursive, so bail out if we hit the limit.
932 if (Depth++ == MaxDepth)
933 return 0;
934
935 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000936 if (size_t LHSIdx =
937 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
938 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
939 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000940 return Actions.size();
941 }
942
943 return 0;
944}
945
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000946Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
947 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
948
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000949 if (Value *V = SimplifyVectorOp(I))
950 return ReplaceInstUsesWith(I, V);
951
Hal Finkel60db0582014-09-07 18:57:58 +0000952 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000953 return ReplaceInstUsesWith(I, V);
954
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000955 // Handle the integer div common cases
956 if (Instruction *Common = commonIDivTransforms(I))
957 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000958
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000959 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000960 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000961 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000962 const APInt *C1, *C2;
963 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
964 match(Op1, m_APInt(C2))) {
965 bool Overflow;
966 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
967 if (!Overflow)
968 return BinaryOperator::CreateUDiv(
969 X, ConstantInt::get(X->getType(), C2ShlC1));
970 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000971 }
972
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000973 // (zext A) udiv (zext B) --> zext (A udiv B)
974 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
975 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +0000976 return new ZExtInst(
977 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
978 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000979
David Majnemer37f8f442013-07-04 21:17:49 +0000980 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
981 SmallVector<UDivFoldAction, 6> UDivActions;
982 if (visitUDivOperand(Op0, Op1, I, UDivActions))
983 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
984 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
985 Value *ActionOp1 = UDivActions[i].OperandToFold;
986 Instruction *Inst;
987 if (Action)
988 Inst = Action(Op0, ActionOp1, I, *this);
989 else {
990 // This action joins two actions together. The RHS of this action is
991 // simply the last action we processed, we saved the LHS action index in
992 // the joining action.
993 size_t SelectRHSIdx = i - 1;
994 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
995 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
996 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
997 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
998 SelectLHS, SelectRHS);
999 }
1000
1001 // If this is the last action to process, return it to the InstCombiner.
1002 // Otherwise, we insert it before the UDiv and record it so that we may
1003 // use it as part of a joining action (i.e., a SelectInst).
1004 if (e - i != 1) {
1005 Inst->insertBefore(&I);
1006 UDivActions[i].FoldResult = Inst;
1007 } else
1008 return Inst;
1009 }
1010
Craig Topperf40110f2014-04-25 05:29:35 +00001011 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001012}
1013
1014Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1016
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001017 if (Value *V = SimplifyVectorOp(I))
1018 return ReplaceInstUsesWith(I, V);
1019
Hal Finkel60db0582014-09-07 18:57:58 +00001020 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001021 return ReplaceInstUsesWith(I, V);
1022
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001023 // Handle the integer div common cases
1024 if (Instruction *Common = commonIDivTransforms(I))
1025 return Common;
1026
Benjamin Kramer72196f32014-01-19 15:24:22 +00001027 // sdiv X, -1 == -X
1028 if (match(Op1, m_AllOnes()))
1029 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001030
Benjamin Kramer72196f32014-01-19 15:24:22 +00001031 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001032 // sdiv X, C --> ashr exact X, log2(C)
1033 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001034 RHS->getValue().isPowerOf2()) {
1035 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1036 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001037 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001038 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001039 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001040
Benjamin Kramer72196f32014-01-19 15:24:22 +00001041 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001042 // X/INT_MIN -> X == INT_MIN
1043 if (RHS->isMinSignedValue())
1044 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1045
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001046 // -X/C --> X/-C provided the negation doesn't overflow.
1047 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001048 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001049 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1050 ConstantExpr::getNeg(RHS));
1051 }
1052
1053 // If the sign bits of both operands are zero (i.e. we can prove they are
1054 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001055 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001056 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001057 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1058 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001059 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001060 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1061 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001062
Chris Lattner6b657ae2011-02-10 05:36:31 +00001063 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001064 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1065 // Safe because the only negative value (1 << Y) can take on is
1066 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1067 // the sign bit set.
1068 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1069 }
1070 }
1071 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001072
Craig Topperf40110f2014-04-25 05:29:35 +00001073 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001074}
1075
Shuxin Yang320f52a2013-01-14 22:48:41 +00001076/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1077/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001078/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001079/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001080/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001081/// returned; otherwise, NULL is returned.
1082///
Suyog Sardaea205512014-10-07 11:56:06 +00001083static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001084 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001085 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001086 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001087
1088 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001089 APFloat Reciprocal(FpVal.getSemantics());
1090 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001091
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001092 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001093 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1094 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1095 Cvt = !Reciprocal.isDenormal();
1096 }
1097
1098 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001099 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001100
1101 ConstantFP *R;
1102 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1103 return BinaryOperator::CreateFMul(Dividend, R);
1104}
1105
Frits van Bommel2a559512011-01-29 17:50:27 +00001106Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1108
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001109 if (Value *V = SimplifyVectorOp(I))
1110 return ReplaceInstUsesWith(I, V);
1111
Hal Finkel60db0582014-09-07 18:57:58 +00001112 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001113 return ReplaceInstUsesWith(I, V);
1114
Stephen Lina9b57f62013-07-20 07:13:13 +00001115 if (isa<Constant>(Op0))
1116 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1117 if (Instruction *R = FoldOpIntoSelect(I, SI))
1118 return R;
1119
Shuxin Yang320f52a2013-01-14 22:48:41 +00001120 bool AllowReassociate = I.hasUnsafeAlgebra();
1121 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001122
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001123 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001124 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1125 if (Instruction *R = FoldOpIntoSelect(I, SI))
1126 return R;
1127
Shuxin Yang320f52a2013-01-14 22:48:41 +00001128 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001129 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001130 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001131 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001132 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001133
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001134 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001135 // (X*C1)/C2 => X * (C1/C2)
1136 //
1137 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001138 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001139 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001140 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001141 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1142 //
1143 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001144 if (isNormalFp(C)) {
1145 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001146 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001147 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148 }
1149 }
1150
1151 if (Res) {
1152 Res->setFastMathFlags(I.getFastMathFlags());
1153 return Res;
1154 }
1155 }
1156
1157 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001158 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1159 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001160 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001161 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001162
Craig Topperf40110f2014-04-25 05:29:35 +00001163 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001164 }
1165
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001166 if (AllowReassociate && isa<Constant>(Op0)) {
1167 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001168 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001169 Value *X;
1170 bool CreateDiv = true;
1171
1172 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001173 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001174 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001175 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001176 // C1 / (X/C2) => (C1*C2) / X
1177 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001178 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001179 // C1 / (C2/X) => (C1/C2) * X
1180 Fold = ConstantExpr::getFDiv(C1, C2);
1181 CreateDiv = false;
1182 }
1183
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001184 if (Fold && isNormalFp(Fold)) {
1185 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1186 : BinaryOperator::CreateFMul(X, Fold);
1187 R->setFastMathFlags(I.getFastMathFlags());
1188 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001189 }
Craig Topperf40110f2014-04-25 05:29:35 +00001190 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001191 }
1192
1193 if (AllowReassociate) {
1194 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001195 Value *NewInst = nullptr;
1196 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001197
1198 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1199 // (X/Y) / Z => X / (Y*Z)
1200 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001201 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001202 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001203 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1204 FastMathFlags Flags = I.getFastMathFlags();
1205 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1206 RI->setFastMathFlags(Flags);
1207 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001208 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1209 }
1210 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1211 // Z / (X/Y) => Z*Y / X
1212 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001213 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001214 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001215 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1216 FastMathFlags Flags = I.getFastMathFlags();
1217 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1218 RI->setFastMathFlags(Flags);
1219 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001220 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1221 }
1222 }
1223
1224 if (NewInst) {
1225 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1226 T->setDebugLoc(I.getDebugLoc());
1227 SimpR->setFastMathFlags(I.getFastMathFlags());
1228 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001229 }
1230 }
1231
Craig Topperf40110f2014-04-25 05:29:35 +00001232 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001233}
1234
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001235/// This function implements the transforms common to both integer remainder
1236/// instructions (urem and srem). It is called by the visitors to those integer
1237/// remainder instructions.
1238/// @brief Common integer remainder transforms
1239Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1240 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1241
Chris Lattner7c99f192011-05-22 18:18:41 +00001242 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001243 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001244 I.setOperand(1, V);
1245 return &I;
1246 }
1247
Duncan Sandsa3e36992011-05-02 16:27:02 +00001248 // Handle cases involving: rem X, (select Cond, Y, Z)
1249 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1250 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001251
Benjamin Kramer72196f32014-01-19 15:24:22 +00001252 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001253 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1254 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1255 if (Instruction *R = FoldOpIntoSelect(I, SI))
1256 return R;
1257 } else if (isa<PHINode>(Op0I)) {
1258 if (Instruction *NV = FoldOpIntoPhi(I))
1259 return NV;
1260 }
1261
1262 // See if we can fold away this rem instruction.
1263 if (SimplifyDemandedInstructionBits(I))
1264 return &I;
1265 }
1266 }
1267
Craig Topperf40110f2014-04-25 05:29:35 +00001268 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001269}
1270
1271Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1273
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001274 if (Value *V = SimplifyVectorOp(I))
1275 return ReplaceInstUsesWith(I, V);
1276
Hal Finkel60db0582014-09-07 18:57:58 +00001277 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001278 return ReplaceInstUsesWith(I, V);
1279
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001280 if (Instruction *common = commonIRemTransforms(I))
1281 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001282
David Majnemer6c30f492013-05-12 00:07:05 +00001283 // (zext A) urem (zext B) --> zext (A urem B)
1284 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1285 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1286 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1287 I.getType());
1288
David Majnemer470b0772013-05-11 09:01:28 +00001289 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001290 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001291 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001292 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001293 return BinaryOperator::CreateAnd(Op0, Add);
1294 }
1295
Nick Lewycky7459be62013-07-13 01:16:47 +00001296 // 1 urem X -> zext(X != 1)
1297 if (match(Op0, m_One())) {
1298 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1299 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1300 return ReplaceInstUsesWith(I, Ext);
1301 }
1302
Craig Topperf40110f2014-04-25 05:29:35 +00001303 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001304}
1305
1306Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1308
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001309 if (Value *V = SimplifyVectorOp(I))
1310 return ReplaceInstUsesWith(I, V);
1311
Hal Finkel60db0582014-09-07 18:57:58 +00001312 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001313 return ReplaceInstUsesWith(I, V);
1314
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001315 // Handle the integer rem common cases
1316 if (Instruction *Common = commonIRemTransforms(I))
1317 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001318
David Majnemerdb077302014-10-13 22:37:51 +00001319 {
1320 const APInt *Y;
1321 // X % -Y -> X % Y
1322 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001323 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001324 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001325 return &I;
1326 }
David Majnemerdb077302014-10-13 22:37:51 +00001327 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001328
1329 // If the sign bits of both operands are zero (i.e. we can prove they are
1330 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001331 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001332 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001333 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1334 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001335 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001336 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1337 }
1338 }
1339
1340 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001341 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1342 Constant *C = cast<Constant>(Op1);
1343 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001344
1345 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001346 bool hasMissing = false;
1347 for (unsigned i = 0; i != VWidth; ++i) {
1348 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001349 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001350 hasMissing = true;
1351 break;
1352 }
1353
1354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001355 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001356 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001357 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001358
Chris Lattner0256be92012-01-27 03:08:05 +00001359 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001360 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001361 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001362 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001363 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001364 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001365 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001366 }
1367 }
1368
1369 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001370 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001371 Worklist.AddValue(I.getOperand(1));
1372 I.setOperand(1, NewRHSV);
1373 return &I;
1374 }
1375 }
1376 }
1377
Craig Topperf40110f2014-04-25 05:29:35 +00001378 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001379}
1380
1381Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001383
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001384 if (Value *V = SimplifyVectorOp(I))
1385 return ReplaceInstUsesWith(I, V);
1386
Hal Finkel60db0582014-09-07 18:57:58 +00001387 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001388 return ReplaceInstUsesWith(I, V);
1389
1390 // Handle cases involving: rem X, (select Cond, Y, Z)
1391 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1392 return &I;
1393
Craig Topperf40110f2014-04-25 05:29:35 +00001394 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001395}