blob: 8c48dce81de71f446f3a62152bcf2f1dbf731a26 [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner7c99f192011-05-22 18:18:41 +000024
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000028static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
29 Instruction *CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000030 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
32 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000033 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner388cb8a2011-05-23 00:32:19 +000035 bool MadeChange = false;
36
Chris Lattner7c99f192011-05-22 18:18:41 +000037 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000039 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000042 A = IC.Builder->CreateSub(A, B);
David Majnemerdad21032014-10-14 20:28:40 +000043 return IC.Builder->CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000044 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045
Chris Lattner388cb8a2011-05-23 00:32:19 +000046 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +000049 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
50 0, IC.getAssumptionTracker(),
51 CxtI,
52 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000055 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 I->setOperand(0, V2);
57 MadeChange = true;
58 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000059
Chris Lattner388cb8a2011-05-23 00:32:19 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattner388cb8a2011-05-23 00:32:19 +000065 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
67 MadeChange = true;
68 }
69 }
70
Chris Lattner162dfc32011-05-22 18:26:48 +000071 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000072 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000074
Craig Topperf40110f2014-04-25 05:29:35 +000075 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000076}
77
78
Chris Lattnerdc054bf2010-01-05 06:09:35 +000079/// MultiplyOverflows - True if the multiply can not be expressed in an int
80/// this size.
David Majnemer27adb122014-10-12 08:34:24 +000081static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
82 bool IsSigned) {
83 bool Overflow;
84 if (IsSigned)
85 Product = C1.smul_ov(C2, Overflow);
86 else
87 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088
David Majnemer27adb122014-10-12 08:34:24 +000089 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090}
91
David Majnemerf9a095d2014-08-16 08:55:06 +000092/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94 bool IsSigned) {
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
97
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
99 if (IsSigned)
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
101 else
102 APInt::udivrem(C1, C2, Quotient, Remainder);
103
104 return Remainder.isMinValue();
105}
106
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107/// \brief A helper routine of InstCombiner::visitMul().
108///
109/// If C is a vector of known powers of 2, then this function returns
110/// a new vector obtained from C replacing each element with its logBase2.
111/// Return a null pointer otherwise.
112static Constant *getLogBase2Vector(ConstantDataVector *CV) {
113 const APInt *IVal;
114 SmallVector<Constant *, 4> Elts;
115
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
121 }
122
123 return ConstantVector::get(Elts);
124}
125
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000126Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000127 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
129
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000130 if (Value *V = SimplifyVectorOp(I))
131 return ReplaceInstUsesWith(I, V);
132
Hal Finkel60db0582014-09-07 18:57:58 +0000133 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000134 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000135
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000136 if (Value *V = SimplifyUsingDistributiveLaws(I))
137 return ReplaceInstUsesWith(I, V);
138
Chris Lattner6b657ae2011-02-10 05:36:31 +0000139 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
140 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000141
Rafael Espindola65281bf2013-05-31 14:27:15 +0000142 // Also allow combining multiply instructions on vectors.
143 {
144 Value *NewOp;
145 Constant *C1, *C2;
146 const APInt *IVal;
147 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
148 m_Constant(C1))) &&
149 match(C1, m_APInt(IVal)))
150 // ((X << C1)*C2) == (X * (C2 << C1))
151 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000152
Rafael Espindola65281bf2013-05-31 14:27:15 +0000153 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000154 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000155 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
156 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
157 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
158 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
159 // Replace X*(2^C) with X << C, where C is a vector of known
160 // constant powers of 2.
161 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000162
Rafael Espindola65281bf2013-05-31 14:27:15 +0000163 if (NewCst) {
164 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000165
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000166 if (I.hasNoUnsignedWrap())
167 Shl->setHasNoUnsignedWrap();
168
Rafael Espindola65281bf2013-05-31 14:27:15 +0000169 return Shl;
170 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000171 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000172 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000173
Rafael Espindola65281bf2013-05-31 14:27:15 +0000174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000175 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
176 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
177 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000178 {
179 const APInt & Val = CI->getValue();
180 const APInt &PosVal = Val.abs();
181 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000182 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000183 if (Op0->hasOneUse()) {
184 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000185 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000186 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
187 Sub = Builder->CreateSub(X, Y, "suba");
188 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
189 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
190 if (Sub)
191 return
192 BinaryOperator::CreateMul(Sub,
193 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000194 }
195 }
196 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000197 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000198
Chris Lattner6b657ae2011-02-10 05:36:31 +0000199 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000200 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000201 // Try to fold constant mul into select arguments.
202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
203 if (Instruction *R = FoldOpIntoSelect(I, SI))
204 return R;
205
206 if (isa<PHINode>(Op0))
207 if (Instruction *NV = FoldOpIntoPhi(I))
208 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000209
210 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
211 {
212 Value *X;
213 Constant *C1;
214 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000215 Value *Mul = Builder->CreateMul(C1, Op1);
216 // Only go forward with the transform if C1*CI simplifies to a tidier
217 // constant.
218 if (!match(Mul, m_Mul(m_Value(), m_Value())))
219 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000220 }
221 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000222 }
223
224 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
225 if (Value *Op1v = dyn_castNegVal(Op1))
226 return BinaryOperator::CreateMul(Op0v, Op1v);
227
228 // (X / Y) * Y = X - (X % Y)
229 // (X / Y) * -Y = (X % Y) - X
230 {
231 Value *Op1C = Op1;
232 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
233 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000234 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000235 BO->getOpcode() != Instruction::SDiv)) {
236 Op1C = Op0;
237 BO = dyn_cast<BinaryOperator>(Op1);
238 }
239 Value *Neg = dyn_castNegVal(Op1C);
240 if (BO && BO->hasOneUse() &&
241 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
242 (BO->getOpcode() == Instruction::UDiv ||
243 BO->getOpcode() == Instruction::SDiv)) {
244 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
245
Chris Lattner35315d02011-02-06 21:44:57 +0000246 // If the division is exact, X % Y is zero, so we end up with X or -X.
247 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000248 if (SDiv->isExact()) {
249 if (Op1BO == Op1C)
250 return ReplaceInstUsesWith(I, Op0BO);
251 return BinaryOperator::CreateNeg(Op0BO);
252 }
253
254 Value *Rem;
255 if (BO->getOpcode() == Instruction::UDiv)
256 Rem = Builder->CreateURem(Op0BO, Op1BO);
257 else
258 Rem = Builder->CreateSRem(Op0BO, Op1BO);
259 Rem->takeName(BO);
260
261 if (Op1BO == Op1C)
262 return BinaryOperator::CreateSub(Op0BO, Rem);
263 return BinaryOperator::CreateSub(Rem, Op0BO);
264 }
265 }
266
267 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000268 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000269 return BinaryOperator::CreateAnd(Op0, Op1);
270
271 // X*(1 << Y) --> X << Y
272 // (1 << Y)*X --> X << Y
273 {
274 Value *Y;
275 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
276 return BinaryOperator::CreateShl(Op1, Y);
277 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
278 return BinaryOperator::CreateShl(Op0, Y);
279 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000280
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000281 // If one of the operands of the multiply is a cast from a boolean value, then
282 // we know the bool is either zero or one, so this is a 'masking' multiply.
283 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000284 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000285 // -2 is "-1 << 1" so it is all bits set except the low one.
286 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000287
Craig Topperf40110f2014-04-25 05:29:35 +0000288 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000289 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000290 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000291 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292 BoolCast = Op1, OtherOp = Op0;
293
294 if (BoolCast) {
295 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000296 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000297 return BinaryOperator::CreateAnd(V, OtherOp);
298 }
299 }
300
Craig Topperf40110f2014-04-25 05:29:35 +0000301 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000302}
303
Sanjay Patel17045f72014-10-14 00:33:23 +0000304/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000305static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000306 if (!Op->hasOneUse())
307 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000308
Sanjay Patel17045f72014-10-14 00:33:23 +0000309 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
310 if (!II)
311 return;
312 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
313 return;
314 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000315
Sanjay Patel17045f72014-10-14 00:33:23 +0000316 Value *OpLog2Of = II->getArgOperand(0);
317 if (!OpLog2Of->hasOneUse())
318 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000319
Sanjay Patel17045f72014-10-14 00:33:23 +0000320 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
321 if (!I)
322 return;
323 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
324 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000325
Sanjay Patel17045f72014-10-14 00:33:23 +0000326 if (match(I->getOperand(0), m_SpecificFP(0.5)))
327 Y = I->getOperand(1);
328 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
329 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000330}
Pedro Artigas993acd02012-11-30 22:07:05 +0000331
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000332static bool isFiniteNonZeroFp(Constant *C) {
333 if (C->getType()->isVectorTy()) {
334 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
335 ++I) {
336 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
337 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
338 return false;
339 }
340 return true;
341 }
342
343 return isa<ConstantFP>(C) &&
344 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
345}
346
347static bool isNormalFp(Constant *C) {
348 if (C->getType()->isVectorTy()) {
349 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
350 ++I) {
351 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
352 if (!CFP || !CFP->getValueAPF().isNormal())
353 return false;
354 }
355 return true;
356 }
357
358 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
359}
360
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000361/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
362/// true iff the given value is FMul or FDiv with one and only one operand
363/// being a normal constant (i.e. not Zero/NaN/Infinity).
364static bool isFMulOrFDivWithConstant(Value *V) {
365 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000366 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000367 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000368 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000369
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000370 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
371 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000372
373 if (C0 && C1)
374 return false;
375
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000376 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000377}
378
379/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
380/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
381/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000382/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000383/// resulting expression. Note that this function could return NULL in
384/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000386Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000387 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000388 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
389
390 Value *Opnd0 = FMulOrDiv->getOperand(0);
391 Value *Opnd1 = FMulOrDiv->getOperand(1);
392
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000393 Constant *C0 = dyn_cast<Constant>(Opnd0);
394 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000395
Craig Topperf40110f2014-04-25 05:29:35 +0000396 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000397
398 // (X * C0) * C => X * (C0*C)
399 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
400 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000401 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000402 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
403 } else {
404 if (C0) {
405 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000406 if (FMulOrDiv->hasOneUse()) {
407 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000408 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000409 if (isNormalFp(F))
410 R = BinaryOperator::CreateFDiv(F, Opnd1);
411 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000412 } else {
413 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000414 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000415 if (isNormalFp(F)) {
416 R = BinaryOperator::CreateFMul(Opnd0, F);
417 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000418 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000419 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000420 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000421 R = BinaryOperator::CreateFDiv(Opnd0, F);
422 }
423 }
424 }
425
426 if (R) {
427 R->setHasUnsafeAlgebra(true);
428 InsertNewInstWith(R, *InsertBefore);
429 }
430
431 return R;
432}
433
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000434Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000435 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000436 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
437
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000438 if (Value *V = SimplifyVectorOp(I))
439 return ReplaceInstUsesWith(I, V);
440
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000441 if (isa<Constant>(Op0))
442 std::swap(Op0, Op1);
443
Hal Finkel60db0582014-09-07 18:57:58 +0000444 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
445 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000446 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000447
Shuxin Yange8227452013-01-15 21:09:32 +0000448 bool AllowReassociate = I.hasUnsafeAlgebra();
449
Michael Ilsemand5787be2012-12-12 00:28:32 +0000450 // Simplify mul instructions with a constant RHS.
451 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000452 // Try to fold constant mul into select arguments.
453 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
454 if (Instruction *R = FoldOpIntoSelect(I, SI))
455 return R;
456
457 if (isa<PHINode>(Op0))
458 if (Instruction *NV = FoldOpIntoPhi(I))
459 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000460
Owen Andersonf74cfe02014-01-16 20:36:42 +0000461 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000462 if (match(Op1, m_SpecificFP(-1.0))) {
463 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
464 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000465 RI->copyFastMathFlags(&I);
466 return RI;
467 }
468
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000469 Constant *C = cast<Constant>(Op1);
470 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000471 // Let MDC denote an expression in one of these forms:
472 // X * C, C/X, X/C, where C is a constant.
473 //
474 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000475 if (isFMulOrFDivWithConstant(Op0))
476 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000477 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000478
Quentin Colombete684a6d2013-02-28 21:12:40 +0000479 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000480 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
481 if (FAddSub &&
482 (FAddSub->getOpcode() == Instruction::FAdd ||
483 FAddSub->getOpcode() == Instruction::FSub)) {
484 Value *Opnd0 = FAddSub->getOperand(0);
485 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000486 Constant *C0 = dyn_cast<Constant>(Opnd0);
487 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000488 bool Swap = false;
489 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000490 std::swap(C0, C1);
491 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000492 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000493 }
494
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000495 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000496 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000497 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000498 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000499 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000500 if (M0 && M1) {
501 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
502 std::swap(M0, M1);
503
Benjamin Kramer67485762013-09-30 15:39:59 +0000504 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
505 ? BinaryOperator::CreateFAdd(M0, M1)
506 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000507 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000508 return RI;
509 }
510 }
511 }
512 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000513 }
514
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000515 // sqrt(X) * sqrt(X) -> X
516 if (AllowReassociate && (Op0 == Op1))
517 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
518 if (II->getIntrinsicID() == Intrinsic::sqrt)
519 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000520
Pedro Artigasd8795042012-11-30 19:09:41 +0000521 // Under unsafe algebra do:
522 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000523 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000524 Value *OpX = nullptr;
525 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000526 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000527 detectLog2OfHalf(Op0, OpY, Log2);
528 if (OpY) {
529 OpX = Op1;
530 } else {
531 detectLog2OfHalf(Op1, OpY, Log2);
532 if (OpY) {
533 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000534 }
535 }
536 // if pattern detected emit alternate sequence
537 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000538 BuilderTy::FastMathFlagGuard Guard(*Builder);
539 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000540 Log2->setArgOperand(0, OpY);
541 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000542 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
543 FSub->takeName(&I);
544 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000545 }
546 }
547
Shuxin Yange8227452013-01-15 21:09:32 +0000548 // Handle symmetric situation in a 2-iteration loop
549 Value *Opnd0 = Op0;
550 Value *Opnd1 = Op1;
551 for (int i = 0; i < 2; i++) {
552 bool IgnoreZeroSign = I.hasNoSignedZeros();
553 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000554 BuilderTy::FastMathFlagGuard Guard(*Builder);
555 Builder->SetFastMathFlags(I.getFastMathFlags());
556
Shuxin Yange8227452013-01-15 21:09:32 +0000557 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
558 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000559
Shuxin Yange8227452013-01-15 21:09:32 +0000560 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000561 if (N1) {
562 Value *FMul = Builder->CreateFMul(N0, N1);
563 FMul->takeName(&I);
564 return ReplaceInstUsesWith(I, FMul);
565 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000566
Shuxin Yange8227452013-01-15 21:09:32 +0000567 if (Opnd0->hasOneUse()) {
568 // -X * Y => -(X*Y) (Promote negation as high as possible)
569 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000570 Value *Neg = Builder->CreateFNeg(T);
571 Neg->takeName(&I);
572 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000573 }
574 }
Shuxin Yange8227452013-01-15 21:09:32 +0000575
576 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000577 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000578 // 1) to form a power expression (of X).
579 // 2) potentially shorten the critical path: After transformation, the
580 // latency of the instruction Y is amortized by the expression of X*X,
581 // and therefore Y is in a "less critical" position compared to what it
582 // was before the transformation.
583 //
584 if (AllowReassociate) {
585 Value *Opnd0_0, *Opnd0_1;
586 if (Opnd0->hasOneUse() &&
587 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000588 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000589 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
590 Y = Opnd0_1;
591 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
592 Y = Opnd0_0;
593
594 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000595 BuilderTy::FastMathFlagGuard Guard(*Builder);
596 Builder->SetFastMathFlags(I.getFastMathFlags());
597 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000598
Benjamin Kramer67485762013-09-30 15:39:59 +0000599 Value *R = Builder->CreateFMul(T, Y);
600 R->takeName(&I);
601 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000602 }
603 }
604 }
605
606 if (!isa<Constant>(Op1))
607 std::swap(Opnd0, Opnd1);
608 else
609 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000610 }
611
Craig Topperf40110f2014-04-25 05:29:35 +0000612 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000613}
614
615/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
616/// instruction.
617bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
618 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000619
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000620 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
621 int NonNullOperand = -1;
622 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
623 if (ST->isNullValue())
624 NonNullOperand = 2;
625 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
626 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
627 if (ST->isNullValue())
628 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000629
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000630 if (NonNullOperand == -1)
631 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000632
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000633 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000634
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000635 // Change the div/rem to use 'Y' instead of the select.
636 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000637
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000638 // Okay, we know we replace the operand of the div/rem with 'Y' with no
639 // problem. However, the select, or the condition of the select may have
640 // multiple uses. Based on our knowledge that the operand must be non-zero,
641 // propagate the known value for the select into other uses of it, and
642 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000643
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000644 // If the select and condition only have a single use, don't bother with this,
645 // early exit.
646 if (SI->use_empty() && SelectCond->hasOneUse())
647 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 // Scan the current block backward, looking for other uses of SI.
650 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 while (BBI != BBFront) {
653 --BBI;
654 // If we found a call to a function, we can't assume it will return, so
655 // information from below it cannot be propagated above it.
656 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
657 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000658
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000659 // Replace uses of the select or its condition with the known values.
660 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
661 I != E; ++I) {
662 if (*I == SI) {
663 *I = SI->getOperand(NonNullOperand);
664 Worklist.Add(BBI);
665 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000666 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000667 Worklist.Add(BBI);
668 }
669 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000671 // If we past the instruction, quit looking for it.
672 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000673 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000674 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000675 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000676
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000677 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000678 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000679 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000680
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000681 }
682 return true;
683}
684
685
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000686/// This function implements the transforms common to both integer division
687/// instructions (udiv and sdiv). It is called by the visitors to those integer
688/// division instructions.
689/// @brief Common integer divide transforms
690Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
692
Chris Lattner7c99f192011-05-22 18:18:41 +0000693 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000694 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000695 I.setOperand(1, V);
696 return &I;
697 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000698
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000699 // Handle cases involving: [su]div X, (select Cond, Y, Z)
700 // This does not apply for fdiv.
701 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
702 return &I;
703
David Majnemer27adb122014-10-12 08:34:24 +0000704 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
705 const APInt *C2;
706 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000707 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000708 const APInt *C1;
709 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000710
David Majnemer27adb122014-10-12 08:34:24 +0000711 // (X / C1) / C2 -> X / (C1*C2)
712 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
713 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
714 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
715 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
716 return BinaryOperator::Create(I.getOpcode(), X,
717 ConstantInt::get(I.getType(), Product));
718 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000719
David Majnemer27adb122014-10-12 08:34:24 +0000720 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
721 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
722 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
723
724 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
725 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
726 BinaryOperator *BO = BinaryOperator::Create(
727 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
728 BO->setIsExact(I.isExact());
729 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000730 }
731
David Majnemer27adb122014-10-12 08:34:24 +0000732 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
733 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
734 BinaryOperator *BO = BinaryOperator::Create(
735 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
736 BO->setHasNoUnsignedWrap(
737 !IsSigned &&
738 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
739 BO->setHasNoSignedWrap(
740 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
741 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000742 }
743 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000744
David Majnemer27adb122014-10-12 08:34:24 +0000745 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
746 *C1 != C1->getBitWidth() - 1) ||
747 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
748 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
749 APInt C1Shifted = APInt::getOneBitSet(
750 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
751
752 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
753 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
754 BinaryOperator *BO = BinaryOperator::Create(
755 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
756 BO->setIsExact(I.isExact());
757 return BO;
758 }
759
760 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
761 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
762 BinaryOperator *BO = BinaryOperator::Create(
763 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
764 BO->setHasNoUnsignedWrap(
765 !IsSigned &&
766 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
767 BO->setHasNoSignedWrap(
768 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
769 return BO;
770 }
771 }
772
773 if (*C2 != 0) { // avoid X udiv 0
774 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
775 if (Instruction *R = FoldOpIntoSelect(I, SI))
776 return R;
777 if (isa<PHINode>(Op0))
778 if (Instruction *NV = FoldOpIntoPhi(I))
779 return NV;
780 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000781 }
782 }
783
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000784 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
785 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
786 bool isSigned = I.getOpcode() == Instruction::SDiv;
787 if (isSigned) {
788 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
789 // result is one, if Op1 is -1 then the result is minus one, otherwise
790 // it's zero.
791 Value *Inc = Builder->CreateAdd(Op1, One);
792 Value *Cmp = Builder->CreateICmpULT(
793 Inc, ConstantInt::get(I.getType(), 3));
794 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
795 } else {
796 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
797 // result is one, otherwise it's zero.
798 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
799 }
800 }
801 }
802
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000803 // See if we can fold away this div instruction.
804 if (SimplifyDemandedInstructionBits(I))
805 return &I;
806
Duncan Sands771e82a2011-01-28 16:51:11 +0000807 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000808 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000809 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
810 bool isSigned = I.getOpcode() == Instruction::SDiv;
811 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
812 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
813 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000814 }
815
Craig Topperf40110f2014-04-25 05:29:35 +0000816 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000817}
818
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000819/// dyn_castZExtVal - Checks if V is a zext or constant that can
820/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000821static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000822 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
823 if (Z->getSrcTy() == Ty)
824 return Z->getOperand(0);
825 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
826 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
827 return ConstantExpr::getTrunc(C, Ty);
828 }
Craig Topperf40110f2014-04-25 05:29:35 +0000829 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000830}
831
David Majnemer37f8f442013-07-04 21:17:49 +0000832namespace {
833const unsigned MaxDepth = 6;
834typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
835 const BinaryOperator &I,
836 InstCombiner &IC);
837
838/// \brief Used to maintain state for visitUDivOperand().
839struct UDivFoldAction {
840 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
841 ///< operand. This can be zero if this action
842 ///< joins two actions together.
843
844 Value *OperandToFold; ///< Which operand to fold.
845 union {
846 Instruction *FoldResult; ///< The instruction returned when FoldAction is
847 ///< invoked.
848
849 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
850 ///< joins two actions together.
851 };
852
853 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000854 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000855 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
856 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
857};
858}
859
860// X udiv 2^C -> X >> C
861static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
862 const BinaryOperator &I, InstCombiner &IC) {
863 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
864 BinaryOperator *LShr = BinaryOperator::CreateLShr(
865 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000866 if (I.isExact())
867 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000868 return LShr;
869}
870
871// X udiv C, where C >= signbit
872static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
873 const BinaryOperator &I, InstCombiner &IC) {
874 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
875
876 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
877 ConstantInt::get(I.getType(), 1));
878}
879
880// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
881static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
882 InstCombiner &IC) {
883 Instruction *ShiftLeft = cast<Instruction>(Op1);
884 if (isa<ZExtInst>(ShiftLeft))
885 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
886
887 const APInt &CI =
888 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
889 Value *N = ShiftLeft->getOperand(1);
890 if (CI != 1)
891 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
892 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
893 N = IC.Builder->CreateZExt(N, Z->getDestTy());
894 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000895 if (I.isExact())
896 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000897 return LShr;
898}
899
900// \brief Recursively visits the possible right hand operands of a udiv
901// instruction, seeing through select instructions, to determine if we can
902// replace the udiv with something simpler. If we find that an operand is not
903// able to simplify the udiv, we abort the entire transformation.
904static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
905 SmallVectorImpl<UDivFoldAction> &Actions,
906 unsigned Depth = 0) {
907 // Check to see if this is an unsigned division with an exact power of 2,
908 // if so, convert to a right shift.
909 if (match(Op1, m_Power2())) {
910 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
911 return Actions.size();
912 }
913
914 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
915 // X udiv C, where C >= signbit
916 if (C->getValue().isNegative()) {
917 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
918 return Actions.size();
919 }
920
921 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
922 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
923 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
924 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
925 return Actions.size();
926 }
927
928 // The remaining tests are all recursive, so bail out if we hit the limit.
929 if (Depth++ == MaxDepth)
930 return 0;
931
932 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000933 if (size_t LHSIdx =
934 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
935 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
936 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000937 return Actions.size();
938 }
939
940 return 0;
941}
942
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000943Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
944 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
945
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000946 if (Value *V = SimplifyVectorOp(I))
947 return ReplaceInstUsesWith(I, V);
948
Hal Finkel60db0582014-09-07 18:57:58 +0000949 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000950 return ReplaceInstUsesWith(I, V);
951
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000952 // Handle the integer div common cases
953 if (Instruction *Common = commonIDivTransforms(I))
954 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000955
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000956 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000957 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000958 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000959 const APInt *C1, *C2;
960 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
961 match(Op1, m_APInt(C2))) {
962 bool Overflow;
963 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
964 if (!Overflow)
965 return BinaryOperator::CreateUDiv(
966 X, ConstantInt::get(X->getType(), C2ShlC1));
967 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000968 }
969
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000970 // (zext A) udiv (zext B) --> zext (A udiv B)
971 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
972 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +0000973 return new ZExtInst(
974 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
975 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000976
David Majnemer37f8f442013-07-04 21:17:49 +0000977 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
978 SmallVector<UDivFoldAction, 6> UDivActions;
979 if (visitUDivOperand(Op0, Op1, I, UDivActions))
980 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
981 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
982 Value *ActionOp1 = UDivActions[i].OperandToFold;
983 Instruction *Inst;
984 if (Action)
985 Inst = Action(Op0, ActionOp1, I, *this);
986 else {
987 // This action joins two actions together. The RHS of this action is
988 // simply the last action we processed, we saved the LHS action index in
989 // the joining action.
990 size_t SelectRHSIdx = i - 1;
991 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
992 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
993 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
994 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
995 SelectLHS, SelectRHS);
996 }
997
998 // If this is the last action to process, return it to the InstCombiner.
999 // Otherwise, we insert it before the UDiv and record it so that we may
1000 // use it as part of a joining action (i.e., a SelectInst).
1001 if (e - i != 1) {
1002 Inst->insertBefore(&I);
1003 UDivActions[i].FoldResult = Inst;
1004 } else
1005 return Inst;
1006 }
1007
Craig Topperf40110f2014-04-25 05:29:35 +00001008 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001009}
1010
1011Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1013
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001014 if (Value *V = SimplifyVectorOp(I))
1015 return ReplaceInstUsesWith(I, V);
1016
Hal Finkel60db0582014-09-07 18:57:58 +00001017 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001018 return ReplaceInstUsesWith(I, V);
1019
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001020 // Handle the integer div common cases
1021 if (Instruction *Common = commonIDivTransforms(I))
1022 return Common;
1023
Benjamin Kramer72196f32014-01-19 15:24:22 +00001024 // sdiv X, -1 == -X
1025 if (match(Op1, m_AllOnes()))
1026 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001027
Benjamin Kramer72196f32014-01-19 15:24:22 +00001028 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001029 // sdiv X, C --> ashr exact X, log2(C)
1030 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001031 RHS->getValue().isPowerOf2()) {
1032 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1033 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001034 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001035 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001036 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001037
Benjamin Kramer72196f32014-01-19 15:24:22 +00001038 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001039 // X/INT_MIN -> X == INT_MIN
1040 if (RHS->isMinSignedValue())
1041 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1042
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001043 // -X/C --> X/-C provided the negation doesn't overflow.
1044 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001045 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001046 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1047 ConstantExpr::getNeg(RHS));
1048 }
1049
1050 // If the sign bits of both operands are zero (i.e. we can prove they are
1051 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001052 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001053 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001054 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1055 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001056 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001057 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1058 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001059
Chris Lattner6b657ae2011-02-10 05:36:31 +00001060 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001061 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1062 // Safe because the only negative value (1 << Y) can take on is
1063 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1064 // the sign bit set.
1065 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1066 }
1067 }
1068 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001069
Craig Topperf40110f2014-04-25 05:29:35 +00001070 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001071}
1072
Shuxin Yang320f52a2013-01-14 22:48:41 +00001073/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1074/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001075/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001076/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001077/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001078/// returned; otherwise, NULL is returned.
1079///
Suyog Sardaea205512014-10-07 11:56:06 +00001080static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001081 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001082 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001083 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001084
1085 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001086 APFloat Reciprocal(FpVal.getSemantics());
1087 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001088
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001089 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001090 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1091 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1092 Cvt = !Reciprocal.isDenormal();
1093 }
1094
1095 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001096 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001097
1098 ConstantFP *R;
1099 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1100 return BinaryOperator::CreateFMul(Dividend, R);
1101}
1102
Frits van Bommel2a559512011-01-29 17:50:27 +00001103Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1105
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001106 if (Value *V = SimplifyVectorOp(I))
1107 return ReplaceInstUsesWith(I, V);
1108
Hal Finkel60db0582014-09-07 18:57:58 +00001109 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001110 return ReplaceInstUsesWith(I, V);
1111
Stephen Lina9b57f62013-07-20 07:13:13 +00001112 if (isa<Constant>(Op0))
1113 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1114 if (Instruction *R = FoldOpIntoSelect(I, SI))
1115 return R;
1116
Shuxin Yang320f52a2013-01-14 22:48:41 +00001117 bool AllowReassociate = I.hasUnsafeAlgebra();
1118 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001119
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001120 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001121 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1122 if (Instruction *R = FoldOpIntoSelect(I, SI))
1123 return R;
1124
Shuxin Yang320f52a2013-01-14 22:48:41 +00001125 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001126 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001127 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001128 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001129 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001130
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001131 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001132 // (X*C1)/C2 => X * (C1/C2)
1133 //
1134 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001135 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001136 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001137 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001138 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1139 //
1140 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001141 if (isNormalFp(C)) {
1142 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001143 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001144 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001145 }
1146 }
1147
1148 if (Res) {
1149 Res->setFastMathFlags(I.getFastMathFlags());
1150 return Res;
1151 }
1152 }
1153
1154 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001155 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1156 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001157 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001158 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001159
Craig Topperf40110f2014-04-25 05:29:35 +00001160 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001161 }
1162
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001163 if (AllowReassociate && isa<Constant>(Op0)) {
1164 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001165 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001166 Value *X;
1167 bool CreateDiv = true;
1168
1169 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001170 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001171 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001172 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001173 // C1 / (X/C2) => (C1*C2) / X
1174 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001175 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001176 // C1 / (C2/X) => (C1/C2) * X
1177 Fold = ConstantExpr::getFDiv(C1, C2);
1178 CreateDiv = false;
1179 }
1180
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001181 if (Fold && isNormalFp(Fold)) {
1182 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1183 : BinaryOperator::CreateFMul(X, Fold);
1184 R->setFastMathFlags(I.getFastMathFlags());
1185 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001186 }
Craig Topperf40110f2014-04-25 05:29:35 +00001187 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001188 }
1189
1190 if (AllowReassociate) {
1191 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001192 Value *NewInst = nullptr;
1193 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001194
1195 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1196 // (X/Y) / Z => X / (Y*Z)
1197 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001198 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001199 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001200 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1201 FastMathFlags Flags = I.getFastMathFlags();
1202 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1203 RI->setFastMathFlags(Flags);
1204 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001205 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1206 }
1207 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1208 // Z / (X/Y) => Z*Y / X
1209 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001210 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001211 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001212 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1213 FastMathFlags Flags = I.getFastMathFlags();
1214 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1215 RI->setFastMathFlags(Flags);
1216 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001217 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1218 }
1219 }
1220
1221 if (NewInst) {
1222 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1223 T->setDebugLoc(I.getDebugLoc());
1224 SimpR->setFastMathFlags(I.getFastMathFlags());
1225 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001226 }
1227 }
1228
Craig Topperf40110f2014-04-25 05:29:35 +00001229 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001230}
1231
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001232/// This function implements the transforms common to both integer remainder
1233/// instructions (urem and srem). It is called by the visitors to those integer
1234/// remainder instructions.
1235/// @brief Common integer remainder transforms
1236Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1237 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1238
Chris Lattner7c99f192011-05-22 18:18:41 +00001239 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001240 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001241 I.setOperand(1, V);
1242 return &I;
1243 }
1244
Duncan Sandsa3e36992011-05-02 16:27:02 +00001245 // Handle cases involving: rem X, (select Cond, Y, Z)
1246 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1247 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001248
Benjamin Kramer72196f32014-01-19 15:24:22 +00001249 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001250 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1251 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1252 if (Instruction *R = FoldOpIntoSelect(I, SI))
1253 return R;
1254 } else if (isa<PHINode>(Op0I)) {
1255 if (Instruction *NV = FoldOpIntoPhi(I))
1256 return NV;
1257 }
1258
1259 // See if we can fold away this rem instruction.
1260 if (SimplifyDemandedInstructionBits(I))
1261 return &I;
1262 }
1263 }
1264
Craig Topperf40110f2014-04-25 05:29:35 +00001265 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001266}
1267
1268Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1270
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001271 if (Value *V = SimplifyVectorOp(I))
1272 return ReplaceInstUsesWith(I, V);
1273
Hal Finkel60db0582014-09-07 18:57:58 +00001274 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001275 return ReplaceInstUsesWith(I, V);
1276
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001277 if (Instruction *common = commonIRemTransforms(I))
1278 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001279
David Majnemer6c30f492013-05-12 00:07:05 +00001280 // (zext A) urem (zext B) --> zext (A urem B)
1281 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1282 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1283 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1284 I.getType());
1285
David Majnemer470b0772013-05-11 09:01:28 +00001286 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001287 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001288 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001289 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001290 return BinaryOperator::CreateAnd(Op0, Add);
1291 }
1292
Nick Lewycky7459be62013-07-13 01:16:47 +00001293 // 1 urem X -> zext(X != 1)
1294 if (match(Op0, m_One())) {
1295 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1296 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1297 return ReplaceInstUsesWith(I, Ext);
1298 }
1299
Craig Topperf40110f2014-04-25 05:29:35 +00001300 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001301}
1302
1303Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1304 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1305
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001306 if (Value *V = SimplifyVectorOp(I))
1307 return ReplaceInstUsesWith(I, V);
1308
Hal Finkel60db0582014-09-07 18:57:58 +00001309 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001310 return ReplaceInstUsesWith(I, V);
1311
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001312 // Handle the integer rem common cases
1313 if (Instruction *Common = commonIRemTransforms(I))
1314 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001315
David Majnemerdb077302014-10-13 22:37:51 +00001316 {
1317 const APInt *Y;
1318 // X % -Y -> X % Y
1319 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001320 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001321 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001322 return &I;
1323 }
David Majnemerdb077302014-10-13 22:37:51 +00001324 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001325
1326 // If the sign bits of both operands are zero (i.e. we can prove they are
1327 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001328 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001329 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001330 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1331 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001332 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001333 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1334 }
1335 }
1336
1337 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001338 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1339 Constant *C = cast<Constant>(Op1);
1340 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001341
1342 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001343 bool hasMissing = false;
1344 for (unsigned i = 0; i != VWidth; ++i) {
1345 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001346 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001347 hasMissing = true;
1348 break;
1349 }
1350
1351 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001352 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001353 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001354 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001355
Chris Lattner0256be92012-01-27 03:08:05 +00001356 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001357 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001358 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001359 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001360 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001361 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001362 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001363 }
1364 }
1365
1366 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001367 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001368 Worklist.AddValue(I.getOperand(1));
1369 I.setOperand(1, NewRHSV);
1370 return &I;
1371 }
1372 }
1373 }
1374
Craig Topperf40110f2014-04-25 05:29:35 +00001375 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001376}
1377
1378Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001380
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001381 if (Value *V = SimplifyVectorOp(I))
1382 return ReplaceInstUsesWith(I, V);
1383
Hal Finkel60db0582014-09-07 18:57:58 +00001384 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001385 return ReplaceInstUsesWith(I, V);
1386
1387 // Handle cases involving: rem X, (select Cond, Y, Z)
1388 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1389 return &I;
1390
Craig Topperf40110f2014-04-25 05:29:35 +00001391 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001392}