blob: 840a25fb81318c5b95e366e1b5d3f90c8ed82b6a [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
Pedro Artigas993acd02012-11-30 22:07:05 +0000307//
308// Detect pattern:
309//
310// log2(Y*0.5)
311//
312// And check for corresponding fast math flags
313//
314
315static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000316
317 if (!Op->hasOneUse())
318 return;
319
320 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
321 if (!II)
322 return;
323 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
324 return;
325 Log2 = II;
326
327 Value *OpLog2Of = II->getArgOperand(0);
328 if (!OpLog2Of->hasOneUse())
329 return;
330
331 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
332 if (!I)
333 return;
334 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
335 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000336
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000337 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000338 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000339 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000340 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000341}
Pedro Artigas993acd02012-11-30 22:07:05 +0000342
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000343static bool isFiniteNonZeroFp(Constant *C) {
344 if (C->getType()->isVectorTy()) {
345 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
346 ++I) {
347 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
348 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
349 return false;
350 }
351 return true;
352 }
353
354 return isa<ConstantFP>(C) &&
355 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
356}
357
358static bool isNormalFp(Constant *C) {
359 if (C->getType()->isVectorTy()) {
360 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
361 ++I) {
362 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
363 if (!CFP || !CFP->getValueAPF().isNormal())
364 return false;
365 }
366 return true;
367 }
368
369 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
370}
371
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000372/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
373/// true iff the given value is FMul or FDiv with one and only one operand
374/// being a normal constant (i.e. not Zero/NaN/Infinity).
375static bool isFMulOrFDivWithConstant(Value *V) {
376 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000377 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000378 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000379 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000380
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000381 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
382 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000383
384 if (C0 && C1)
385 return false;
386
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000387 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000388}
389
390/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
391/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
392/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000393/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000394/// resulting expression. Note that this function could return NULL in
395/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000396///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000397Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000398 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000399 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
400
401 Value *Opnd0 = FMulOrDiv->getOperand(0);
402 Value *Opnd1 = FMulOrDiv->getOperand(1);
403
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000404 Constant *C0 = dyn_cast<Constant>(Opnd0);
405 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000406
Craig Topperf40110f2014-04-25 05:29:35 +0000407 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000408
409 // (X * C0) * C => X * (C0*C)
410 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
411 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000412 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000413 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
414 } else {
415 if (C0) {
416 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000417 if (FMulOrDiv->hasOneUse()) {
418 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000419 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000420 if (isNormalFp(F))
421 R = BinaryOperator::CreateFDiv(F, Opnd1);
422 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000423 } else {
424 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000425 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000426 if (isNormalFp(F)) {
427 R = BinaryOperator::CreateFMul(Opnd0, F);
428 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000429 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000430 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000431 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000432 R = BinaryOperator::CreateFDiv(Opnd0, F);
433 }
434 }
435 }
436
437 if (R) {
438 R->setHasUnsafeAlgebra(true);
439 InsertNewInstWith(R, *InsertBefore);
440 }
441
442 return R;
443}
444
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000445Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000446 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000447 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
448
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000449 if (Value *V = SimplifyVectorOp(I))
450 return ReplaceInstUsesWith(I, V);
451
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000452 if (isa<Constant>(Op0))
453 std::swap(Op0, Op1);
454
Hal Finkel60db0582014-09-07 18:57:58 +0000455 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
456 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000457 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000458
Shuxin Yange8227452013-01-15 21:09:32 +0000459 bool AllowReassociate = I.hasUnsafeAlgebra();
460
Michael Ilsemand5787be2012-12-12 00:28:32 +0000461 // Simplify mul instructions with a constant RHS.
462 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000463 // Try to fold constant mul into select arguments.
464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
465 if (Instruction *R = FoldOpIntoSelect(I, SI))
466 return R;
467
468 if (isa<PHINode>(Op0))
469 if (Instruction *NV = FoldOpIntoPhi(I))
470 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000471
Owen Andersonf74cfe02014-01-16 20:36:42 +0000472 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000473 if (match(Op1, m_SpecificFP(-1.0))) {
474 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
475 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000476 RI->copyFastMathFlags(&I);
477 return RI;
478 }
479
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000480 Constant *C = cast<Constant>(Op1);
481 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000482 // Let MDC denote an expression in one of these forms:
483 // X * C, C/X, X/C, where C is a constant.
484 //
485 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000486 if (isFMulOrFDivWithConstant(Op0))
487 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000488 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000489
Quentin Colombete684a6d2013-02-28 21:12:40 +0000490 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000491 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
492 if (FAddSub &&
493 (FAddSub->getOpcode() == Instruction::FAdd ||
494 FAddSub->getOpcode() == Instruction::FSub)) {
495 Value *Opnd0 = FAddSub->getOperand(0);
496 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000497 Constant *C0 = dyn_cast<Constant>(Opnd0);
498 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000499 bool Swap = false;
500 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000501 std::swap(C0, C1);
502 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000503 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000504 }
505
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000506 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000507 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000508 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000509 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000510 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000511 if (M0 && M1) {
512 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
513 std::swap(M0, M1);
514
Benjamin Kramer67485762013-09-30 15:39:59 +0000515 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
516 ? BinaryOperator::CreateFAdd(M0, M1)
517 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000518 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000519 return RI;
520 }
521 }
522 }
523 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000524 }
525
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000526 // sqrt(X) * sqrt(X) -> X
527 if (AllowReassociate && (Op0 == Op1))
528 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
529 if (II->getIntrinsicID() == Intrinsic::sqrt)
530 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000531
Pedro Artigasd8795042012-11-30 19:09:41 +0000532 // Under unsafe algebra do:
533 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000534 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000535 Value *OpX = nullptr;
536 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000537 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000538 detectLog2OfHalf(Op0, OpY, Log2);
539 if (OpY) {
540 OpX = Op1;
541 } else {
542 detectLog2OfHalf(Op1, OpY, Log2);
543 if (OpY) {
544 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000545 }
546 }
547 // if pattern detected emit alternate sequence
548 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000549 BuilderTy::FastMathFlagGuard Guard(*Builder);
550 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000551 Log2->setArgOperand(0, OpY);
552 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000553 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
554 FSub->takeName(&I);
555 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000556 }
557 }
558
Shuxin Yange8227452013-01-15 21:09:32 +0000559 // Handle symmetric situation in a 2-iteration loop
560 Value *Opnd0 = Op0;
561 Value *Opnd1 = Op1;
562 for (int i = 0; i < 2; i++) {
563 bool IgnoreZeroSign = I.hasNoSignedZeros();
564 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000565 BuilderTy::FastMathFlagGuard Guard(*Builder);
566 Builder->SetFastMathFlags(I.getFastMathFlags());
567
Shuxin Yange8227452013-01-15 21:09:32 +0000568 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
569 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000570
Shuxin Yange8227452013-01-15 21:09:32 +0000571 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000572 if (N1) {
573 Value *FMul = Builder->CreateFMul(N0, N1);
574 FMul->takeName(&I);
575 return ReplaceInstUsesWith(I, FMul);
576 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000577
Shuxin Yange8227452013-01-15 21:09:32 +0000578 if (Opnd0->hasOneUse()) {
579 // -X * Y => -(X*Y) (Promote negation as high as possible)
580 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000581 Value *Neg = Builder->CreateFNeg(T);
582 Neg->takeName(&I);
583 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000584 }
585 }
Shuxin Yange8227452013-01-15 21:09:32 +0000586
587 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000588 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000589 // 1) to form a power expression (of X).
590 // 2) potentially shorten the critical path: After transformation, the
591 // latency of the instruction Y is amortized by the expression of X*X,
592 // and therefore Y is in a "less critical" position compared to what it
593 // was before the transformation.
594 //
595 if (AllowReassociate) {
596 Value *Opnd0_0, *Opnd0_1;
597 if (Opnd0->hasOneUse() &&
598 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000599 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000600 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
601 Y = Opnd0_1;
602 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
603 Y = Opnd0_0;
604
605 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000606 BuilderTy::FastMathFlagGuard Guard(*Builder);
607 Builder->SetFastMathFlags(I.getFastMathFlags());
608 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000609
Benjamin Kramer67485762013-09-30 15:39:59 +0000610 Value *R = Builder->CreateFMul(T, Y);
611 R->takeName(&I);
612 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000613 }
614 }
615 }
616
617 if (!isa<Constant>(Op1))
618 std::swap(Opnd0, Opnd1);
619 else
620 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000621 }
622
Craig Topperf40110f2014-04-25 05:29:35 +0000623 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000624}
625
626/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
627/// instruction.
628bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
629 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000630
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000631 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
632 int NonNullOperand = -1;
633 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
634 if (ST->isNullValue())
635 NonNullOperand = 2;
636 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
637 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
638 if (ST->isNullValue())
639 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000641 if (NonNullOperand == -1)
642 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000643
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000644 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000646 // Change the div/rem to use 'Y' instead of the select.
647 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 // Okay, we know we replace the operand of the div/rem with 'Y' with no
650 // problem. However, the select, or the condition of the select may have
651 // multiple uses. Based on our knowledge that the operand must be non-zero,
652 // propagate the known value for the select into other uses of it, and
653 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000654
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000655 // If the select and condition only have a single use, don't bother with this,
656 // early exit.
657 if (SI->use_empty() && SelectCond->hasOneUse())
658 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000659
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000660 // Scan the current block backward, looking for other uses of SI.
661 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000662
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000663 while (BBI != BBFront) {
664 --BBI;
665 // If we found a call to a function, we can't assume it will return, so
666 // information from below it cannot be propagated above it.
667 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
668 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000669
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000670 // Replace uses of the select or its condition with the known values.
671 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
672 I != E; ++I) {
673 if (*I == SI) {
674 *I = SI->getOperand(NonNullOperand);
675 Worklist.Add(BBI);
676 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000677 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000678 Worklist.Add(BBI);
679 }
680 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 // If we past the instruction, quit looking for it.
683 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000684 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000685 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000686 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000687
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000688 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000689 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000691
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000692 }
693 return true;
694}
695
696
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697/// This function implements the transforms common to both integer division
698/// instructions (udiv and sdiv). It is called by the visitors to those integer
699/// division instructions.
700/// @brief Common integer divide transforms
701Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
703
Chris Lattner7c99f192011-05-22 18:18:41 +0000704 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000705 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000706 I.setOperand(1, V);
707 return &I;
708 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000709
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000710 // Handle cases involving: [su]div X, (select Cond, Y, Z)
711 // This does not apply for fdiv.
712 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
713 return &I;
714
David Majnemer27adb122014-10-12 08:34:24 +0000715 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
716 const APInt *C2;
717 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000718 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000719 const APInt *C1;
720 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000721
David Majnemer27adb122014-10-12 08:34:24 +0000722 // (X / C1) / C2 -> X / (C1*C2)
723 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
724 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
725 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
726 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
727 return BinaryOperator::Create(I.getOpcode(), X,
728 ConstantInt::get(I.getType(), Product));
729 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000730
David Majnemer27adb122014-10-12 08:34:24 +0000731 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
732 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
733 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
734
735 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
736 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
737 BinaryOperator *BO = BinaryOperator::Create(
738 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
739 BO->setIsExact(I.isExact());
740 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000741 }
742
David Majnemer27adb122014-10-12 08:34:24 +0000743 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
744 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
745 BinaryOperator *BO = BinaryOperator::Create(
746 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
747 BO->setHasNoUnsignedWrap(
748 !IsSigned &&
749 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
750 BO->setHasNoSignedWrap(
751 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
752 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000753 }
754 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000755
David Majnemer27adb122014-10-12 08:34:24 +0000756 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
757 *C1 != C1->getBitWidth() - 1) ||
758 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
759 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
760 APInt C1Shifted = APInt::getOneBitSet(
761 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
762
763 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
764 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
765 BinaryOperator *BO = BinaryOperator::Create(
766 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
767 BO->setIsExact(I.isExact());
768 return BO;
769 }
770
771 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
772 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
773 BinaryOperator *BO = BinaryOperator::Create(
774 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
775 BO->setHasNoUnsignedWrap(
776 !IsSigned &&
777 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
778 BO->setHasNoSignedWrap(
779 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
780 return BO;
781 }
782 }
783
784 if (*C2 != 0) { // avoid X udiv 0
785 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
786 if (Instruction *R = FoldOpIntoSelect(I, SI))
787 return R;
788 if (isa<PHINode>(Op0))
789 if (Instruction *NV = FoldOpIntoPhi(I))
790 return NV;
791 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000792 }
793 }
794
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000795 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
796 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
797 bool isSigned = I.getOpcode() == Instruction::SDiv;
798 if (isSigned) {
799 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
800 // result is one, if Op1 is -1 then the result is minus one, otherwise
801 // it's zero.
802 Value *Inc = Builder->CreateAdd(Op1, One);
803 Value *Cmp = Builder->CreateICmpULT(
804 Inc, ConstantInt::get(I.getType(), 3));
805 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
806 } else {
807 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
808 // result is one, otherwise it's zero.
809 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
810 }
811 }
812 }
813
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000814 // See if we can fold away this div instruction.
815 if (SimplifyDemandedInstructionBits(I))
816 return &I;
817
Duncan Sands771e82a2011-01-28 16:51:11 +0000818 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000819 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000820 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
821 bool isSigned = I.getOpcode() == Instruction::SDiv;
822 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
823 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
824 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000825 }
826
Craig Topperf40110f2014-04-25 05:29:35 +0000827 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000828}
829
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000830/// dyn_castZExtVal - Checks if V is a zext or constant that can
831/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000832static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000833 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
834 if (Z->getSrcTy() == Ty)
835 return Z->getOperand(0);
836 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
837 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
838 return ConstantExpr::getTrunc(C, Ty);
839 }
Craig Topperf40110f2014-04-25 05:29:35 +0000840 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000841}
842
David Majnemer37f8f442013-07-04 21:17:49 +0000843namespace {
844const unsigned MaxDepth = 6;
845typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
846 const BinaryOperator &I,
847 InstCombiner &IC);
848
849/// \brief Used to maintain state for visitUDivOperand().
850struct UDivFoldAction {
851 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
852 ///< operand. This can be zero if this action
853 ///< joins two actions together.
854
855 Value *OperandToFold; ///< Which operand to fold.
856 union {
857 Instruction *FoldResult; ///< The instruction returned when FoldAction is
858 ///< invoked.
859
860 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
861 ///< joins two actions together.
862 };
863
864 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000865 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000866 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
867 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
868};
869}
870
871// X udiv 2^C -> X >> C
872static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
873 const BinaryOperator &I, InstCombiner &IC) {
874 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
875 BinaryOperator *LShr = BinaryOperator::CreateLShr(
876 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000877 if (I.isExact())
878 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000879 return LShr;
880}
881
882// X udiv C, where C >= signbit
883static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
884 const BinaryOperator &I, InstCombiner &IC) {
885 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
886
887 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
888 ConstantInt::get(I.getType(), 1));
889}
890
891// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
892static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
893 InstCombiner &IC) {
894 Instruction *ShiftLeft = cast<Instruction>(Op1);
895 if (isa<ZExtInst>(ShiftLeft))
896 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
897
898 const APInt &CI =
899 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
900 Value *N = ShiftLeft->getOperand(1);
901 if (CI != 1)
902 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
903 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
904 N = IC.Builder->CreateZExt(N, Z->getDestTy());
905 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000906 if (I.isExact())
907 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000908 return LShr;
909}
910
911// \brief Recursively visits the possible right hand operands of a udiv
912// instruction, seeing through select instructions, to determine if we can
913// replace the udiv with something simpler. If we find that an operand is not
914// able to simplify the udiv, we abort the entire transformation.
915static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
916 SmallVectorImpl<UDivFoldAction> &Actions,
917 unsigned Depth = 0) {
918 // Check to see if this is an unsigned division with an exact power of 2,
919 // if so, convert to a right shift.
920 if (match(Op1, m_Power2())) {
921 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
922 return Actions.size();
923 }
924
925 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
926 // X udiv C, where C >= signbit
927 if (C->getValue().isNegative()) {
928 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
929 return Actions.size();
930 }
931
932 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
933 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
934 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
935 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
936 return Actions.size();
937 }
938
939 // The remaining tests are all recursive, so bail out if we hit the limit.
940 if (Depth++ == MaxDepth)
941 return 0;
942
943 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000944 if (size_t LHSIdx =
945 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
946 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
947 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000948 return Actions.size();
949 }
950
951 return 0;
952}
953
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000954Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
956
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000957 if (Value *V = SimplifyVectorOp(I))
958 return ReplaceInstUsesWith(I, V);
959
Hal Finkel60db0582014-09-07 18:57:58 +0000960 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000961 return ReplaceInstUsesWith(I, V);
962
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000963 // Handle the integer div common cases
964 if (Instruction *Common = commonIDivTransforms(I))
965 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000966
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000967 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000968 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000969 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000970 const APInt *C1, *C2;
971 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
972 match(Op1, m_APInt(C2))) {
973 bool Overflow;
974 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
975 if (!Overflow)
976 return BinaryOperator::CreateUDiv(
977 X, ConstantInt::get(X->getType(), C2ShlC1));
978 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000979 }
980
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000981 // (zext A) udiv (zext B) --> zext (A udiv B)
982 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
983 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +0000984 return new ZExtInst(
985 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
986 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000987
David Majnemer37f8f442013-07-04 21:17:49 +0000988 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
989 SmallVector<UDivFoldAction, 6> UDivActions;
990 if (visitUDivOperand(Op0, Op1, I, UDivActions))
991 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
992 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
993 Value *ActionOp1 = UDivActions[i].OperandToFold;
994 Instruction *Inst;
995 if (Action)
996 Inst = Action(Op0, ActionOp1, I, *this);
997 else {
998 // This action joins two actions together. The RHS of this action is
999 // simply the last action we processed, we saved the LHS action index in
1000 // the joining action.
1001 size_t SelectRHSIdx = i - 1;
1002 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1003 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1004 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1005 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1006 SelectLHS, SelectRHS);
1007 }
1008
1009 // If this is the last action to process, return it to the InstCombiner.
1010 // Otherwise, we insert it before the UDiv and record it so that we may
1011 // use it as part of a joining action (i.e., a SelectInst).
1012 if (e - i != 1) {
1013 Inst->insertBefore(&I);
1014 UDivActions[i].FoldResult = Inst;
1015 } else
1016 return Inst;
1017 }
1018
Craig Topperf40110f2014-04-25 05:29:35 +00001019 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001020}
1021
1022Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1024
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001025 if (Value *V = SimplifyVectorOp(I))
1026 return ReplaceInstUsesWith(I, V);
1027
Hal Finkel60db0582014-09-07 18:57:58 +00001028 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001029 return ReplaceInstUsesWith(I, V);
1030
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001031 // Handle the integer div common cases
1032 if (Instruction *Common = commonIDivTransforms(I))
1033 return Common;
1034
Benjamin Kramer72196f32014-01-19 15:24:22 +00001035 // sdiv X, -1 == -X
1036 if (match(Op1, m_AllOnes()))
1037 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001038
Benjamin Kramer72196f32014-01-19 15:24:22 +00001039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001040 // sdiv X, C --> ashr exact X, log2(C)
1041 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001042 RHS->getValue().isPowerOf2()) {
1043 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1044 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001045 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001046 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001047 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001048
Benjamin Kramer72196f32014-01-19 15:24:22 +00001049 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001050 // X/INT_MIN -> X == INT_MIN
1051 if (RHS->isMinSignedValue())
1052 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1053
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001054 // -X/C --> X/-C provided the negation doesn't overflow.
1055 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001056 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001057 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1058 ConstantExpr::getNeg(RHS));
1059 }
1060
1061 // If the sign bits of both operands are zero (i.e. we can prove they are
1062 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001063 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001064 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001065 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1066 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001067 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001068 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1069 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001070
Chris Lattner6b657ae2011-02-10 05:36:31 +00001071 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001072 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1073 // Safe because the only negative value (1 << Y) can take on is
1074 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1075 // the sign bit set.
1076 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1077 }
1078 }
1079 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001080
Craig Topperf40110f2014-04-25 05:29:35 +00001081 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001082}
1083
Shuxin Yang320f52a2013-01-14 22:48:41 +00001084/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1085/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001086/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001087/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001088/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001089/// returned; otherwise, NULL is returned.
1090///
Suyog Sardaea205512014-10-07 11:56:06 +00001091static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001092 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001093 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001094 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001095
1096 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001097 APFloat Reciprocal(FpVal.getSemantics());
1098 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001099
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001100 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001101 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1102 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1103 Cvt = !Reciprocal.isDenormal();
1104 }
1105
1106 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001107 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001108
1109 ConstantFP *R;
1110 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1111 return BinaryOperator::CreateFMul(Dividend, R);
1112}
1113
Frits van Bommel2a559512011-01-29 17:50:27 +00001114Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1116
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001117 if (Value *V = SimplifyVectorOp(I))
1118 return ReplaceInstUsesWith(I, V);
1119
Hal Finkel60db0582014-09-07 18:57:58 +00001120 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001121 return ReplaceInstUsesWith(I, V);
1122
Stephen Lina9b57f62013-07-20 07:13:13 +00001123 if (isa<Constant>(Op0))
1124 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1125 if (Instruction *R = FoldOpIntoSelect(I, SI))
1126 return R;
1127
Shuxin Yang320f52a2013-01-14 22:48:41 +00001128 bool AllowReassociate = I.hasUnsafeAlgebra();
1129 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001130
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001131 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001132 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1133 if (Instruction *R = FoldOpIntoSelect(I, SI))
1134 return R;
1135
Shuxin Yang320f52a2013-01-14 22:48:41 +00001136 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001137 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001138 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001139 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001140 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001141
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001142 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001143 // (X*C1)/C2 => X * (C1/C2)
1144 //
1145 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001146 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001147 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001148 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001149 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1150 //
1151 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001152 if (isNormalFp(C)) {
1153 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001154 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001155 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001156 }
1157 }
1158
1159 if (Res) {
1160 Res->setFastMathFlags(I.getFastMathFlags());
1161 return Res;
1162 }
1163 }
1164
1165 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001166 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1167 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001168 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001169 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001170
Craig Topperf40110f2014-04-25 05:29:35 +00001171 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001172 }
1173
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001174 if (AllowReassociate && isa<Constant>(Op0)) {
1175 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001176 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001177 Value *X;
1178 bool CreateDiv = true;
1179
1180 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001181 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001182 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001183 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001184 // C1 / (X/C2) => (C1*C2) / X
1185 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001186 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001187 // C1 / (C2/X) => (C1/C2) * X
1188 Fold = ConstantExpr::getFDiv(C1, C2);
1189 CreateDiv = false;
1190 }
1191
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001192 if (Fold && isNormalFp(Fold)) {
1193 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1194 : BinaryOperator::CreateFMul(X, Fold);
1195 R->setFastMathFlags(I.getFastMathFlags());
1196 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001197 }
Craig Topperf40110f2014-04-25 05:29:35 +00001198 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001199 }
1200
1201 if (AllowReassociate) {
1202 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001203 Value *NewInst = nullptr;
1204 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001205
1206 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1207 // (X/Y) / Z => X / (Y*Z)
1208 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001209 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001210 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001211 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1212 FastMathFlags Flags = I.getFastMathFlags();
1213 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1214 RI->setFastMathFlags(Flags);
1215 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001216 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1217 }
1218 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1219 // Z / (X/Y) => Z*Y / X
1220 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001221 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001222 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001223 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1224 FastMathFlags Flags = I.getFastMathFlags();
1225 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1226 RI->setFastMathFlags(Flags);
1227 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001228 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1229 }
1230 }
1231
1232 if (NewInst) {
1233 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1234 T->setDebugLoc(I.getDebugLoc());
1235 SimpR->setFastMathFlags(I.getFastMathFlags());
1236 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001237 }
1238 }
1239
Craig Topperf40110f2014-04-25 05:29:35 +00001240 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001241}
1242
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001243/// This function implements the transforms common to both integer remainder
1244/// instructions (urem and srem). It is called by the visitors to those integer
1245/// remainder instructions.
1246/// @brief Common integer remainder transforms
1247Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1249
Chris Lattner7c99f192011-05-22 18:18:41 +00001250 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001251 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001252 I.setOperand(1, V);
1253 return &I;
1254 }
1255
Duncan Sandsa3e36992011-05-02 16:27:02 +00001256 // Handle cases involving: rem X, (select Cond, Y, Z)
1257 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1258 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001259
Benjamin Kramer72196f32014-01-19 15:24:22 +00001260 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001261 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1262 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1263 if (Instruction *R = FoldOpIntoSelect(I, SI))
1264 return R;
1265 } else if (isa<PHINode>(Op0I)) {
1266 if (Instruction *NV = FoldOpIntoPhi(I))
1267 return NV;
1268 }
1269
1270 // See if we can fold away this rem instruction.
1271 if (SimplifyDemandedInstructionBits(I))
1272 return &I;
1273 }
1274 }
1275
Craig Topperf40110f2014-04-25 05:29:35 +00001276 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001277}
1278
1279Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1280 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1281
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001282 if (Value *V = SimplifyVectorOp(I))
1283 return ReplaceInstUsesWith(I, V);
1284
Hal Finkel60db0582014-09-07 18:57:58 +00001285 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001286 return ReplaceInstUsesWith(I, V);
1287
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001288 if (Instruction *common = commonIRemTransforms(I))
1289 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001290
David Majnemer6c30f492013-05-12 00:07:05 +00001291 // (zext A) urem (zext B) --> zext (A urem B)
1292 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1293 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1294 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1295 I.getType());
1296
David Majnemer470b0772013-05-11 09:01:28 +00001297 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001298 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001299 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001300 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001301 return BinaryOperator::CreateAnd(Op0, Add);
1302 }
1303
Nick Lewycky7459be62013-07-13 01:16:47 +00001304 // 1 urem X -> zext(X != 1)
1305 if (match(Op0, m_One())) {
1306 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1307 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1308 return ReplaceInstUsesWith(I, Ext);
1309 }
1310
Craig Topperf40110f2014-04-25 05:29:35 +00001311 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001312}
1313
1314Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1315 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1316
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001317 if (Value *V = SimplifyVectorOp(I))
1318 return ReplaceInstUsesWith(I, V);
1319
Hal Finkel60db0582014-09-07 18:57:58 +00001320 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001321 return ReplaceInstUsesWith(I, V);
1322
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001323 // Handle the integer rem common cases
1324 if (Instruction *Common = commonIRemTransforms(I))
1325 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001326
David Majnemerdb077302014-10-13 22:37:51 +00001327 {
1328 const APInt *Y;
1329 // X % -Y -> X % Y
1330 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001331 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001332 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001333 return &I;
1334 }
David Majnemerdb077302014-10-13 22:37:51 +00001335 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001336
1337 // If the sign bits of both operands are zero (i.e. we can prove they are
1338 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001339 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001340 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001341 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1342 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001343 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001344 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1345 }
1346 }
1347
1348 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001349 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1350 Constant *C = cast<Constant>(Op1);
1351 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001352
1353 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001354 bool hasMissing = false;
1355 for (unsigned i = 0; i != VWidth; ++i) {
1356 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001357 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001358 hasMissing = true;
1359 break;
1360 }
1361
1362 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001363 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001364 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001365 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001366
Chris Lattner0256be92012-01-27 03:08:05 +00001367 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001368 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001369 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001370 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001371 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001372 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001373 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001374 }
1375 }
1376
1377 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001378 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001379 Worklist.AddValue(I.getOperand(1));
1380 I.setOperand(1, NewRHSV);
1381 return &I;
1382 }
1383 }
1384 }
1385
Craig Topperf40110f2014-04-25 05:29:35 +00001386 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001387}
1388
1389Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001390 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001391
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001392 if (Value *V = SimplifyVectorOp(I))
1393 return ReplaceInstUsesWith(I, V);
1394
Hal Finkel60db0582014-09-07 18:57:58 +00001395 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001396 return ReplaceInstUsesWith(I, V);
1397
1398 // Handle cases involving: rem X, (select Cond, Y, Z)
1399 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1400 return &I;
1401
Craig Topperf40110f2014-04-25 05:29:35 +00001402 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001403}